@optimystic/db-p2p 0.1.2 → 0.1.3
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
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.OptimysticDbP2P = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var OptimysticDbP2P=(()=>{var OD=Object.create;var ah=Object.defineProperty;var RD=Object.getOwnPropertyDescriptor;var ND=Object.getOwnPropertyNames;var BD=Object.getPrototypeOf,UD=Object.prototype.hasOwnProperty;var ee=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var _=(r,e)=>()=>(r&&(e=r(r=0)),e);var At=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),z=(r,e)=>{for(var t in e)ah(r,t,{get:e[t],enumerable:!0})},z5=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ND(e))!UD.call(r,s)&&s!==t&&ah(r,s,{get:()=>e[s],enumerable:!(n=RD(e,s))||n.enumerable});return r};var ie=(r,e,t)=>(t=r!=null?OD(BD(r)):{},z5(e||!r||!r.__esModule?ah(t,"default",{value:r,enumerable:!0}):t,r)),$5=r=>z5(ah({},"__esModule",{value:!0}),r);function rs(r){return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}var cc=_(()=>{});function ae(r=0){return rs(Am.Buffer.alloc(r))}function tt(r=0){return rs(Am.Buffer.allocUnsafe(r))}var Am,rt=_(()=>{Am=ee("node:buffer");cc()});function Ae(r){if(r<WD)return 1;if(r<jD)return 2;if(r<YD)return 3;if(r<Cm)return 4;if(r<Tm)return 5;if(r<_m)return 6;if(r<Pm)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function In(r,e,t=0){switch(Ae(r)){case 8:e[t++]=r&255|Se,r/=128;case 7:e[t++]=r&255|Se,r/=128;case 6:e[t++]=r&255|Se,r/=128;case 5:e[t++]=r&255|Se,r/=128;case 4:e[t++]=r&255|Se,r>>>=7;case 3:e[t++]=r&255|Se,r>>>=7;case 2:e[t++]=r&255|Se,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function XD(r,e,t=0){switch(Ae(r)){case 8:e.set(t++,r&255|Se),r/=128;case 7:e.set(t++,r&255|Se),r/=128;case 6:e.set(t++,r&255|Se),r/=128;case 5:e.set(t++,r&255|Se),r/=128;case 4:e.set(t++,r&255|Se),r>>>=7;case 3:e.set(t++,r&255|Se),r>>>=7;case 2:e.set(t++,r&255|Se),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Dm(r,e){let t=r[e],n=0;if(n+=t&Ct,t<Se||(t=r[e+1],n+=(t&Ct)<<7,t<Se)||(t=r[e+2],n+=(t&Ct)<<14,t<Se)||(t=r[e+3],n+=(t&Ct)<<21,t<Se)||(t=r[e+4],n+=(t&Ct)*Cm,t<Se)||(t=r[e+5],n+=(t&Ct)*Tm,t<Se)||(t=r[e+6],n+=(t&Ct)*_m,t<Se)||(t=r[e+7],n+=(t&Ct)*Pm,t<Se))return n;throw new RangeError("Could not decode varint")}function QD(r,e){let t=r.get(e),n=0;if(n+=t&Ct,t<Se||(t=r.get(e+1),n+=(t&Ct)<<7,t<Se)||(t=r.get(e+2),n+=(t&Ct)<<14,t<Se)||(t=r.get(e+3),n+=(t&Ct)<<21,t<Se)||(t=r.get(e+4),n+=(t&Ct)*Cm,t<Se)||(t=r.get(e+5),n+=(t&Ct)*Tm,t<Se)||(t=r.get(e+6),n+=(t&Ct)*_m,t<Se)||(t=r.get(e+7),n+=(t&Ct)*Pm,t<Se))return n;throw new RangeError("Could not decode varint")}function Vr(r,e,t=0){return e==null&&(e=tt(Ae(r))),e instanceof Uint8Array?In(r,e,t):XD(r,e,t)}function jt(r,e=0){return r instanceof Uint8Array?Dm(r,e):QD(r,e)}var WD,jD,YD,Cm,Tm,_m,Pm,Se,Ct,gr=_(()=>{rt();WD=Math.pow(2,7),jD=Math.pow(2,14),YD=Math.pow(2,21),Cm=Math.pow(2,28),Tm=Math.pow(2,35),_m=Math.pow(2,42),Pm=Math.pow(2,49),Se=128,Ct=127});function Ee(r,e){return rs(G5.Buffer.concat(r,e))}var G5,bt=_(()=>{G5=ee("node:buffer");cc()});function W(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var Ne=_(()=>{});function W5(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function hh(r){return!!r?.[j5]}var j5,U,Be=_(()=>{rt();bt();Ne();j5=Symbol.for("@achingbrain/uint8arraylist");U=class r{bufs;length;[j5]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(hh(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(hh(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=W5(this.bufs,e);return t.buf[t.index]}set(e,t){let n=W5(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(hh(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:s}=this._subList(e,t);return Ee(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:Ee(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),o=new r;return o.length=s,o.bufs=[...n],o}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let h=e-a;n.push(i.subarray(h,h+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!hh(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let h=0;h<o;h++)i[h]=-1;for(let h=0;h<s;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let h=t;h<=c;h+=u){u=0;for(let p=l;p>=0;p--){let f=this.get(h+p);if(n[p]!==f){u=Math.max(1,p-a[f]);break}}if(u===0)return h}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=tt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let s=ae(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let s=ae(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let s=ae(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=tt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let s=ae(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let s=ae(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let s=ae(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let s=ae(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let s=ae(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!W(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((s,o)=>s+o.byteLength,0)),n.length=t,n}}});var X5,Q5=_(()=>{X5=Symbol.for("@libp2p/connection")});var J5=_(()=>{});var Z5=_(()=>{});var ex=_(()=>{});var Mm,tx=_(()=>{Mm=Symbol.for("@libp2p/content-routing")});var rr,yh,bh,R,Xo,hc,zs,Tn,wh,ns,dc,$s,Qo,ss,xh,vh,Eh,Rt,Sh,Gr,Dr,Ih,os,Hs,fc,Ah,Jo,is,rx=_(()=>{rr=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}},yh=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},bh=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},R=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Xo=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},hc=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}},zs=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}},Tn=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},wh=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}},ns=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},dc=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}},$s=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},Qo=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},ss=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},xh=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},vh=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},Eh=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},Rt=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}},Sh=class extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}},Gr=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Dr=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}},Ih=class extends Error{static name="AlreadyStartedError";constructor(e="Already started"){super(e),this.name="AlreadyStartedError"}},os=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},Hs=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}},fc=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},Ah=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},Jo=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},is=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}});var Ch,as,Th,_h,nx=_(()=>{Ch=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},as=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},Th=class extends as{constructor(e,t){super(!0,e,t)}},_h=class extends as{constructor(e,t){super(!1,e,t)}}});var sx=_(()=>{});var ox=_(()=>{});var ix=_(()=>{});var ax=_(()=>{});var pc,cx=_(()=>{pc=Symbol.for("@libp2p/peer-discovery")});function cs(r){return!!r?.[Ph]}var Ph,lx=_(()=>{Ph=Symbol.for("@libp2p/peer-id")});var ux=_(()=>{});var Om,hx=_(()=>{Om=Symbol.for("@libp2p/peer-routing")});var mc,dx=_(()=>{mc="keep-alive"});var fx=_(()=>{});function Dh(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function kh(...r){let e=[];for(let t of r)Dh(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function Lh(...r){let e=[];for(let t of r)Dh(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var px=_(()=>{});var mx=_(()=>{});var gx=_(()=>{});var yx=_(()=>{});var bx=_(()=>{});var Mh,gc,wx=_(()=>{Mh=Symbol.for("@libp2p/transport");(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(gc||(gc={}))});var xx,j,vx=_(()=>{xx=ee("node:events"),j=(r,...e)=>{try{(0,xx.setMaxListeners)(r,...e)}catch{}}});var me,Ue=_(()=>{vx();me=class extends EventTarget{#e=new Map;constructor(){super(),j(1/0,this)}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let s=this.#e.get(e);s!=null&&(s=s.filter(({callback:o})=>o!==t),this.#e.set(e,s))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:s})=>!s),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}}});var nt,yc,V=_(()=>{Q5();J5();Z5();ex();tx();rx();nx();sx();ox();ix();ax();cx();lx();ux();hx();dx();fx();px();mx();gx();yx();bx();wx();Ue();nt=Symbol.for("@libp2p/service-capabilities"),yc=Symbol.for("@libp2p/service-dependencies")});function Ex(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function ls(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var xX,bc=_(()=>{xX=new Uint8Array(0)});function tk(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var v=d[y],S=0,E=w-1;(v!==0||S<g)&&E!==-1;E--,S++)v+=256*x[E]>>>0,x[E]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var A=c.repeat(m);I<w;++I)A+=r.charAt(x[I]);return A}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*w[S]>>>0,w[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(d[m]!==" "){for(var E=b-y;E!==b&&w[E]===0;)E++;for(var I=new Uint8Array(g+(b-E)),A=g;E!==b;)I[A++]=w[E++];return I}}}function f(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:f}}var rk,nk,Sx,Ix=_(()=>{rk=tk,nk=rk,Sx=nk});function Ax(r,e){return new Bm({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}function Cx({name:r,prefix:e,encode:t,decode:n}){return new Um(r,e,t,n)}function Zo({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=Sx(t,r);return Cx({prefix:e,name:r,encode:n,decode:o=>ls(s(o))})}function sk(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function ok(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function ik(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Wr({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=ik(n);return Cx({prefix:e,name:r,encode(o){return ok(o,n,t)},decode(o){return sk(o,s,t,r)}})}var Rm,Nm,Bm,Um,Oh=_(()=>{bc();Ix();Rm=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Nm=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Ax(this,e)}},Bm=class{decoders;constructor(e){this.decoders=e}or(e){return Ax(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};Um=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new Rm(e,t,n),this.decoder=new Nm(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}});var wt,TX,ei=_(()=>{Oh();wt=Zo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),TX=Zo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var wc,DX,kX,LX,MX,OX,RX,NX,BX,Tx=_(()=>{Oh();wc=Wr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),DX=Wr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),kX=Wr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),LX=Wr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),MX=Wr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),OX=Wr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),RX=Wr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),NX=Wr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),BX=Wr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var Rh,FX,_x=_(()=>{Oh();Rh=Zo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),FX=Zo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});function kx(r,e,t){e=e||[],t=t||0;for(var n=t;r>=uk;)e[t++]=r&255|Px,r/=128;for(;r&lk;)e[t++]=r&255|Px,r>>>=7;return e[t]=r|0,kx.bytes=t-n+1,e}function Km(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Km.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&Dx)<<s:(i&Dx)*Math.pow(2,s),s+=7}while(i>=dk);return Km.bytes=o-n,t}var ak,Px,ck,lk,uk,hk,dk,Dx,fk,pk,mk,gk,yk,bk,wk,xk,vk,Ek,Sk,Ik,xc,Lx=_(()=>{ak=kx,Px=128,ck=127,lk=~ck,uk=Math.pow(2,31);hk=Km,dk=128,Dx=127;fk=Math.pow(2,7),pk=Math.pow(2,14),mk=Math.pow(2,21),gk=Math.pow(2,28),yk=Math.pow(2,35),bk=Math.pow(2,42),wk=Math.pow(2,49),xk=Math.pow(2,56),vk=Math.pow(2,63),Ek=function(r){return r<fk?1:r<pk?2:r<mk?3:r<gk?4:r<yk?5:r<bk?6:r<wk?7:r<xk?8:r<vk?9:10},Sk={encode:ak,decode:hk,encodingLength:Ek},Ik=Sk,xc=Ik});function vc(r,e=0){return[xc.decode(r,e),xc.decode.bytes]}function ti(r,e,t=0){return xc.encode(r,e,t),e}function ri(r){return xc.encodingLength(r)}var Fm=_(()=>{Lx()});function us(r,e){let t=e.byteLength,n=ri(r),s=n+ri(t),o=new Uint8Array(s+t);return ti(r,o,0),ti(t,o,n),o.set(e,s),new ni(r,t,e,o)}function Ox(r){let e=ls(r),[t,n]=vc(e),[s,o]=vc(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new ni(t,s,i,e)}function Rx(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Ex(r.bytes,t.bytes)}}var ni,Nh=_(()=>{bc();Fm();ni=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}}});var Bx=_(()=>{});function Ux(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Ck(t,zm(r),e??wt.encoder);default:return Tk(t,zm(r),e??wc.encoder)}}function zm(r){let e=Kx.get(r);if(e==null){let t=new Map;return Kx.set(r,t),t}return e}function Ak(r,e){switch(r[0]){case"Q":{let t=e??wt;return[wt.prefix,t.decode(`${wt.prefix}${r}`)]}case wt.prefix:{let t=e??wt;return[wt.prefix,t.decode(r)]}case wc.prefix:{let t=e??wc;return[wc.prefix,t.decode(r)]}case Rh.prefix:{let t=e??Rh;return[Rh.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Ck(r,e,t){let{prefix:n}=t;if(n!==wt.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function Tk(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}function Fx(r,e,t){let n=ri(r),s=n+ri(e),o=new Uint8Array(s+t.byteLength);return ti(r,o,0),ti(e,o,n),o.set(t,s),o}var Kx,jr,Ec,_k,Pk,Sc=_(()=>{Tx();_x();ei();bc();Nh();Fm();Bx();Kx=new WeakMap;jr=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Ec)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==_k)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=us(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Rx(e.multihash,n.multihash)}toString(e){return Ux(this,e)}toJSON(){return{"/":Ux(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??Fx(n,s,o.bytes))}else if(t[Pk]===!0){let{version:n,multihash:s,code:o}=t,i=Ox(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Ec)throw new Error(`Version 0 CID must use dag-pb (code: ${Ec}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=Fx(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ec,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=ls(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new ni(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,p]=vc(e.subarray(t));return t+=p,h},s=n(),o=Ec;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=Ak(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return zm(o).set(n,e),o}};Ec=112,_k=18;Pk=Symbol.for("@ipld/js-cid/CID")});function kk(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return us(zx,$x(r))}var zx,Dk,$x,si,Bh=_(()=>{bc();Nh();zx=0,Dk="identity",$x=ls;si={code:zx,name:Dk,encode:$x,digest:kk}});function Hx(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function br(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function qx(r){return new TextEncoder().encode(r)}function Vx(r){return new TextDecoder().decode(r)}var ZX,_n=_(()=>{ZX=new Uint8Array(0)});function Lk(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var v=d[y],S=0,E=w-1;(v!==0||S<g)&&E!==-1;E--,S++)v+=256*x[E]>>>0,x[E]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var A=c.repeat(m);I<w;++I)A+=r.charAt(x[I]);return A}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*w[S]>>>0,w[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(d[m]!==" "){for(var E=b-y;E!==b&&w[E]===0;)E++;for(var I=new Uint8Array(g+(b-E)),A=g;E!==b;)I[A++]=w[E++];return I}}}function f(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:f}}var Mk,Ok,Wx,jx=_(()=>{Mk=Lk,Ok=Mk,Wx=Ok});function Yx(r,e){return new qm({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}function oi({name:r,prefix:e,encode:t,decode:n}){return new Vm(r,e,t,n)}function hs({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=Wx(t,r);return oi({prefix:e,name:r,encode:n,decode:o=>br(s(o))})}function Rk(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function Nk(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function Bk(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function $e({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=Bk(n);return oi({prefix:e,name:r,encode(o){return Nk(o,n,t)},decode(o){return Rk(o,s,t,r)}})}var $m,Hm,qm,Vm,kr=_(()=>{_n();jx();$m=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Hm=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Yx(this,e)}},qm=class{decoders;constructor(e){this.decoders=e}or(e){return Yx(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};Vm=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new $m(e,t,n),this.decoder=new Hm(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}});var Gm={};z(Gm,{base10:()=>Uk});var Uk,Xx=_(()=>{kr();Uk=hs({prefix:"9",name:"base10",alphabet:"0123456789"})});var Wm={};z(Wm,{base16:()=>Kk,base16upper:()=>Fk});var Kk,Fk,Qx=_(()=>{kr();Kk=$e({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Fk=$e({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var jm={};z(jm,{base2:()=>zk});var zk,Jx=_(()=>{kr();zk=$e({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var Ym={};z(Ym,{base256emoji:()=>Gk});function qk(r){return r.reduce((e,t)=>(e+=$k[t],e),"")}function Vk(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=Hk[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var Zx,$k,Hk,Gk,e4=_(()=>{kr();Zx=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),$k=Zx.reduce((r,e,t)=>(r[t]=e,r),[]),Hk=Zx.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);Gk=oi({prefix:"\u{1F680}",name:"base256emoji",encode:qk,decode:Vk})});var Xm={};z(Xm,{base32:()=>ii,base32hex:()=>Xk,base32hexpad:()=>Jk,base32hexpadupper:()=>Zk,base32hexupper:()=>Qk,base32pad:()=>jk,base32padupper:()=>Yk,base32upper:()=>Wk,base32z:()=>e7});var ii,Wk,jk,Yk,Xk,Qk,Jk,Zk,e7,Qm=_(()=>{kr();ii=$e({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Wk=$e({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),jk=$e({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Yk=$e({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Xk=$e({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Qk=$e({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Jk=$e({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Zk=$e({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),e7=$e({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var Jm={};z(Jm,{base36:()=>Ic,base36upper:()=>t7});var Ic,t7,Zm=_(()=>{kr();Ic=hs({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),t7=hs({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var e0={};z(e0,{base58btc:()=>Yr,base58flickr:()=>r7});var Yr,r7,t0=_(()=>{kr();Yr=hs({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),r7=hs({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var r0={};z(r0,{base64:()=>n7,base64pad:()=>s7,base64url:()=>o7,base64urlpad:()=>i7});var n7,s7,o7,i7,t4=_(()=>{kr();n7=$e({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),s7=$e({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),o7=$e({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),i7=$e({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var n0={};z(n0,{base8:()=>a7});var a7,r4=_(()=>{kr();a7=$e({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var s0={};z(s0,{identity:()=>c7});var c7,n4=_(()=>{_n();kr();c7=oi({prefix:"\0",name:"identity",encode:r=>Vx(r),decode:r=>qx(r)})});var mQ,gQ,s4=_(()=>{mQ=new TextEncoder,gQ=new TextDecoder});var o4=_(()=>{_n()});function c4(r,e,t){e=e||[],t=t||0;for(var n=t;r>=p7;)e[t++]=r&255|i4,r/=128;for(;r&f7;)e[t++]=r&255|i4,r>>>=7;return e[t]=r|0,c4.bytes=t-n+1,e}function o0(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw o0.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&a4)<<s:(i&a4)*Math.pow(2,s),s+=7}while(i>=g7);return o0.bytes=o-n,t}var h7,i4,d7,f7,p7,m7,g7,a4,y7,b7,w7,x7,v7,E7,S7,I7,A7,C7,T7,_7,Ac,l4=_(()=>{h7=c4,i4=128,d7=127,f7=~d7,p7=Math.pow(2,31);m7=o0,g7=128,a4=127;y7=Math.pow(2,7),b7=Math.pow(2,14),w7=Math.pow(2,21),x7=Math.pow(2,28),v7=Math.pow(2,35),E7=Math.pow(2,42),S7=Math.pow(2,49),I7=Math.pow(2,56),A7=Math.pow(2,63),C7=function(r){return r<y7?1:r<b7?2:r<w7?3:r<x7?4:r<v7?5:r<E7?6:r<S7?7:r<I7?8:r<A7?9:10},T7={encode:h7,decode:m7,encodingLength:C7},_7=T7,Ac=_7});function Cc(r,e=0){return[Ac.decode(r,e),Ac.decode.bytes]}function ai(r,e,t=0){return Ac.encode(r,e,t),e}function ci(r){return Ac.encodingLength(r)}var Kh=_(()=>{l4()});function ui(r,e){let t=e.byteLength,n=ci(r),s=n+ci(t),o=new Uint8Array(s+t);return ai(r,o,0),ai(t,o,n),o.set(e,s),new li(r,t,e,o)}function u4(r){let e=br(r),[t,n]=Cc(e),[s,o]=Cc(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new li(t,s,i,e)}function h4(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Hx(r.bytes,t.bytes)}}var li,_c=_(()=>{_n();Kh();li=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}}});var i0={};z(i0,{identity:()=>k7});function D7(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return ui(d4,f4(r))}var d4,P7,f4,k7,p4=_(()=>{_n();_c();d4=0,P7="identity",f4=br;k7={code:d4,name:P7,encode:f4,digest:D7}});function c0({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new a0(r,e,t,n,s)}function m4(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return ui(e,r)}var L7,a0,l0=_(()=>{_c();L7=20;a0=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??L7,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?m4(n,this.code,t?.truncate):n.then(s=>m4(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}}});var h0={};z(h0,{sha256:()=>M7,sha512:()=>O7});var u0,M7,O7,y4=_(()=>{u0=ie(ee("crypto"),1);_n();l0();M7=c0({name:"sha2-256",code:18,encode:r=>br(u0.default.createHash("sha256").update(r).digest())}),O7=c0({name:"sha2-512",code:19,encode:r=>br(u0.default.createHash("sha512").update(r).digest())})});var d0=_(()=>{});function b4(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return N7(t,f0(r),e??Yr.encoder);default:return B7(t,f0(r),e??ii.encoder)}}function f0(r){let e=w4.get(r);if(e==null){let t=new Map;return w4.set(r,t),t}return e}function R7(r,e){switch(r[0]){case"Q":{let t=e??Yr;return[Yr.prefix,t.decode(`${Yr.prefix}${r}`)]}case Yr.prefix:{let t=e??Yr;return[Yr.prefix,t.decode(r)]}case ii.prefix:{let t=e??ii;return[ii.prefix,t.decode(r)]}case Ic.prefix:{let t=e??Ic;return[Ic.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function N7(r,e,t){let{prefix:n}=t;if(n!==Yr.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function B7(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}function x4(r,e,t){let n=ci(r),s=n+ci(e),o=new Uint8Array(s+t.byteLength);return ai(r,o,0),ai(e,o,n),o.set(t,s),o}var w4,Fh,Pc,U7,K7,v4=_(()=>{Qm();Zm();t0();_n();_c();Kh();d0();w4=new WeakMap;Fh=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Pc)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==U7)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=ui(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&h4(e.multihash,n.multihash)}toString(e){return b4(this,e)}toJSON(){return{"/":b4(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??x4(n,s,o.bytes))}else if(t[K7]===!0){let{version:n,multihash:s,code:o}=t,i=u4(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Pc)throw new Error(`Version 0 CID must use dag-pb (code: ${Pc}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=x4(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Pc,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=br(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new li(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,p]=Cc(e.subarray(t));return t+=p,h},s=n(),o=Pc;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=R7(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return f0(o).set(n,e),o}};Pc=112,U7=18;K7=Symbol.for("@ipld/js-cid/CID")});var E4=_(()=>{});var S4=_(()=>{});var I4=_(()=>{});var A4=_(()=>{});var C4=_(()=>{E4();S4();I4();d0();A4()});var T4=_(()=>{_n();v4();_c();l0();Kh();C4()});var p0,KQ,_4=_(()=>{Xx();Qx();Jx();e4();Qm();Zm();t0();t4();r4();n4();s4();o4();p4();y4();T4();p0={...s0,...jm,...n0,...Gm,...Wm,...Xm,...Jm,...e0,...r0,...Ym},KQ={...h0,...i0}});function D4(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var P4,m0,F7,zh,g0=_(()=>{_4();rt();P4=D4("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),m0=D4("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=tt(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),F7={utf8:P4,"utf-8":P4,hex:p0.base16,latin1:m0,ascii:m0,binary:m0,...p0},zh=F7});function D(r,e="utf8"){let t=zh[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return e==="utf8"||e==="utf-8"?rs(k4.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}var k4,te=_(()=>{k4=ee("node:buffer");g0();cc()});function P(r,e="utf8"){let t=zh[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return e==="utf8"||e==="utf-8"?L4.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}var L4,ce=_(()=>{L4=ee("node:buffer");g0()});function Pn(r,e={offset:0}){let t=r[e.offset]&z7;if(e.offset++,M4[t]!=null)return M4[t](r,e);throw new Error("No decoder for tag "+t)}function kc(r,e){let t=0;if((r[e.offset]&y0)===y0){let n=r[e.offset]&$7,s="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)s+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(s,16)}else t=r[e.offset],e.offset++;return t}function Dc(r,e){kc(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=Pn(r,e);if(n===null)break;t.push(n)}return t}function H7(r,e){let t=kc(r,e),n=e.offset,s=e.offset+t,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function q7(r,e){let t=kc(r,e),n=e.offset+t,s=r[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let h=0;h<c.length;h++)u+=c[h]<<h*7;a+=`.${u}`,c=[]}}return a}function V7(r,e){return e.offset++,null}function G7(r,e){let t=kc(r,e),n=r[e.offset];e.offset++;let s=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function W7(r,e){let t=kc(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function j7(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new U;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function $h(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=j7(r.byteLength);return new U(Uint8Array.from([e.byteLength|y0]),e)}function Nt(r){let e=new U,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new U(Uint8Array.from([2]),$h(e),e)}function Lc(r){let e=Uint8Array.from([0]),t=new U(e,r);return new U(Uint8Array.from([3]),$h(t),t)}function O4(r){return new U(Uint8Array.from([4]),$h(r),r)}function Lr(r,e=48){let t=new U;for(let n of r)t.append(n);return new U(Uint8Array.from([e]),$h(t),t)}var z7,y0,$7,M4,b0=_(()=>{Be();z7=parseInt("11111",2),y0=parseInt("10000000",2),$7=parseInt("01111111",2),M4={0:Dc,1:Dc,2:H7,3:G7,4:W7,5:V7,6:q7,16:Dc,22:Dc,48:Dc}});async function R4(r="P-256"){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function N4(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let s=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}async function B4(r,e,t,n){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,e,t.subarray());return n?.signal?.throwIfAborted(),o}var w0=_(()=>{});function S0(r){let e=Pn(r);return U4(e)}function U4(r){let e=r[1][1][0],t=1,n,s;if(e.byteLength===x0*2+1)return n=P(e.subarray(t,t+x0),"base64url"),s=P(e.subarray(t+x0),"base64url"),new qs({...J7,key_ops:["verify"],x:n,y:s});if(e.byteLength===v0*2+1)return n=P(e.subarray(t,t+v0),"base64url"),s=P(e.subarray(t+v0),"base64url"),new qs({...Z7,key_ops:["verify"],x:n,y:s});if(e.byteLength===E0*2+1)return n=P(e.subarray(t,t+E0),"base64url"),s=P(e.subarray(t+E0),"base64url"),new qs({...eL,key_ops:["verify"],x:n,y:s});throw new R(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function K4(r){return Lr([Nt(Uint8Array.from([1])),O4(D(r.d??"","base64url")),Lr([z4(r.crv)],160),Lr([Lc(new U(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function F4(r){return Lr([Nt(Uint8Array.from([1])),Lr([z4(r.crv)],160),Lr([Lc(new U(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function z4(r){if(r==="P-256")return Y7;if(r==="P-384")return X7;if(r==="P-521")return Q7;throw new R(`Invalid curve ${r}`)}async function $4(r="P-256"){let e=await R4(r);return new Hh(e.privateKey)}var Y7,X7,Q7,J7,Z7,eL,x0,v0,E0,I0=_(()=>{V();Be();te();ce();b0();H4();w0();Y7=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),X7=Uint8Array.from([6,5,43,129,4,0,34]),Q7=Uint8Array.from([6,5,43,129,4,0,35]),J7={ext:!0,kty:"EC",crv:"P-256"},Z7={ext:!0,kty:"EC",crv:"P-384"},eL={ext:!0,kty:"EC",crv:"P-521"},x0=32,v0=48,E0=66});var qs,Hh,H4=_(()=>{ei();Sc();Bh();Ne();Bt();I0();w0();qs=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=F4(this.jwk)),this._raw}toMultihash(){return si.digest(dt(this))}toCID(){return jr.createV1(114,this.toMultihash())}toString(){return wt.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}async verify(e,t,n){return B4(this.jwk,t,e,n)}},Hh=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new qs({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=K4(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}async sign(e,t){return N4(this.jwk,e,t)}}});function sL(r){let t=Vs.default.createPrivateKey({format:"jwk",key:{crv:"Ed25519",x:"",d:P(r,"base64url"),kty:"OKP"}}).export({format:"jwk"});if(t.x==null||t.x==="")throw new Error("Could not export JWK public key");return D(t.x,"base64url")}function q4(){let r=tL("ed25519",{publicKeyEncoding:{type:"spki",format:"jwk"},privateKeyEncoding:{type:"pkcs8",format:"jwk"}}),e=D(r.privateKey.d,"base64url"),t=D(r.publicKey.x,"base64url");return{privateKey:Ee([e,t],e.byteLength+t.byteLength),publicKey:t}}function V4(r,e){if(!(r instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');let t,n;if(r.byteLength===qh)t=r.subarray(0,32),n=r.subarray(32);else if(r.byteLength===rL)t=r.subarray(0,32),n=sL(t);else throw new TypeError('"key" must be 64 or 32 bytes in length.');let s=Vs.default.createPrivateKey({format:"jwk",key:{crv:"Ed25519",d:P(t,"base64url"),x:P(n,"base64url"),kty:"OKP"}});return Vs.default.sign(null,e instanceof Uint8Array?e:e.subarray(),s)}function G4(r,e,t){if(r.byteLength!==Mc)throw new TypeError('"key" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');if(e.byteLength!==nL)throw new TypeError('"sig" must be 64 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"sig" must be a node.js Buffer, or Uint8Array.');let n=Vs.default.createPublicKey({format:"jwk",key:{crv:"Ed25519",x:P(r,"base64url"),kty:"OKP"}});return Vs.default.verify(null,t instanceof Uint8Array?t:t.subarray(),n,e)}var Vs,tL,Mc,qh,rL,nL,A0=_(()=>{Vs=ie(ee("crypto"),1);bt();te();ce();tL=Vs.default.generateKeyPairSync,Mc=32,qh=64,rL=32,nL=64});function C0(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var j4=_(()=>{bt();te()});var Oc,Vh,Y4=_(()=>{ei();Sc();Bh();Ne();j4();Bt();T0();A0();Oc=class{type="Ed25519";raw;constructor(e){this.raw=Gh(e,Mc)}toMultihash(){return si.digest(dt(this))}toCID(){return jr.createV1(114,this.toMultihash())}toString(){return wt.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let s=G4(this.raw,t,e);return C0(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}},Vh=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=Gh(e,qh),this.publicKey=new Oc(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=V4(this.raw,e);return C0(n)?n.then(s=>(t?.signal?.throwIfAborted(),s)):(t?.signal?.throwIfAborted(),n)}}});function _0(r){return r=Gh(r,Mc),new Oc(r)}async function X4(){let{privateKey:r,publicKey:e}=q4();return new Vh(r,e)}function Gh(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new R(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var T0=_(()=>{V();Y4();A0()});function Q4(r,e,t){P0[0]=r,e[t]=ds[0],e[t+1]=ds[1],e[t+2]=ds[2],e[t+3]=ds[3]}function J4(r,e){return ds[0]=r[e],ds[1]=r[e+1],ds[2]=r[e+2],ds[3]=r[e+3],P0[0]}function Z4(r,e,t){D0[0]=r,e[t]=Tt[0],e[t+1]=Tt[1],e[t+2]=Tt[2],e[t+3]=Tt[3],e[t+4]=Tt[4],e[t+5]=Tt[5],e[t+6]=Tt[6],e[t+7]=Tt[7]}function ev(r,e){return Tt[0]=r[e],Tt[1]=r[e+1],Tt[2]=r[e+2],Tt[3]=r[e+3],Tt[4]=r[e+4],Tt[5]=r[e+5],Tt[6]=r[e+6],Tt[7]=r[e+7],D0[0]}var P0,ds,D0,Tt,k0=_(()=>{P0=new Float32Array([-0]),ds=new Uint8Array(P0.buffer);D0=new Float64Array([-0]),Tt=new Uint8Array(D0.buffer)});var oL,iL,nr,Gs,tv,L0=_(()=>{oL=BigInt(Number.MAX_SAFE_INTEGER),iL=BigInt(Number.MIN_SAFE_INTEGER),nr=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return Gs;if(e<oL&&e>iL)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,s=e-(n<<32n);return t&&(n=~n|0n,s=~s|0n,++s>tv&&(s=0n,++n>tv&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return Gs;let t=e<0;t&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):Gs}},Gs=new nr(0,0);Gs.toBigInt=function(){return 0n};Gs.zzEncode=Gs.zzDecode=function(){return this};Gs.length=function(){return 1};tv=4294967296n});function rv(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function nv(r,e,t){if(t-e<1)return"";let s,o=[],i=0,a;for(;e<t;)a=r[e++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function M0(r,e,t){let n=t,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128);return t-n}var O0=_(()=>{});function Mr(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Wh(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}function N0(r){return new R0(r instanceof Uint8Array?r:r.subarray())}var R0,B0=_(()=>{gr();k0();L0();O0();R0=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Mr(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Mr(this,4);return Wh(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Mr(this,4);return Wh(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Mr(this,4);let e=J4(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Mr(this,4);let e=ev(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Mr(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return nv(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Mr(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Mr(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new nr(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Mr(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Mr(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Mr(this,8);let e=Wh(this.buf,this.pos+=4),t=Wh(this.buf,this.pos+=4);return new nr(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Dm(this.buf,this.pos);return this.pos+=Ae(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}});function Q(r,e,t){let n=N0(r);return e.decode(n,void 0,t)}var ov=_(()=>{B0()});function U0(r){let e=r??8192,t=e>>>1,n,s=e;return function(i){if(i<1||i>t)return tt(i);s+i>e&&(n=tt(e),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var iv=_(()=>{rt()});function K0(){}function cL(r){return globalThis.Buffer!=null?tt(r):aL(r)}function F0(r,e,t){e[t]=r&255}function lL(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function jh(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Rc(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function uL(r,e,t){e.set(r,t)}function hL(r,e,t){e.set(r,t)}function dL(r,e,t){r.length<40?M0(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(D(r),t)}function H0(){return new Nc}var Ws,z0,aL,Nc,$0,q0=_(()=>{gr();rt();te();k0();L0();iv();O0();Ws=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};z0=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},aL=U0();Nc=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ws(K0,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Ws(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new $0((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(jh,10,nr.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=nr.fromBigInt(e);return this._push(jh,t.length(),t)}uint64Number(e){return this._push(In,Ae(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=nr.fromBigInt(e).zzEncode();return this._push(jh,t.length(),t)}sint64Number(e){let t=nr.fromNumber(e).zzEncode();return this._push(jh,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(F0,1,e?1:0)}fixed32(e){return this._push(Rc,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=nr.fromBigInt(e);return this._push(Rc,4,t.lo)._push(Rc,4,t.hi)}fixed64Number(e){let t=nr.fromNumber(e);return this._push(Rc,4,t.lo)._push(Rc,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Q4,4,e)}double(e){return this._push(Z4,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(F0,1,0):this.uint32(t)._push(uL,t,e)}string(e){let t=rv(e);return t!==0?this.uint32(t)._push(M0,t,e):this._push(F0,1,0)}fork(){return this.states=new z0(this),this.head=this.tail=new Ws(K0,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Ws(K0,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=cL(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};$0=class extends Ws{next;constructor(e,t){super(lL,e,t),this.next=void 0}};globalThis.Buffer!=null&&(Nc.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(hL,e,r),this},Nc.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(dL,e,r),this})});function J(r,e){let t=H0();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var av=_(()=>{q0()});function Yh(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}var hi,V0=_(()=>{(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(hi||(hi={}))});function sr(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(o,i){let a=e(o);i.int32(a)},n=function(o){let i=o.int32();return e(i)};return Yh("enum",hi.VARINT,t,n)}var cv=_(()=>{V0()});function Z(r,e){return Yh("message",hi.LENGTH_DELIMITED,r,e)}var lv=_(()=>{V0()});var _e,Bc,wr=_(()=>{ov();av();cv();lv();B0();q0();_e=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Bc=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"}});var Je,G0,Xr,W0,j0=_(()=>{wr();(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Je||(Je={}));(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(G0||(G0={}));(function(r){r.codec=()=>sr(G0)})(Je||(Je={}));(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Je.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=Je.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(Xr||(Xr={}));(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Je.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=Je.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(W0||(W0={}))});function Uc(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function xr(r,e=""){if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${r}`)}}function ge(r,e,t=""){let n=Uc(r),s=r?.length,o=e!==void 0;if(!n||o&&s!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function js(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");xr(r.outputLen),xr(r.blockLen)}function di(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function dv(r,e){ge(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function kn(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Xh(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Or(r,e){return r<<32-e|r>>>e}function Ys(r){if(ge(r),fv)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=fL[r[t]];return e}function hv(r){if(r>=Dn._0&&r<=Dn._9)return r-Dn._0;if(r>=Dn.A&&r<=Dn.F)return r-(Dn.A-10);if(r>=Dn.a&&r<=Dn.f)return r-(Dn.a-10)}function Xs(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(fv)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){let i=hv(r.charCodeAt(o)),a=hv(r.charCodeAt(o+1));if(i===void 0||a===void 0){let c=r[o]+r[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}n[s]=i*16+a}return n}function Rr(...r){let e=0;for(let n=0;n<r.length;n++){let s=r[n];ge(s),e+=s.length}let t=new Uint8Array(e);for(let n=0,s=0;n<r.length;n++){let o=r[n];t.set(o,s),s+=o.length}return t}function pv(r,e={}){let t=(s,o)=>r(o).update(s).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=s=>r(s),Object.assign(t,e),Object.freeze(t)}function Qr(r=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}var fv,fL,Dn,mv,Jr=_(()=>{fv=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",fL=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));Dn={_0:48,_9:57,A:65,F:70,a:97,f:102};mv=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])})});function fs(r){if(isNaN(r)||r<=0)throw new R("random bytes length must be a Number bigger than 0");return Qr(r)}var gv=_(()=>{V();Jr()});function yv(r,e,t){return r&e^~r&t}function bv(r,e,t){return r&e^r&t^e&t}var Qh,Ln,wv=_(()=>{Jr();Qh=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,s){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Xh(this.buffer)}update(e){di(this),ge(e);let{view:t,buffer:n,blockLen:s}=this,o=e.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let c=Xh(e);for(;s<=o-i;i+=s)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){di(this),dv(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:s,isLE:o}=this,{pos:i}=this;t[i++]=128,kn(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(n,0),i=0);for(let h=i;h<s;h++)t[h]=0;n.setBigUint64(s-8,BigInt(this.length*8),o),this.process(n,0);let a=Xh(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:s,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=s,e.pos=a,s%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Ln=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225])});var pL,ps,Y0,X0,Yt,Kc=_(()=>{wv();Jr();pL=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ps=new Uint32Array(64),Y0=class extends Qh{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[e,t,n,s,o,i,a,c]}set(e,t,n,s,o,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let h=0;h<16;h++,t+=4)ps[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let p=ps[h-15],f=ps[h-2],d=Or(p,7)^Or(p,18)^p>>>3,m=Or(f,17)^Or(f,19)^f>>>10;ps[h]=m+ps[h-7]+d+ps[h-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){let p=Or(a,6)^Or(a,11)^Or(a,25),f=u+p+yv(a,c,l)+pL[h]+ps[h]|0,m=(Or(n,2)^Or(n,13)^Or(n,22))+bv(n,s,o)|0;u=l,l=c,c=a,a=i+f|0,i=o,o=s,s=n,n=f+m|0}n=n+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,s,o,i,a,c,l,u)}roundClean(){kn(ps)}destroy(){this.set(0,0,0,0,0,0,0,0),kn(this.buffer)}},X0=class extends Y0{A=Ln[0]|0;B=Ln[1]|0;C=Ln[2]|0;D=Ln[3]|0;E=Ln[4]|0;F=Ln[5]|0;G=Ln[6]|0;H=Ln[7]|0;constructor(){super(32)}},Yt=pv(()=>new X0,mv(1))});var fi,Fc,xv=_(()=>{ei();Sc();Ne();Q0();fi=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=zc.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return jr.createV1(114,this._multihash)}toString(){return wt.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){return Ev(this.jwk,t,e,n)}},Fc=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=zc.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}sign(e,t){return vv(this.jwk,e,t)}}});var zc={};z(zc,{MAX_RSA_KEY_SIZE:()=>J0,generateRSAKeyPair:()=>a2,jwkToJWKKeyPair:()=>Iv,jwkToPkcs1:()=>bL,jwkToPkix:()=>r2,jwkToRSAPrivateKey:()=>i2,pkcs1MessageToJwk:()=>e2,pkcs1MessageToRSAPrivateKey:()=>n2,pkcs1ToJwk:()=>yL,pkcs1ToRSAPrivateKey:()=>Sv,pkixMessageToJwk:()=>t2,pkixMessageToRSAPublicKey:()=>o2,pkixToJwk:()=>wL,pkixToRSAPublicKey:()=>s2});function yL(r){let e=Pn(r);return e2(e)}function e2(r){return{n:P(r[1],"base64url"),e:P(r[2],"base64url"),d:P(r[3],"base64url"),p:P(r[4],"base64url"),q:P(r[5],"base64url"),dp:P(r[6],"base64url"),dq:P(r[7],"base64url"),qi:P(r[8],"base64url"),kty:"RSA"}}function bL(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new R("JWK was missing components");return Lr([Nt(Uint8Array.from([0])),Nt(D(r.n,"base64url")),Nt(D(r.e,"base64url")),Nt(D(r.d,"base64url")),Nt(D(r.p,"base64url")),Nt(D(r.q,"base64url")),Nt(D(r.dp,"base64url")),Nt(D(r.dq,"base64url")),Nt(D(r.qi,"base64url"))]).subarray()}function wL(r){let e=Pn(r,{offset:0});return t2(e)}function t2(r){let e=Pn(r[1],{offset:0});return{kty:"RSA",n:P(e[0],"base64url"),e:P(e[1],"base64url")}}function r2(r){if(r.n==null||r.e==null)throw new R("JWK was missing components");return Lr([gL,Lc(Lr([Nt(D(r.n,"base64url")),Nt(D(r.e,"base64url"))]))]).subarray()}function Sv(r){let e=Pn(r);return n2(e)}function n2(r){let e=e2(r);return i2(e)}function s2(r,e){if(r.byteLength>=mL)throw new Xo("Key size is too large");let t=Pn(r,{offset:0});return o2(t,r,e)}function o2(r,e,t){let n=t2(r);if(t==null){let s=Yt(Xr.encode({Type:Je.RSA,Data:e}));t=us(Z0,s)}return new fi(n,t)}function i2(r){if(Cv(r)>J0)throw new R("Key size is too large");let e=Iv(r),t=Yt(Xr.encode({Type:Je.RSA,Data:r2(e.publicKey)})),n=us(Z0,t);return new Fc(e.privateKey,new fi(e.publicKey,n))}async function a2(r){if(r>J0)throw new R("Key size is too large");let e=await Av(r),t=Yt(Xr.encode({Type:Je.RSA,Data:r2(e.publicKey)})),n=us(Z0,t);return new Fc(e.privateKey,new fi(e.publicKey,n))}function Iv(r){if(r==null)throw new R("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var J0,Z0,mL,gL,c2=_(()=>{V();Kc();Nh();te();ce();j0();b0();xv();Q0();J0=8192,Z0=18,mL=1062,gL=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0])});async function Av(r,e){let t=await xL("rsa",{modulusLength:r,publicKeyEncoding:{type:"pkcs1",format:"jwk"},privateKeyEncoding:{type:"pkcs1",format:"jwk"}});return e?.signal?.throwIfAborted(),{privateKey:t.privateKey,publicKey:t.publicKey}}function vv(r,e,t){t?.signal?.throwIfAborted();let n=Jh.default.createSign("RSA-SHA256");if(e instanceof Uint8Array)n.update(e);else for(let s of e)n.update(s);return n.sign({format:"jwk",key:r})}function Ev(r,e,t,n){n?.signal?.throwIfAborted();let s=Jh.default.createVerify("RSA-SHA256");if(t instanceof Uint8Array)s.update(t);else for(let o of t)s.update(o);return s.verify({format:"jwk",key:r},e)}function Cv(r){if(r.kty!=="RSA")throw new R("Invalid key type");if(r.n==null)throw new R("Invalid key modulus");return D(r.n,"base64url").length*8}var Jh,Tv,xL,Q0=_(()=>{Jh=ie(ee("node:crypto"),1),Tv=ee("node:util");V();te();c2();xL=(0,Tv.promisify)(Jh.default.generateKeyPair)});function $c(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function _v(r){if(typeof r=="bigint"){if(!Zh(r))throw new Error("positive bigint expected, got "+r)}else xr(r);return r}function Hc(r){let e=_v(r).toString(16);return e.length&1?"0"+e:e}function Pv(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?u2:BigInt("0x"+r)}function pi(r){return Pv(Ys(r))}function mi(r){return Pv(Ys(td(ge(r)).reverse()))}function ed(r,e){xr(e),r=_v(r);let t=Xs(r.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function qc(r,e){return ed(r,e).reverse()}function td(r){return Uint8Array.from(r)}function vL(r,e,t){return Zh(r)&&Zh(e)&&Zh(t)&&e<=r&&r<t}function Vc(r,e,t,n){if(!vL(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function h2(r){let e;for(e=0;r>u2;r>>=l2,e+=1);return e}function Dv(r,e,t){if(xr(r,"hashLen"),xr(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");let n=g=>new Uint8Array(g),s=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,h=()=>{c.fill(1),l.fill(0),u=0},p=(...g)=>t(l,Rr(c,...g)),f=(g=s)=>{l=p(o,g),c=p(),g.length!==0&&(l=p(i,g),c=p())},d=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let g=0,y=[];for(;g<e;){c=p();let b=c.slice();y.push(b),g+=c.length}return Rr(...y)};return(g,y)=>{h(),f(g);let b;for(;!(b=y(d()));)f();return h(),b}}function Qs(r,e={},t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(o,i,a){let c=r[o];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${l}`)}let s=(o,i)=>Object.entries(o).forEach(([a,c])=>n(a,c,i));s(e,!1),s(t,!0)}function d2(r){let e=new WeakMap;return(t,...n)=>{let s=e.get(t);if(s!==void 0)return s;let o=r(t,...n);return e.set(t,o),o}}var u2,l2,Zh,Gc,Wc=_(()=>{Jr();Jr();u2=BigInt(0),l2=BigInt(1);Zh=r=>typeof r=="bigint"&&u2<=r;Gc=r=>(l2<<BigInt(r))-l2});function Ut(r,e){let t=r%e;return t>=Kt?t:e+t}function Me(r,e,t){let n=r;for(;e-- >Kt;)n*=n,n%=t;return n}function kv(r,e){if(r===Kt)throw new Error("invert: expected non-zero number");if(e<=Kt)throw new Error("invert: expected positive modulus, got "+e);let t=Ut(r,e),n=e,s=Kt,o=_t,i=_t,a=Kt;for(;t!==Kt;){let l=n/t,u=n%t,h=s-i*l,p=o-a*l;n=t,t=u,s=i,o=a,i=h,a=p}if(n!==_t)throw new Error("invert: does not exist");return Ut(s,e)}function p2(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function Uv(r,e){let t=(r.ORDER+_t)/Ov,n=r.pow(e,t);return p2(r,n,e),n}function IL(r,e){let t=(r.ORDER-Rv)/Nv,n=r.mul(e,Js),s=r.pow(n,t),o=r.mul(e,s),i=r.mul(r.mul(o,Js),s),a=r.mul(o,r.sub(i,r.ONE));return p2(r,a,e),a}function AL(r){let e=gi(r),t=Kv(r),n=t(e,e.neg(e.ONE)),s=t(e,n),o=t(e,e.neg(n)),i=(r+EL)/Bv;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,n),h=a.mul(l,s),p=a.mul(l,o),f=a.eql(a.sqr(u),c),d=a.eql(a.sqr(h),c);l=a.cmov(l,u,f),u=a.cmov(p,h,d);let m=a.eql(a.sqr(u),c),g=a.cmov(l,u,m);return p2(a,g,c),g}}function Kv(r){if(r<Mv)throw new Error("sqrt is not defined for small field");let e=r-_t,t=0;for(;e%Js===Kt;)e/=Js,t++;let n=Js,s=gi(r);for(;Lv(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Uv;let o=s.pow(n,e),i=(e+_t)/Js;return function(c,l){if(c.is0(l))return l;if(Lv(c,l)!==1)throw new Error("Cannot find square root");let u=t,h=c.mul(c.ONE,o),p=c.pow(l,e),f=c.pow(l,i);for(;!c.eql(p,c.ONE);){if(c.is0(p))return c.ZERO;let d=1,m=c.sqr(p);for(;!c.eql(m,c.ONE);)if(d++,m=c.sqr(m),d===u)throw new Error("Cannot find square root");let g=_t<<BigInt(u-d-1),y=c.pow(h,g);u=d,h=c.sqr(y),p=c.mul(p,h),f=c.mul(f,y)}return f}}function CL(r){return r%Ov===Mv?Uv:r%Nv===Rv?IL:r%Bv===SL?AL(r):Kv(r)}function m2(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=TL.reduce((n,s)=>(n[s]="function",n),e);return Qs(r,t),r}function _L(r,e,t){if(t<Kt)throw new Error("invalid exponent, negatives unsupported");if(t===Kt)return r.ONE;if(t===_t)return e;let n=r.ONE,s=e;for(;t>Kt;)t&_t&&(n=r.mul(n,s)),s=r.sqr(s),t>>=_t;return n}function jc(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),s=e.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),o=r.inv(s);return e.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),o),n}function Lv(r,e){let t=(r.ORDER-_t)/Js,n=r.pow(e,t),s=r.eql(n,r.ONE),o=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!s&&!o&&!i)throw new Error("invalid Legendre symbol result");return s?1:o?0:-1}function PL(r,e){e!==void 0&&xr(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function gi(r,e={}){return new f2(r,e)}function Fv(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function g2(r){let e=Fv(r);return e+Math.ceil(e/2)}function y2(r,e,t=!1){ge(r);let n=r.length,s=Fv(e),o=g2(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=t?mi(r):pi(r),a=Ut(i,e-_t)+_t;return t?qc(a,s):ed(a,s)}var Kt,_t,Js,Mv,Ov,Rv,EL,Nv,SL,Bv,TL,f2,yi=_(()=>{Wc();Kt=BigInt(0),_t=BigInt(1),Js=BigInt(2),Mv=BigInt(3),Ov=BigInt(4),Rv=BigInt(5),EL=BigInt(7),Nv=BigInt(8),SL=BigInt(9),Bv=BigInt(16);TL=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];f2=class{ORDER;BITS;BYTES;isLE;ZERO=Kt;ONE=_t;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=Kt)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:s,nByteLength:o}=PL(e,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=s,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return Ut(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return Kt<=e&&e<this.ORDER}is0(e){return e===Kt}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&_t)===_t}neg(e){return Ut(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return Ut(e*e,this.ORDER)}add(e,t){return Ut(e+t,this.ORDER)}sub(e,t){return Ut(e-t,this.ORDER)}mul(e,t){return Ut(e*t,this.ORDER)}pow(e,t){return _L(this,e,t)}div(e,t){return Ut(e*kv(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return kv(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=CL(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?qc(e,this.BYTES):ed(e,this.BYTES)}fromBytes(e,t=!1){ge(e);let{_lengths:n,BYTES:s,isLE:o,ORDER:i,_mod:a}=this;if(n){if(!n.includes(e.length)||e.length>s)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(s);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let c=o?mi(e):pi(e);if(a&&(c=Ut(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return jc(this,e)}cmov(e,t,n){return n?t:e}}});function Yc(r,e){let t=e.negate();return r?t:e}function v2(r,e){let t=jc(r.Fp,e.map(n=>n.Z));return e.map((n,s)=>r.fromAffine(n.toAffine(t[s])))}function qv(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function b2(r,e){qv(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),s=2**r,o=Gc(r),i=BigInt(r);return{windows:t,windowSize:n,mask:o,maxNumber:s,shiftBy:i}}function zv(r,e,t){let{windowSize:n,mask:s,maxNumber:o,shiftBy:i}=t,a=Number(r&s),c=r>>i;a>n&&(a-=o,c+=Zs);let l=e*n,u=l+Math.abs(a)-1,h=a===0,p=a<0,f=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:p,isNegF:f,offsetF:l}}function x2(r){return Vv.get(r)||1}function $v(r){if(r!==bi)throw new Error("invalid wNAF")}function Gv(r,e,t,n){let s=e,o=r.ZERO,i=r.ZERO;for(;t>bi||n>bi;)t&Zs&&(o=o.add(s)),n&Zs&&(i=i.add(s)),s=s.double(),t>>=Zs,n>>=Zs;return{p1:o,p2:i}}function Hv(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return m2(e),e}else return gi(r,{isLE:t})}function Wv(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>bi))throw new Error(`CURVE.${c} must be positive bigint`)}let s=Hv(e.p,t.Fp,n),o=Hv(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!s.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:s,Fn:o}}function nd(r,e){return function(n){let s=r(n);return{secretKey:s,publicKey:e(s)}}}var bi,Zs,w2,Vv,rd,E2=_(()=>{Wc();yi();bi=BigInt(0),Zs=BigInt(1);w2=new WeakMap,Vv=new WeakMap;rd=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let s=e;for(;t>bi;)t&Zs&&(n=n.add(s)),s=s.double(),t>>=Zs;return n}precomputeWindow(e,t){let{windows:n,windowSize:s}=b2(t,this.bits),o=[],i=e,a=i;for(let c=0;c<n;c++){a=i,o.push(a);for(let l=1;l<s;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE,i=b2(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:h,isNegF:p,offsetF:f}=zv(n,a,i);n=c,u?o=o.add(Yc(p,t[f])):s=s.add(Yc(h,t[l]))}return $v(n),{p:s,f:o}}wNAFUnsafe(e,t,n,s=this.ZERO){let o=b2(e,this.bits);for(let i=0;i<o.windows&&n!==bi;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=zv(n,i,o);if(n=a,!l){let h=t[c];s=s.add(u?h.negate():h)}}return $v(n),s}getPrecomputes(e,t,n){let s=w2.get(t);return s||(s=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(s=n(s)),w2.set(t,s))),s}cached(e,t,n){let s=x2(e);return this.wNAF(s,this.getPrecomputes(s,e,n),t)}unsafe(e,t,n,s){let o=x2(e);return o===1?this._unsafeLadder(e,t,s):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),t,s)}createCache(e,t){qv(t,this.bits),Vv.set(e,t),w2.delete(e)}hasCache(e){return x2(e)!==1}}});var sd,wi,S2=_(()=>{Jr();sd=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(js(e),ge(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,s=new Uint8Array(n);s.set(t.length>n?e.create().update(t).digest():t);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),kn(s)}update(e){return di(this),this.iHash.update(e),this}digestInto(e){di(this),ge(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:s,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},wi=(r,e,t)=>new sd(r,e).update(t).digest();wi.create=(r,e)=>new sd(r,e)});function DL(r,e,t){let[[n,s],[o,i]]=e,a=jv(i*r,t),c=jv(-s*r,t),l=r-a*n-c*o,u=-a*s-c*i,h=l<Mn,p=u<Mn;h&&(l=-l),p&&(u=-u);let f=Gc(Math.ceil(h2(t)/2))+xi;if(l<Mn||l>=f||u<Mn||u>=f)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:h,k1:l,k2neg:p,k2:u}}function A2(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function I2(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return $c(t.lowS,"lowS"),$c(t.prehash,"prehash"),t.format!==void 0&&A2(t.format),t}function Xv(r,e={}){let t=Wv("weierstrass",r,e),{Fp:n,Fn:s}=t,o=t.CURVE,{h:i,n:a}=o;Qs(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!n.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=Jv(n,s);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(H,L,C){let{x:T,y:M}=L.toAffine(),B=n.toBytes(T);if($c(C,"isCompressed"),C){u();let N=!n.isOdd(M);return Rr(Qv(N),B)}else return Rr(Uint8Array.of(4),B,n.toBytes(M))}function p(H){ge(H,void 0,"Point");let{publicKey:L,publicKeyUncompressed:C}=l,T=H.length,M=H[0],B=H.subarray(1);if(T===L&&(M===2||M===3)){let N=n.fromBytes(B);if(!n.isValid(N))throw new Error("bad point: is not on curve, wrong x");let k=m(N),O;try{O=n.sqrt(k)}catch(ve){let ue=ve instanceof Error?": "+ve.message:"";throw new Error("bad point: is not on curve, sqrt error"+ue)}u();let K=n.isOdd(O);return(M&1)===1!==K&&(O=n.neg(O)),{x:N,y:O}}else if(T===C&&M===4){let N=n.BYTES,k=n.fromBytes(B.subarray(0,N)),O=n.fromBytes(B.subarray(N,N*2));if(!g(k,O))throw new Error("bad point: is not on curve");return{x:k,y:O}}else throw new Error(`bad point: got length ${T}, expected compressed=${L} or uncompressed=${C}`)}let f=e.toBytes||h,d=e.fromBytes||p;function m(H){let L=n.sqr(H),C=n.mul(L,H);return n.add(n.add(C,n.mul(H,o.a)),o.b)}function g(H,L){let C=n.sqr(L),T=m(H);return n.eql(C,T)}if(!g(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let y=n.mul(n.pow(o.a,od),kL),b=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(y,b)))throw new Error("bad curve params: a or b");function w(H,L,C=!1){if(!n.isValid(L)||C&&n.is0(L))throw new Error(`bad point coordinate ${H}`);return L}function x(H){if(!(H instanceof A))throw new Error("Weierstrass Point expected")}function v(H){if(!c||!c.basises)throw new Error("no endo");return DL(H,c.basises,s.ORDER)}let S=d2((H,L)=>{let{X:C,Y:T,Z:M}=H;if(n.eql(M,n.ONE))return{x:C,y:T};let B=H.is0();L==null&&(L=B?n.ONE:n.inv(M));let N=n.mul(C,L),k=n.mul(T,L),O=n.mul(M,L);if(B)return{x:n.ZERO,y:n.ZERO};if(!n.eql(O,n.ONE))throw new Error("invZ was invalid");return{x:N,y:k}}),E=d2(H=>{if(H.is0()){if(e.allowInfinityPoint&&!n.is0(H.Y))return;throw new Error("bad point: ZERO")}let{x:L,y:C}=H.toAffine();if(!n.isValid(L)||!n.isValid(C))throw new Error("bad point: x or y not field elements");if(!g(L,C))throw new Error("bad point: equation left != right");if(!H.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function I(H,L,C,T,M){return C=new A(n.mul(C.X,H),C.Y,C.Z),L=Yc(T,L),C=Yc(M,C),L.add(C)}class A{static BASE=new A(o.Gx,o.Gy,n.ONE);static ZERO=new A(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=s;X;Y;Z;constructor(L,C,T){this.X=w("x",L),this.Y=w("y",C,!0),this.Z=w("z",T),Object.freeze(this)}static CURVE(){return o}static fromAffine(L){let{x:C,y:T}=L||{};if(!L||!n.isValid(C)||!n.isValid(T))throw new Error("invalid affine point");if(L instanceof A)throw new Error("projective point not allowed");return n.is0(C)&&n.is0(T)?A.ZERO:new A(C,T,n.ONE)}static fromBytes(L){let C=A.fromAffine(d(ge(L,void 0,"point")));return C.assertValidity(),C}static fromHex(L){return A.fromBytes(Xs(L))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(L=8,C=!0){return ne.createCache(this,L),C||this.multiply(od),this}assertValidity(){E(this)}hasEvenY(){let{y:L}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(L)}equals(L){x(L);let{X:C,Y:T,Z:M}=this,{X:B,Y:N,Z:k}=L,O=n.eql(n.mul(C,k),n.mul(B,M)),K=n.eql(n.mul(T,k),n.mul(N,M));return O&&K}negate(){return new A(this.X,n.neg(this.Y),this.Z)}double(){let{a:L,b:C}=o,T=n.mul(C,od),{X:M,Y:B,Z:N}=this,k=n.ZERO,O=n.ZERO,K=n.ZERO,F=n.mul(M,M),ve=n.mul(B,B),ue=n.mul(N,N),se=n.mul(M,B);return se=n.add(se,se),K=n.mul(M,N),K=n.add(K,K),k=n.mul(L,K),O=n.mul(T,ue),O=n.add(k,O),k=n.sub(ve,O),O=n.add(ve,O),O=n.mul(k,O),k=n.mul(se,k),K=n.mul(T,K),ue=n.mul(L,ue),se=n.sub(F,ue),se=n.mul(L,se),se=n.add(se,K),K=n.add(F,F),F=n.add(K,F),F=n.add(F,ue),F=n.mul(F,se),O=n.add(O,F),ue=n.mul(B,N),ue=n.add(ue,ue),F=n.mul(ue,se),k=n.sub(k,F),K=n.mul(ue,ve),K=n.add(K,K),K=n.add(K,K),new A(k,O,K)}add(L){x(L);let{X:C,Y:T,Z:M}=this,{X:B,Y:N,Z:k}=L,O=n.ZERO,K=n.ZERO,F=n.ZERO,ve=o.a,ue=n.mul(o.b,od),se=n.mul(C,B),pe=n.mul(T,N),Te=n.mul(M,k),Qe=n.add(C,T),ye=n.add(B,N);Qe=n.mul(Qe,ye),ye=n.add(se,pe),Qe=n.sub(Qe,ye),ye=n.add(C,M);let et=n.add(B,k);return ye=n.mul(ye,et),et=n.add(se,Te),ye=n.sub(ye,et),et=n.add(T,M),O=n.add(N,k),et=n.mul(et,O),O=n.add(pe,Te),et=n.sub(et,O),F=n.mul(ve,ye),O=n.mul(ue,Te),F=n.add(O,F),O=n.sub(pe,F),F=n.add(pe,F),K=n.mul(O,F),pe=n.add(se,se),pe=n.add(pe,se),Te=n.mul(ve,Te),ye=n.mul(ue,ye),pe=n.add(pe,Te),Te=n.sub(se,Te),Te=n.mul(ve,Te),ye=n.add(ye,Te),se=n.mul(pe,ye),K=n.add(K,se),se=n.mul(et,ye),O=n.mul(Qe,O),O=n.sub(O,se),se=n.mul(Qe,pe),F=n.mul(et,F),F=n.add(F,se),new A(O,K,F)}subtract(L){return this.add(L.negate())}is0(){return this.equals(A.ZERO)}multiply(L){let{endo:C}=e;if(!s.isValidNot0(L))throw new Error("invalid scalar: out of range");let T,M,B=N=>ne.cached(this,N,k=>v2(A,k));if(C){let{k1neg:N,k1:k,k2neg:O,k2:K}=v(L),{p:F,f:ve}=B(k),{p:ue,f:se}=B(K);M=ve.add(se),T=I(C.beta,F,ue,N,O)}else{let{p:N,f:k}=B(L);T=N,M=k}return v2(A,[T,M])[0]}multiplyUnsafe(L){let{endo:C}=e,T=this;if(!s.isValid(L))throw new Error("invalid scalar: out of range");if(L===Mn||T.is0())return A.ZERO;if(L===xi)return T;if(ne.hasCache(this))return this.multiply(L);if(C){let{k1neg:M,k1:B,k2neg:N,k2:k}=v(L),{p1:O,p2:K}=Gv(A,T,B,k);return I(C.beta,O,K,M,N)}else return ne.unsafe(T,L)}toAffine(L){return S(this,L)}isTorsionFree(){let{isTorsionFree:L}=e;return i===xi?!0:L?L(A,this):ne.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:L}=e;return i===xi?this:L?L(A,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(L=!0){return $c(L,"isCompressed"),this.assertValidity(),f(A,this,L)}toHex(L=!0){return Ys(this.toBytes(L))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let X=s.BITS,ne=new rd(A,e.endo?Math.ceil(X/2):X);return A.BASE.precompute(8),A}function Qv(r){return Uint8Array.of(r?2:3)}function Jv(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function LL(r,e={}){let{Fn:t}=r,n=e.randomBytes||Qr,s=Object.assign(Jv(r.Fp,t),{seed:g2(t.ORDER)});function o(f){try{let d=t.fromBytes(f);return t.isValidNot0(d)}catch{return!1}}function i(f,d){let{publicKey:m,publicKeyUncompressed:g}=s;try{let y=f.length;return d===!0&&y!==m||d===!1&&y!==g?!1:!!r.fromBytes(f)}catch{return!1}}function a(f=n(s.seed)){return y2(ge(f,s.seed,"seed"),t.ORDER)}function c(f,d=!0){return r.BASE.multiply(t.fromBytes(f)).toBytes(d)}function l(f){let{secretKey:d,publicKey:m,publicKeyUncompressed:g}=s;if(!Uc(f)||"_lengths"in t&&t._lengths||d===m)return;let y=ge(f,void 0,"key").length;return y===m||y===g}function u(f,d,m=!0){if(l(f)===!0)throw new Error("first arg must be private key");if(l(d)===!1)throw new Error("second arg must be public key");let g=t.fromBytes(f);return r.fromBytes(d).multiply(g).toBytes(m)}let h={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},p=nd(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:p,Point:r,utils:h,lengths:s})}function Zv(r,e,t={}){js(e),Qs(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes||Qr,s=t.hmac||((C,T)=>wi(e,C,T)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:p,lengths:f}=LL(r,t),d={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},m=a*Yv<o.ORDER;function g(C){let T=a>>xi;return C>T}function y(C,T){if(!i.isValidNot0(T))throw new Error(`invalid signature ${C}: out of range 1..Point.Fn.ORDER`);return T}function b(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function w(C,T){A2(T);let M=f.signature,B=T==="compact"?M:T==="recovered"?M+1:void 0;return ge(C,B)}class x{r;s;recovery;constructor(T,M,B){if(this.r=y("r",T),this.s=y("s",M),B!=null){if(b(),![0,1,2,3].includes(B))throw new Error("invalid recovery id");this.recovery=B}Object.freeze(this)}static fromBytes(T,M=d.format){w(T,M);let B;if(M==="der"){let{r:K,s:F}=ms.toSig(ge(T));return new x(K,F)}M==="recovered"&&(B=T[0],M="compact",T=T.subarray(1));let N=f.signature/2,k=T.subarray(0,N),O=T.subarray(N,N*2);return new x(i.fromBytes(k),i.fromBytes(O),B)}static fromHex(T,M){return this.fromBytes(Xs(T),M)}assertRecovery(){let{recovery:T}=this;if(T==null)throw new Error("invalid recovery id: must be present");return T}addRecoveryBit(T){return new x(this.r,this.s,T)}recoverPublicKey(T){let{r:M,s:B}=this,N=this.assertRecovery(),k=N===2||N===3?M+a:M;if(!o.isValid(k))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let O=o.toBytes(k),K=r.fromBytes(Rr(Qv((N&1)===0),O)),F=i.inv(k),ve=S(ge(T,void 0,"msgHash")),ue=i.create(-ve*F),se=i.create(B*F),pe=r.BASE.multiplyUnsafe(ue).add(K.multiplyUnsafe(se));if(pe.is0())throw new Error("invalid recovery: point at infinify");return pe.assertValidity(),pe}hasHighS(){return g(this.s)}toBytes(T=d.format){if(A2(T),T==="der")return Xs(ms.hexFromSig(this));let{r:M,s:B}=this,N=i.toBytes(M),k=i.toBytes(B);return T==="recovered"?(b(),Rr(Uint8Array.of(this.assertRecovery()),N,k)):Rr(N,k)}toHex(T){return Ys(this.toBytes(T))}}let v=t.bits2int||function(T){if(T.length>8192)throw new Error("input is too large");let M=pi(T),B=T.length*8-c;return B>0?M>>BigInt(B):M},S=t.bits2int_modN||function(T){return i.create(v(T))},E=Gc(c);function I(C){return Vc("num < 2^"+c,C,Mn,E),i.toBytes(C)}function A(C,T){return ge(C,void 0,"message"),T?ge(e(C),void 0,"prehashed message"):C}function X(C,T,M){let{lowS:B,prehash:N,extraEntropy:k}=I2(M,d);C=A(C,N);let O=S(C),K=i.fromBytes(T);if(!i.isValidNot0(K))throw new Error("invalid private key");let F=[I(K),I(O)];if(k!=null&&k!==!1){let pe=k===!0?n(f.secretKey):k;F.push(ge(pe,void 0,"extraEntropy"))}let ve=Rr(...F),ue=O;function se(pe){let Te=v(pe);if(!i.isValidNot0(Te))return;let Qe=i.inv(Te),ye=r.BASE.multiply(Te).toAffine(),et=i.create(ye.x);if(et===Mn)return;let Wo=i.create(Qe*i.create(ue+et*K));if(Wo===Mn)return;let ih=(ye.x===et?0:2)|Number(ye.y&xi),ac=Wo;return B&&g(Wo)&&(ac=i.neg(Wo),ih^=1),new x(et,ac,m?void 0:ih)}return{seed:ve,k2sig:se}}function ne(C,T,M={}){let{seed:B,k2sig:N}=X(C,T,M);return Dv(e.outputLen,i.BYTES,s)(B,N).toBytes(M.format)}function H(C,T,M,B={}){let{lowS:N,prehash:k,format:O}=I2(B,d);if(M=ge(M,void 0,"publicKey"),T=A(T,k),!Uc(C)){let K=C instanceof x?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+K)}w(C,O);try{let K=x.fromBytes(C,O),F=r.fromBytes(M);if(N&&K.hasHighS())return!1;let{r:ve,s:ue}=K,se=S(T),pe=i.inv(ue),Te=i.create(se*pe),Qe=i.create(ve*pe),ye=r.BASE.multiplyUnsafe(Te).add(F.multiplyUnsafe(Qe));return ye.is0()?!1:i.create(ye.x)===ve}catch{return!1}}function L(C,T,M={}){let{prehash:B}=I2(M,d);return T=A(T,B),x.fromBytes(C,"recovered").recoverPublicKey(T).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:h,utils:p,lengths:f,Point:r,sign:ne,verify:H,recoverPublicKey:L,Signature:x,hash:e})}var jv,C2,ms,Mn,xi,Yv,od,kL,eE=_(()=>{S2();Jr();Wc();E2();yi();jv=(r,e)=>(r+(r>=0?e:-e)/Yv)/e;C2=class extends Error{constructor(e=""){super(e)}},ms={Err:C2,_tlv:{encode:(r,e)=>{let{Err:t}=ms;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,s=Hc(n);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let o=n>127?Hc(s.length/2|128):"";return Hc(r)+o+s+e},decode(r,e){let{Err:t}=ms,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let s=e[n++],o=!!(s&128),i=0;if(!o)i=s;else{let c=s&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=ms;if(r<Mn)throw new e("integer: negative integers are not allowed");let t=Hc(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=ms;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return pi(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=ms,s=ge(r,void 0,"signature"),{v:o,l:i}=n.decode(48,s);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,o),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=ms,n=e.encode(2,t.encode(r.r)),s=e.encode(2,t.encode(r.s)),o=n+s;return e.encode(48,o)}},Mn=BigInt(0),xi=BigInt(1),Yv=BigInt(2),od=BigInt(3),kL=BigInt(4)});function OL(r){let e=_2.p,t=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,h=Me(u,t,e)*u%e,p=Me(h,t,e)*u%e,f=Me(p,tE,e)*l%e,d=Me(f,s,e)*f%e,m=Me(d,o,e)*d%e,g=Me(m,a,e)*m%e,y=Me(g,c,e)*g%e,b=Me(y,a,e)*m%e,w=Me(b,t,e)*u%e,x=Me(w,i,e)*d%e,v=Me(x,n,e)*l%e,S=Me(v,tE,e);if(!T2.eql(T2.sqr(S),r))throw new Error("Cannot find square root");return S}var _2,ML,tE,T2,RL,st,eo=_(()=>{Kc();yi();eE();_2={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},ML={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},tE=BigInt(2);T2=gi(_2.p,{sqrt:OL}),RL=Xv(_2,{Fp:T2,endo:ML}),st=Zv(RL,Yt)});var id,ad,rE=_(()=>{id=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},ad=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}});function nE(r,e,t){t?.signal?.throwIfAborted();let n=P2.default.createHash("sha256");if(e instanceof Uint8Array)n.update(e);else for(let o of e)n.update(o);let s=n.digest();try{return st.sign(s,r,{prehash:!1,format:"der"})}catch(o){throw new id(String(o))}}function sE(r,e,t,n){n?.signal?.throwIfAborted();let s=P2.default.createHash("sha256");if(t instanceof Uint8Array)s.update(t);else for(let i of t)s.update(i);let o=s.digest();try{return st.verify(e,o,r,{prehash:!1,format:"der"})}catch(i){throw new ad(String(i))}}var P2,oE=_(()=>{P2=ie(ee("node:crypto"),1);eo();rE()});var Xc,cd,iE=_(()=>{ei();Sc();Bh();Ne();Bt();D2();oE();Xc=class{type="secp256k1";raw;_key;constructor(e){this._key=lE(e),this.raw=aE(this._key)}toMultihash(){return si.digest(dt(this))}toCID(){return jr.createV1(114,this.toMultihash())}toString(){return wt.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){return sE(this._key,t,e,n)}},cd=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=cE(e),this.publicKey=new Xc(t??uE(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}sign(e,t){return nE(this.raw,e,t)}}});function k2(r){return new Xc(r)}async function hE(){let r=NL();return new cd(r)}function aE(r){return st.Point.fromBytes(r).toBytes()}function cE(r){try{return st.getPublicKey(r,!0),r}catch(e){throw new hc(String(e))}}function lE(r){try{return st.Point.fromBytes(r),r}catch(e){throw new Xo(String(e))}}function uE(r){try{return st.getPublicKey(r,!0)}catch(e){throw new hc(String(e))}}function NL(){return st.utils.randomSecretKey()}var D2=_(()=>{V();eo();iE()});async function dE(r,e){if(r==="Ed25519")return X4();if(r==="secp256k1")return hE();if(r==="RSA")return a2(BL(e));if(r==="ECDSA")return $4(UL(e));throw new is}function Ft(r,e){let{Type:t,Data:n}=Xr.decode(r),s=n??new Uint8Array;switch(t){case Je.RSA:return s2(s,e);case Je.Ed25519:return _0(s);case Je.secp256k1:return k2(s);case Je.ECDSA:return S0(s);default:throw new is}}function fE(r){let{Type:e,Data:t}=Xr.decode(r.digest),n=t??new Uint8Array;switch(e){case Je.Ed25519:return _0(n);case Je.secp256k1:return k2(n);case Je.ECDSA:return S0(n);default:throw new is}}function dt(r){return Xr.encode({Type:Je[r.type],Data:r.raw})}function BL(r){return r==null?2048:parseInt(r,10)}function UL(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new R("Unsupported curve, should be P-256, P-384 or P-521")}var Bt=_(()=>{V();I0();T0();j0();c2();D2()});function pE(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Nr(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var Lee,vi=_(()=>{Lee=new Uint8Array(0)});function KL(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var v=d[y],S=0,E=w-1;(v!==0||S<g)&&E!==-1;E--,S++)v+=256*x[E]>>>0,x[E]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var A=c.repeat(m);I<w;++I)A+=r.charAt(x[I]);return A}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*w[S]>>>0,w[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(d[m]!==" "){for(var E=b-y;E!==b&&w[E]===0;)E++;for(var I=new Uint8Array(g+(b-E)),A=g;E!==b;)I[A++]=w[E++];return I}}}function f(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:f}}var FL,zL,mE,gE=_(()=>{FL=KL,zL=FL,mE=zL});function yE(r,e){return new O2({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}function bE({name:r,prefix:e,encode:t,decode:n}){return new R2(r,e,t,n)}function Ei({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=mE(t,r);return bE({prefix:e,name:r,encode:n,decode:o=>Nr(s(o))})}function $L(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function HL(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function qL(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Zr({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=qL(n);return bE({prefix:e,name:r,encode(o){return HL(o,n,t)},decode(o){return $L(o,s,t,r)}})}var L2,M2,O2,R2,ld=_(()=>{vi();gE();L2=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},M2=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return yE(this,e)}},O2=class{decoders;constructor(e){this.decoders=e}or(e){return yE(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};R2=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new L2(e,t,n),this.decoder=new M2(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}});var or,Kee,ud=_(()=>{ld();or=Ei({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Kee=Ei({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var Qc,$ee,Hee,qee,Vee,Gee,Wee,jee,Yee,wE=_(()=>{ld();Qc=Zr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),$ee=Zr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Hee=Zr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),qee=Zr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Vee=Zr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Gee=Zr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Wee=Zr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),jee=Zr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Yee=Zr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var hd,Jee,xE=_(()=>{ld();hd=Ei({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Jee=Ei({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});function SE(r,e,t){e=e||[],t=t||0;for(var n=t;r>=jL;)e[t++]=r&255|vE,r/=128;for(;r&WL;)e[t++]=r&255|vE,r>>>=7;return e[t]=r|0,SE.bytes=t-n+1,e}function N2(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw N2.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&EE)<<s:(i&EE)*Math.pow(2,s),s+=7}while(i>=XL);return N2.bytes=o-n,t}var VL,vE,GL,WL,jL,YL,XL,EE,QL,JL,ZL,eM,tM,rM,nM,sM,oM,iM,aM,cM,Jc,IE=_(()=>{VL=SE,vE=128,GL=127,WL=~GL,jL=Math.pow(2,31);YL=N2,XL=128,EE=127;QL=Math.pow(2,7),JL=Math.pow(2,14),ZL=Math.pow(2,21),eM=Math.pow(2,28),tM=Math.pow(2,35),rM=Math.pow(2,42),nM=Math.pow(2,49),sM=Math.pow(2,56),oM=Math.pow(2,63),iM=function(r){return r<QL?1:r<JL?2:r<ZL?3:r<eM?4:r<tM?5:r<rM?6:r<nM?7:r<sM?8:r<oM?9:10},aM={encode:VL,decode:YL,encodingLength:iM},cM=aM,Jc=cM});function Zc(r,e=0){return[Jc.decode(r,e),Jc.decode.bytes]}function Si(r,e,t=0){return Jc.encode(r,e,t),e}function Ii(r){return Jc.encodingLength(r)}var B2=_(()=>{IE()});function Ci(r,e){let t=e.byteLength,n=Ii(r),s=n+Ii(t),o=new Uint8Array(s+t);return Si(r,o,0),Si(t,o,n),o.set(e,s),new Ai(r,t,e,o)}function el(r){let e=Nr(r),[t,n]=Zc(e),[s,o]=Zc(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Ai(t,s,i,e)}function CE(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&pE(r.bytes,t.bytes)}}var Ai,tl=_(()=>{vi();B2();Ai=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}}});var TE=_(()=>{});function _E(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return uM(t,U2(r),e??or.encoder);default:return hM(t,U2(r),e??Qc.encoder)}}function U2(r){let e=PE.get(r);if(e==null){let t=new Map;return PE.set(r,t),t}return e}function lM(r,e){switch(r[0]){case"Q":{let t=e??or;return[or.prefix,t.decode(`${or.prefix}${r}`)]}case or.prefix:{let t=e??or;return[or.prefix,t.decode(r)]}case Qc.prefix:{let t=e??Qc;return[Qc.prefix,t.decode(r)]}case hd.prefix:{let t=e??hd;return[hd.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function uM(r,e,t){let{prefix:n}=t;if(n!==or.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function hM(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}function DE(r,e,t){let n=Ii(r),s=n+Ii(e),o=new Uint8Array(s+t.byteLength);return Si(r,o,0),Si(e,o,n),o.set(t,s),o}var PE,to,rl,dM,fM,K2=_(()=>{wE();xE();ud();vi();tl();B2();TE();PE=new WeakMap;to=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==rl)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==dM)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Ci(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&CE(e.multihash,n.multihash)}toString(e){return _E(this,e)}toJSON(){return{"/":_E(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??DE(n,s,o.bytes))}else if(t[fM]===!0){let{version:n,multihash:s,code:o}=t,i=el(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==rl)throw new Error(`Version 0 CID must use dag-pb (code: ${rl}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=DE(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,rl,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=Nr(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new Ai(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,p]=Zc(e.subarray(t));return t+=p,h},s=n(),o=rl;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=lM(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return U2(o).set(n,e),o}};rl=112,dM=18;fM=Symbol.for("@ipld/js-cid/CID")});function mM(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Ci(kE,LE(r))}var kE,pM,LE,fd,F2=_(()=>{vi();tl();kE=0,pM="identity",LE=Nr;fd={code:kE,name:pM,encode:LE,digest:mM}});function $2({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new z2(r,e,t,n,s)}function ME(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Ci(e,r)}var gM,z2,OE=_(()=>{tl();gM=20;z2=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??gM,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?ME(n,this.code,t?.truncate):n.then(s=>ME(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}}});var H2,RE,pte,NE=_(()=>{H2=ie(ee("crypto"),1);vi();OE();RE=$2({name:"sha2-256",code:18,encode:r=>Nr(H2.default.createHash("sha256").update(r).digest())}),pte=$2({name:"sha2-512",code:19,encode:r=>Nr(H2.default.createHash("sha512").update(r).digest())})});var BE,yM,nl,sl,ol,il,bM,al,UE=_(()=>{V();ud();K2();F2();Ne();te();ce();BE=Symbol.for("nodejs.util.inspect.custom"),yM=114,nl=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Ph]=!0;toString(){return this.string==null&&(this.string=or.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return to.createV1(yM,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return W(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return W(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[BE](){return`PeerId(${this.toString()})`}},sl=class extends nl{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},ol=class extends nl{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},il=class extends nl{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},bM=2336,al=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=fd.digest(D(this.url))}[BE](){return`PeerId(${this.url})`}[Ph]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return to.createV1(bM,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=P(e)),e.toString()===this.toString())}}});var V2={};z(V2,{peerIdFromCID:()=>en,peerIdFromMultihash:()=>Br,peerIdFromPrivateKey:()=>q2,peerIdFromPublicKey:()=>On,peerIdFromString:()=>de});function de(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=el(or.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return en(to.parse(r));if(e==null)throw new R('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=el(e.decode(r))}return Br(t)}function On(r){if(r.type==="Ed25519")return new ol({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new il({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new sl({multihash:r.toCID().multihash,publicKey:r});throw new is}function q2(r){return On(r.publicKey)}function Br(r){if(vM(r))return new sl({multihash:r});if(xM(r))try{let e=fE(r);if(e.type==="Ed25519")return new ol({multihash:r,publicKey:e});if(e.type==="secp256k1")return new il({multihash:r,publicKey:e})}catch{let t=P(r.digest);return new al(new URL(t))}throw new vh("Supplied PeerID Multihash is invalid")}function en(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==wM&&r.code!==KE)throw new xh("Supplied PeerID CID is invalid");if(r.code===KE){let e=P(r.multihash.digest);return new al(new URL(e))}return Br(r.multihash)}function xM(r){return r.code===fd.code}function vM(r){return r.code===RE.code}var wM,KE,ke=_(()=>{Bt();V();ud();K2();tl();F2();NE();ce();UE();wM=114,KE=2336});var Tg=_(()=>{"use strict"});var PS=At((Oie,_S)=>{var Oi=1e3,Ri=Oi*60,Ni=Ri*60,oo=Ni*24,VR=oo*7,GR=oo*365.25;_S.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return WR(r);if(t==="number"&&isFinite(r))return e.long?YR(r):jR(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function WR(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*GR;case"weeks":case"week":case"w":return t*VR;case"days":case"day":case"d":return t*oo;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Ni;case"minutes":case"minute":case"mins":case"min":case"m":return t*Ri;case"seconds":case"second":case"secs":case"sec":case"s":return t*Oi;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function jR(r){var e=Math.abs(r);return e>=oo?Math.round(r/oo)+"d":e>=Ni?Math.round(r/Ni)+"h":e>=Ri?Math.round(r/Ri)+"m":e>=Oi?Math.round(r/Oi)+"s":r+"ms"}function YR(r){var e=Math.abs(r);return e>=oo?xd(r,e,oo,"day"):e>=Ni?xd(r,e,Ni,"hour"):e>=Ri?xd(r,e,Ri,"minute"):e>=Oi?xd(r,e,Oi,"second"):r+" ms"}function xd(r,e,t,n){var s=e>=t*1.5;return Math.round(r/t)+" "+n+(s?"s":"")}});var $g=At((Rie,DS)=>{function XR(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=s,t.enabled=a,t.humanize=PS(),t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let h=0;for(let p=0;p<u.length;p++)h=(h<<5)-h+u.charCodeAt(p),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(u){let h,p=null,f,d;function m(...g){if(!m.enabled)return;let y=m,b=Number(new Date),w=b-(h||b);y.diff=w,y.prev=h,y.curr=b,h=b,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let x=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(S,E)=>{if(S==="%%")return"%";x++;let I=t.formatters[E];if(typeof I=="function"){let A=g[x];S=I.call(y,A),g.splice(x,1),x--}return S}),t.formatArgs.call(y,g),(y.log||t.log).apply(y,g)}return m.namespace=u,m.useColors=t.useColors(),m.color=t.selectColor(u),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(f!==t.namespaces&&(f=t.namespaces,d=t.enabled(u)),d),set:g=>{p=g}}),typeof t.init=="function"&&t.init(m),m}function n(u,h){let p=t(this.namespace+(typeof h>"u"?":":h)+u);return p.log=this.log,p}function s(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let h=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let p of h)p[0]==="-"?t.skips.push(p.slice(1)):t.names.push(p)}function o(u,h){let p=0,f=0,d=-1,m=0;for(;p<u.length;)if(f<h.length&&(h[f]===u[p]||h[f]==="*"))h[f]==="*"?(d=f,m=p,f++):(p++,f++);else if(d!==-1)f=d+1,m++,p=m;else return!1;for(;f<h.length&&h[f]==="*";)f++;return f===h.length}function i(){let u=[...t.names,...t.skips.map(h=>"-"+h)].join(",");return t.enable(""),u}function a(u){for(let h of t.skips)if(o(u,h))return!1;for(let h of t.names)if(o(u,h))return!0;return!1}function c(u){return u instanceof Error?u.stack||u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}DS.exports=XR});var kS=At((Qt,vd)=>{Qt.formatArgs=JR;Qt.save=ZR;Qt.load=e9;Qt.useColors=QR;Qt.storage=t9();Qt.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Qt.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function QR(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let r;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function JR(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+vd.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(n=t))}),r.splice(n,0,e)}Qt.log=console.debug||console.log||(()=>{});function ZR(r){try{r?Qt.storage.setItem("debug",r):Qt.storage.removeItem("debug")}catch{}}function e9(){let r;try{r=Qt.storage.getItem("debug")||Qt.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function t9(){try{return localStorage}catch{}}vd.exports=$g()(Qt);var{formatters:r9}=vd.exports;r9.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var MS={};z(MS,{createSupportsColor:()=>qg,default:()=>pl});function Er(r,e=globalThis.Deno?globalThis.Deno.args:Sd.default.argv){let t=r.startsWith("-")?"":r.length===1?"-":"--",n=e.indexOf(t+r),s=e.indexOf("--");return n!==-1&&(s===-1||n<s)}function n9(){if(!("FORCE_COLOR"in Ke))return;if(Ke.FORCE_COLOR==="true")return 1;if(Ke.FORCE_COLOR==="false")return 0;if(Ke.FORCE_COLOR.length===0)return 1;let r=Math.min(Number.parseInt(Ke.FORCE_COLOR,10),3);if([0,1,2,3].includes(r))return r}function s9(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function o9(r,{streamIsTTY:e,sniffFlags:t=!0}={}){let n=n9();n!==void 0&&(Ed=n);let s=t?Ed:n;if(s===0)return 0;if(t){if(Er("color=16m")||Er("color=full")||Er("color=truecolor"))return 3;if(Er("color=256"))return 2}if("TF_BUILD"in Ke&&"AGENT_NAME"in Ke)return 1;if(r&&!e&&s===void 0)return 0;let o=s||0;if(Ke.TERM==="dumb")return o;if(Sd.default.platform==="win32"){let i=LS.default.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in Ke)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(i=>i in Ke)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(i=>i in Ke)||Ke.CI_NAME==="codeship"?1:o;if("TEAMCITY_VERSION"in Ke)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Ke.TEAMCITY_VERSION)?1:0;if(Ke.COLORTERM==="truecolor"||Ke.TERM==="xterm-kitty"||Ke.TERM==="xterm-ghostty"||Ke.TERM==="wezterm")return 3;if("TERM_PROGRAM"in Ke){let i=Number.parseInt((Ke.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Ke.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Ke.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Ke.TERM)||"COLORTERM"in Ke?1:o}function qg(r,e={}){let t=o9(r,{streamIsTTY:r&&r.isTTY,...e});return s9(t)}var Sd,LS,Hg,Ke,Ed,i9,pl,Vg=_(()=>{Sd=ie(ee("node:process"),1),LS=ie(ee("node:os"),1),Hg=ie(ee("node:tty"),1);({env:Ke}=Sd.default);Er("no-color")||Er("no-colors")||Er("color=false")||Er("color=never")?Ed=0:(Er("color")||Er("colors")||Er("color=true")||Er("color=always"))&&(Ed=1);i9={stdout:qg({isTTY:Hg.default.isatty(1)}),stderr:qg({isTTY:Hg.default.isatty(2)})},pl=i9});var RS=At((ft,Ad)=>{var a9=ee("tty"),Id=ee("util");ft.init=p9;ft.log=h9;ft.formatArgs=l9;ft.save=d9;ft.load=f9;ft.useColors=c9;ft.destroy=Id.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");ft.colors=[6,2,3,4,5,1];try{let r=(Vg(),$5(MS));r&&(r.stderr||r).level>=2&&(ft.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}ft.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,o)=>o.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),r[t]=n,r},{});function c9(){return"colors"in ft.inspectOpts?!!ft.inspectOpts.colors:a9.isatty(process.stderr.fd)}function l9(r){let{namespace:e,useColors:t}=this;if(t){let n=this.color,s="\x1B[3"+(n<8?n:"8;5;"+n),o=` ${s};1m${e} \x1B[0m`;r[0]=o+r[0].split(`
|
|
2
|
+
"use strict";var OptimysticDbP2P=(()=>{var OD=Object.create;var ah=Object.defineProperty;var RD=Object.getOwnPropertyDescriptor;var ND=Object.getOwnPropertyNames;var BD=Object.getPrototypeOf,UD=Object.prototype.hasOwnProperty;var ee=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var _=(r,e)=>()=>(r&&(e=r(r=0)),e);var At=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),z=(r,e)=>{for(var t in e)ah(r,t,{get:e[t],enumerable:!0})},z5=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ND(e))!UD.call(r,s)&&s!==t&&ah(r,s,{get:()=>e[s],enumerable:!(n=RD(e,s))||n.enumerable});return r};var ie=(r,e,t)=>(t=r!=null?OD(BD(r)):{},z5(e||!r||!r.__esModule?ah(t,"default",{value:r,enumerable:!0}):t,r)),$5=r=>z5(ah({},"__esModule",{value:!0}),r);function rs(r){return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}var cc=_(()=>{});function ae(r=0){return rs(Am.Buffer.alloc(r))}function tt(r=0){return rs(Am.Buffer.allocUnsafe(r))}var Am,rt=_(()=>{Am=ee("node:buffer");cc()});function Ae(r){if(r<WD)return 1;if(r<jD)return 2;if(r<YD)return 3;if(r<Cm)return 4;if(r<Tm)return 5;if(r<_m)return 6;if(r<Pm)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function In(r,e,t=0){switch(Ae(r)){case 8:e[t++]=r&255|Se,r/=128;case 7:e[t++]=r&255|Se,r/=128;case 6:e[t++]=r&255|Se,r/=128;case 5:e[t++]=r&255|Se,r/=128;case 4:e[t++]=r&255|Se,r>>>=7;case 3:e[t++]=r&255|Se,r>>>=7;case 2:e[t++]=r&255|Se,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function XD(r,e,t=0){switch(Ae(r)){case 8:e.set(t++,r&255|Se),r/=128;case 7:e.set(t++,r&255|Se),r/=128;case 6:e.set(t++,r&255|Se),r/=128;case 5:e.set(t++,r&255|Se),r/=128;case 4:e.set(t++,r&255|Se),r>>>=7;case 3:e.set(t++,r&255|Se),r>>>=7;case 2:e.set(t++,r&255|Se),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Dm(r,e){let t=r[e],n=0;if(n+=t&Ct,t<Se||(t=r[e+1],n+=(t&Ct)<<7,t<Se)||(t=r[e+2],n+=(t&Ct)<<14,t<Se)||(t=r[e+3],n+=(t&Ct)<<21,t<Se)||(t=r[e+4],n+=(t&Ct)*Cm,t<Se)||(t=r[e+5],n+=(t&Ct)*Tm,t<Se)||(t=r[e+6],n+=(t&Ct)*_m,t<Se)||(t=r[e+7],n+=(t&Ct)*Pm,t<Se))return n;throw new RangeError("Could not decode varint")}function QD(r,e){let t=r.get(e),n=0;if(n+=t&Ct,t<Se||(t=r.get(e+1),n+=(t&Ct)<<7,t<Se)||(t=r.get(e+2),n+=(t&Ct)<<14,t<Se)||(t=r.get(e+3),n+=(t&Ct)<<21,t<Se)||(t=r.get(e+4),n+=(t&Ct)*Cm,t<Se)||(t=r.get(e+5),n+=(t&Ct)*Tm,t<Se)||(t=r.get(e+6),n+=(t&Ct)*_m,t<Se)||(t=r.get(e+7),n+=(t&Ct)*Pm,t<Se))return n;throw new RangeError("Could not decode varint")}function Vr(r,e,t=0){return e==null&&(e=tt(Ae(r))),e instanceof Uint8Array?In(r,e,t):XD(r,e,t)}function jt(r,e=0){return r instanceof Uint8Array?Dm(r,e):QD(r,e)}var WD,jD,YD,Cm,Tm,_m,Pm,Se,Ct,gr=_(()=>{rt();WD=Math.pow(2,7),jD=Math.pow(2,14),YD=Math.pow(2,21),Cm=Math.pow(2,28),Tm=Math.pow(2,35),_m=Math.pow(2,42),Pm=Math.pow(2,49),Se=128,Ct=127});function Ee(r,e){return rs(G5.Buffer.concat(r,e))}var G5,bt=_(()=>{G5=ee("node:buffer");cc()});function W(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var Ne=_(()=>{});function W5(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function hh(r){return!!r?.[j5]}var j5,U,Be=_(()=>{rt();bt();Ne();j5=Symbol.for("@achingbrain/uint8arraylist");U=class r{bufs;length;[j5]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(hh(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(hh(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=W5(this.bufs,e);return t.buf[t.index]}set(e,t){let n=W5(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(hh(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:s}=this._subList(e,t);return Ee(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:Ee(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),o=new r;return o.length=s,o.bufs=[...n],o}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let h=e-a;n.push(i.subarray(h,h+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!hh(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let h=0;h<o;h++)i[h]=-1;for(let h=0;h<s;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let h=t;h<=c;h+=u){u=0;for(let p=l;p>=0;p--){let f=this.get(h+p);if(n[p]!==f){u=Math.max(1,p-a[f]);break}}if(u===0)return h}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=tt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let s=ae(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let s=ae(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let s=ae(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=tt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let s=ae(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let s=ae(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let s=ae(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let s=ae(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let s=ae(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!W(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((s,o)=>s+o.byteLength,0)),n.length=t,n}}});var X5,Q5=_(()=>{X5=Symbol.for("@libp2p/connection")});var J5=_(()=>{});var Z5=_(()=>{});var ex=_(()=>{});var Mm,tx=_(()=>{Mm=Symbol.for("@libp2p/content-routing")});var rr,yh,bh,R,Xo,hc,zs,Tn,wh,ns,dc,$s,Qo,ss,xh,vh,Eh,Rt,Sh,Gr,Dr,Ih,os,Hs,fc,Ah,Jo,is,rx=_(()=>{rr=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}},yh=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},bh=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},R=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Xo=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},hc=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}},zs=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}},Tn=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},wh=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}},ns=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},dc=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}},$s=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},Qo=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},ss=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},xh=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},vh=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},Eh=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},Rt=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}},Sh=class extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}},Gr=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Dr=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}},Ih=class extends Error{static name="AlreadyStartedError";constructor(e="Already started"){super(e),this.name="AlreadyStartedError"}},os=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},Hs=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}},fc=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},Ah=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},Jo=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},is=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}});var Ch,as,Th,_h,nx=_(()=>{Ch=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},as=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},Th=class extends as{constructor(e,t){super(!0,e,t)}},_h=class extends as{constructor(e,t){super(!1,e,t)}}});var sx=_(()=>{});var ox=_(()=>{});var ix=_(()=>{});var ax=_(()=>{});var pc,cx=_(()=>{pc=Symbol.for("@libp2p/peer-discovery")});function cs(r){return!!r?.[Ph]}var Ph,lx=_(()=>{Ph=Symbol.for("@libp2p/peer-id")});var ux=_(()=>{});var Om,hx=_(()=>{Om=Symbol.for("@libp2p/peer-routing")});var mc,dx=_(()=>{mc="keep-alive"});var fx=_(()=>{});function Dh(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function kh(...r){let e=[];for(let t of r)Dh(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function Lh(...r){let e=[];for(let t of r)Dh(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var px=_(()=>{});var mx=_(()=>{});var gx=_(()=>{});var yx=_(()=>{});var bx=_(()=>{});var Mh,gc,wx=_(()=>{Mh=Symbol.for("@libp2p/transport");(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(gc||(gc={}))});var xx,j,vx=_(()=>{xx=ee("node:events"),j=(r,...e)=>{try{(0,xx.setMaxListeners)(r,...e)}catch{}}});var me,Ue=_(()=>{vx();me=class extends EventTarget{#e=new Map;constructor(){super(),j(1/0,this)}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let s=this.#e.get(e);s!=null&&(s=s.filter(({callback:o})=>o!==t),this.#e.set(e,s))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:s})=>!s),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}}});var nt,yc,V=_(()=>{Q5();J5();Z5();ex();tx();rx();nx();sx();ox();ix();ax();cx();lx();ux();hx();dx();fx();px();mx();gx();yx();bx();wx();Ue();nt=Symbol.for("@libp2p/service-capabilities"),yc=Symbol.for("@libp2p/service-dependencies")});function Ex(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function ls(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var xX,bc=_(()=>{xX=new Uint8Array(0)});function tk(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var v=d[y],S=0,E=w-1;(v!==0||S<g)&&E!==-1;E--,S++)v+=256*x[E]>>>0,x[E]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var A=c.repeat(m);I<w;++I)A+=r.charAt(x[I]);return A}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*w[S]>>>0,w[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(d[m]!==" "){for(var E=b-y;E!==b&&w[E]===0;)E++;for(var I=new Uint8Array(g+(b-E)),A=g;E!==b;)I[A++]=w[E++];return I}}}function f(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:f}}var rk,nk,Sx,Ix=_(()=>{rk=tk,nk=rk,Sx=nk});function Ax(r,e){return new Bm({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}function Cx({name:r,prefix:e,encode:t,decode:n}){return new Um(r,e,t,n)}function Zo({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=Sx(t,r);return Cx({prefix:e,name:r,encode:n,decode:o=>ls(s(o))})}function sk(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function ok(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function ik(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Wr({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=ik(n);return Cx({prefix:e,name:r,encode(o){return ok(o,n,t)},decode(o){return sk(o,s,t,r)}})}var Rm,Nm,Bm,Um,Oh=_(()=>{bc();Ix();Rm=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Nm=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Ax(this,e)}},Bm=class{decoders;constructor(e){this.decoders=e}or(e){return Ax(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};Um=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new Rm(e,t,n),this.decoder=new Nm(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}});var wt,TX,ei=_(()=>{Oh();wt=Zo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),TX=Zo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var wc,DX,kX,LX,MX,OX,RX,NX,BX,Tx=_(()=>{Oh();wc=Wr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),DX=Wr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),kX=Wr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),LX=Wr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),MX=Wr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),OX=Wr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),RX=Wr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),NX=Wr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),BX=Wr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var Rh,FX,_x=_(()=>{Oh();Rh=Zo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),FX=Zo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});function kx(r,e,t){e=e||[],t=t||0;for(var n=t;r>=uk;)e[t++]=r&255|Px,r/=128;for(;r&lk;)e[t++]=r&255|Px,r>>>=7;return e[t]=r|0,kx.bytes=t-n+1,e}function Km(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Km.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&Dx)<<s:(i&Dx)*Math.pow(2,s),s+=7}while(i>=dk);return Km.bytes=o-n,t}var ak,Px,ck,lk,uk,hk,dk,Dx,fk,pk,mk,gk,yk,bk,wk,xk,vk,Ek,Sk,Ik,xc,Lx=_(()=>{ak=kx,Px=128,ck=127,lk=~ck,uk=Math.pow(2,31);hk=Km,dk=128,Dx=127;fk=Math.pow(2,7),pk=Math.pow(2,14),mk=Math.pow(2,21),gk=Math.pow(2,28),yk=Math.pow(2,35),bk=Math.pow(2,42),wk=Math.pow(2,49),xk=Math.pow(2,56),vk=Math.pow(2,63),Ek=function(r){return r<fk?1:r<pk?2:r<mk?3:r<gk?4:r<yk?5:r<bk?6:r<wk?7:r<xk?8:r<vk?9:10},Sk={encode:ak,decode:hk,encodingLength:Ek},Ik=Sk,xc=Ik});function vc(r,e=0){return[xc.decode(r,e),xc.decode.bytes]}function ti(r,e,t=0){return xc.encode(r,e,t),e}function ri(r){return xc.encodingLength(r)}var Fm=_(()=>{Lx()});function us(r,e){let t=e.byteLength,n=ri(r),s=n+ri(t),o=new Uint8Array(s+t);return ti(r,o,0),ti(t,o,n),o.set(e,s),new ni(r,t,e,o)}function Ox(r){let e=ls(r),[t,n]=vc(e),[s,o]=vc(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new ni(t,s,i,e)}function Rx(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Ex(r.bytes,t.bytes)}}var ni,Nh=_(()=>{bc();Fm();ni=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}}});var Bx=_(()=>{});function Ux(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Ck(t,zm(r),e??wt.encoder);default:return Tk(t,zm(r),e??wc.encoder)}}function zm(r){let e=Kx.get(r);if(e==null){let t=new Map;return Kx.set(r,t),t}return e}function Ak(r,e){switch(r[0]){case"Q":{let t=e??wt;return[wt.prefix,t.decode(`${wt.prefix}${r}`)]}case wt.prefix:{let t=e??wt;return[wt.prefix,t.decode(r)]}case wc.prefix:{let t=e??wc;return[wc.prefix,t.decode(r)]}case Rh.prefix:{let t=e??Rh;return[Rh.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Ck(r,e,t){let{prefix:n}=t;if(n!==wt.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function Tk(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}function Fx(r,e,t){let n=ri(r),s=n+ri(e),o=new Uint8Array(s+t.byteLength);return ti(r,o,0),ti(e,o,n),o.set(t,s),o}var Kx,jr,Ec,_k,Pk,Sc=_(()=>{Tx();_x();ei();bc();Nh();Fm();Bx();Kx=new WeakMap;jr=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Ec)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==_k)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=us(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Rx(e.multihash,n.multihash)}toString(e){return Ux(this,e)}toJSON(){return{"/":Ux(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??Fx(n,s,o.bytes))}else if(t[Pk]===!0){let{version:n,multihash:s,code:o}=t,i=Ox(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Ec)throw new Error(`Version 0 CID must use dag-pb (code: ${Ec}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=Fx(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ec,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=ls(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new ni(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,p]=vc(e.subarray(t));return t+=p,h},s=n(),o=Ec;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=Ak(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return zm(o).set(n,e),o}};Ec=112,_k=18;Pk=Symbol.for("@ipld/js-cid/CID")});function kk(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return us(zx,$x(r))}var zx,Dk,$x,si,Bh=_(()=>{bc();Nh();zx=0,Dk="identity",$x=ls;si={code:zx,name:Dk,encode:$x,digest:kk}});function Hx(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function br(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function qx(r){return new TextEncoder().encode(r)}function Vx(r){return new TextDecoder().decode(r)}var ZX,_n=_(()=>{ZX=new Uint8Array(0)});function Lk(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var v=d[y],S=0,E=w-1;(v!==0||S<g)&&E!==-1;E--,S++)v+=256*x[E]>>>0,x[E]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var A=c.repeat(m);I<w;++I)A+=r.charAt(x[I]);return A}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*w[S]>>>0,w[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(d[m]!==" "){for(var E=b-y;E!==b&&w[E]===0;)E++;for(var I=new Uint8Array(g+(b-E)),A=g;E!==b;)I[A++]=w[E++];return I}}}function f(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:f}}var Mk,Ok,Wx,jx=_(()=>{Mk=Lk,Ok=Mk,Wx=Ok});function Yx(r,e){return new qm({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}function oi({name:r,prefix:e,encode:t,decode:n}){return new Vm(r,e,t,n)}function hs({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=Wx(t,r);return oi({prefix:e,name:r,encode:n,decode:o=>br(s(o))})}function Rk(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function Nk(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function Bk(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function $e({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=Bk(n);return oi({prefix:e,name:r,encode(o){return Nk(o,n,t)},decode(o){return Rk(o,s,t,r)}})}var $m,Hm,qm,Vm,kr=_(()=>{_n();jx();$m=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Hm=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Yx(this,e)}},qm=class{decoders;constructor(e){this.decoders=e}or(e){return Yx(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};Vm=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new $m(e,t,n),this.decoder=new Hm(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}});var Gm={};z(Gm,{base10:()=>Uk});var Uk,Xx=_(()=>{kr();Uk=hs({prefix:"9",name:"base10",alphabet:"0123456789"})});var Wm={};z(Wm,{base16:()=>Kk,base16upper:()=>Fk});var Kk,Fk,Qx=_(()=>{kr();Kk=$e({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Fk=$e({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var jm={};z(jm,{base2:()=>zk});var zk,Jx=_(()=>{kr();zk=$e({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var Ym={};z(Ym,{base256emoji:()=>Gk});function qk(r){return r.reduce((e,t)=>(e+=$k[t],e),"")}function Vk(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=Hk[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var Zx,$k,Hk,Gk,e4=_(()=>{kr();Zx=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),$k=Zx.reduce((r,e,t)=>(r[t]=e,r),[]),Hk=Zx.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);Gk=oi({prefix:"\u{1F680}",name:"base256emoji",encode:qk,decode:Vk})});var Xm={};z(Xm,{base32:()=>ii,base32hex:()=>Xk,base32hexpad:()=>Jk,base32hexpadupper:()=>Zk,base32hexupper:()=>Qk,base32pad:()=>jk,base32padupper:()=>Yk,base32upper:()=>Wk,base32z:()=>e7});var ii,Wk,jk,Yk,Xk,Qk,Jk,Zk,e7,Qm=_(()=>{kr();ii=$e({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Wk=$e({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),jk=$e({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Yk=$e({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Xk=$e({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Qk=$e({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Jk=$e({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Zk=$e({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),e7=$e({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var Jm={};z(Jm,{base36:()=>Ic,base36upper:()=>t7});var Ic,t7,Zm=_(()=>{kr();Ic=hs({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),t7=hs({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var e0={};z(e0,{base58btc:()=>Yr,base58flickr:()=>r7});var Yr,r7,t0=_(()=>{kr();Yr=hs({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),r7=hs({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var r0={};z(r0,{base64:()=>n7,base64pad:()=>s7,base64url:()=>o7,base64urlpad:()=>i7});var n7,s7,o7,i7,t4=_(()=>{kr();n7=$e({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),s7=$e({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),o7=$e({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),i7=$e({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var n0={};z(n0,{base8:()=>a7});var a7,r4=_(()=>{kr();a7=$e({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var s0={};z(s0,{identity:()=>c7});var c7,n4=_(()=>{_n();kr();c7=oi({prefix:"\0",name:"identity",encode:r=>Vx(r),decode:r=>qx(r)})});var mQ,gQ,s4=_(()=>{mQ=new TextEncoder,gQ=new TextDecoder});var o4=_(()=>{_n()});function c4(r,e,t){e=e||[],t=t||0;for(var n=t;r>=p7;)e[t++]=r&255|i4,r/=128;for(;r&f7;)e[t++]=r&255|i4,r>>>=7;return e[t]=r|0,c4.bytes=t-n+1,e}function o0(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw o0.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&a4)<<s:(i&a4)*Math.pow(2,s),s+=7}while(i>=g7);return o0.bytes=o-n,t}var h7,i4,d7,f7,p7,m7,g7,a4,y7,b7,w7,x7,v7,E7,S7,I7,A7,C7,T7,_7,Ac,l4=_(()=>{h7=c4,i4=128,d7=127,f7=~d7,p7=Math.pow(2,31);m7=o0,g7=128,a4=127;y7=Math.pow(2,7),b7=Math.pow(2,14),w7=Math.pow(2,21),x7=Math.pow(2,28),v7=Math.pow(2,35),E7=Math.pow(2,42),S7=Math.pow(2,49),I7=Math.pow(2,56),A7=Math.pow(2,63),C7=function(r){return r<y7?1:r<b7?2:r<w7?3:r<x7?4:r<v7?5:r<E7?6:r<S7?7:r<I7?8:r<A7?9:10},T7={encode:h7,decode:m7,encodingLength:C7},_7=T7,Ac=_7});function Cc(r,e=0){return[Ac.decode(r,e),Ac.decode.bytes]}function ai(r,e,t=0){return Ac.encode(r,e,t),e}function ci(r){return Ac.encodingLength(r)}var Kh=_(()=>{l4()});function ui(r,e){let t=e.byteLength,n=ci(r),s=n+ci(t),o=new Uint8Array(s+t);return ai(r,o,0),ai(t,o,n),o.set(e,s),new li(r,t,e,o)}function u4(r){let e=br(r),[t,n]=Cc(e),[s,o]=Cc(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new li(t,s,i,e)}function h4(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Hx(r.bytes,t.bytes)}}var li,_c=_(()=>{_n();Kh();li=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}}});var i0={};z(i0,{identity:()=>k7});function D7(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return ui(d4,f4(r))}var d4,P7,f4,k7,p4=_(()=>{_n();_c();d4=0,P7="identity",f4=br;k7={code:d4,name:P7,encode:f4,digest:D7}});function c0({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new a0(r,e,t,n,s)}function m4(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return ui(e,r)}var L7,a0,l0=_(()=>{_c();L7=20;a0=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??L7,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?m4(n,this.code,t?.truncate):n.then(s=>m4(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}}});var h0={};z(h0,{sha256:()=>M7,sha512:()=>O7});var u0,M7,O7,y4=_(()=>{u0=ie(ee("crypto"),1);_n();l0();M7=c0({name:"sha2-256",code:18,encode:r=>br(u0.default.createHash("sha256").update(r).digest())}),O7=c0({name:"sha2-512",code:19,encode:r=>br(u0.default.createHash("sha512").update(r).digest())})});var d0=_(()=>{});function b4(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return N7(t,f0(r),e??Yr.encoder);default:return B7(t,f0(r),e??ii.encoder)}}function f0(r){let e=w4.get(r);if(e==null){let t=new Map;return w4.set(r,t),t}return e}function R7(r,e){switch(r[0]){case"Q":{let t=e??Yr;return[Yr.prefix,t.decode(`${Yr.prefix}${r}`)]}case Yr.prefix:{let t=e??Yr;return[Yr.prefix,t.decode(r)]}case ii.prefix:{let t=e??ii;return[ii.prefix,t.decode(r)]}case Ic.prefix:{let t=e??Ic;return[Ic.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function N7(r,e,t){let{prefix:n}=t;if(n!==Yr.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function B7(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}function x4(r,e,t){let n=ci(r),s=n+ci(e),o=new Uint8Array(s+t.byteLength);return ai(r,o,0),ai(e,o,n),o.set(t,s),o}var w4,Fh,Pc,U7,K7,v4=_(()=>{Qm();Zm();t0();_n();_c();Kh();d0();w4=new WeakMap;Fh=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Pc)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==U7)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=ui(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&h4(e.multihash,n.multihash)}toString(e){return b4(this,e)}toJSON(){return{"/":b4(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??x4(n,s,o.bytes))}else if(t[K7]===!0){let{version:n,multihash:s,code:o}=t,i=u4(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Pc)throw new Error(`Version 0 CID must use dag-pb (code: ${Pc}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=x4(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Pc,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=br(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new li(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,p]=Cc(e.subarray(t));return t+=p,h},s=n(),o=Pc;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=R7(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return f0(o).set(n,e),o}};Pc=112,U7=18;K7=Symbol.for("@ipld/js-cid/CID")});var E4=_(()=>{});var S4=_(()=>{});var I4=_(()=>{});var A4=_(()=>{});var C4=_(()=>{E4();S4();I4();d0();A4()});var T4=_(()=>{_n();v4();_c();l0();Kh();C4()});var p0,KQ,_4=_(()=>{Xx();Qx();Jx();e4();Qm();Zm();t0();t4();r4();n4();s4();o4();p4();y4();T4();p0={...s0,...jm,...n0,...Gm,...Wm,...Xm,...Jm,...e0,...r0,...Ym},KQ={...h0,...i0}});function D4(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var P4,m0,F7,zh,g0=_(()=>{_4();rt();P4=D4("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),m0=D4("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=tt(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),F7={utf8:P4,"utf-8":P4,hex:p0.base16,latin1:m0,ascii:m0,binary:m0,...p0},zh=F7});function D(r,e="utf8"){let t=zh[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return e==="utf8"||e==="utf-8"?rs(k4.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}var k4,te=_(()=>{k4=ee("node:buffer");g0();cc()});function P(r,e="utf8"){let t=zh[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return e==="utf8"||e==="utf-8"?L4.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}var L4,ce=_(()=>{L4=ee("node:buffer");g0()});function Pn(r,e={offset:0}){let t=r[e.offset]&z7;if(e.offset++,M4[t]!=null)return M4[t](r,e);throw new Error("No decoder for tag "+t)}function kc(r,e){let t=0;if((r[e.offset]&y0)===y0){let n=r[e.offset]&$7,s="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)s+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(s,16)}else t=r[e.offset],e.offset++;return t}function Dc(r,e){kc(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=Pn(r,e);if(n===null)break;t.push(n)}return t}function H7(r,e){let t=kc(r,e),n=e.offset,s=e.offset+t,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function q7(r,e){let t=kc(r,e),n=e.offset+t,s=r[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let h=0;h<c.length;h++)u+=c[h]<<h*7;a+=`.${u}`,c=[]}}return a}function V7(r,e){return e.offset++,null}function G7(r,e){let t=kc(r,e),n=r[e.offset];e.offset++;let s=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function W7(r,e){let t=kc(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function j7(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new U;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function $h(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=j7(r.byteLength);return new U(Uint8Array.from([e.byteLength|y0]),e)}function Nt(r){let e=new U,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new U(Uint8Array.from([2]),$h(e),e)}function Lc(r){let e=Uint8Array.from([0]),t=new U(e,r);return new U(Uint8Array.from([3]),$h(t),t)}function O4(r){return new U(Uint8Array.from([4]),$h(r),r)}function Lr(r,e=48){let t=new U;for(let n of r)t.append(n);return new U(Uint8Array.from([e]),$h(t),t)}var z7,y0,$7,M4,b0=_(()=>{Be();z7=parseInt("11111",2),y0=parseInt("10000000",2),$7=parseInt("01111111",2),M4={0:Dc,1:Dc,2:H7,3:G7,4:W7,5:V7,6:q7,16:Dc,22:Dc,48:Dc}});async function R4(r="P-256"){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function N4(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let s=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}async function B4(r,e,t,n){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,e,t.subarray());return n?.signal?.throwIfAborted(),o}var w0=_(()=>{});function S0(r){let e=Pn(r);return U4(e)}function U4(r){let e=r[1][1][0],t=1,n,s;if(e.byteLength===x0*2+1)return n=P(e.subarray(t,t+x0),"base64url"),s=P(e.subarray(t+x0),"base64url"),new qs({...J7,key_ops:["verify"],x:n,y:s});if(e.byteLength===v0*2+1)return n=P(e.subarray(t,t+v0),"base64url"),s=P(e.subarray(t+v0),"base64url"),new qs({...Z7,key_ops:["verify"],x:n,y:s});if(e.byteLength===E0*2+1)return n=P(e.subarray(t,t+E0),"base64url"),s=P(e.subarray(t+E0),"base64url"),new qs({...eL,key_ops:["verify"],x:n,y:s});throw new R(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function K4(r){return Lr([Nt(Uint8Array.from([1])),O4(D(r.d??"","base64url")),Lr([z4(r.crv)],160),Lr([Lc(new U(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function F4(r){return Lr([Nt(Uint8Array.from([1])),Lr([z4(r.crv)],160),Lr([Lc(new U(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function z4(r){if(r==="P-256")return Y7;if(r==="P-384")return X7;if(r==="P-521")return Q7;throw new R(`Invalid curve ${r}`)}async function $4(r="P-256"){let e=await R4(r);return new Hh(e.privateKey)}var Y7,X7,Q7,J7,Z7,eL,x0,v0,E0,I0=_(()=>{V();Be();te();ce();b0();H4();w0();Y7=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),X7=Uint8Array.from([6,5,43,129,4,0,34]),Q7=Uint8Array.from([6,5,43,129,4,0,35]),J7={ext:!0,kty:"EC",crv:"P-256"},Z7={ext:!0,kty:"EC",crv:"P-384"},eL={ext:!0,kty:"EC",crv:"P-521"},x0=32,v0=48,E0=66});var qs,Hh,H4=_(()=>{ei();Sc();Bh();Ne();Bt();I0();w0();qs=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=F4(this.jwk)),this._raw}toMultihash(){return si.digest(dt(this))}toCID(){return jr.createV1(114,this.toMultihash())}toString(){return wt.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}async verify(e,t,n){return B4(this.jwk,t,e,n)}},Hh=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new qs({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=K4(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}async sign(e,t){return N4(this.jwk,e,t)}}});function sL(r){let t=Vs.default.createPrivateKey({format:"jwk",key:{crv:"Ed25519",x:"",d:P(r,"base64url"),kty:"OKP"}}).export({format:"jwk"});if(t.x==null||t.x==="")throw new Error("Could not export JWK public key");return D(t.x,"base64url")}function q4(){let r=tL("ed25519",{publicKeyEncoding:{type:"spki",format:"jwk"},privateKeyEncoding:{type:"pkcs8",format:"jwk"}}),e=D(r.privateKey.d,"base64url"),t=D(r.publicKey.x,"base64url");return{privateKey:Ee([e,t],e.byteLength+t.byteLength),publicKey:t}}function V4(r,e){if(!(r instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');let t,n;if(r.byteLength===qh)t=r.subarray(0,32),n=r.subarray(32);else if(r.byteLength===rL)t=r.subarray(0,32),n=sL(t);else throw new TypeError('"key" must be 64 or 32 bytes in length.');let s=Vs.default.createPrivateKey({format:"jwk",key:{crv:"Ed25519",d:P(t,"base64url"),x:P(n,"base64url"),kty:"OKP"}});return Vs.default.sign(null,e instanceof Uint8Array?e:e.subarray(),s)}function G4(r,e,t){if(r.byteLength!==Mc)throw new TypeError('"key" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');if(e.byteLength!==nL)throw new TypeError('"sig" must be 64 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"sig" must be a node.js Buffer, or Uint8Array.');let n=Vs.default.createPublicKey({format:"jwk",key:{crv:"Ed25519",x:P(r,"base64url"),kty:"OKP"}});return Vs.default.verify(null,t instanceof Uint8Array?t:t.subarray(),n,e)}var Vs,tL,Mc,qh,rL,nL,A0=_(()=>{Vs=ie(ee("crypto"),1);bt();te();ce();tL=Vs.default.generateKeyPairSync,Mc=32,qh=64,rL=32,nL=64});function C0(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var j4=_(()=>{bt();te()});var Oc,Vh,Y4=_(()=>{ei();Sc();Bh();Ne();j4();Bt();T0();A0();Oc=class{type="Ed25519";raw;constructor(e){this.raw=Gh(e,Mc)}toMultihash(){return si.digest(dt(this))}toCID(){return jr.createV1(114,this.toMultihash())}toString(){return wt.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let s=G4(this.raw,t,e);return C0(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}},Vh=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=Gh(e,qh),this.publicKey=new Oc(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=V4(this.raw,e);return C0(n)?n.then(s=>(t?.signal?.throwIfAborted(),s)):(t?.signal?.throwIfAborted(),n)}}});function _0(r){return r=Gh(r,Mc),new Oc(r)}async function X4(){let{privateKey:r,publicKey:e}=q4();return new Vh(r,e)}function Gh(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new R(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var T0=_(()=>{V();Y4();A0()});function Q4(r,e,t){P0[0]=r,e[t]=ds[0],e[t+1]=ds[1],e[t+2]=ds[2],e[t+3]=ds[3]}function J4(r,e){return ds[0]=r[e],ds[1]=r[e+1],ds[2]=r[e+2],ds[3]=r[e+3],P0[0]}function Z4(r,e,t){D0[0]=r,e[t]=Tt[0],e[t+1]=Tt[1],e[t+2]=Tt[2],e[t+3]=Tt[3],e[t+4]=Tt[4],e[t+5]=Tt[5],e[t+6]=Tt[6],e[t+7]=Tt[7]}function ev(r,e){return Tt[0]=r[e],Tt[1]=r[e+1],Tt[2]=r[e+2],Tt[3]=r[e+3],Tt[4]=r[e+4],Tt[5]=r[e+5],Tt[6]=r[e+6],Tt[7]=r[e+7],D0[0]}var P0,ds,D0,Tt,k0=_(()=>{P0=new Float32Array([-0]),ds=new Uint8Array(P0.buffer);D0=new Float64Array([-0]),Tt=new Uint8Array(D0.buffer)});var oL,iL,nr,Gs,tv,L0=_(()=>{oL=BigInt(Number.MAX_SAFE_INTEGER),iL=BigInt(Number.MIN_SAFE_INTEGER),nr=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return Gs;if(e<oL&&e>iL)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,s=e-(n<<32n);return t&&(n=~n|0n,s=~s|0n,++s>tv&&(s=0n,++n>tv&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return Gs;let t=e<0;t&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):Gs}},Gs=new nr(0,0);Gs.toBigInt=function(){return 0n};Gs.zzEncode=Gs.zzDecode=function(){return this};Gs.length=function(){return 1};tv=4294967296n});function rv(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function nv(r,e,t){if(t-e<1)return"";let s,o=[],i=0,a;for(;e<t;)a=r[e++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function M0(r,e,t){let n=t,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128);return t-n}var O0=_(()=>{});function Mr(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Wh(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}function N0(r){return new R0(r instanceof Uint8Array?r:r.subarray())}var R0,B0=_(()=>{gr();k0();L0();O0();R0=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Mr(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Mr(this,4);return Wh(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Mr(this,4);return Wh(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Mr(this,4);let e=J4(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Mr(this,4);let e=ev(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Mr(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return nv(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Mr(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Mr(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new nr(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Mr(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Mr(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Mr(this,8);let e=Wh(this.buf,this.pos+=4),t=Wh(this.buf,this.pos+=4);return new nr(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Dm(this.buf,this.pos);return this.pos+=Ae(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}});function Q(r,e,t){let n=N0(r);return e.decode(n,void 0,t)}var ov=_(()=>{B0()});function U0(r){let e=r??8192,t=e>>>1,n,s=e;return function(i){if(i<1||i>t)return tt(i);s+i>e&&(n=tt(e),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var iv=_(()=>{rt()});function K0(){}function cL(r){return globalThis.Buffer!=null?tt(r):aL(r)}function F0(r,e,t){e[t]=r&255}function lL(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function jh(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Rc(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function uL(r,e,t){e.set(r,t)}function hL(r,e,t){e.set(r,t)}function dL(r,e,t){r.length<40?M0(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(D(r),t)}function H0(){return new Nc}var Ws,z0,aL,Nc,$0,q0=_(()=>{gr();rt();te();k0();L0();iv();O0();Ws=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};z0=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},aL=U0();Nc=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ws(K0,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Ws(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new $0((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(jh,10,nr.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=nr.fromBigInt(e);return this._push(jh,t.length(),t)}uint64Number(e){return this._push(In,Ae(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=nr.fromBigInt(e).zzEncode();return this._push(jh,t.length(),t)}sint64Number(e){let t=nr.fromNumber(e).zzEncode();return this._push(jh,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(F0,1,e?1:0)}fixed32(e){return this._push(Rc,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=nr.fromBigInt(e);return this._push(Rc,4,t.lo)._push(Rc,4,t.hi)}fixed64Number(e){let t=nr.fromNumber(e);return this._push(Rc,4,t.lo)._push(Rc,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Q4,4,e)}double(e){return this._push(Z4,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(F0,1,0):this.uint32(t)._push(uL,t,e)}string(e){let t=rv(e);return t!==0?this.uint32(t)._push(M0,t,e):this._push(F0,1,0)}fork(){return this.states=new z0(this),this.head=this.tail=new Ws(K0,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Ws(K0,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=cL(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};$0=class extends Ws{next;constructor(e,t){super(lL,e,t),this.next=void 0}};globalThis.Buffer!=null&&(Nc.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(hL,e,r),this},Nc.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(dL,e,r),this})});function J(r,e){let t=H0();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var av=_(()=>{q0()});function Yh(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}var hi,V0=_(()=>{(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(hi||(hi={}))});function sr(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(o,i){let a=e(o);i.int32(a)},n=function(o){let i=o.int32();return e(i)};return Yh("enum",hi.VARINT,t,n)}var cv=_(()=>{V0()});function Z(r,e){return Yh("message",hi.LENGTH_DELIMITED,r,e)}var lv=_(()=>{V0()});var _e,Bc,wr=_(()=>{ov();av();cv();lv();B0();q0();_e=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Bc=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"}});var Je,G0,Xr,W0,j0=_(()=>{wr();(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Je||(Je={}));(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(G0||(G0={}));(function(r){r.codec=()=>sr(G0)})(Je||(Je={}));(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Je.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=Je.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(Xr||(Xr={}));(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Je.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=Je.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(W0||(W0={}))});function Uc(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function xr(r,e=""){if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${r}`)}}function ge(r,e,t=""){let n=Uc(r),s=r?.length,o=e!==void 0;if(!n||o&&s!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function js(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");xr(r.outputLen),xr(r.blockLen)}function di(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function dv(r,e){ge(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function kn(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Xh(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Or(r,e){return r<<32-e|r>>>e}function Ys(r){if(ge(r),fv)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=fL[r[t]];return e}function hv(r){if(r>=Dn._0&&r<=Dn._9)return r-Dn._0;if(r>=Dn.A&&r<=Dn.F)return r-(Dn.A-10);if(r>=Dn.a&&r<=Dn.f)return r-(Dn.a-10)}function Xs(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(fv)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){let i=hv(r.charCodeAt(o)),a=hv(r.charCodeAt(o+1));if(i===void 0||a===void 0){let c=r[o]+r[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}n[s]=i*16+a}return n}function Rr(...r){let e=0;for(let n=0;n<r.length;n++){let s=r[n];ge(s),e+=s.length}let t=new Uint8Array(e);for(let n=0,s=0;n<r.length;n++){let o=r[n];t.set(o,s),s+=o.length}return t}function pv(r,e={}){let t=(s,o)=>r(o).update(s).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=s=>r(s),Object.assign(t,e),Object.freeze(t)}function Qr(r=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}var fv,fL,Dn,mv,Jr=_(()=>{fv=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",fL=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));Dn={_0:48,_9:57,A:65,F:70,a:97,f:102};mv=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])})});function fs(r){if(isNaN(r)||r<=0)throw new R("random bytes length must be a Number bigger than 0");return Qr(r)}var gv=_(()=>{V();Jr()});function yv(r,e,t){return r&e^~r&t}function bv(r,e,t){return r&e^r&t^e&t}var Qh,Ln,wv=_(()=>{Jr();Qh=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,s){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Xh(this.buffer)}update(e){di(this),ge(e);let{view:t,buffer:n,blockLen:s}=this,o=e.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let c=Xh(e);for(;s<=o-i;i+=s)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){di(this),dv(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:s,isLE:o}=this,{pos:i}=this;t[i++]=128,kn(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(n,0),i=0);for(let h=i;h<s;h++)t[h]=0;n.setBigUint64(s-8,BigInt(this.length*8),o),this.process(n,0);let a=Xh(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:s,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=s,e.pos=a,s%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Ln=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225])});var pL,ps,Y0,X0,Yt,Kc=_(()=>{wv();Jr();pL=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ps=new Uint32Array(64),Y0=class extends Qh{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[e,t,n,s,o,i,a,c]}set(e,t,n,s,o,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let h=0;h<16;h++,t+=4)ps[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let p=ps[h-15],f=ps[h-2],d=Or(p,7)^Or(p,18)^p>>>3,m=Or(f,17)^Or(f,19)^f>>>10;ps[h]=m+ps[h-7]+d+ps[h-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){let p=Or(a,6)^Or(a,11)^Or(a,25),f=u+p+yv(a,c,l)+pL[h]+ps[h]|0,m=(Or(n,2)^Or(n,13)^Or(n,22))+bv(n,s,o)|0;u=l,l=c,c=a,a=i+f|0,i=o,o=s,s=n,n=f+m|0}n=n+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,s,o,i,a,c,l,u)}roundClean(){kn(ps)}destroy(){this.set(0,0,0,0,0,0,0,0),kn(this.buffer)}},X0=class extends Y0{A=Ln[0]|0;B=Ln[1]|0;C=Ln[2]|0;D=Ln[3]|0;E=Ln[4]|0;F=Ln[5]|0;G=Ln[6]|0;H=Ln[7]|0;constructor(){super(32)}},Yt=pv(()=>new X0,mv(1))});var fi,Fc,xv=_(()=>{ei();Sc();Ne();Q0();fi=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=zc.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return jr.createV1(114,this._multihash)}toString(){return wt.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){return Ev(this.jwk,t,e,n)}},Fc=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=zc.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}sign(e,t){return vv(this.jwk,e,t)}}});var zc={};z(zc,{MAX_RSA_KEY_SIZE:()=>J0,generateRSAKeyPair:()=>a2,jwkToJWKKeyPair:()=>Iv,jwkToPkcs1:()=>bL,jwkToPkix:()=>r2,jwkToRSAPrivateKey:()=>i2,pkcs1MessageToJwk:()=>e2,pkcs1MessageToRSAPrivateKey:()=>n2,pkcs1ToJwk:()=>yL,pkcs1ToRSAPrivateKey:()=>Sv,pkixMessageToJwk:()=>t2,pkixMessageToRSAPublicKey:()=>o2,pkixToJwk:()=>wL,pkixToRSAPublicKey:()=>s2});function yL(r){let e=Pn(r);return e2(e)}function e2(r){return{n:P(r[1],"base64url"),e:P(r[2],"base64url"),d:P(r[3],"base64url"),p:P(r[4],"base64url"),q:P(r[5],"base64url"),dp:P(r[6],"base64url"),dq:P(r[7],"base64url"),qi:P(r[8],"base64url"),kty:"RSA"}}function bL(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new R("JWK was missing components");return Lr([Nt(Uint8Array.from([0])),Nt(D(r.n,"base64url")),Nt(D(r.e,"base64url")),Nt(D(r.d,"base64url")),Nt(D(r.p,"base64url")),Nt(D(r.q,"base64url")),Nt(D(r.dp,"base64url")),Nt(D(r.dq,"base64url")),Nt(D(r.qi,"base64url"))]).subarray()}function wL(r){let e=Pn(r,{offset:0});return t2(e)}function t2(r){let e=Pn(r[1],{offset:0});return{kty:"RSA",n:P(e[0],"base64url"),e:P(e[1],"base64url")}}function r2(r){if(r.n==null||r.e==null)throw new R("JWK was missing components");return Lr([gL,Lc(Lr([Nt(D(r.n,"base64url")),Nt(D(r.e,"base64url"))]))]).subarray()}function Sv(r){let e=Pn(r);return n2(e)}function n2(r){let e=e2(r);return i2(e)}function s2(r,e){if(r.byteLength>=mL)throw new Xo("Key size is too large");let t=Pn(r,{offset:0});return o2(t,r,e)}function o2(r,e,t){let n=t2(r);if(t==null){let s=Yt(Xr.encode({Type:Je.RSA,Data:e}));t=us(Z0,s)}return new fi(n,t)}function i2(r){if(Cv(r)>J0)throw new R("Key size is too large");let e=Iv(r),t=Yt(Xr.encode({Type:Je.RSA,Data:r2(e.publicKey)})),n=us(Z0,t);return new Fc(e.privateKey,new fi(e.publicKey,n))}async function a2(r){if(r>J0)throw new R("Key size is too large");let e=await Av(r),t=Yt(Xr.encode({Type:Je.RSA,Data:r2(e.publicKey)})),n=us(Z0,t);return new Fc(e.privateKey,new fi(e.publicKey,n))}function Iv(r){if(r==null)throw new R("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var J0,Z0,mL,gL,c2=_(()=>{V();Kc();Nh();te();ce();j0();b0();xv();Q0();J0=8192,Z0=18,mL=1062,gL=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0])});async function Av(r,e){let t=await xL("rsa",{modulusLength:r,publicKeyEncoding:{type:"pkcs1",format:"jwk"},privateKeyEncoding:{type:"pkcs1",format:"jwk"}});return e?.signal?.throwIfAborted(),{privateKey:t.privateKey,publicKey:t.publicKey}}function vv(r,e,t){t?.signal?.throwIfAborted();let n=Jh.default.createSign("RSA-SHA256");if(e instanceof Uint8Array)n.update(e);else for(let s of e)n.update(s);return n.sign({format:"jwk",key:r})}function Ev(r,e,t,n){n?.signal?.throwIfAborted();let s=Jh.default.createVerify("RSA-SHA256");if(t instanceof Uint8Array)s.update(t);else for(let o of t)s.update(o);return s.verify({format:"jwk",key:r},e)}function Cv(r){if(r.kty!=="RSA")throw new R("Invalid key type");if(r.n==null)throw new R("Invalid key modulus");return D(r.n,"base64url").length*8}var Jh,Tv,xL,Q0=_(()=>{Jh=ie(ee("node:crypto"),1),Tv=ee("node:util");V();te();c2();xL=(0,Tv.promisify)(Jh.default.generateKeyPair)});function $c(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function _v(r){if(typeof r=="bigint"){if(!Zh(r))throw new Error("positive bigint expected, got "+r)}else xr(r);return r}function Hc(r){let e=_v(r).toString(16);return e.length&1?"0"+e:e}function Pv(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?u2:BigInt("0x"+r)}function pi(r){return Pv(Ys(r))}function mi(r){return Pv(Ys(td(ge(r)).reverse()))}function ed(r,e){xr(e),r=_v(r);let t=Xs(r.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function qc(r,e){return ed(r,e).reverse()}function td(r){return Uint8Array.from(r)}function vL(r,e,t){return Zh(r)&&Zh(e)&&Zh(t)&&e<=r&&r<t}function Vc(r,e,t,n){if(!vL(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function h2(r){let e;for(e=0;r>u2;r>>=l2,e+=1);return e}function Dv(r,e,t){if(xr(r,"hashLen"),xr(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");let n=g=>new Uint8Array(g),s=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,h=()=>{c.fill(1),l.fill(0),u=0},p=(...g)=>t(l,Rr(c,...g)),f=(g=s)=>{l=p(o,g),c=p(),g.length!==0&&(l=p(i,g),c=p())},d=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let g=0,y=[];for(;g<e;){c=p();let b=c.slice();y.push(b),g+=c.length}return Rr(...y)};return(g,y)=>{h(),f(g);let b;for(;!(b=y(d()));)f();return h(),b}}function Qs(r,e={},t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(o,i,a){let c=r[o];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${l}`)}let s=(o,i)=>Object.entries(o).forEach(([a,c])=>n(a,c,i));s(e,!1),s(t,!0)}function d2(r){let e=new WeakMap;return(t,...n)=>{let s=e.get(t);if(s!==void 0)return s;let o=r(t,...n);return e.set(t,o),o}}var u2,l2,Zh,Gc,Wc=_(()=>{Jr();Jr();u2=BigInt(0),l2=BigInt(1);Zh=r=>typeof r=="bigint"&&u2<=r;Gc=r=>(l2<<BigInt(r))-l2});function Ut(r,e){let t=r%e;return t>=Kt?t:e+t}function Me(r,e,t){let n=r;for(;e-- >Kt;)n*=n,n%=t;return n}function kv(r,e){if(r===Kt)throw new Error("invert: expected non-zero number");if(e<=Kt)throw new Error("invert: expected positive modulus, got "+e);let t=Ut(r,e),n=e,s=Kt,o=_t,i=_t,a=Kt;for(;t!==Kt;){let l=n/t,u=n%t,h=s-i*l,p=o-a*l;n=t,t=u,s=i,o=a,i=h,a=p}if(n!==_t)throw new Error("invert: does not exist");return Ut(s,e)}function p2(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function Uv(r,e){let t=(r.ORDER+_t)/Ov,n=r.pow(e,t);return p2(r,n,e),n}function IL(r,e){let t=(r.ORDER-Rv)/Nv,n=r.mul(e,Js),s=r.pow(n,t),o=r.mul(e,s),i=r.mul(r.mul(o,Js),s),a=r.mul(o,r.sub(i,r.ONE));return p2(r,a,e),a}function AL(r){let e=gi(r),t=Kv(r),n=t(e,e.neg(e.ONE)),s=t(e,n),o=t(e,e.neg(n)),i=(r+EL)/Bv;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,n),h=a.mul(l,s),p=a.mul(l,o),f=a.eql(a.sqr(u),c),d=a.eql(a.sqr(h),c);l=a.cmov(l,u,f),u=a.cmov(p,h,d);let m=a.eql(a.sqr(u),c),g=a.cmov(l,u,m);return p2(a,g,c),g}}function Kv(r){if(r<Mv)throw new Error("sqrt is not defined for small field");let e=r-_t,t=0;for(;e%Js===Kt;)e/=Js,t++;let n=Js,s=gi(r);for(;Lv(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Uv;let o=s.pow(n,e),i=(e+_t)/Js;return function(c,l){if(c.is0(l))return l;if(Lv(c,l)!==1)throw new Error("Cannot find square root");let u=t,h=c.mul(c.ONE,o),p=c.pow(l,e),f=c.pow(l,i);for(;!c.eql(p,c.ONE);){if(c.is0(p))return c.ZERO;let d=1,m=c.sqr(p);for(;!c.eql(m,c.ONE);)if(d++,m=c.sqr(m),d===u)throw new Error("Cannot find square root");let g=_t<<BigInt(u-d-1),y=c.pow(h,g);u=d,h=c.sqr(y),p=c.mul(p,h),f=c.mul(f,y)}return f}}function CL(r){return r%Ov===Mv?Uv:r%Nv===Rv?IL:r%Bv===SL?AL(r):Kv(r)}function m2(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=TL.reduce((n,s)=>(n[s]="function",n),e);return Qs(r,t),r}function _L(r,e,t){if(t<Kt)throw new Error("invalid exponent, negatives unsupported");if(t===Kt)return r.ONE;if(t===_t)return e;let n=r.ONE,s=e;for(;t>Kt;)t&_t&&(n=r.mul(n,s)),s=r.sqr(s),t>>=_t;return n}function jc(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),s=e.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),o=r.inv(s);return e.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),o),n}function Lv(r,e){let t=(r.ORDER-_t)/Js,n=r.pow(e,t),s=r.eql(n,r.ONE),o=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!s&&!o&&!i)throw new Error("invalid Legendre symbol result");return s?1:o?0:-1}function PL(r,e){e!==void 0&&xr(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function gi(r,e={}){return new f2(r,e)}function Fv(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function g2(r){let e=Fv(r);return e+Math.ceil(e/2)}function y2(r,e,t=!1){ge(r);let n=r.length,s=Fv(e),o=g2(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=t?mi(r):pi(r),a=Ut(i,e-_t)+_t;return t?qc(a,s):ed(a,s)}var Kt,_t,Js,Mv,Ov,Rv,EL,Nv,SL,Bv,TL,f2,yi=_(()=>{Wc();Kt=BigInt(0),_t=BigInt(1),Js=BigInt(2),Mv=BigInt(3),Ov=BigInt(4),Rv=BigInt(5),EL=BigInt(7),Nv=BigInt(8),SL=BigInt(9),Bv=BigInt(16);TL=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];f2=class{ORDER;BITS;BYTES;isLE;ZERO=Kt;ONE=_t;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=Kt)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:s,nByteLength:o}=PL(e,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=s,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return Ut(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return Kt<=e&&e<this.ORDER}is0(e){return e===Kt}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&_t)===_t}neg(e){return Ut(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return Ut(e*e,this.ORDER)}add(e,t){return Ut(e+t,this.ORDER)}sub(e,t){return Ut(e-t,this.ORDER)}mul(e,t){return Ut(e*t,this.ORDER)}pow(e,t){return _L(this,e,t)}div(e,t){return Ut(e*kv(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return kv(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=CL(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?qc(e,this.BYTES):ed(e,this.BYTES)}fromBytes(e,t=!1){ge(e);let{_lengths:n,BYTES:s,isLE:o,ORDER:i,_mod:a}=this;if(n){if(!n.includes(e.length)||e.length>s)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(s);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let c=o?mi(e):pi(e);if(a&&(c=Ut(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return jc(this,e)}cmov(e,t,n){return n?t:e}}});function Yc(r,e){let t=e.negate();return r?t:e}function v2(r,e){let t=jc(r.Fp,e.map(n=>n.Z));return e.map((n,s)=>r.fromAffine(n.toAffine(t[s])))}function qv(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function b2(r,e){qv(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),s=2**r,o=Gc(r),i=BigInt(r);return{windows:t,windowSize:n,mask:o,maxNumber:s,shiftBy:i}}function zv(r,e,t){let{windowSize:n,mask:s,maxNumber:o,shiftBy:i}=t,a=Number(r&s),c=r>>i;a>n&&(a-=o,c+=Zs);let l=e*n,u=l+Math.abs(a)-1,h=a===0,p=a<0,f=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:p,isNegF:f,offsetF:l}}function x2(r){return Vv.get(r)||1}function $v(r){if(r!==bi)throw new Error("invalid wNAF")}function Gv(r,e,t,n){let s=e,o=r.ZERO,i=r.ZERO;for(;t>bi||n>bi;)t&Zs&&(o=o.add(s)),n&Zs&&(i=i.add(s)),s=s.double(),t>>=Zs,n>>=Zs;return{p1:o,p2:i}}function Hv(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return m2(e),e}else return gi(r,{isLE:t})}function Wv(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>bi))throw new Error(`CURVE.${c} must be positive bigint`)}let s=Hv(e.p,t.Fp,n),o=Hv(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!s.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:s,Fn:o}}function nd(r,e){return function(n){let s=r(n);return{secretKey:s,publicKey:e(s)}}}var bi,Zs,w2,Vv,rd,E2=_(()=>{Wc();yi();bi=BigInt(0),Zs=BigInt(1);w2=new WeakMap,Vv=new WeakMap;rd=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let s=e;for(;t>bi;)t&Zs&&(n=n.add(s)),s=s.double(),t>>=Zs;return n}precomputeWindow(e,t){let{windows:n,windowSize:s}=b2(t,this.bits),o=[],i=e,a=i;for(let c=0;c<n;c++){a=i,o.push(a);for(let l=1;l<s;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE,i=b2(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:h,isNegF:p,offsetF:f}=zv(n,a,i);n=c,u?o=o.add(Yc(p,t[f])):s=s.add(Yc(h,t[l]))}return $v(n),{p:s,f:o}}wNAFUnsafe(e,t,n,s=this.ZERO){let o=b2(e,this.bits);for(let i=0;i<o.windows&&n!==bi;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=zv(n,i,o);if(n=a,!l){let h=t[c];s=s.add(u?h.negate():h)}}return $v(n),s}getPrecomputes(e,t,n){let s=w2.get(t);return s||(s=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(s=n(s)),w2.set(t,s))),s}cached(e,t,n){let s=x2(e);return this.wNAF(s,this.getPrecomputes(s,e,n),t)}unsafe(e,t,n,s){let o=x2(e);return o===1?this._unsafeLadder(e,t,s):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),t,s)}createCache(e,t){qv(t,this.bits),Vv.set(e,t),w2.delete(e)}hasCache(e){return x2(e)!==1}}});var sd,wi,S2=_(()=>{Jr();sd=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(js(e),ge(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,s=new Uint8Array(n);s.set(t.length>n?e.create().update(t).digest():t);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),kn(s)}update(e){return di(this),this.iHash.update(e),this}digestInto(e){di(this),ge(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:s,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},wi=(r,e,t)=>new sd(r,e).update(t).digest();wi.create=(r,e)=>new sd(r,e)});function DL(r,e,t){let[[n,s],[o,i]]=e,a=jv(i*r,t),c=jv(-s*r,t),l=r-a*n-c*o,u=-a*s-c*i,h=l<Mn,p=u<Mn;h&&(l=-l),p&&(u=-u);let f=Gc(Math.ceil(h2(t)/2))+xi;if(l<Mn||l>=f||u<Mn||u>=f)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:h,k1:l,k2neg:p,k2:u}}function A2(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function I2(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return $c(t.lowS,"lowS"),$c(t.prehash,"prehash"),t.format!==void 0&&A2(t.format),t}function Xv(r,e={}){let t=Wv("weierstrass",r,e),{Fp:n,Fn:s}=t,o=t.CURVE,{h:i,n:a}=o;Qs(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!n.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=Jv(n,s);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(H,L,C){let{x:T,y:M}=L.toAffine(),B=n.toBytes(T);if($c(C,"isCompressed"),C){u();let N=!n.isOdd(M);return Rr(Qv(N),B)}else return Rr(Uint8Array.of(4),B,n.toBytes(M))}function p(H){ge(H,void 0,"Point");let{publicKey:L,publicKeyUncompressed:C}=l,T=H.length,M=H[0],B=H.subarray(1);if(T===L&&(M===2||M===3)){let N=n.fromBytes(B);if(!n.isValid(N))throw new Error("bad point: is not on curve, wrong x");let k=m(N),O;try{O=n.sqrt(k)}catch(ve){let ue=ve instanceof Error?": "+ve.message:"";throw new Error("bad point: is not on curve, sqrt error"+ue)}u();let K=n.isOdd(O);return(M&1)===1!==K&&(O=n.neg(O)),{x:N,y:O}}else if(T===C&&M===4){let N=n.BYTES,k=n.fromBytes(B.subarray(0,N)),O=n.fromBytes(B.subarray(N,N*2));if(!g(k,O))throw new Error("bad point: is not on curve");return{x:k,y:O}}else throw new Error(`bad point: got length ${T}, expected compressed=${L} or uncompressed=${C}`)}let f=e.toBytes||h,d=e.fromBytes||p;function m(H){let L=n.sqr(H),C=n.mul(L,H);return n.add(n.add(C,n.mul(H,o.a)),o.b)}function g(H,L){let C=n.sqr(L),T=m(H);return n.eql(C,T)}if(!g(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let y=n.mul(n.pow(o.a,od),kL),b=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(y,b)))throw new Error("bad curve params: a or b");function w(H,L,C=!1){if(!n.isValid(L)||C&&n.is0(L))throw new Error(`bad point coordinate ${H}`);return L}function x(H){if(!(H instanceof A))throw new Error("Weierstrass Point expected")}function v(H){if(!c||!c.basises)throw new Error("no endo");return DL(H,c.basises,s.ORDER)}let S=d2((H,L)=>{let{X:C,Y:T,Z:M}=H;if(n.eql(M,n.ONE))return{x:C,y:T};let B=H.is0();L==null&&(L=B?n.ONE:n.inv(M));let N=n.mul(C,L),k=n.mul(T,L),O=n.mul(M,L);if(B)return{x:n.ZERO,y:n.ZERO};if(!n.eql(O,n.ONE))throw new Error("invZ was invalid");return{x:N,y:k}}),E=d2(H=>{if(H.is0()){if(e.allowInfinityPoint&&!n.is0(H.Y))return;throw new Error("bad point: ZERO")}let{x:L,y:C}=H.toAffine();if(!n.isValid(L)||!n.isValid(C))throw new Error("bad point: x or y not field elements");if(!g(L,C))throw new Error("bad point: equation left != right");if(!H.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function I(H,L,C,T,M){return C=new A(n.mul(C.X,H),C.Y,C.Z),L=Yc(T,L),C=Yc(M,C),L.add(C)}class A{static BASE=new A(o.Gx,o.Gy,n.ONE);static ZERO=new A(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=s;X;Y;Z;constructor(L,C,T){this.X=w("x",L),this.Y=w("y",C,!0),this.Z=w("z",T),Object.freeze(this)}static CURVE(){return o}static fromAffine(L){let{x:C,y:T}=L||{};if(!L||!n.isValid(C)||!n.isValid(T))throw new Error("invalid affine point");if(L instanceof A)throw new Error("projective point not allowed");return n.is0(C)&&n.is0(T)?A.ZERO:new A(C,T,n.ONE)}static fromBytes(L){let C=A.fromAffine(d(ge(L,void 0,"point")));return C.assertValidity(),C}static fromHex(L){return A.fromBytes(Xs(L))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(L=8,C=!0){return ne.createCache(this,L),C||this.multiply(od),this}assertValidity(){E(this)}hasEvenY(){let{y:L}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(L)}equals(L){x(L);let{X:C,Y:T,Z:M}=this,{X:B,Y:N,Z:k}=L,O=n.eql(n.mul(C,k),n.mul(B,M)),K=n.eql(n.mul(T,k),n.mul(N,M));return O&&K}negate(){return new A(this.X,n.neg(this.Y),this.Z)}double(){let{a:L,b:C}=o,T=n.mul(C,od),{X:M,Y:B,Z:N}=this,k=n.ZERO,O=n.ZERO,K=n.ZERO,F=n.mul(M,M),ve=n.mul(B,B),ue=n.mul(N,N),se=n.mul(M,B);return se=n.add(se,se),K=n.mul(M,N),K=n.add(K,K),k=n.mul(L,K),O=n.mul(T,ue),O=n.add(k,O),k=n.sub(ve,O),O=n.add(ve,O),O=n.mul(k,O),k=n.mul(se,k),K=n.mul(T,K),ue=n.mul(L,ue),se=n.sub(F,ue),se=n.mul(L,se),se=n.add(se,K),K=n.add(F,F),F=n.add(K,F),F=n.add(F,ue),F=n.mul(F,se),O=n.add(O,F),ue=n.mul(B,N),ue=n.add(ue,ue),F=n.mul(ue,se),k=n.sub(k,F),K=n.mul(ue,ve),K=n.add(K,K),K=n.add(K,K),new A(k,O,K)}add(L){x(L);let{X:C,Y:T,Z:M}=this,{X:B,Y:N,Z:k}=L,O=n.ZERO,K=n.ZERO,F=n.ZERO,ve=o.a,ue=n.mul(o.b,od),se=n.mul(C,B),pe=n.mul(T,N),Te=n.mul(M,k),Qe=n.add(C,T),be=n.add(B,N);Qe=n.mul(Qe,be),be=n.add(se,pe),Qe=n.sub(Qe,be),be=n.add(C,M);let et=n.add(B,k);return be=n.mul(be,et),et=n.add(se,Te),be=n.sub(be,et),et=n.add(T,M),O=n.add(N,k),et=n.mul(et,O),O=n.add(pe,Te),et=n.sub(et,O),F=n.mul(ve,be),O=n.mul(ue,Te),F=n.add(O,F),O=n.sub(pe,F),F=n.add(pe,F),K=n.mul(O,F),pe=n.add(se,se),pe=n.add(pe,se),Te=n.mul(ve,Te),be=n.mul(ue,be),pe=n.add(pe,Te),Te=n.sub(se,Te),Te=n.mul(ve,Te),be=n.add(be,Te),se=n.mul(pe,be),K=n.add(K,se),se=n.mul(et,be),O=n.mul(Qe,O),O=n.sub(O,se),se=n.mul(Qe,pe),F=n.mul(et,F),F=n.add(F,se),new A(O,K,F)}subtract(L){return this.add(L.negate())}is0(){return this.equals(A.ZERO)}multiply(L){let{endo:C}=e;if(!s.isValidNot0(L))throw new Error("invalid scalar: out of range");let T,M,B=N=>ne.cached(this,N,k=>v2(A,k));if(C){let{k1neg:N,k1:k,k2neg:O,k2:K}=v(L),{p:F,f:ve}=B(k),{p:ue,f:se}=B(K);M=ve.add(se),T=I(C.beta,F,ue,N,O)}else{let{p:N,f:k}=B(L);T=N,M=k}return v2(A,[T,M])[0]}multiplyUnsafe(L){let{endo:C}=e,T=this;if(!s.isValid(L))throw new Error("invalid scalar: out of range");if(L===Mn||T.is0())return A.ZERO;if(L===xi)return T;if(ne.hasCache(this))return this.multiply(L);if(C){let{k1neg:M,k1:B,k2neg:N,k2:k}=v(L),{p1:O,p2:K}=Gv(A,T,B,k);return I(C.beta,O,K,M,N)}else return ne.unsafe(T,L)}toAffine(L){return S(this,L)}isTorsionFree(){let{isTorsionFree:L}=e;return i===xi?!0:L?L(A,this):ne.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:L}=e;return i===xi?this:L?L(A,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(L=!0){return $c(L,"isCompressed"),this.assertValidity(),f(A,this,L)}toHex(L=!0){return Ys(this.toBytes(L))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let X=s.BITS,ne=new rd(A,e.endo?Math.ceil(X/2):X);return A.BASE.precompute(8),A}function Qv(r){return Uint8Array.of(r?2:3)}function Jv(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function LL(r,e={}){let{Fn:t}=r,n=e.randomBytes||Qr,s=Object.assign(Jv(r.Fp,t),{seed:g2(t.ORDER)});function o(f){try{let d=t.fromBytes(f);return t.isValidNot0(d)}catch{return!1}}function i(f,d){let{publicKey:m,publicKeyUncompressed:g}=s;try{let y=f.length;return d===!0&&y!==m||d===!1&&y!==g?!1:!!r.fromBytes(f)}catch{return!1}}function a(f=n(s.seed)){return y2(ge(f,s.seed,"seed"),t.ORDER)}function c(f,d=!0){return r.BASE.multiply(t.fromBytes(f)).toBytes(d)}function l(f){let{secretKey:d,publicKey:m,publicKeyUncompressed:g}=s;if(!Uc(f)||"_lengths"in t&&t._lengths||d===m)return;let y=ge(f,void 0,"key").length;return y===m||y===g}function u(f,d,m=!0){if(l(f)===!0)throw new Error("first arg must be private key");if(l(d)===!1)throw new Error("second arg must be public key");let g=t.fromBytes(f);return r.fromBytes(d).multiply(g).toBytes(m)}let h={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},p=nd(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:p,Point:r,utils:h,lengths:s})}function Zv(r,e,t={}){js(e),Qs(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes||Qr,s=t.hmac||((C,T)=>wi(e,C,T)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:p,lengths:f}=LL(r,t),d={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},m=a*Yv<o.ORDER;function g(C){let T=a>>xi;return C>T}function y(C,T){if(!i.isValidNot0(T))throw new Error(`invalid signature ${C}: out of range 1..Point.Fn.ORDER`);return T}function b(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function w(C,T){A2(T);let M=f.signature,B=T==="compact"?M:T==="recovered"?M+1:void 0;return ge(C,B)}class x{r;s;recovery;constructor(T,M,B){if(this.r=y("r",T),this.s=y("s",M),B!=null){if(b(),![0,1,2,3].includes(B))throw new Error("invalid recovery id");this.recovery=B}Object.freeze(this)}static fromBytes(T,M=d.format){w(T,M);let B;if(M==="der"){let{r:K,s:F}=ms.toSig(ge(T));return new x(K,F)}M==="recovered"&&(B=T[0],M="compact",T=T.subarray(1));let N=f.signature/2,k=T.subarray(0,N),O=T.subarray(N,N*2);return new x(i.fromBytes(k),i.fromBytes(O),B)}static fromHex(T,M){return this.fromBytes(Xs(T),M)}assertRecovery(){let{recovery:T}=this;if(T==null)throw new Error("invalid recovery id: must be present");return T}addRecoveryBit(T){return new x(this.r,this.s,T)}recoverPublicKey(T){let{r:M,s:B}=this,N=this.assertRecovery(),k=N===2||N===3?M+a:M;if(!o.isValid(k))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let O=o.toBytes(k),K=r.fromBytes(Rr(Qv((N&1)===0),O)),F=i.inv(k),ve=S(ge(T,void 0,"msgHash")),ue=i.create(-ve*F),se=i.create(B*F),pe=r.BASE.multiplyUnsafe(ue).add(K.multiplyUnsafe(se));if(pe.is0())throw new Error("invalid recovery: point at infinify");return pe.assertValidity(),pe}hasHighS(){return g(this.s)}toBytes(T=d.format){if(A2(T),T==="der")return Xs(ms.hexFromSig(this));let{r:M,s:B}=this,N=i.toBytes(M),k=i.toBytes(B);return T==="recovered"?(b(),Rr(Uint8Array.of(this.assertRecovery()),N,k)):Rr(N,k)}toHex(T){return Ys(this.toBytes(T))}}let v=t.bits2int||function(T){if(T.length>8192)throw new Error("input is too large");let M=pi(T),B=T.length*8-c;return B>0?M>>BigInt(B):M},S=t.bits2int_modN||function(T){return i.create(v(T))},E=Gc(c);function I(C){return Vc("num < 2^"+c,C,Mn,E),i.toBytes(C)}function A(C,T){return ge(C,void 0,"message"),T?ge(e(C),void 0,"prehashed message"):C}function X(C,T,M){let{lowS:B,prehash:N,extraEntropy:k}=I2(M,d);C=A(C,N);let O=S(C),K=i.fromBytes(T);if(!i.isValidNot0(K))throw new Error("invalid private key");let F=[I(K),I(O)];if(k!=null&&k!==!1){let pe=k===!0?n(f.secretKey):k;F.push(ge(pe,void 0,"extraEntropy"))}let ve=Rr(...F),ue=O;function se(pe){let Te=v(pe);if(!i.isValidNot0(Te))return;let Qe=i.inv(Te),be=r.BASE.multiply(Te).toAffine(),et=i.create(be.x);if(et===Mn)return;let Wo=i.create(Qe*i.create(ue+et*K));if(Wo===Mn)return;let ih=(be.x===et?0:2)|Number(be.y&xi),ac=Wo;return B&&g(Wo)&&(ac=i.neg(Wo),ih^=1),new x(et,ac,m?void 0:ih)}return{seed:ve,k2sig:se}}function ne(C,T,M={}){let{seed:B,k2sig:N}=X(C,T,M);return Dv(e.outputLen,i.BYTES,s)(B,N).toBytes(M.format)}function H(C,T,M,B={}){let{lowS:N,prehash:k,format:O}=I2(B,d);if(M=ge(M,void 0,"publicKey"),T=A(T,k),!Uc(C)){let K=C instanceof x?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+K)}w(C,O);try{let K=x.fromBytes(C,O),F=r.fromBytes(M);if(N&&K.hasHighS())return!1;let{r:ve,s:ue}=K,se=S(T),pe=i.inv(ue),Te=i.create(se*pe),Qe=i.create(ve*pe),be=r.BASE.multiplyUnsafe(Te).add(F.multiplyUnsafe(Qe));return be.is0()?!1:i.create(be.x)===ve}catch{return!1}}function L(C,T,M={}){let{prehash:B}=I2(M,d);return T=A(T,B),x.fromBytes(C,"recovered").recoverPublicKey(T).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:h,utils:p,lengths:f,Point:r,sign:ne,verify:H,recoverPublicKey:L,Signature:x,hash:e})}var jv,C2,ms,Mn,xi,Yv,od,kL,eE=_(()=>{S2();Jr();Wc();E2();yi();jv=(r,e)=>(r+(r>=0?e:-e)/Yv)/e;C2=class extends Error{constructor(e=""){super(e)}},ms={Err:C2,_tlv:{encode:(r,e)=>{let{Err:t}=ms;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,s=Hc(n);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let o=n>127?Hc(s.length/2|128):"";return Hc(r)+o+s+e},decode(r,e){let{Err:t}=ms,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let s=e[n++],o=!!(s&128),i=0;if(!o)i=s;else{let c=s&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=ms;if(r<Mn)throw new e("integer: negative integers are not allowed");let t=Hc(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=ms;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return pi(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=ms,s=ge(r,void 0,"signature"),{v:o,l:i}=n.decode(48,s);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,o),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=ms,n=e.encode(2,t.encode(r.r)),s=e.encode(2,t.encode(r.s)),o=n+s;return e.encode(48,o)}},Mn=BigInt(0),xi=BigInt(1),Yv=BigInt(2),od=BigInt(3),kL=BigInt(4)});function OL(r){let e=_2.p,t=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,h=Me(u,t,e)*u%e,p=Me(h,t,e)*u%e,f=Me(p,tE,e)*l%e,d=Me(f,s,e)*f%e,m=Me(d,o,e)*d%e,g=Me(m,a,e)*m%e,y=Me(g,c,e)*g%e,b=Me(y,a,e)*m%e,w=Me(b,t,e)*u%e,x=Me(w,i,e)*d%e,v=Me(x,n,e)*l%e,S=Me(v,tE,e);if(!T2.eql(T2.sqr(S),r))throw new Error("Cannot find square root");return S}var _2,ML,tE,T2,RL,st,eo=_(()=>{Kc();yi();eE();_2={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},ML={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},tE=BigInt(2);T2=gi(_2.p,{sqrt:OL}),RL=Xv(_2,{Fp:T2,endo:ML}),st=Zv(RL,Yt)});var id,ad,rE=_(()=>{id=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},ad=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}});function nE(r,e,t){t?.signal?.throwIfAborted();let n=P2.default.createHash("sha256");if(e instanceof Uint8Array)n.update(e);else for(let o of e)n.update(o);let s=n.digest();try{return st.sign(s,r,{prehash:!1,format:"der"})}catch(o){throw new id(String(o))}}function sE(r,e,t,n){n?.signal?.throwIfAborted();let s=P2.default.createHash("sha256");if(t instanceof Uint8Array)s.update(t);else for(let i of t)s.update(i);let o=s.digest();try{return st.verify(e,o,r,{prehash:!1,format:"der"})}catch(i){throw new ad(String(i))}}var P2,oE=_(()=>{P2=ie(ee("node:crypto"),1);eo();rE()});var Xc,cd,iE=_(()=>{ei();Sc();Bh();Ne();Bt();D2();oE();Xc=class{type="secp256k1";raw;_key;constructor(e){this._key=lE(e),this.raw=aE(this._key)}toMultihash(){return si.digest(dt(this))}toCID(){return jr.createV1(114,this.toMultihash())}toString(){return wt.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){return sE(this._key,t,e,n)}},cd=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=cE(e),this.publicKey=new Xc(t??uE(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}sign(e,t){return nE(this.raw,e,t)}}});function k2(r){return new Xc(r)}async function hE(){let r=NL();return new cd(r)}function aE(r){return st.Point.fromBytes(r).toBytes()}function cE(r){try{return st.getPublicKey(r,!0),r}catch(e){throw new hc(String(e))}}function lE(r){try{return st.Point.fromBytes(r),r}catch(e){throw new Xo(String(e))}}function uE(r){try{return st.getPublicKey(r,!0)}catch(e){throw new hc(String(e))}}function NL(){return st.utils.randomSecretKey()}var D2=_(()=>{V();eo();iE()});async function dE(r,e){if(r==="Ed25519")return X4();if(r==="secp256k1")return hE();if(r==="RSA")return a2(BL(e));if(r==="ECDSA")return $4(UL(e));throw new is}function Ft(r,e){let{Type:t,Data:n}=Xr.decode(r),s=n??new Uint8Array;switch(t){case Je.RSA:return s2(s,e);case Je.Ed25519:return _0(s);case Je.secp256k1:return k2(s);case Je.ECDSA:return S0(s);default:throw new is}}function fE(r){let{Type:e,Data:t}=Xr.decode(r.digest),n=t??new Uint8Array;switch(e){case Je.Ed25519:return _0(n);case Je.secp256k1:return k2(n);case Je.ECDSA:return S0(n);default:throw new is}}function dt(r){return Xr.encode({Type:Je[r.type],Data:r.raw})}function BL(r){return r==null?2048:parseInt(r,10)}function UL(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new R("Unsupported curve, should be P-256, P-384 or P-521")}var Bt=_(()=>{V();I0();T0();j0();c2();D2()});function pE(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Nr(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var Lee,vi=_(()=>{Lee=new Uint8Array(0)});function KL(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var v=d[y],S=0,E=w-1;(v!==0||S<g)&&E!==-1;E--,S++)v+=256*x[E]>>>0,x[E]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var A=c.repeat(m);I<w;++I)A+=r.charAt(x[I]);return A}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*w[S]>>>0,w[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(d[m]!==" "){for(var E=b-y;E!==b&&w[E]===0;)E++;for(var I=new Uint8Array(g+(b-E)),A=g;E!==b;)I[A++]=w[E++];return I}}}function f(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:f}}var FL,zL,mE,gE=_(()=>{FL=KL,zL=FL,mE=zL});function yE(r,e){return new O2({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}function bE({name:r,prefix:e,encode:t,decode:n}){return new R2(r,e,t,n)}function Ei({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=mE(t,r);return bE({prefix:e,name:r,encode:n,decode:o=>Nr(s(o))})}function $L(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function HL(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function qL(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Zr({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=qL(n);return bE({prefix:e,name:r,encode(o){return HL(o,n,t)},decode(o){return $L(o,s,t,r)}})}var L2,M2,O2,R2,ld=_(()=>{vi();gE();L2=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},M2=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return yE(this,e)}},O2=class{decoders;constructor(e){this.decoders=e}or(e){return yE(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};R2=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new L2(e,t,n),this.decoder=new M2(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}});var or,Kee,ud=_(()=>{ld();or=Ei({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Kee=Ei({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var Qc,$ee,Hee,qee,Vee,Gee,Wee,jee,Yee,wE=_(()=>{ld();Qc=Zr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),$ee=Zr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Hee=Zr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),qee=Zr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Vee=Zr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Gee=Zr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Wee=Zr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),jee=Zr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Yee=Zr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var hd,Jee,xE=_(()=>{ld();hd=Ei({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Jee=Ei({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});function SE(r,e,t){e=e||[],t=t||0;for(var n=t;r>=jL;)e[t++]=r&255|vE,r/=128;for(;r&WL;)e[t++]=r&255|vE,r>>>=7;return e[t]=r|0,SE.bytes=t-n+1,e}function N2(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw N2.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&EE)<<s:(i&EE)*Math.pow(2,s),s+=7}while(i>=XL);return N2.bytes=o-n,t}var VL,vE,GL,WL,jL,YL,XL,EE,QL,JL,ZL,eM,tM,rM,nM,sM,oM,iM,aM,cM,Jc,IE=_(()=>{VL=SE,vE=128,GL=127,WL=~GL,jL=Math.pow(2,31);YL=N2,XL=128,EE=127;QL=Math.pow(2,7),JL=Math.pow(2,14),ZL=Math.pow(2,21),eM=Math.pow(2,28),tM=Math.pow(2,35),rM=Math.pow(2,42),nM=Math.pow(2,49),sM=Math.pow(2,56),oM=Math.pow(2,63),iM=function(r){return r<QL?1:r<JL?2:r<ZL?3:r<eM?4:r<tM?5:r<rM?6:r<nM?7:r<sM?8:r<oM?9:10},aM={encode:VL,decode:YL,encodingLength:iM},cM=aM,Jc=cM});function Zc(r,e=0){return[Jc.decode(r,e),Jc.decode.bytes]}function Si(r,e,t=0){return Jc.encode(r,e,t),e}function Ii(r){return Jc.encodingLength(r)}var B2=_(()=>{IE()});function Ci(r,e){let t=e.byteLength,n=Ii(r),s=n+Ii(t),o=new Uint8Array(s+t);return Si(r,o,0),Si(t,o,n),o.set(e,s),new Ai(r,t,e,o)}function el(r){let e=Nr(r),[t,n]=Zc(e),[s,o]=Zc(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Ai(t,s,i,e)}function CE(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&pE(r.bytes,t.bytes)}}var Ai,tl=_(()=>{vi();B2();Ai=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}}});var TE=_(()=>{});function _E(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return uM(t,U2(r),e??or.encoder);default:return hM(t,U2(r),e??Qc.encoder)}}function U2(r){let e=PE.get(r);if(e==null){let t=new Map;return PE.set(r,t),t}return e}function lM(r,e){switch(r[0]){case"Q":{let t=e??or;return[or.prefix,t.decode(`${or.prefix}${r}`)]}case or.prefix:{let t=e??or;return[or.prefix,t.decode(r)]}case Qc.prefix:{let t=e??Qc;return[Qc.prefix,t.decode(r)]}case hd.prefix:{let t=e??hd;return[hd.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function uM(r,e,t){let{prefix:n}=t;if(n!==or.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function hM(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}function DE(r,e,t){let n=Ii(r),s=n+Ii(e),o=new Uint8Array(s+t.byteLength);return Si(r,o,0),Si(e,o,n),o.set(t,s),o}var PE,to,rl,dM,fM,K2=_(()=>{wE();xE();ud();vi();tl();B2();TE();PE=new WeakMap;to=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==rl)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==dM)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Ci(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&CE(e.multihash,n.multihash)}toString(e){return _E(this,e)}toJSON(){return{"/":_E(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??DE(n,s,o.bytes))}else if(t[fM]===!0){let{version:n,multihash:s,code:o}=t,i=el(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==rl)throw new Error(`Version 0 CID must use dag-pb (code: ${rl}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=DE(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,rl,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=Nr(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new Ai(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,p]=Zc(e.subarray(t));return t+=p,h},s=n(),o=rl;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=lM(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return U2(o).set(n,e),o}};rl=112,dM=18;fM=Symbol.for("@ipld/js-cid/CID")});function mM(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Ci(kE,LE(r))}var kE,pM,LE,fd,F2=_(()=>{vi();tl();kE=0,pM="identity",LE=Nr;fd={code:kE,name:pM,encode:LE,digest:mM}});function $2({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new z2(r,e,t,n,s)}function ME(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Ci(e,r)}var gM,z2,OE=_(()=>{tl();gM=20;z2=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??gM,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?ME(n,this.code,t?.truncate):n.then(s=>ME(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}}});var H2,RE,pte,NE=_(()=>{H2=ie(ee("crypto"),1);vi();OE();RE=$2({name:"sha2-256",code:18,encode:r=>Nr(H2.default.createHash("sha256").update(r).digest())}),pte=$2({name:"sha2-512",code:19,encode:r=>Nr(H2.default.createHash("sha512").update(r).digest())})});var BE,yM,nl,sl,ol,il,bM,al,UE=_(()=>{V();ud();K2();F2();Ne();te();ce();BE=Symbol.for("nodejs.util.inspect.custom"),yM=114,nl=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Ph]=!0;toString(){return this.string==null&&(this.string=or.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return to.createV1(yM,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return W(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return W(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[BE](){return`PeerId(${this.toString()})`}},sl=class extends nl{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},ol=class extends nl{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},il=class extends nl{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},bM=2336,al=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=fd.digest(D(this.url))}[BE](){return`PeerId(${this.url})`}[Ph]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return to.createV1(bM,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=P(e)),e.toString()===this.toString())}}});var V2={};z(V2,{peerIdFromCID:()=>en,peerIdFromMultihash:()=>Br,peerIdFromPrivateKey:()=>q2,peerIdFromPublicKey:()=>On,peerIdFromString:()=>de});function de(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=el(or.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return en(to.parse(r));if(e==null)throw new R('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=el(e.decode(r))}return Br(t)}function On(r){if(r.type==="Ed25519")return new ol({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new il({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new sl({multihash:r.toCID().multihash,publicKey:r});throw new is}function q2(r){return On(r.publicKey)}function Br(r){if(vM(r))return new sl({multihash:r});if(xM(r))try{let e=fE(r);if(e.type==="Ed25519")return new ol({multihash:r,publicKey:e});if(e.type==="secp256k1")return new il({multihash:r,publicKey:e})}catch{let t=P(r.digest);return new al(new URL(t))}throw new vh("Supplied PeerID Multihash is invalid")}function en(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==wM&&r.code!==KE)throw new xh("Supplied PeerID CID is invalid");if(r.code===KE){let e=P(r.multihash.digest);return new al(new URL(e))}return Br(r.multihash)}function xM(r){return r.code===fd.code}function vM(r){return r.code===RE.code}var wM,KE,ke=_(()=>{Bt();V();ud();K2();tl();F2();NE();ce();UE();wM=114,KE=2336});var Tg=_(()=>{"use strict"});var PS=At((Rie,_S)=>{var Oi=1e3,Ri=Oi*60,Ni=Ri*60,oo=Ni*24,VR=oo*7,GR=oo*365.25;_S.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return WR(r);if(t==="number"&&isFinite(r))return e.long?YR(r):jR(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function WR(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*GR;case"weeks":case"week":case"w":return t*VR;case"days":case"day":case"d":return t*oo;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Ni;case"minutes":case"minute":case"mins":case"min":case"m":return t*Ri;case"seconds":case"second":case"secs":case"sec":case"s":return t*Oi;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function jR(r){var e=Math.abs(r);return e>=oo?Math.round(r/oo)+"d":e>=Ni?Math.round(r/Ni)+"h":e>=Ri?Math.round(r/Ri)+"m":e>=Oi?Math.round(r/Oi)+"s":r+"ms"}function YR(r){var e=Math.abs(r);return e>=oo?xd(r,e,oo,"day"):e>=Ni?xd(r,e,Ni,"hour"):e>=Ri?xd(r,e,Ri,"minute"):e>=Oi?xd(r,e,Oi,"second"):r+" ms"}function xd(r,e,t,n){var s=e>=t*1.5;return Math.round(r/t)+" "+n+(s?"s":"")}});var $g=At((Nie,DS)=>{function XR(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=s,t.enabled=a,t.humanize=PS(),t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let h=0;for(let p=0;p<u.length;p++)h=(h<<5)-h+u.charCodeAt(p),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(u){let h,p=null,f,d;function m(...g){if(!m.enabled)return;let y=m,b=Number(new Date),w=b-(h||b);y.diff=w,y.prev=h,y.curr=b,h=b,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let x=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(S,E)=>{if(S==="%%")return"%";x++;let I=t.formatters[E];if(typeof I=="function"){let A=g[x];S=I.call(y,A),g.splice(x,1),x--}return S}),t.formatArgs.call(y,g),(y.log||t.log).apply(y,g)}return m.namespace=u,m.useColors=t.useColors(),m.color=t.selectColor(u),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(f!==t.namespaces&&(f=t.namespaces,d=t.enabled(u)),d),set:g=>{p=g}}),typeof t.init=="function"&&t.init(m),m}function n(u,h){let p=t(this.namespace+(typeof h>"u"?":":h)+u);return p.log=this.log,p}function s(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let h=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let p of h)p[0]==="-"?t.skips.push(p.slice(1)):t.names.push(p)}function o(u,h){let p=0,f=0,d=-1,m=0;for(;p<u.length;)if(f<h.length&&(h[f]===u[p]||h[f]==="*"))h[f]==="*"?(d=f,m=p,f++):(p++,f++);else if(d!==-1)f=d+1,m++,p=m;else return!1;for(;f<h.length&&h[f]==="*";)f++;return f===h.length}function i(){let u=[...t.names,...t.skips.map(h=>"-"+h)].join(",");return t.enable(""),u}function a(u){for(let h of t.skips)if(o(u,h))return!1;for(let h of t.names)if(o(u,h))return!0;return!1}function c(u){return u instanceof Error?u.stack||u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}DS.exports=XR});var kS=At((Qt,vd)=>{Qt.formatArgs=JR;Qt.save=ZR;Qt.load=e9;Qt.useColors=QR;Qt.storage=t9();Qt.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Qt.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function QR(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let r;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function JR(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+vd.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(n=t))}),r.splice(n,0,e)}Qt.log=console.debug||console.log||(()=>{});function ZR(r){try{r?Qt.storage.setItem("debug",r):Qt.storage.removeItem("debug")}catch{}}function e9(){let r;try{r=Qt.storage.getItem("debug")||Qt.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function t9(){try{return localStorage}catch{}}vd.exports=$g()(Qt);var{formatters:r9}=vd.exports;r9.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var MS={};z(MS,{createSupportsColor:()=>qg,default:()=>pl});function Er(r,e=globalThis.Deno?globalThis.Deno.args:Sd.default.argv){let t=r.startsWith("-")?"":r.length===1?"-":"--",n=e.indexOf(t+r),s=e.indexOf("--");return n!==-1&&(s===-1||n<s)}function n9(){if(!("FORCE_COLOR"in Ke))return;if(Ke.FORCE_COLOR==="true")return 1;if(Ke.FORCE_COLOR==="false")return 0;if(Ke.FORCE_COLOR.length===0)return 1;let r=Math.min(Number.parseInt(Ke.FORCE_COLOR,10),3);if([0,1,2,3].includes(r))return r}function s9(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function o9(r,{streamIsTTY:e,sniffFlags:t=!0}={}){let n=n9();n!==void 0&&(Ed=n);let s=t?Ed:n;if(s===0)return 0;if(t){if(Er("color=16m")||Er("color=full")||Er("color=truecolor"))return 3;if(Er("color=256"))return 2}if("TF_BUILD"in Ke&&"AGENT_NAME"in Ke)return 1;if(r&&!e&&s===void 0)return 0;let o=s||0;if(Ke.TERM==="dumb")return o;if(Sd.default.platform==="win32"){let i=LS.default.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in Ke)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(i=>i in Ke)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(i=>i in Ke)||Ke.CI_NAME==="codeship"?1:o;if("TEAMCITY_VERSION"in Ke)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Ke.TEAMCITY_VERSION)?1:0;if(Ke.COLORTERM==="truecolor"||Ke.TERM==="xterm-kitty"||Ke.TERM==="xterm-ghostty"||Ke.TERM==="wezterm")return 3;if("TERM_PROGRAM"in Ke){let i=Number.parseInt((Ke.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Ke.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Ke.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Ke.TERM)||"COLORTERM"in Ke?1:o}function qg(r,e={}){let t=o9(r,{streamIsTTY:r&&r.isTTY,...e});return s9(t)}var Sd,LS,Hg,Ke,Ed,i9,pl,Vg=_(()=>{Sd=ie(ee("node:process"),1),LS=ie(ee("node:os"),1),Hg=ie(ee("node:tty"),1);({env:Ke}=Sd.default);Er("no-color")||Er("no-colors")||Er("color=false")||Er("color=never")?Ed=0:(Er("color")||Er("colors")||Er("color=true")||Er("color=always"))&&(Ed=1);i9={stdout:qg({isTTY:Hg.default.isatty(1)}),stderr:qg({isTTY:Hg.default.isatty(2)})},pl=i9});var RS=At((ft,Ad)=>{var a9=ee("tty"),Id=ee("util");ft.init=p9;ft.log=h9;ft.formatArgs=l9;ft.save=d9;ft.load=f9;ft.useColors=c9;ft.destroy=Id.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");ft.colors=[6,2,3,4,5,1];try{let r=(Vg(),$5(MS));r&&(r.stderr||r).level>=2&&(ft.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}ft.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,o)=>o.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),r[t]=n,r},{});function c9(){return"colors"in ft.inspectOpts?!!ft.inspectOpts.colors:a9.isatty(process.stderr.fd)}function l9(r){let{namespace:e,useColors:t}=this;if(t){let n=this.color,s="\x1B[3"+(n<8?n:"8;5;"+n),o=` ${s};1m${e} \x1B[0m`;r[0]=o+r[0].split(`
|
|
3
3
|
`).join(`
|
|
4
4
|
`+o),r.push(s+"m+"+Ad.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=u9()+e+" "+r[0]}function u9(){return ft.inspectOpts.hideDate?"":new Date().toISOString()+" "}function h9(...r){return process.stderr.write(Id.formatWithOptions(ft.inspectOpts,...r)+`
|
|
5
5
|
`)}function d9(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function f9(){return process.env.DEBUG}function p9(r){r.inspectOpts={};let e=Object.keys(ft.inspectOpts);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=ft.inspectOpts[e[t]]}Ad.exports=$g()(ft);var{formatters:OS}=Ad.exports;OS.o=function(r){return this.inspectOpts.colors=this.useColors,Id.inspect(r,this.inspectOpts).split(`
|
|
6
|
-
`).map(e=>e.trim()).join(" ")};OS.O=function(r){return this.inspectOpts.colors=this.useColors,Id.inspect(r,this.inspectOpts)}});var Wg=At((Nie,Gg)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Gg.exports=kS():Gg.exports=RS()});var x8=At(eu=>{(function(){var r,e,t,n,s,o,i,a;a=function(c){var l,u,h,p;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,h=(c&65280)>>>8,p=c&255,[l,u,h,p].join(".")},i=function(c){var l,u,h,p,f,d;for(l=[],h=p=0;p<=3&&c.length!==0;h=++p){if(h>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}d=e(c),f=d[0],u=d[1],c=c.substring(u),l.push(f)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),o=t("a"),s=t("A"),e=function(c){var l,u,h,p,f;for(p=0,l=10,u="9",h=0,c.length>1&&c[h]==="0"&&(c[h+1]==="x"||c[h+1]==="X"?(h+=2,l=16):"0"<=c[h+1]&&c[h+1]<="9"&&(h++,l=8,u="7")),f=h;h<c.length;){if("0"<=c[h]&&c[h]<=u)p=p*l+(t(c[h])-n)>>>0;else if(l===16)if("a"<=c[h]&&c[h]<="f")p=p*l+(10+t(c[h])-o)>>>0;else if("A"<=c[h]&&c[h]<="F")p=p*l+(10+t(c[h])-s)>>>0;else break;else break;if(p>4294967295)throw new Error("too large");h++}if(h===f)throw new Error("empty octet");return[p,h]},r=(function(){function c(l,u){var h,p,f,d;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(d=l.split("/",2),l=d[0],u=d[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=i(u)}catch(m){throw h=m,new Error("Invalid mask: "+u)}for(p=f=32;f>=0;p=--f)if(this.maskLong===4294967295<<32-p>>>0){this.bitmask=p;break}}else if(u||u===0)this.bitmask=parseInt(u,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(m){throw h=m,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+u);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var u,h,p;for(p=i(this.first),h=i(this.last),u=0;p<=h;)l(a(p),p,u),u++,p++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c})(),eu.ip2long=i,eu.long2ip=a,eu.Netmask=r}).call(eu)});var HC=At((ewe,$C)=>{$C.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function s(o,i){t[o]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(o){return t[o]!==void 0||n[o]!==void 0},remove:function(o){t[o]!==void 0&&(t[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var i=t[o];if(i!==void 0)return i;if((i=n[o])!==void 0)return s(o,i),i},set:function(o,i){t[o]!==void 0?t[o]=i:s(o,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Tw=At(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.TAG_LENGTH=dn.DATA_CHUNK_LENGTH=dn.NONCE_LENGTH=dn.KEY_LENGTH=void 0;dn.KEY_LENGTH=32;dn.NONCE_LENGTH=12;dn.DATA_CHUNK_LENGTH=65536;dn.TAG_LENGTH=16});var cT=At(Zp=>{"use strict";Object.defineProperty(Zp,"__esModule",{value:!0});Zp.ChaCha20Poly1305=void 0;var je=Tw(),_w=class{constructor(e){this.ctx=e;let t=e.cpKey.value;this.wasmKeyArr=new Uint8Array(e.memory.buffer,t,je.KEY_LENGTH);let n=e.cpNonce.value;this.wasmNonceArr=new Uint8Array(e.memory.buffer,n,je.NONCE_LENGTH);let s=e.cpAssociatedData.value;this.wasmAdArr=new Uint8Array(e.memory.buffer,s,je.KEY_LENGTH);let o=e.cpInput.value;this.wasmInputArr=new Uint8Array(e.memory.buffer,o,je.DATA_CHUNK_LENGTH);let i=e.chacha20Output.value;this.wasmChacha20OutputArr=new Uint8Array(e.memory.buffer,i,je.DATA_CHUNK_LENGTH);let a=e.poly1305Output.value;this.wasmPoly1305OutputArr=new Uint8Array(e.memory.buffer,a,je.TAG_LENGTH);let c=e.debug.value;this.wasmDebugArr=new Uint32Array(e.memory.buffer,c,64)}seal(e,t,n,s,o){this.init(e,t,s);let i=n.length+je.TAG_LENGTH,a;if(o){if(o.length!==i)throw new Error("ChaCha20Poly1305: incorrect destination length");a=o}else a=new Uint8Array(i);let c=s?.length??0;return this.sealUpdate(n,c,a),a.set(this.wasmPoly1305OutputArr,n.length),a}open(e,t,n,s,o){this.init(e,t,s);let i=n.subarray(0,n.length-je.TAG_LENGTH),a;if(o){if(o.length!==i.length)throw new Error("ChaCha20Poly1305: incorrect destination length");a=o}else a=new Uint8Array(i.length);let c=s?.length??0;this.openUpdate(i,c,a);let l=n.subarray(n.length-je.TAG_LENGTH,n.length);return this.isSameTag(l)?a:null}init(e,t,n=new Uint8Array(0)){if(e.length!=je.KEY_LENGTH)throw Error(`Invalid chacha20poly1305 key length ${e.length}, expect ${je.KEY_LENGTH}`);if(n.length>je.KEY_LENGTH)throw Error(`Invalid ad length ${n.length}, expect <= ${je.KEY_LENGTH}`);if(t.length!==je.NONCE_LENGTH)throw Error(`Invalid nonce length ${t.length}, expect ${je.NONCE_LENGTH}`);this.wasmKeyArr.set(e),this.wasmNonceArr.set(t),this.wasmAdArr.set(n)}openUpdate(e,t,n){this.commonUpdate(e,this.ctx.openUpdate,t,n)}sealUpdate(e,t,n){this.commonUpdate(e,this.ctx.sealUpdate,t,n)}commonUpdate(e,t,n,s){let o=e.length;if(e.length<=je.DATA_CHUNK_LENGTH){this.wasmInputArr.set(e),t(!0,!0,o,o,n),s.set(o===je.DATA_CHUNK_LENGTH?this.wasmChacha20OutputArr:this.wasmChacha20OutputArr.subarray(0,o));return}for(let i=0;i<o;i+=je.DATA_CHUNK_LENGTH){let a=Math.min(o,i+je.DATA_CHUNK_LENGTH);this.wasmInputArr.set(e.subarray(i,a));let c=i===0,l=i+je.DATA_CHUNK_LENGTH>=o;t(c,l,a-i,o,n),s.set(a-i===je.DATA_CHUNK_LENGTH?this.wasmChacha20OutputArr:this.wasmChacha20OutputArr.subarray(0,a-i),i)}}isSameTag(e){let t=!0;for(let n=0;n<je.TAG_LENGTH;n++)if(this.wasmPoly1305OutputArr[n]!==e[n]){t=!1;break}return t}};Zp.ChaCha20Poly1305=_w});var lT=At(e1=>{"use strict";Object.defineProperty(e1,"__esModule",{value:!0});e1.Poly1305=void 0;var Vn=Tw(),Pw=class{constructor(e){this.ctx=e;let t=e.poly1305Key.value;this.wasmKeyArr=new Uint8Array(e.memory.buffer,t,Vn.KEY_LENGTH);let n=e.poly1305Input.value;this.wasmInputArr=new Uint8Array(e.memory.buffer,n,Vn.DATA_CHUNK_LENGTH);let s=e.poly1305Output.value;this.wasmOutputArr=new Uint8Array(e.memory.buffer,s,Vn.TAG_LENGTH);let o=e.debug.value;this.wasmDebugArr=new Uint32Array(e.memory.buffer,o,64)}init(e){if(e.length!=Vn.KEY_LENGTH)throw Error(`Invalid poly1305 key length ${e.length}, expect ${Vn.KEY_LENGTH}`);this.wasmKeyArr.set(e),this.ctx.poly1305Init()}update(e){if(e.length<=Vn.DATA_CHUNK_LENGTH){this.wasmInputArr.set(e),this.ctx.poly1305Update(e.length);return}for(let t=0;t<e.length;t+=Vn.DATA_CHUNK_LENGTH){let n=Math.min(e.length,t+Vn.DATA_CHUNK_LENGTH);this.wasmInputArr.set(e.subarray(t,n)),this.ctx.poly1305Update(n-t)}}digest(){this.ctx.poly1305Digest();let e=new Uint8Array(Vn.TAG_LENGTH);return e.set(this.wasmOutputArr),e}};e1.Poly1305=Pw});var uT=At(t1=>{"use strict";Object.defineProperty(t1,"__esModule",{value:!0});t1.wasmCode=void 0;t1.wasmCode=Uint8Array.from([0,97,115,109,1,0,0,0,1,58,10,96,0,0,96,2,127,127,0,96,1,127,0,96,3,127,127,127,0,96,1,127,1,127,96,4,127,127,127,127,0,96,5,127,127,127,127,127,0,96,0,1,127,96,2,127,127,1,127,96,5,127,127,127,127,127,1,127,2,13,1,3,101,110,118,5,97,98,111,114,116,0,5,3,34,33,2,8,1,4,0,4,7,0,0,3,3,2,1,9,4,2,0,3,1,2,2,1,0,0,0,5,1,1,1,6,1,6,0,5,3,1,0,1,6,238,1,47,127,0,65,32,11,127,0,65,16,11,127,0,65,128,128,4,11,127,0,65,16,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,7,226,2,23,6,109,101,109,111,114,121,2,0,21,67,72,65,67,72,65,50,48,95,73,78,80,85,84,95,76,69,78,71,84,72,3,2,23,67,72,65,67,72,65,50,48,95,67,79,85,78,84,69,82,95,76,69,78,71,84,72,3,3,13,99,104,97,99,104,97,50,48,73,110,112,117,116,3,6,11,99,104,97,99,104,97,50,48,75,101,121,3,8,15,99,104,97,99,104,97,50,48,67,111,117,110,116,101,114,3,10,14,99,104,97,99,104,97,50,48,79,117,116,112,117,116,3,12,23,99,104,97,99,104,97,50,48,83,116,114,101,97,109,88,79,82,85,112,100,97,116,101,0,15,10,75,69,89,95,76,69,78,71,84,72,3,0,10,84,65,71,95,76,69,78,71,84,72,3,1,12,112,111,108,121,49,51,48,53,73,110,105,116,0,17,14,112,111,108,121,49,51,48,53,85,112,100,97,116,101,0,20,14,112,111,108,121,49,51,48,53,68,105,103,101,115,116,0,24,13,112,111,108,121,49,51,48,53,73,110,112,117,116,3,19,11,112,111,108,121,49,51,48,53,75,101,121,3,18,14,112,111,108,121,49,51,48,53,79,117,116,112,117,116,3,20,10,111,112,101,110,85,112,100,97,116,101,0,30,10,115,101,97,108,85,112,100,97,116,101,0,32,5,99,112,75,101,121,3,37,7,99,112,78,111,110,99,101,3,39,7,99,112,73,110,112,117,116,3,43,16,99,112,65,115,115,111,99,105,97,116,101,100,68,97,116,97,3,41,5,100,101,98,117,103,3,46,8,1,33,10,195,47,33,70,1,2,127,32,0,63,0,34,2,65,16,116,34,1,75,4,64,32,2,32,0,32,1,107,65,255,255,3,106,65,128,128,124,113,65,16,118,34,1,32,2,32,1,74,27,64,0,65,0,72,4,64,32,1,64,0,65,0,72,4,64,0,11,11,11,32,0,36,5,11,82,1,3,127,32,0,65,240,255,255,255,3,75,4,64,0,11,35,5,65,16,106,34,3,32,0,65,15,106,65,112,113,34,2,65,16,32,2,65,16,75,27,34,4,106,16,1,32,3,65,16,107,34,2,32,4,54,2,0,32,2,65,1,54,2,4,32,2,32,1,54,2,8,32,2,32,0,54,2,12,32,3,11,37,1,1,127,3,64,32,1,4,64,32,0,34,2,65,1,106,33,0,32,2,65,0,58,0,0,32,1,65,1,107,33,1,12,1,11,11,11,42,1,1,127,32,0,65,240,255,255,255,3,75,4,64,65,32,65,208,0,65,54,65,42,16,0,0,11,32,0,65,0,16,2,34,1,32,0,16,3,32,1,11,67,0,65,128,3,36,4,65,128,3,36,5,65,128,128,4,16,4,36,6,35,6,36,7,65,32,16,4,36,8,35,8,36,9,65,16,16,4,36,10,35,10,36,11,65,128,128,4,16,4,36,12,35,12,36,13,65,192,0,16,4,36,14,35,14,36,15,11,83,1,1,127,65,128,2,65,0,16,2,34,1,65,128,2,16,3,32,0,69,4,64,65,12,65,2,16,2,33,0,11,32,0,65,0,54,2,0,32,0,65,0,54,2,4,32,0,65,0,54,2,8,32,0,40,2,0,26,32,0,32,1,54,2,0,32,0,32,1,54,2,4,32,0,65,128,2,54,2,8,32,0,11,10,0,65,12,65,3,16,2,16,6,11,95,0,16,7,36,16,35,16,40,2,0,36,17,65,32,16,4,36,18,65,128,128,4,16,4,36,19,65,16,16,4,36,20,35,18,36,21,35,19,36,22,35,20,36,23,65,16,16,4,36,24,35,24,36,25,65,20,16,4,36,26,35,26,36,27,65,20,16,4,36,28,35,28,36,29,65,16,16,4,36,30,35,30,36,31,65,20,16,4,36,35,35,35,36,36,11,55,0,65,32,16,4,36,37,35,37,36,38,65,12,16,4,36,39,35,39,36,40,65,32,16,4,36,41,35,41,36,42,65,128,128,4,16,4,36,43,35,43,36,44,16,7,36,45,35,45,40,2,0,36,46,11,22,0,32,1,32,2,65,255,1,113,65,4,110,65,2,116,106,32,0,54,2,0,11,188,6,1,31,127,65,229,240,193,139,6,33,5,65,238,200,129,153,3,33,6,65,178,218,136,203,7,33,14,65,244,202,129,217,6,33,7,32,2,40,2,0,34,19,33,4,32,2,65,4,106,40,2,0,34,20,33,8,32,2,65,8,106,40,2,0,34,21,33,3,32,2,65,12,106,40,2,0,34,22,33,13,32,2,65,16,106,40,2,0,34,23,33,15,32,2,65,20,106,40,2,0,34,24,33,9,32,2,65,24,106,40,2,0,34,25,33,10,32,2,65,28,106,40,2,0,34,26,33,2,32,1,40,2,0,34,27,33,11,32,1,65,4,106,40,2,0,34,28,33,16,32,1,65,8,106,40,2,0,34,29,33,12,32,1,65,12,106,40,2,0,34,30,33,1,3,64,32,18,65,20,72,4,64,32,3,32,10,32,12,32,3,32,14,106,34,3,115,65,16,119,34,14,106,34,10,115,65,12,119,34,12,32,10,32,14,32,3,32,12,106,34,3,115,65,8,119,34,14,106,34,10,115,33,12,32,13,32,2,32,1,32,7,32,13,106,34,1,115,65,16,119,34,2,106,34,13,115,65,12,119,34,7,32,13,32,2,32,1,32,7,106,34,13,115,65,8,119,34,1,106,34,2,115,33,7,32,4,32,15,32,11,32,4,32,5,106,34,4,115,65,16,119,34,5,106,34,15,115,65,12,119,34,11,32,15,32,5,32,4,32,11,106,34,4,115,65,8,119,34,5,106,34,15,115,33,11,32,10,32,1,32,8,32,9,32,16,32,6,32,8,106,34,1,115,65,16,119,34,8,106,34,6,115,65,12,119,34,9,32,6,32,8,32,1,32,9,106,34,1,115,65,8,119,34,6,106,34,9,115,65,7,119,34,10,32,4,106,34,17,115,65,16,119,34,31,106,33,8,32,2,32,5,32,12,65,7,119,34,5,32,1,106,34,32,115,65,16,119,34,33,106,33,1,32,9,32,14,32,13,32,11,65,7,119,34,9,106,34,11,115,65,16,119,34,12,106,33,4,32,15,32,6,32,3,32,7,65,7,119,34,3,106,34,6,115,65,16,119,34,7,106,34,2,32,6,32,2,32,3,115,65,12,119,34,3,106,34,14,32,7,115,65,8,119,34,16,106,34,15,32,3,115,65,7,119,33,13,32,11,32,4,32,9,115,65,12,119,34,2,106,34,7,32,12,115,65,8,119,34,12,32,4,106,34,9,32,2,115,65,7,119,33,4,32,32,32,1,32,5,115,65,12,119,34,3,106,34,6,32,33,115,65,8,119,34,11,32,1,106,34,2,32,3,115,65,7,119,33,3,32,17,32,8,32,10,115,65,12,119,34,17,106,34,5,32,31,115,65,8,119,34,1,32,8,106,34,10,32,17,115,65,7,119,33,8,32,18,65,2,106,33,18,12,1,11,11,32,5,65,229,240,193,139,6,106,32,0,65,0,16,10,32,6,65,238,200,129,153,3,106,32,0,65,4,16,10,32,14,65,178,218,136,203,7,106,32,0,65,8,16,10,32,7,65,244,202,129,217,6,106,32,0,65,12,16,10,32,4,32,19,106,32,0,65,16,16,10,32,8,32,20,106,32,0,65,20,16,10,32,3,32,21,106,32,0,65,24,16,10,32,13,32,22,106,32,0,65,28,16,10,32,15,32,23,106,32,0,65,32,16,10,32,9,32,24,106,32,0,65,36,16,10,32,10,32,25,106,32,0,65,40,16,10,32,2,32,26,106,32,0,65,44,16,10,32,11,32,27,106,32,0,65,48,16,10,32,16,32,28,106,32,0,65,52,16,10,32,12,32,29,106,32,0,65,56,16,10,32,1,32,30,106,32,0,65,60,16,10,11,97,1,4,127,65,4,33,3,65,1,33,1,3,64,32,3,34,2,65,1,107,33,3,32,2,65,255,1,113,4,64,32,1,32,0,32,4,65,255,1,113,106,34,2,45,0,0,106,33,1,32,2,32,1,58,0,0,32,1,65,8,118,33,1,32,4,65,1,106,33,4,12,1,11,11,32,1,65,0,74,4,64,65,144,1,65,208,1,65,135,2,65,4,16,0,0,11,11,8,0,32,0,32,1,16,3,11,108,1,2,127,3,64,32,6,32,1,73,4,64,35,15,32,3,32,2,16,11,32,6,33,5,3,64,32,5,32,1,73,65,0,32,5,32,6,65,64,107,73,27,4,64,32,4,32,5,106,32,0,32,5,106,45,0,0,35,15,32,5,32,6,107,106,45,0,0,115,58,0,0,32,5,65,1,106,33,5,12,1,11,11,32,3,16,12,32,6,65,64,107,33,6,12,1,11,11,35,15,65,192,0,16,13,32,1,11,14,0,35,7,32,0,35,9,35,11,35,13,16,14,11,204,4,1,1,127,35,27,32,0,45,0,0,32,0,65,1,106,45,0,0,65,8,116,114,34,1,65,255,63,113,59,1,0,35,27,65,2,106,32,1,65,13,118,32,0,65,2,106,45,0,0,32,0,65,3,106,45,0,0,65,8,116,114,34,1,65,3,116,114,65,255,63,113,59,1,0,35,27,65,4,106,32,1,65,10,118,32,0,65,4,106,45,0,0,32,0,65,5,106,45,0,0,65,8,116,114,34,1,65,6,116,114,65,131,62,113,59,1,0,35,27,65,6,106,32,1,65,7,118,32,0,65,6,106,45,0,0,32,0,65,7,106,45,0,0,65,8,116,114,34,1,65,9,116,114,65,255,63,113,59,1,0,35,27,65,8,106,32,1,65,4,118,32,0,65,8,106,45,0,0,32,0,65,9,106,45,0,0,65,8,116,114,34,1,65,12,116,114,65,255,1,113,59,1,0,35,27,65,10,106,32,1,65,1,118,65,254,63,113,59,1,0,35,27,65,12,106,32,1,65,14,118,32,0,65,10,106,45,0,0,32,0,65,11,106,45,0,0,65,8,116,114,34,1,65,2,116,114,65,255,63,113,59,1,0,35,27,65,14,106,32,1,65,11,118,32,0,65,12,106,45,0,0,32,0,65,13,106,45,0,0,65,8,116,114,34,1,65,5,116,114,65,129,63,113,59,1,0,35,27,65,16,106,32,1,65,8,118,32,0,65,14,106,45,0,0,32,0,65,15,106,45,0,0,65,8,116,114,34,1,65,8,116,114,65,255,63,113,59,1,0,35,27,65,18,106,32,1,65,5,118,65,255,0,113,59,1,0,35,31,32,0,65,16,106,45,0,0,32,0,65,17,106,45,0,0,65,8,116,114,59,1,0,35,31,65,2,106,32,0,65,18,106,45,0,0,32,0,65,19,106,45,0,0,65,8,116,114,59,1,0,35,31,65,4,106,32,0,65,20,106,45,0,0,32,0,65,21,106,45,0,0,65,8,116,114,59,1,0,35,31,65,6,106,32,0,65,22,106,45,0,0,32,0,65,23,106,45,0,0,65,8,116,114,59,1,0,35,31,65,8,106,32,0,65,24,106,45,0,0,32,0,65,25,106,45,0,0,65,8,116,114,59,1,0,35,31,65,10,106,32,0,65,26,106,45,0,0,32,0,65,27,106,45,0,0,65,8,116,114,59,1,0,35,31,65,12,106,32,0,65,28,106,45,0,0,32,0,65,29,106,45,0,0,65,8,116,114,59,1,0,35,31,65,14,106,32,0,65,30,106,45,0,0,32,0,65,31,106,45,0,0,65,8,116,114,59,1,0,11,6,0,35,21,16,16,11,166,13,1,32,127,65,0,65,128,16,35,33,27,33,34,35,29,47,1,0,33,3,35,29,65,2,106,47,1,0,33,4,35,29,65,4,106,47,1,0,33,8,35,29,65,6,106,47,1,0,33,9,35,29,65,8,106,47,1,0,33,10,35,29,65,10,106,47,1,0,33,11,35,29,65,12,106,47,1,0,33,12,35,29,65,14,106,47,1,0,33,13,35,29,65,16,106,47,1,0,33,14,35,29,65,18,106,47,1,0,33,6,35,27,47,1,0,33,17,35,27,65,2,106,47,1,0,33,18,35,27,65,4,106,47,1,0,33,20,35,27,65,6,106,47,1,0,33,22,35,27,65,8,106,47,1,0,33,24,35,27,65,10,106,47,1,0,33,26,35,27,65,12,106,47,1,0,33,29,35,27,65,14,106,47,1,0,33,30,35,27,65,16,106,47,1,0,33,31,35,27,65,18,106,47,1,0,33,33,3,64,32,2,65,16,79,4,64,32,3,32,0,32,1,106,45,0,0,32,0,32,1,65,1,106,106,45,0,0,65,8,116,114,34,15,65,255,63,113,106,34,3,32,17,108,32,4,32,0,32,1,65,2,106,106,45,0,0,32,0,32,1,65,3,106,106,45,0,0,65,8,116,114,34,16,65,3,116,32,15,65,255,255,3,113,65,13,118,114,65,255,63,113,106,34,4,32,33,65,5,108,34,15,108,106,32,8,32,0,32,1,65,4,106,106,45,0,0,32,0,32,1,65,5,106,106,45,0,0,65,8,116,114,34,19,65,6,116,32,16,65,255,255,3,113,65,10,118,114,65,255,63,113,106,34,8,32,31,65,5,108,34,16,108,106,32,9,32,0,32,1,65,6,106,106,45,0,0,32,0,32,1,65,7,106,106,45,0,0,65,8,116,114,34,21,65,9,116,32,19,65,255,255,3,113,65,7,118,114,65,255,63,113,106,34,9,32,30,65,5,108,34,19,108,106,32,10,32,0,32,1,65,8,106,106,45,0,0,32,0,32,1,65,9,106,106,45,0,0,65,8,116,114,34,23,65,12,116,32,21,65,255,255,3,113,65,4,118,114,65,255,63,113,106,34,10,32,29,65,5,108,34,21,108,106,34,32,65,255,63,113,32,11,32,23,65,255,255,3,113,65,1,118,65,255,63,113,106,34,11,32,26,65,5,108,34,27,108,106,32,12,32,0,32,1,65,10,106,106,45,0,0,32,0,32,1,65,11,106,106,45,0,0,65,8,116,114,34,28,65,2,116,32,23,65,255,255,3,113,65,14,118,114,65,255,63,113,106,34,12,32,24,65,5,108,34,23,108,106,32,13,32,0,32,1,65,12,106,106,45,0,0,32,0,32,1,65,13,106,106,45,0,0,65,8,116,114,34,25,65,5,116,32,28,65,255,255,3,113,65,11,118,114,65,255,63,113,106,34,13,32,22,65,5,108,34,28,108,106,32,14,32,25,65,255,255,3,113,65,8,118,32,0,32,1,65,14,106,106,45,0,0,32,0,32,1,65,15,106,106,45,0,0,65,8,116,114,34,25,65,8,116,114,65,255,63,113,106,34,14,32,20,65,5,108,34,7,108,106,33,5,32,11,32,21,108,32,32,65,13,118,32,5,32,6,32,34,32,25,65,255,255,3,113,65,5,118,114,65,255,255,3,113,106,34,6,32,18,65,5,108,108,106,34,32,65,13,118,106,32,3,32,18,108,106,32,4,32,17,108,106,32,8,32,15,108,106,32,9,32,16,108,106,32,10,32,19,108,106,34,25,65,255,63,113,106,32,12,32,27,108,106,32,13,32,23,108,106,32,14,32,28,108,106,33,5,32,11,32,19,108,32,25,65,13,118,32,5,32,6,32,7,108,106,34,25,65,13,118,106,32,3,32,20,108,106,32,4,32,18,108,106,32,8,32,17,108,106,32,9,32,15,108,106,32,10,32,16,108,106,34,7,65,255,63,113,106,32,12,32,21,108,106,32,13,32,27,108,106,32,14,32,23,108,106,33,5,32,11,32,16,108,32,7,65,13,118,32,5,32,6,32,28,108,106,34,28,65,13,118,106,32,3,32,22,108,106,32,4,32,20,108,106,32,8,32,18,108,106,32,9,32,17,108,106,32,10,32,15,108,106,34,7,65,255,63,113,106,32,12,32,19,108,106,32,13,32,21,108,106,32,14,32,27,108,106,33,5,32,11,32,15,108,32,7,65,13,118,32,5,32,6,32,23,108,106,34,23,65,13,118,106,32,3,32,24,108,106,32,4,32,22,108,106,32,8,32,20,108,106,32,9,32,18,108,106,32,10,32,17,108,106,34,7,65,255,63,113,106,32,12,32,16,108,106,32,13,32,19,108,106,32,14,32,21,108,106,33,5,32,11,32,17,108,32,7,65,13,118,32,5,32,6,32,27,108,106,34,27,65,13,118,106,32,3,32,26,108,106,32,4,32,24,108,106,32,8,32,22,108,106,32,9,32,20,108,106,32,10,32,18,108,106,34,7,65,255,63,113,106,32,12,32,15,108,106,32,13,32,16,108,106,32,14,32,19,108,106,33,5,32,11,32,18,108,32,7,65,13,118,32,5,32,6,32,21,108,106,34,21,65,13,118,106,32,3,32,29,108,106,32,4,32,26,108,106,32,8,32,24,108,106,32,9,32,22,108,106,32,10,32,20,108,106,34,7,65,255,63,113,106,32,12,32,17,108,106,32,13,32,15,108,106,32,14,32,16,108,106,33,5,32,11,32,20,108,32,7,65,13,118,32,5,32,6,32,19,108,106,34,19,65,13,118,106,32,3,32,30,108,106,32,4,32,29,108,106,32,8,32,26,108,106,32,9,32,24,108,106,32,10,32,22,108,106,34,7,65,255,63,113,106,32,12,32,18,108,106,32,13,32,17,108,106,32,14,32,15,108,106,33,5,32,11,32,22,108,32,7,65,13,118,32,5,32,6,32,16,108,106,34,16,65,13,118,106,32,3,32,31,108,106,32,4,32,30,108,106,32,8,32,29,108,106,32,9,32,26,108,106,32,10,32,24,108,106,34,7,65,255,63,113,106,32,12,32,20,108,106,32,13,32,18,108,106,32,14,32,17,108,106,33,5,32,11,32,24,108,32,7,65,13,118,32,5,32,6,32,15,108,106,34,15,65,13,118,106,32,3,32,33,108,106,32,4,32,31,108,106,32,8,32,30,108,106,32,9,32,29,108,106,32,10,32,26,108,106,34,3,65,255,63,113,106,32,12,32,22,108,106,32,13,32,20,108,106,32,14,32,18,108,106,33,4,32,3,65,13,118,32,4,32,6,32,17,108,106,34,6,65,13,118,106,34,3,32,3,65,2,116,106,32,32,65,255,63,113,106,34,3,65,13,118,33,4,32,3,65,255,63,113,33,3,32,25,65,255,63,113,32,4,106,33,4,32,28,65,255,63,113,33,8,32,23,65,255,63,113,33,9,32,27,65,255,63,113,33,10,32,21,65,255,63,113,33,11,32,19,65,255,63,113,33,12,32,16,65,255,63,113,33,13,32,15,65,255,63,113,33,14,32,6,65,255,63,113,33,6,32,1,65,16,106,33,1,32,2,65,16,107,33,2,12,1,11,11,35,29,32,3,59,1,0,35,29,65,2,106,32,4,59,1,0,35,29,65,4,106,32,8,59,1,0,35,29,65,6,106,32,9,59,1,0,35,29,65,8,106,32,10,59,1,0,35,29,65,10,106,32,11,59,1,0,35,29,65,12,106,32,12,59,1,0,35,29,65,14,106,32,13,59,1,0,35,29,65,16,106,32,14,59,1,0,35,29,65,18,106,32,6,59,1,0,11,203,1,1,3,127,35,32,4,64,65,16,35,32,107,34,3,32,1,75,4,64,32,1,33,3,11,3,64,32,2,32,3,73,4,64,35,25,32,2,35,32,106,106,32,0,32,2,106,45,0,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,1,32,3,107,33,1,32,3,33,4,32,3,35,32,106,36,32,35,32,65,16,73,4,64,15,11,35,25,65,0,65,16,16,18,65,0,36,32,11,2,127,32,1,65,16,79,4,64,32,0,32,4,32,1,32,1,65,15,113,107,34,3,16,18,32,3,32,4,106,33,4,32,1,32,3,107,33,1,11,32,1,11,4,64,65,0,33,2,3,64,32,2,32,1,73,4,64,35,25,32,2,35,32,106,106,32,0,32,2,32,4,106,106,45,0,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,1,35,32,106,36,32,11,11,8,0,35,22,32,0,16,19,11,149,9,1,3,127,35,32,4,64,35,32,34,1,35,25,106,65,1,58,0,0,32,1,65,1,106,33,1,3,64,32,1,65,16,73,4,64,32,1,35,25,106,65,0,58,0,0,32,1,65,1,106,33,1,12,1,11,11,65,1,36,33,35,25,65,0,65,16,16,18,11,35,29,65,2,106,47,1,0,65,13,118,33,2,35,29,65,2,106,35,29,65,2,106,47,1,0,65,255,63,113,59,1,0,65,2,33,1,3,64,32,1,65,10,73,4,64,32,1,65,1,116,34,3,35,29,106,32,2,32,3,35,29,106,47,1,0,106,59,1,0,32,3,35,29,106,47,1,0,65,13,118,33,2,32,3,35,29,106,32,3,35,29,106,47,1,0,65,255,63,113,59,1,0,32,1,65,1,106,33,1,12,1,11,11,35,29,35,29,47,1,0,32,2,65,5,108,106,59,1,0,35,29,47,1,0,33,1,35,29,35,29,47,1,0,65,255,63,113,59,1,0,35,29,65,2,106,35,29,65,2,106,47,1,0,32,1,65,255,255,3,113,65,13,118,106,59,1,0,35,29,65,2,106,47,1,0,33,1,35,29,65,2,106,35,29,65,2,106,47,1,0,65,255,63,113,59,1,0,35,29,65,4,106,35,29,65,4,106,47,1,0,32,1,65,255,255,3,113,65,13,118,106,59,1,0,35,36,35,29,47,1,0,65,5,106,59,1,0,35,36,47,1,0,65,13,118,33,2,35,36,35,36,47,1,0,65,255,63,113,59,1,0,65,1,33,1,3,64,32,1,65,10,73,4,64,32,1,65,1,116,34,3,35,36,106,32,2,32,3,35,29,106,47,1,0,106,59,1,0,32,3,35,36,106,47,1,0,65,13,118,33,2,32,3,35,36,106,32,3,35,36,106,47,1,0,65,255,63,113,59,1,0,32,1,65,1,106,33,1,12,1,11,11,35,36,65,18,106,35,36,65,18,106,47,1,0,65,128,64,106,59,1,0,32,2,65,1,115,65,1,107,33,2,65,0,33,1,3,64,32,1,65,10,73,4,64,32,1,65,1,116,34,3,35,36,106,32,2,32,3,35,36,106,47,1,0,113,59,1,0,32,1,65,1,106,33,1,12,1,11,11,32,2,65,127,115,33,3,65,0,33,1,3,64,32,1,65,10,73,4,64,32,1,65,1,116,34,2,35,29,106,32,2,35,36,106,47,1,0,32,3,32,2,35,29,106,47,1,0,113,114,59,1,0,32,1,65,1,106,33,1,12,1,11,11,35,29,35,29,47,1,0,35,29,65,2,106,47,1,0,65,13,116,114,59,1,0,35,29,65,2,106,35,29,65,4,106,47,1,0,65,10,116,35,29,65,2,106,47,1,0,65,3,118,114,59,1,0,35,29,65,4,106,35,29,65,6,106,47,1,0,65,7,116,35,29,65,4,106,47,1,0,65,6,118,114,59,1,0,35,29,65,6,106,35,29,65,8,106,47,1,0,65,4,116,35,29,65,6,106,47,1,0,65,9,118,114,59,1,0,35,29,65,8,106,35,29,65,10,106,47,1,0,65,1,116,35,29,65,8,106,47,1,0,65,12,118,114,35,29,65,12,106,47,1,0,65,14,116,114,59,1,0,35,29,65,10,106,35,29,65,14,106,47,1,0,65,11,116,35,29,65,12,106,47,1,0,65,2,118,114,59,1,0,35,29,65,12,106,35,29,65,16,106,47,1,0,65,8,116,35,29,65,14,106,47,1,0,65,5,118,114,59,1,0,35,29,65,14,106,35,29,65,18,106,47,1,0,65,5,116,35,29,65,16,106,47,1,0,65,8,118,114,59,1,0,35,29,35,29,47,1,0,35,31,47,1,0,106,34,2,59,1,0,65,1,33,1,3,64,32,1,65,8,73,4,64,32,1,65,1,116,34,3,35,29,106,47,1,0,32,3,35,31,106,47,1,0,106,32,2,65,16,118,106,33,2,35,29,32,3,106,32,2,59,1,0,32,1,65,1,106,33,1,12,1,11,11,32,0,35,29,47,1,0,58,0,0,32,0,65,1,106,35,29,47,1,0,65,8,118,58,0,0,32,0,65,2,106,35,29,65,2,106,47,1,0,58,0,0,32,0,65,3,106,35,29,65,2,106,47,1,0,65,8,118,58,0,0,32,0,65,4,106,35,29,65,4,106,47,1,0,58,0,0,32,0,65,5,106,35,29,65,4,106,47,1,0,65,8,118,58,0,0,32,0,65,6,106,35,29,65,6,106,47,1,0,58,0,0,32,0,65,7,106,35,29,65,6,106,47,1,0,65,8,118,58,0,0,32,0,65,8,106,35,29,65,8,106,47,1,0,58,0,0,32,0,65,9,106,35,29,65,8,106,47,1,0,65,8,118,58,0,0,32,0,65,10,106,35,29,65,10,106,47,1,0,58,0,0,32,0,65,11,106,35,29,65,10,106,47,1,0,65,8,118,58,0,0,32,0,65,12,106,35,29,65,12,106,47,1,0,58,0,0,32,0,65,13,106,35,29,65,12,106,47,1,0,65,8,118,58,0,0,32,0,65,14,106,35,29,65,14,106,47,1,0,58,0,0,32,0,65,15,106,35,29,65,14,106,47,1,0,65,8,118,58,0,0,65,1,36,34,11,11,0,32,0,32,1,65,1,116,16,3,11,38,0,35,25,65,16,16,13,35,27,65,10,16,22,35,29,65,10,16,22,35,31,65,8,16,22,65,0,36,32,65,0,36,33,65,0,36,34,11,33,1,1,127,35,23,33,0,35,34,4,64,65,144,2,65,208,2,65,226,3,65,4,16,0,0,11,32,0,16,21,16,23,11,39,1,1,127,3,64,32,0,65,32,73,4,64,32,0,35,7,106,65,0,58,0,0,32,0,65,1,106,33,0,12,1,11,11,65,32,16,15,26,11,152,2,1,1,127,3,64,32,4,65,32,72,4,64,32,4,35,9,106,32,0,32,4,106,45,0,0,58,0,0,32,4,65,1,106,33,4,12,1,11,11,65,0,33,4,3,64,32,4,65,4,72,4,64,32,4,35,11,106,65,0,58,0,0,32,4,65,1,106,33,4,12,1,11,11,65,4,33,4,3,64,32,4,65,16,72,4,64,32,4,35,11,106,32,1,32,4,65,4,107,106,45,0,0,58,0,0,32,4,65,1,106,33,4,12,1,11,11,16,25,65,0,33,4,3,64,32,4,65,32,72,4,64,32,4,35,21,106,32,4,35,13,106,45,0,0,58,0,0,32,4,65,1,106,33,4,12,1,11,11,35,21,16,16,32,3,65,0,75,4,64,65,0,33,4,3,64,32,4,32,3,73,4,64,32,4,35,22,106,32,2,32,4,106,45,0,0,58,0,0,32,4,65,1,106,33,4,12,1,11,11,32,3,16,20,32,3,65,15,113,65,0,75,4,64,65,16,32,3,65,15,113,107,34,1,65,0,74,4,64,65,0,33,0,3,64,32,0,32,1,72,4,64,32,0,35,22,106,65,0,58,0,0,32,0,65,1,106,33,0,12,1,11,11,32,1,16,20,11,11,11,11,65,1,1,127,3,64,32,2,32,1,73,4,64,35,22,32,2,106,32,0,32,2,106,45,0,0,58,0,0,35,7,32,2,106,32,0,32,2,106,45,0,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,1,16,20,32,1,16,15,26,11,27,0,32,0,32,1,65,0,16,10,32,0,173,66,128,128,128,128,16,127,167,32,1,65,4,16,10,11,87,1,2,127,32,0,65,15,113,65,0,75,4,64,65,16,32,0,65,15,113,107,34,3,65,0,74,4,64,3,64,32,2,32,3,72,4,64,32,2,35,22,106,65,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,3,16,20,11,11,32,1,35,22,16,28,65,8,16,20,32,0,35,22,16,28,65,8,16,20,16,24,11,34,0,32,0,4,64,35,38,35,40,35,42,32,4,16,26,11,35,44,32,2,16,27,32,1,4,64,32,3,32,4,16,29,11,11,89,1,1,127,3,64,32,2,32,1,73,4,64,35,7,32,2,106,32,0,32,2,106,45,0,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,1,16,15,26,65,0,33,2,3,64,32,2,32,1,73,4,64,35,22,32,2,106,32,2,35,13,106,45,0,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,1,16,20,11,34,0,32,0,4,64,35,38,35,40,35,42,32,4,16,26,11,35,44,32,2,16,31,32,1,4,64,32,3,32,4,16,29,11,11,8,0,16,5,16,8,16,9,11,11,234,2,6,0,65,16,11,43,28,0,0,0,1,0,0,0,1,0,0,0,28,0,0,0,73,0,110,0,118,0,97,0,108,0,105,0,100,0,32,0,108,0,101,0,110,0,103,0,116,0,104,0,65,192,0,11,53,38,0,0,0,1,0,0,0,1,0,0,0,38,0,0,0,126,0,108,0,105,0,98,0,47,0,97,0,114,0,114,0,97,0,121,0,98,0,117,0,102,0,102,0,101,0,114,0,46,0,116,0,115,0,65,128,1,11,63,48,0,0,0,1,0,0,0,1,0,0,0,48,0,0,0,67,0,104,0,97,0,67,0,104,0,97,0,58,0,32,0,99,0,111,0,117,0,110,0,116,0,101,0,114,0,32,0,111,0,118,0,101,0,114,0,102,0,108,0,111,0,119,0,65,192,1,11,55,40,0,0,0,1,0,0,0,1,0,0,0,40,0,0,0,97,0,115,0,115,0,101,0,109,0,98,0,108,0,121,0,47,0,99,0,104,0,97,0,99,0,104,0,97,0,50,0,48,0,46,0,116,0,115,0,65,128,2,11,57,42,0,0,0,1,0,0,0,1,0,0,0,42,0,0,0,80,0,111,0,108,0,121,0,49,0,51,0,48,0,53,0,32,0,119,0,97,0,115,0,32,0,102,0,105,0,110,0,105,0,115,0,104,0,101,0,100,0,65,192,2,11,55,40,0,0,0,1,0,0,0,1,0,0,0,40,0,0,0,97,0,115,0,115,0,101,0,109,0,98,0,108,0,121,0,47,0,112,0,111,0,108,0,121,0,49,0,51,0,48,0,53,0,46,0,116,0,115])});var Dw=At(r1=>{"use strict";Object.defineProperty(r1,"__esModule",{value:!0});r1.newInstance=void 0;var aH=uT(),cH=new WebAssembly.Module(aH.wasmCode),lH={env:{abort:function(r,e,t,n){throw Error(`abort: ${r}:${e}:${t}:${n}`)}}};function uH(){return new WebAssembly.Instance(cH,lH).exports}r1.newInstance=uH});var fT=At(n1=>{"use strict";Object.defineProperty(n1,"__esModule",{value:!0});n1.chacha20StreamXOR=void 0;var hH=Dw(),fn=hH.newInstance(),dH=fn.chacha20Input.value,fH=fn.chacha20Output.value,pH=fn.chacha20Key.value,mH=fn.chacha20Counter.value,{CHACHA20_INPUT_LENGTH:Ia,KEY_LENGTH:kw,CHACHA20_COUNTER_LENGTH:dT}=fn,gH=new Uint8Array(fn.memory.buffer,dH,Ia),hT=new Uint8Array(fn.memory.buffer,fH,Ia),yH=new Uint8Array(fn.memory.buffer,pH,kw),bH=new Uint8Array(fn.memory.buffer,mH,dT);function wH(r,e,t){if(r.length!=kw)throw new Error("ChaCha: key size must be 32 bytes, expected "+kw+" got "+r.length);if(e.length!=dT)throw new Error("ChaCha nonce with counter must be 16 bytes");yH.set(r),bH.set(e);let n=new Uint8Array(t.length),s=Math.floor(t.length/Ia);for(let o=0;o<=s;o++){let i=o*Ia,a=Math.min((o+1)*Ia,t.length);gH.set(s===0?t:t.subarray(i,a));let c=a-i,l=fn.chacha20StreamXORUpdate(c);n.set(l===Ia?hT:hT.subarray(0,l),i)}return n}n1.chacha20StreamXOR=wH});var pT=At(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.newInstance=pn.chacha20StreamXOR=pn.Poly1305=pn.ChaCha20Poly1305=void 0;var xH=cT();Object.defineProperty(pn,"ChaCha20Poly1305",{enumerable:!0,get:function(){return xH.ChaCha20Poly1305}});var vH=lT();Object.defineProperty(pn,"Poly1305",{enumerable:!0,get:function(){return vH.Poly1305}});var EH=fT();Object.defineProperty(pn,"chacha20StreamXOR",{enumerable:!0,get:function(){return EH.chacha20StreamXOR}});var SH=Dw();Object.defineProperty(pn,"newInstance",{enumerable:!0,get:function(){return SH.newInstance}})});var vT=At((r4e,xT)=>{function OH(){return!!(typeof window<"u"&&typeof window.process=="object"&&window.process.type==="renderer"||typeof process<"u"&&typeof process.versions=="object"&&process.versions.electron||typeof navigator=="object"&&typeof navigator.userAgent=="string"&&navigator.userAgent.indexOf("Electron")>=0)}xT.exports=OH});var wP=At((eCe,bP)=>{"use strict";function ze(r,t){var t=t||{};this._capacity=t.capacity,this._head=0,this._tail=0,Array.isArray(r)?this._fromArray(r):(this._capacityMask=3,this._list=new Array(4))}ze.prototype.peekAt=function(e){var t=e;if(t===(t|0)){var n=this.size();if(!(t>=n||t<-n))return t<0&&(t+=n),t=this._head+t&this._capacityMask,this._list[t]}};ze.prototype.get=function(e){return this.peekAt(e)};ze.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]};ze.prototype.peekFront=function(){return this.peek()};ze.prototype.peekBack=function(){return this.peekAt(-1)};Object.defineProperty(ze.prototype,"length",{get:function(){return this.size()}});ze.prototype.size=function(){return this._head===this._tail?0:this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};ze.prototype.unshift=function(e){if(arguments.length===0)return this.size();var t=this._list.length;return this._head=this._head-1+t&this._capacityMask,this._list[this._head]=e,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.pop(),this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};ze.prototype.shift=function(){var e=this._head;if(e!==this._tail){var t=this._list[e];return this._list[e]=void 0,this._head=e+1&this._capacityMask,e<2&&this._tail>1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}};ze.prototype.push=function(e){if(arguments.length===0)return this.size();var t=this._tail;return this._list[t]=e,this._tail=t+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.shift(),this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};ze.prototype.pop=function(){var e=this._tail;if(e!==this._head){var t=this._list.length;this._tail=e-1+t&this._capacityMask;var n=this._list[this._tail];return this._list[this._tail]=void 0,this._head<2&&e>1e4&&e<=t>>>2&&this._shrinkArray(),n}};ze.prototype.removeOne=function(e){var t=e;if(t===(t|0)&&this._head!==this._tail){var n=this.size(),s=this._list.length;if(!(t>=n||t<-n)){t<0&&(t+=n),t=this._head+t&this._capacityMask;var o=this._list[t],i;if(e<n/2){for(i=e;i>0;i--)this._list[t]=this._list[t=t-1+s&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+s&this._capacityMask}else{for(i=n-1-e;i>0;i--)this._list[t]=this._list[t=t+1+s&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+s&this._capacityMask}return o}}};ze.prototype.remove=function(e,t){var n=e,s,o=t;if(n===(n|0)&&this._head!==this._tail){var i=this.size(),a=this._list.length;if(!(n>=i||n<-i||t<1)){if(n<0&&(n+=i),t===1||!t)return s=new Array(1),s[0]=this.removeOne(n),s;if(n===0&&n+t>=i)return s=this.toArray(),this.clear(),s;n+t>i&&(t=i-n);var c;for(s=new Array(t),c=0;c<t;c++)s[c]=this._list[this._head+n+c&this._capacityMask];if(n=this._head+n&this._capacityMask,e+t===i){for(this._tail=this._tail-t+a&this._capacityMask,c=t;c>0;c--)this._list[n=n+1+a&this._capacityMask]=void 0;return s}if(e===0){for(this._head=this._head+t+a&this._capacityMask,c=t-1;c>0;c--)this._list[n=n+1+a&this._capacityMask]=void 0;return s}if(n<i/2){for(this._head=this._head+e+t+a&this._capacityMask,c=e;c>0;c--)this.unshift(this._list[n=n-1+a&this._capacityMask]);for(n=this._head-1+a&this._capacityMask;o>0;)this._list[n=n-1+a&this._capacityMask]=void 0,o--;e<0&&(this._tail=n)}else{for(this._tail=n,n=n+t+a&this._capacityMask,c=i-(t+e);c>0;c--)this.push(this._list[n++]);for(n=this._tail;o>0;)this._list[n=n+1+a&this._capacityMask]=void 0,o--}return this._head<2&&this._tail>1e4&&this._tail<=a>>>2&&this._shrinkArray(),s}}};ze.prototype.splice=function(e,t){var n=e;if(n===(n|0)){var s=this.size();if(n<0&&(n+=s),!(n>s))if(arguments.length>2){var o,i,a,c=arguments.length,l=this._list.length,u=2;if(!s||n<s/2){for(i=new Array(n),o=0;o<n;o++)i[o]=this._list[this._head+o&this._capacityMask];for(t===0?(a=[],n>0&&(this._head=this._head+n+l&this._capacityMask)):(a=this.remove(n,t),this._head=this._head+n+l&this._capacityMask);c>u;)this.unshift(arguments[--c]);for(o=n;o>0;o--)this.unshift(i[o-1])}else{i=new Array(s-(n+t));var h=i.length;for(o=0;o<h;o++)i[o]=this._list[this._head+n+t+o&this._capacityMask];for(t===0?(a=[],n!=s&&(this._tail=this._head+n+l&this._capacityMask)):(a=this.remove(n,t),this._tail=this._tail-h+l&this._capacityMask);u<c;)this.push(arguments[u++]);for(o=0;o<h;o++)this.push(i[o])}return a}else return this.remove(n,t)}};ze.prototype.clear=function(){this._list=new Array(this._list.length),this._head=0,this._tail=0};ze.prototype.isEmpty=function(){return this._head===this._tail};ze.prototype.toArray=function(){return this._copyArray(!1)};ze.prototype._fromArray=function(e){var t=e.length,n=this._nextPowerOf2(t);this._list=new Array(n),this._capacityMask=n-1,this._tail=t;for(var s=0;s<t;s++)this._list[s]=e[s]};ze.prototype._copyArray=function(e,t){var n=this._list,s=n.length,o=this.length;if(t=t|o,t==o&&this._head<this._tail)return this._list.slice(this._head,this._tail);var i=new Array(t),a=0,c;if(e||this._head>this._tail){for(c=this._head;c<s;c++)i[a++]=n[c];for(c=0;c<this._tail;c++)i[a++]=n[c]}else for(c=this._head;c<this._tail;c++)i[a++]=n[c];return i};ze.prototype._growArray=function(){if(this._head!=0){var e=this._copyArray(!0,this._list.length<<1);this._tail=this._list.length,this._head=0,this._list=e}else this._tail=this._list.length,this._list.length<<=1;this._capacityMask=this._capacityMask<<1|1};ze.prototype._shrinkArray=function(){this._list.length>>>=1,this._capacityMask>>>=1};ze.prototype._nextPowerOf2=function(e){var t=Math.log(e)/Math.log(2),n=1<<t+1;return Math.max(n,4)};bP.exports=ze});var zj={};z(zj,{ArachnodeFretAdapter:()=>$l,BlockStorage:()=>Bi,ClusterClient:()=>ro,ClusterCoordinator:()=>ml,ClusterMember:()=>Cd,ClusterService:()=>Td,CoordinatorRepo:()=>_d,Libp2pKeyPeerNetwork:()=>Xl,MemoryRawStorage:()=>gl,NetworkManagerService:()=>xm,ProtocolClient:()=>Cn,RepoClient:()=>Xg,RepoService:()=>Dd,RestorationCoordinator:()=>Kl,RingSelector:()=>Fl,SYNC_PROTOCOL_PREFIX:()=>dA,SYNC_PROTOCOL_VERSION:()=>fA,StorageMonitor:()=>zl,StorageRepo:()=>yl,SyncClient:()=>ho,SyncService:()=>cf,asyncIteratorToArray:()=>uc,buildKnownPeers:()=>Uj,buildSyncProtocol:()=>Ul,clusterMember:()=>jg,clusterService:()=>Yg,computeResponsibility:()=>Bj,coordinatorRepo:()=>Qg,createLibp2pNode:()=>Nj,first:()=>Lm,getNetworkManager:()=>Fj,lessThanLex:()=>LD,networkManagerService:()=>B5,reduce:()=>ek,repoService:()=>Jg,sortPeersByDistance:()=>MD,syncService:()=>l3,xorDistanceBytes:()=>kD});function ut(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var ch=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},jo=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new ch(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new ch(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Em=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Ot(r={}){return KD(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function KD(r,e){e=e??{};let t=e.onEnd,n=new jo,s,o,i,a=ut(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,y)=>{o=b=>{o=null,n.push(b);try{g(r(n))}catch(w){y(w)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ut()})}},l=g=>o!=null?o(g):(n.push(g),s),u=g=>(n=new jo,o!=null?o({error:g}):(n.push({error:g}),s)),h=g=>{if(i)return s;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:g})},p=g=>i?s:(i=!0,g!=null?u(g):l({done:!0})),f=()=>(n=new jo,p(),{done:!0}),d=g=>(p(g),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:f,throw:d,push:h,end:p,get readableLength(){return n.size},onEmpty:async g=>{let y=g?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let b,w;y!=null&&(b=new Promise((x,v)=>{w=()=>{v(new Em)},y.addEventListener("abort",w)}));try{await Promise.race([a.promise,b])}finally{w!=null&&y!=null&&y?.removeEventListener("abort",w)}}},t==null)return s;let m=s;return s={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(g){return m.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:h,end(g){return m.end(g),t!=null&&(t(g),t=void 0),s},get readableLength(){return m.readableLength},onEmpty:g=>m.onEmpty(g)},s}var lh=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function uh(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new lh(t?.errorMessage,t?.errorCode,t?.errorName));let n,s=new lh(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((o,i)=>{n=()=>{i(s)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Sm=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ut(),this.haveNext=ut()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ut(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ut(),await uh(this.readNext.promise,t?.signal,t)}};function H5(){return new Sm}function FD(r){return r[Symbol.asyncIterator]!=null}async function zD(r,e,t){try{await Promise.all(r.map(async n=>{for await(let s of n)await e.push(s,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*$D(r){let e=new AbortController,t=H5();zD(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*HD(r){for(let e of r)yield*e}function qD(...r){let e=[];for(let t of r)FD(t)||e.push(t);return e.length===r.length?HD(e):$D(r)}var Ks=qD;function ht(r,...e){if(r==null)throw new Error("Empty pipeline");if(Im(r)){let n=r;r=()=>n.source}else if(V5(r)||q5(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&Im(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)Im(t[n])&&(t[n]=GD(t[n]));return VD(...t)}var VD=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},q5=r=>r?.[Symbol.asyncIterator]!=null,V5=r=>r?.[Symbol.iterator]!=null,Im=r=>r==null?!1:r.sink!=null&&r.source!=null,GD=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=Ot({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(q5(o))s=async function*(){yield*o,n.end()};else if(V5(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Ks(n,s())}return r.source};gr();Be();rt();var dh=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Yo=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},fh=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},lc=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function ph(r){return r[Symbol.asyncIterator]!=null}function Y5(r,e){if(r.byteLength>e)throw new Yo("Message length too long")}var gh=r=>{let e=Ae(r),t=tt(e);return Vr(r,t),gh.bytes=e,t};gh.bytes=0;function yr(r,e){e=e??{};let t=e.lengthEncoder??gh,n=e?.maxDataLength??4194304;function*s(o){Y5(o,n);let i=t(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return ph(r)?(async function*(){for await(let o of r)yield*s(o)})():(function*(){for(let o of r)yield*s(o)})()}yr.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??gh,n=e?.maxDataLength??4194304;return Y5(r,n),new U(t(r.byteLength),r)};gr();Be();var Fs;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Fs||(Fs={}));var km=r=>{let e=jt(r);return km.bytes=Ae(e),e};km.bytes=0;function Pr(r,e){let t=new U,n=Fs.LENGTH,s=-1,o=e?.lengthDecoder??km,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Fs.LENGTH)try{if(s=o(t),s<0)throw new dh("Invalid message length");if(s>a)throw new Yo("Message length too long");let l=o.bytes;t.consume(l),e?.onLength!=null&&e.onLength(s),n=Fs.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new fh("Message length length too long");break}throw l}if(n===Fs.DATA){if(t.byteLength<s)break;let l=t.sublist(0,s);t.consume(s),e?.onData!=null&&e.onData(l),yield l,n=Fs.LENGTH}}}return ph(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new lc("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new lc("Unexpected end of input")})()}Pr.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:o,value:i}=await r.next(t);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}})();return Pr(n,{...e??{},onLength:o=>{t=o}})};async function Lm(r,e=()=>{throw new Error("No items found")},t){let n=new AbortController,s=typeof t=="number"?setTimeout(()=>n.abort(),t):void 0;try{for await(let o of r(n.signal))return o;return e()}finally{s!==void 0&&clearTimeout(s),n.abort()}}async function uc(r){let e=[];for await(let t of r)e.push(t);return e}function ek(r,e,t){let n=t,s=0;for(let o of r)n=e(n,o,s),++s;return n}var Cn=class{peerId;peerNetwork;constructor(e,t){this.peerId=e,this.peerNetwork=t}async processMessage(e,t,n){let s=await this.peerNetwork.connect(this.peerId,t,{signal:n?.signal});try{let o=ht([new TextEncoder().encode(JSON.stringify(e))],yr);for await(let a of o)s.send(a);let i=ht(s,Pr,async function*(a){for await(let c of a){let l=new TextDecoder().decode(c.subarray());yield JSON.parse(l)}});return await Lm(()=>i,()=>{throw new Error("No response received")})}finally{await s.close()}}};ke();var ro=class r extends Cn{protocolPrefix;constructor(e,t,n){super(e,t),this.protocolPrefix=n}static create(e,t,n){return new r(e,t,n)}async update(e,t=0){let n={operation:"update",record:e},s=(this.protocolPrefix??"/db-p2p")+"/cluster/1.0.0",o;try{o=await this.processMessage(n,s)}catch(i){if(s!=="/db-p2p/cluster/1.0.0")o=await this.processMessage(n,"/db-p2p/cluster/1.0.0");else throw i}if(o?.redirect?.peers?.length){if(t>=2)throw new Error("Redirect loop detected in ClusterClient (max hops reached)");let i=this.peerId.toString(),a=o.redirect.peers.find(u=>u.id!==i)??o.redirect.peers[0],c=de(a.id);if(a.id===i)throw new Error("Redirect loop detected in ClusterClient (same peer)");return this.recordCoordinatorForRecordIfSupported(e,c),await r.create(c,this.peerNetwork,this.protocolPrefix).update(e,t+1)}return o}recordCoordinatorForRecordIfSupported(e,t){let n=e?.message,s;if(n?.commit?.tailId)s=n.commit.tailId;else if(n?.pend?.transforms){let o=Object.keys(n.pend.transforms);o.length>0&&(s=o[0])}if(s){let o=new TextEncoder().encode(s),i=this.peerNetwork;typeof i?.recordCoordinator=="function"&&i.recordCoordinator(o,t)}}};var G2=new Map;function tn(r,e){if(G2.has(r))throw new Error(`Block type ${r} (${e}) already registered (${G2.get(r)})`);return G2.set(r,e),r}function pd(r,[e,t,n,s]){Array.isArray(s)?r[e].splice(t,n,...structuredClone(s)):r[e]=structuredClone(s)}function EM(r,e){for(let t of e)pd(r,t)}function gs(r){if(!r)return[];let e=Object.keys(r.inserts??{}),t=Object.keys(r.updates??{}),n=r.deletes??[];return[...new Set([...e,...t,...n])]}function W2(){return{inserts:{},updates:{},deletes:[]}}function md(r,e){return{...r.inserts&&e in r.inserts?{insert:r.inserts[e]}:{},...r.updates&&e in r.updates?{updates:structuredClone(r.updates[e])}:{},...r.deletes?.includes(e)?{delete:!0}:{}}}function j2(r,e){return{inserts:r.insert?{[e]:r.insert}:{},updates:r.updates?{[e]:r.updates}:{},deletes:r.delete?[e]:[]}}function cl(r,e){if(e.insert&&(r=e.insert),r&&e.updates&&EM(r,e.updates),!e.delete)return r}function Y2(r,e,t){return{inserts:{...r.inserts,...t.insert?{[e]:t.insert}:{}},updates:{...r.updates,...t.updates?{[e]:t.updates}:{}},deletes:[...r.deletes??[],...t.delete?[e]:[]]}}function Xt(r,e){return e??r}var SM=tn("TL","TreeLeaf"),IM=tn("TB","TreeBranch"),AM=Xt("entries"),CM=Xt("partitions"),TM=Xt("nodes");var DM=Xt("entries"),kM=Xt("priorId"),LM=Xt("nextId"),MM=tn("CHD","ChainDataBlock"),OM=Xt("headId"),RM=Xt("tailId"),NM=tn("CHH","ChainHeaderBlock");var $E=ee("node:buffer");function zE(r){return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}function HE(r=0){return zE($E.Buffer.allocUnsafe(r))}var eg={};z(eg,{base10:()=>qM});var Ire=new Uint8Array(0);function qE(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function vr(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function VE(r){return new TextEncoder().encode(r)}function GE(r){return new TextDecoder().decode(r)}function UM(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var v=d[y],S=0,E=w-1;(v!==0||S<g)&&E!==-1;E--,S++)v+=256*x[E]>>>0,x[E]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var A=c.repeat(m);I<w;++I)A+=r.charAt(x[I]);return A}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*w[S]>>>0,w[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(d[m]!==" "){for(var E=b-y;E!==b&&w[E]===0;)E++;for(var I=new Uint8Array(g+(b-E)),A=g;E!==b;)I[A++]=w[E++];return I}}}function f(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:f}}var KM=UM,FM=KM,jE=FM;var X2=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Q2=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return YE(this,e)}},J2=class{decoders;constructor(e){this.decoders=e}or(e){return YE(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function YE(r,e){return new J2({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Z2=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new X2(e,t,n),this.decoder=new Q2(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ti({name:r,prefix:e,encode:t,decode:n}){return new Z2(r,e,t,n)}function ys({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=jE(t,r);return Ti({prefix:e,name:r,encode:n,decode:o=>vr(s(o))})}function zM(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function $M(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function HM(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function He({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=HM(n);return Ti({prefix:e,name:r,encode(o){return $M(o,n,t)},decode(o){return zM(o,s,t,r)}})}var qM=ys({prefix:"9",name:"base10",alphabet:"0123456789"});var tg={};z(tg,{base16:()=>VM,base16upper:()=>GM});var VM=He({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),GM=He({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var rg={};z(rg,{base2:()=>WM});var WM=He({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ng={};z(ng,{base256emoji:()=>JM});var XE=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),jM=XE.reduce((r,e,t)=>(r[t]=e,r),[]),YM=XE.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function XM(r){return r.reduce((e,t)=>(e+=jM[t],e),"")}function QM(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=YM[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var JM=Ti({prefix:"\u{1F680}",name:"base256emoji",encode:XM,decode:QM});var sg={};z(sg,{base32:()=>_i,base32hex:()=>rO,base32hexpad:()=>sO,base32hexpadupper:()=>oO,base32hexupper:()=>nO,base32pad:()=>eO,base32padupper:()=>tO,base32upper:()=>ZM,base32z:()=>iO});var _i=He({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ZM=He({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),eO=He({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),tO=He({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),rO=He({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),nO=He({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),sO=He({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),oO=He({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),iO=He({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var og={};z(og,{base36:()=>ll,base36upper:()=>aO});var ll=ys({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),aO=ys({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ig={};z(ig,{base58btc:()=>rn,base58flickr:()=>cO});var rn=ys({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),cO=ys({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ag={};z(ag,{base64:()=>lO,base64pad:()=>uO,base64url:()=>hO,base64urlpad:()=>dO});var lO=He({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),uO=He({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),hO=He({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),dO=He({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var cg={};z(cg,{base8:()=>fO});var fO=He({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var lg={};z(lg,{identity:()=>pO});var pO=Ti({prefix:"\0",name:"identity",encode:r=>GE(r),decode:r=>VE(r)});var Fre=new TextEncoder,zre=new TextDecoder;var hg={};z(hg,{identity:()=>BO});var yO=ZE,QE=128,bO=127,wO=~bO,xO=Math.pow(2,31);function ZE(r,e,t){e=e||[],t=t||0;for(var n=t;r>=xO;)e[t++]=r&255|QE,r/=128;for(;r&wO;)e[t++]=r&255|QE,r>>>=7;return e[t]=r|0,ZE.bytes=t-n+1,e}var vO=ug,EO=128,JE=127;function ug(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw ug.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&JE)<<s:(i&JE)*Math.pow(2,s),s+=7}while(i>=EO);return ug.bytes=o-n,t}var SO=Math.pow(2,7),IO=Math.pow(2,14),AO=Math.pow(2,21),CO=Math.pow(2,28),TO=Math.pow(2,35),_O=Math.pow(2,42),PO=Math.pow(2,49),DO=Math.pow(2,56),kO=Math.pow(2,63),LO=function(r){return r<SO?1:r<IO?2:r<AO?3:r<CO?4:r<TO?5:r<_O?6:r<PO?7:r<DO?8:r<kO?9:10},MO={encode:yO,decode:vO,encodingLength:LO},OO=MO,ul=OO;function hl(r,e=0){return[ul.decode(r,e),ul.decode.bytes]}function Pi(r,e,t=0){return ul.encode(r,e,t),e}function Di(r){return ul.encodingLength(r)}function Li(r,e){let t=e.byteLength,n=Di(r),s=n+Di(t),o=new Uint8Array(s+t);return Pi(r,o,0),Pi(t,o,n),o.set(e,s),new ki(r,t,e,o)}function eS(r){let e=vr(r),[t,n]=hl(e),[s,o]=hl(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new ki(t,s,i,e)}function tS(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&qE(r.bytes,t.bytes)}}var ki=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var rS=0,RO="identity",nS=vr;function NO(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Li(rS,nS(r))}var BO={code:rS,name:RO,encode:nS,digest:NO};var mg={};z(mg,{sha256:()=>KO,sha512:()=>FO});var pg=ie(ee("crypto"),1);var UO=20;function fg({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new dg(r,e,t,n,s)}var dg=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??UO,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?sS(n,this.code,t?.truncate):n.then(s=>sS(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function sS(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Li(e,r)}var KO=fg({name:"sha2-256",code:18,encode:r=>vr(pg.default.createHash("sha256").update(r).digest())}),FO=fg({name:"sha2-512",code:19,encode:r=>vr(pg.default.createHash("sha512").update(r).digest())});function iS(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return $O(t,gg(r),e??rn.encoder);default:return HO(t,gg(r),e??_i.encoder)}}var aS=new WeakMap;function gg(r){let e=aS.get(r);if(e==null){let t=new Map;return aS.set(r,t),t}return e}var yd=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==fl)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==qO)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Li(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&tS(e.multihash,n.multihash)}toString(e){return iS(this,e)}toJSON(){return{"/":iS(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??cS(n,s,o.bytes))}else if(t[VO]===!0){let{version:n,multihash:s,code:o}=t,i=eS(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==fl)throw new Error(`Version 0 CID must use dag-pb (code: ${fl}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=cS(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,fl,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=vr(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new ki(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,p]=hl(e.subarray(t));return t+=p,h},s=n(),o=fl;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=zO(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return gg(o).set(n,e),o}};function zO(r,e){switch(r[0]){case"Q":{let t=e??rn;return[rn.prefix,t.decode(`${rn.prefix}${r}`)]}case rn.prefix:{let t=e??rn;return[rn.prefix,t.decode(r)]}case _i.prefix:{let t=e??_i;return[_i.prefix,t.decode(r)]}case ll.prefix:{let t=e??ll;return[ll.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function $O(r,e,t){let{prefix:n}=t;if(n!==rn.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function HO(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var fl=112,qO=18;function cS(r,e,t){let n=Di(r),s=n+Di(e),o=new Uint8Array(s+t.byteLength);return Pi(r,o,0),Pi(e,o,n),o.set(t,s),o}var VO=Symbol.for("@ipld/js-cid/CID");var yg={...lg,...rg,...cg,...eg,...tg,...sg,...og,...ig,...ag,...ng},une={...mg,...hg};function uS(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var lS=uS("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),bg=uS("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=HE(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),pne={utf8:lS,"utf-8":lS,hex:yg.base16,latin1:bg,ascii:bg,binary:bg,...yg};var no=class{static lockQueues=new Map;static async acquire(e){let t=this.lockQueues.get(e)??Promise.resolve(),n,s=new Promise(i=>{n=i});return this.lockQueues.set(e,s),await t,()=>{n(),this.lockQueues.get(e)===s&&this.lockQueues.delete(e)}}};var YO=tn("DIH","DiaryHeaderBlock");var XO=tn("TRE","TreeHeaderBlock"),QO=Xt("rootId");var Cg=ie(ee("crypto"),1);var nse=new Uint8Array(0);function bd(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var JO=pS,dS=128,ZO=127,eR=~ZO,tR=Math.pow(2,31);function pS(r,e,t){e=e||[],t=t||0;for(var n=t;r>=tR;)e[t++]=r&255|dS,r/=128;for(;r&eR;)e[t++]=r&255|dS,r>>>=7;return e[t]=r|0,pS.bytes=t-n+1,e}var rR=wg,nR=128,fS=127;function wg(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw wg.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&fS)<<s:(i&fS)*Math.pow(2,s),s+=7}while(i>=nR);return wg.bytes=o-n,t}var sR=Math.pow(2,7),oR=Math.pow(2,14),iR=Math.pow(2,21),aR=Math.pow(2,28),cR=Math.pow(2,35),lR=Math.pow(2,42),uR=Math.pow(2,49),hR=Math.pow(2,56),dR=Math.pow(2,63),fR=function(r){return r<sR?1:r<oR?2:r<iR?3:r<aR?4:r<cR?5:r<lR?6:r<uR?7:r<hR?8:r<dR?9:10},pR={encode:JO,decode:rR,encodingLength:fR},mR=pR,xg=mR;function vg(r,e,t=0){return xg.encode(r,e,t),e}function Eg(r){return xg.encodingLength(r)}function mS(r,e){let t=e.byteLength,n=Eg(r),s=n+Eg(t),o=new Uint8Array(s+t);return vg(r,o,0),vg(t,o,n),o.set(e,s),new Sg(r,t,e,o)}var Sg=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var bR=20;function Ag({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new Ig(r,e,t,n,s)}var Ig=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??bR,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?gS(n,this.code,t?.truncate):n.then(s=>gS(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function gS(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return mS(e,r)}var yS=Ag({name:"sha2-256",code:18,encode:r=>bd(Cg.default.createHash("sha256").update(r).digest())}),fse=Ag({name:"sha2-512",code:19,encode:r=>bd(Cg.default.createHash("sha512").update(r).digest())});var vse=Xt("priorHash");Tg();Tg();var so=class{promise;response;error;t1=Date.now();duration;get isResponse(){return this.response!==void 0}get isError(){return this.error!==void 0}get isComplete(){return this.isResponse||this.isError}async result(){if(this.isResponse)return this.response;if(this.isError)throw this.error;return await this.promise}constructor(e){this.promise=e,e.then(t=>(this.duration=Date.now()-this.t1,this.response=t,t),t=>{this.duration=Date.now()-this.t1,this.error=t})}};function _g(r,e){return r.reduce((t,n)=>{let s=e(n);return(t[s]??=[]).push(n),t},{})}ke();var Ng=ie(ee("crypto"),1);var mie=new Uint8Array(0);function Mi(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var xR=SS,vS=128,vR=127,ER=~vR,SR=Math.pow(2,31);function SS(r,e,t){e=e||[],t=t||0;for(var n=t;r>=SR;)e[t++]=r&255|vS,r/=128;for(;r&ER;)e[t++]=r&255|vS,r>>>=7;return e[t]=r|0,SS.bytes=t-n+1,e}var IR=Pg,AR=128,ES=127;function Pg(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Pg.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&ES)<<s:(i&ES)*Math.pow(2,s),s+=7}while(i>=AR);return Pg.bytes=o-n,t}var CR=Math.pow(2,7),TR=Math.pow(2,14),_R=Math.pow(2,21),PR=Math.pow(2,28),DR=Math.pow(2,35),kR=Math.pow(2,42),LR=Math.pow(2,49),MR=Math.pow(2,56),OR=Math.pow(2,63),RR=function(r){return r<CR?1:r<TR?2:r<_R?3:r<PR?4:r<DR?5:r<kR?6:r<LR?7:r<MR?8:r<OR?9:10},NR={encode:xR,decode:IR,encodingLength:RR},BR=NR,Dg=BR;function kg(r,e,t=0){return Dg.encode(r,e,t),e}function Lg(r){return Dg.encodingLength(r)}function IS(r,e){let t=e.byteLength,n=Lg(r),s=n+Lg(t),o=new Uint8Array(s+t);return kg(r,o,0),kg(t,o,n),o.set(e,s),new Mg(r,t,e,o)}var Mg=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var FR=20;function Rg({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new Og(r,e,t,n,s)}var Og=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??FR,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?AS(n,this.code,t?.truncate):n.then(s=>AS(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function AS(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return IS(e,r)}var nn=Rg({name:"sha2-256",code:18,encode:r=>Mi(Ng.default.createHash("sha256").update(r).digest())}),Aie=Rg({name:"sha2-512",code:19,encode:r=>Mi(Ng.default.createHash("sha512").update(r).digest())});function zR(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var v=d[y],S=0,E=w-1;(v!==0||S<g)&&E!==-1;E--,S++)v+=256*x[E]>>>0,x[E]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var A=c.repeat(m);I<w;++I)A+=r.charAt(x[I]);return A}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*w[S]>>>0,w[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(d[m]!==" "){for(var E=b-y;E!==b&&w[E]===0;)E++;for(var I=new Uint8Array(g+(b-E)),A=g;E!==b;)I[A++]=w[E++];return I}}}function f(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:f}}var $R=zR,HR=$R,CS=HR;var Bg=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Ug=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return TS(this,e)}},Kg=class{decoders;constructor(e){this.decoders=e}or(e){return TS(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function TS(r,e){return new Kg({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Fg=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new Bg(e,t,n),this.decoder=new Ug(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function qR({name:r,prefix:e,encode:t,decode:n}){return new Fg(r,e,t,n)}function zg({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=CS(t,r);return qR({prefix:e,name:r,encode:n,decode:o=>Mi(s(o))})}var wd=zg({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Lie=zg({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});ce();var NS=ie(Wg(),1),m9="optimystic:db-p2p";function Sr(r){return(0,NS.default)(`${m9}:${r}`)}var be=Sr("cluster-member"),xt;(function(r){r[r.Promising=0]="Promising",r[r.OurPromiseNeeded=1]="OurPromiseNeeded",r[r.OurCommitNeeded=2]="OurCommitNeeded",r[r.Consensus=3]="Consensus",r[r.Rejected=4]="Rejected",r[r.Propagating=5]="Propagating"})(xt||(xt={}));function jg(r){return new Cd(r.storageRepo,r.peerNetwork,r.peerId,r.protocolPrefix,r.partitionDetector,r.fretService,r.validator)}var g9=600*1e3,Cd=class{storageRepo;peerNetwork;peerId;protocolPrefix;partitionDetector;fretService;validator;activeTransactions=new Map;executedTransactions=new Map;cleanupQueue=[];pendingUpdates=new Map;constructor(e,t,n,s,o,i,a){this.storageRepo=e,this.peerNetwork=t,this.peerId=n,this.protocolPrefix=s,this.partitionDetector=o,this.fretService=i,this.validator=a,setInterval(()=>this.queueExpiredTransactions(),6e4),setInterval(()=>this.processCleanupQueue(),1e3)}wasTransactionExecuted(e){return this.executedTransactions.has(e)}async update(e){let t=this.pendingUpdates.get(e.messageHash);t&&(be("cluster-member:concurrent-update-wait",{messageHash:e.messageHash}),await t);let n=this.processUpdate(e);this.pendingUpdates.set(e.messageHash,n);try{return await n}finally{setTimeout(()=>{this.pendingUpdates.delete(e.messageHash)},100)}}async processUpdate(e){let t=this.peerId.toString(),n=e.commits[t]?"commit":e.promises[t]?"promise":"initial";if(be("cluster-member:incoming",{messageHash:e.messageHash,phase:n,peerCount:Object.keys(e.peers).length,promiseCount:Object.keys(e.promises).length,commitCount:Object.keys(e.commits).length,existingTransaction:this.activeTransactions.has(e.messageHash)}),this.fretService&&e.networkSizeHint&&e.networkSizeConfidence)try{this.fretService.reportNetworkSize(e.networkSizeHint,e.networkSizeConfidence,"cluster")}catch{}await this.validateRecord(e);let s=this.activeTransactions.get(e.messageHash),o=s?.record||e;s&&be("cluster-member:merge-start",{messageHash:e.messageHash,existingPromises:Object.keys(s.record.promises??{}),existingCommits:Object.keys(s.record.commits??{}),incomingPromises:Object.keys(e.promises??{}),incomingCommits:Object.keys(e.commits??{})}),s&&(o=await this.mergeRecords(s.record,e),be("cluster-member:merge-complete",{messageHash:e.messageHash,mergedPromises:Object.keys(o.promises??{}),mergedCommits:Object.keys(o.commits??{})}));let i=await this.getTransactionPhase(o);be("cluster-member:phase",{messageHash:e.messageHash,phase:i,promises:Object.keys(o.promises??{}),commits:Object.keys(o.commits??{})});let a=!0;switch(i){case xt.OurPromiseNeeded:be("cluster-member:action-promise",{messageHash:e.messageHash}),o=await this.handlePromiseNeeded(o),be("cluster-member:action-promise-complete",{messageHash:e.messageHash,promises:Object.keys(o.promises??{})});break;case xt.OurCommitNeeded:be("cluster-member:action-commit",{messageHash:e.messageHash}),o=await this.handleCommitNeeded(o),be("cluster-member:action-commit-complete",{messageHash:e.messageHash,commits:Object.keys(o.commits??{})}),await this.getTransactionPhase(o)===xt.Consensus&&(be("cluster-member:action-consensus-after-commit",{messageHash:e.messageHash}),await this.handleConsensus(o)),a=!1;break;case xt.Consensus:be("cluster-member:action-consensus",{messageHash:e.messageHash}),await this.handleConsensus(o),a=!1;break;case xt.Rejected:be("cluster-member:action-rejected",{messageHash:e.messageHash}),await this.handleRejection(o),a=!1;break;case xt.Propagating:be("cluster-member:phase-propagating",{messageHash:e.messageHash}),a=!1;break;case xt.Promising:be("cluster-member:phase-promising-blocked",{messageHash:e.messageHash});break}if(a){let c=this.setupTimeouts(o);this.activeTransactions.set(e.messageHash,{record:o,lastUpdate:Date.now(),promiseTimeout:c.promiseTimeout,resolutionTimeout:c.resolutionTimeout}),be("cluster-member:state-persist",{messageHash:e.messageHash,storedPromises:Object.keys(o.promises??{}),storedCommits:Object.keys(o.commits??{})})}else be("cluster-member:state-clear",{messageHash:e.messageHash}),this.clearTransaction(e.messageHash);return be("cluster-member:update-complete",{messageHash:e.messageHash,promiseCount:Object.keys(o.promises).length,commitCount:Object.keys(o.commits).length}),o}async mergeRecords(e,t){if(be("cluster-member:merge-records",{messageHash:e.messageHash,existingPromises:Object.keys(e.promises??{}),existingCommits:Object.keys(e.commits??{}),incomingPromises:Object.keys(t.promises??{}),incomingCommits:Object.keys(t.commits??{})}),e.messageHash!==t.messageHash)throw new Error("Message hash mismatch");if(JSON.stringify(e.message)!==JSON.stringify(t.message))throw new Error("Message content mismatch");if(JSON.stringify(e.peers)!==JSON.stringify(t.peers))throw new Error("Peers mismatch");return{...e,promises:{...e.promises,...t.promises},commits:{...e.commits,...t.commits}}}async validateRecord(e){let t=await this.computeMessageHash(e.message);if(t!==e.messageHash)throw new Error(`Message hash mismatch: expected=${t}, received=${e.messageHash}`);if(await this.validateSignatures(e),e.message.expiration&&e.message.expiration<Date.now())throw new Error("Transaction expired")}async computeMessageHash(e){let t=new TextEncoder().encode(JSON.stringify(e)),n=await nn.digest(t);return wd.encode(n.digest)}async validateSignatures(e){let t=await this.computePromiseHash(e);for(let[s,o]of Object.entries(e.promises))if(!await this.verifySignature(s,t,o))throw new Error(`Invalid promise signature from ${s}`);let n=await this.computeCommitHash(e);for(let[s,o]of Object.entries(e.commits))if(!await this.verifySignature(s,n,o))throw new Error(`Invalid commit signature from ${s}`)}async computePromiseHash(e){let t=new TextEncoder().encode(e.messageHash+JSON.stringify(e.message)),n=await nn.digest(t);return P(n.digest,"base64url")}async computeCommitHash(e){let t=new TextEncoder().encode(e.messageHash+JSON.stringify(e.message)+JSON.stringify(e.promises)),n=await nn.digest(t);return P(n.digest,"base64url")}async verifySignature(e,t,n){return!0}async getTransactionPhase(e){let t=Object.keys(e.peers).length,n=Object.keys(e.promises).length,s=Object.keys(e.commits).length,o=this.peerId.toString(),i=Object.values(e.promises).filter(l=>l.type==="reject"),a=Object.values(e.commits).filter(l=>l.type==="reject");if(i.length>0||this.hasMajority(a.length,t))return xt.Rejected;if(!e.promises[o]&&!this.hasConflict(e))return xt.OurPromiseNeeded;if(n<t)return xt.Promising;if(n===t&&!e.commits[o])return xt.OurCommitNeeded;let c=Object.values(e.commits).filter(l=>l.type==="approve");return this.hasMajority(c.length,t)?xt.Consensus:xt.Propagating}hasMajority(e,t){return e>t/2}async handlePromiseNeeded(e){let t=await this.validatePendOperations(e),n=t.valid?{type:"approve",signature:"approved"}:{type:"reject",signature:"rejected",rejectReason:t.reason};return t.valid||be("cluster-member:validation-rejected",{messageHash:e.messageHash,reason:t.reason}),{...e,promises:{...e.promises,[this.peerId.toString()]:n}}}async validatePendOperations(e){for(let t of e.message.operations)if("pend"in t){let n=t.pend;if(n.rev!==void 0){let s=gs(n.transforms),o=await this.storageRepo.get({blockIds:s});for(let i of s){let c=o[i]?.state?.latest?.rev;if(c!==void 0&&c>=n.rev)return be("cluster-member:validation-stale-revision",{messageHash:e.messageHash,blockId:i,requestedRev:n.rev,latestRev:c}),{valid:!1,reason:`stale revision: block ${i} at rev ${c}, requested rev ${n.rev}`}}}if(this.validator&&n.transaction&&n.operationsHash){let s=await this.validator.validate(n.transaction,n.operationsHash);if(!s.valid)return{valid:!1,reason:s.reason}}}return{valid:!0}}async handleCommitNeeded(e){if(this.hasLocalCommit(e))return e;let t={type:"approve",signature:"committed"};return{...e,commits:{...e.commits,[this.peerId.toString()]:t}}}async handleConsensus(e){if(this.executedTransactions.has(e.messageHash)){be("cluster-member:consensus-already-executed",{messageHash:e.messageHash});return}this.executedTransactions.set(e.messageHash,Date.now());try{for(let t of e.message.operations)if("get"in t)await this.storageRepo.get(t.get);else if("pend"in t){let n=await this.storageRepo.pend(t.pend);if(!n.success)throw be("cluster-member:consensus-pend-failed",{messageHash:e.messageHash,actionId:t.pend.actionId,reason:n.reason,hasMissing:!!n.missing?.length,hasPending:!!n.pending?.length}),new Error(`Consensus pend failed for action ${t.pend.actionId}: ${n.reason??"stale revision"}`)}else if("commit"in t){let n=await this.storageRepo.commit(t.commit);if(!n.success)throw be("cluster-member:consensus-commit-failed",{messageHash:e.messageHash,actionId:t.commit.actionId,reason:n.reason,hasMissing:!!n.missing?.length}),new Error(`Consensus commit failed for action ${t.commit.actionId}: ${n.reason??"stale revision"}`)}else"cancel"in t&&await this.storageRepo.cancel(t.cancel.actionRef)}catch(t){throw this.executedTransactions.delete(e.messageHash),t}}async handleRejection(e){}setupTimeouts(e){return e.message.expiration?{promiseTimeout:setTimeout(()=>this.handleExpiration(e.messageHash),e.message.expiration-Date.now()),resolutionTimeout:setTimeout(()=>this.resolveWithPeers(e.messageHash),e.message.expiration+5e3-Date.now())}:{}}hasConflict(e){let t=Date.now(),n=2e3,s=this.getAffectedBlockIds(e.message.operations);be("cluster-member:hasConflict-check",{messageHash:e.messageHash,activeCount:this.activeTransactions.size,incomingBlockIds:s});for(let[o,i]of Array.from(this.activeTransactions.entries())){if(o===e.messageHash)continue;let a=this.getAffectedBlockIds(i.record.message.operations);if(be("cluster-member:hasConflict-compare",{existing:o,incoming:e.messageHash,existingBlockIds:a,incomingBlockIds:s}),t-i.lastUpdate>n){be("cluster-member:stale-cleanup",{messageHash:o,age:t-i.lastUpdate}),this.clearTransaction(o);continue}if(this.operationsConflict(i.record.message.operations,e.message.operations)){if(this.resolveRace(i.record,e)==="keep-existing")return be("cluster-member:race-keep-existing",{existing:o,incoming:e.messageHash}),!0;be("cluster-member:race-accept-incoming",{existing:o,incoming:e.messageHash}),this.clearTransaction(o);continue}}return!1}resolveRace(e,t){let n=Object.keys(e.promises).length,s=Object.keys(t.promises).length;return n>s?"keep-existing":s>n?"accept-incoming":e.messageHash>t.messageHash?"keep-existing":"accept-incoming"}operationsConflict(e,t){let n=this.getActionId(e),s=this.getActionId(t);if(n&&s&&n===s)return!1;let o=new Set(this.getAffectedBlockIds(e)),i=new Set(this.getAffectedBlockIds(t));for(let a of Array.from(o))if(i.has(a))return be("cluster-member:conflict-detected",{blocks1:Array.from(o),blocks2:Array.from(i),conflictingBlock:a}),!0;return!1}getActionId(e){for(let t of e){if("pend"in t)return t.pend.actionId;if("commit"in t)return t.commit.actionId;if("cancel"in t)return t.cancel.actionRef.actionId}}getAffectedBlockIds(e){let t=new Set;for(let n of e)"get"in n?n.get.blockIds.forEach(s=>t.add(s)):"pend"in n?gs(n.pend.transforms).forEach(s=>t.add(s)):"commit"in n?n.commit.blockIds.forEach(s=>t.add(s)):"cancel"in n&&n.cancel.actionRef.blockIds.forEach(s=>t.add(s));return Array.from(t)}async propagateIfNeeded(e){let t=[];for(let[n,s]of Object.entries(e.peers))if(n!==this.peerId.toString())try{let o=ro.create(de(n),this.peerNetwork,this.protocolPrefix);t.push(o.update(e))}catch(o){console.error(`Failed to propagate to peer ${n}:`,o)}await Promise.allSettled(t)}async handleExpiration(e){let t=this.activeTransactions.get(e);if(t&&!t.record.promises[this.peerId.toString()]){let n={type:"reject",signature:"rejected",rejectReason:"Transaction expired"},s={...t.record,promises:{...t.record.promises,[this.peerId.toString()]:n}};this.activeTransactions.set(e,{...t,record:s}),await this.propagateIfNeeded(s)}}async resolveWithPeers(e){be("cluster-member:resolve-skipped",{messageHash:e,reason:"coordinator-handles-retry"})}queueExpiredTransactions(){let e=Date.now();for(let[n,s]of Array.from(this.activeTransactions.entries()))s.record.message.expiration&&s.record.message.expiration<e&&this.cleanupQueue.push(n);let t=e-g9;for(let[n,s]of Array.from(this.executedTransactions.entries()))s<t&&this.executedTransactions.delete(n)}async processCleanupQueue(){for(;this.cleanupQueue.length>0;){let e=this.cleanupQueue.shift();if(!e)continue;let t=this.activeTransactions.get(e);if(!t)continue;let n=await this.getTransactionPhase(t.record);n!==xt.Consensus&&n!==xt.Rejected&&this.activeTransactions.delete(e)}}hasLocalCommit(e){let t=this.peerId.toString();return!!e.commits[t]}clearTransaction(e){let t=this.activeTransactions.get(e);if(!t){be("cluster-member:clear-miss",{messageHash:e});return}t.promiseTimeout&&clearTimeout(t.promiseTimeout),t.resolutionTimeout&&clearTimeout(t.resolutionTimeout),this.activeTransactions.delete(e),be("cluster-member:clear-done",{messageHash:e,remaining:Array.from(this.activeTransactions.keys())})}};function Yg(r={}){return e=>new Td(e,r)}var Td=class{protocol;maxInboundStreams;maxOutboundStreams;log;cluster;components;running;k;configuredClusterSize;allowDownsize;sizeTolerance;responsibilityK;constructor(e,t={}){this.components=e,this.protocol=t.protocol??(t.protocolPrefix??"/db-p2p")+"/cluster/1.0.0",this.maxInboundStreams=t.maxInboundStreams??32,this.maxOutboundStreams=t.maxOutboundStreams??64,this.log=e.logger.forComponent(t.logPrefix??"db-p2p:cluster"),this.cluster=e.cluster,this.running=!1,this.k=t.kBucketSize??10,this.configuredClusterSize=t.configuredClusterSize??10,this.allowDownsize=t.allowClusterDownsize??!0,this.sizeTolerance=t.clusterSizeTolerance??.5,this.responsibilityK=t.responsibilityK??1}[Symbol.toStringTag]="@libp2p/cluster";async start(){this.running||(await this.components.registrar.handle(this.protocol,this.handleIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.running=!0)}async stop(){this.running&&(await this.components.registrar.unhandle(this.protocol),this.running=!1)}handleIncomingStream(e,t){let n=t.remotePeer,s=async function*(o){for await(let i of o){let a=new TextDecoder().decode(i.subarray()),c=JSON.parse(a),l;if(c.operation==="update"){let h=c.record?.message?.commit?.tailId??c.record?.message?.pend?Object.keys(c.record.message.pend.transforms)[0]:void 0;l=await this.cluster.update(c.record)}else throw new Error(`Unknown operation: ${c.operation}`);if(c.operation==="update"){let h=l;this.log("cluster-service:pre-serialize",{messageHash:h?.messageHash,responseType:typeof l,hasPromises:"promises"in(h??{}),hasCommits:"commits"in(h??{}),promiseKeys:Object.keys(h?.promises??{}),commitKeys:Object.keys(h?.commits??{}),promiseValues:h?.promises,commitValues:h?.commits})}let u=JSON.stringify(l);if(c.operation==="update"){let h=JSON.parse(u);this.log("cluster-service:post-serialize",{messageHash:h?.messageHash,promiseKeys:Object.keys(h?.promises??{}),commitKeys:Object.keys(h?.commits??{})})}yield new TextEncoder().encode(u)}};(async()=>{try{let o=ht(e,i=>Pr(i),s.bind(this),i=>yr(i));for await(let i of o)e.send(i);await e.close()}catch(o){this.log.error("error handling cluster protocol message from %p - %e",n,o),e.abort(o instanceof Error?o:new Error(String(o)))}})()}};ke();var Xg=class r extends Cn{protocolPrefix;constructor(e,t,n){super(e,t),this.protocolPrefix=n}static create(e,t,n){return new r(e,t,n)}async get(e,t){return this.processRepoMessage([{get:e}],t)}async pend(e,t){return this.processRepoMessage([{pend:e}],t)}async cancel(e,t){return this.processRepoMessage([{cancel:{actionRef:e}}],t)}async commit(e,t){return this.processRepoMessage([{commit:e}],t)}async processRepoMessage(e,t,n=0){let s={operations:e,expiration:t.expiration},o=t.expiration??Date.now()+3e4,i=Math.max(1,o-Date.now()),a=async u=>await Promise.race([u(),new Promise((h,p)=>setTimeout(()=>p(new Error("RepoClient timeout")),i))]),c,l=(this.protocolPrefix??"/db-p2p")+"/repo/1.0.0";if(c=await a(()=>super.processMessage(s,l,{signal:t?.signal})),c?.redirect?.peers?.length){if(n>=2)throw new Error("Redirect loop detected in RepoClient (max hops reached)");let u=this.peerId.toString(),h=c.redirect.peers.find(d=>d.id!==u)??c.redirect.peers[0],p=de(h.id);if(h.id===u)throw new Error("Redirect loop detected in RepoClient (same peer)");return this.recordCoordinatorForOpsIfSupported(e,p),await r.create(p,this.peerNetwork,this.protocolPrefix).processRepoMessage(e,t,n+1)}return c}extractKeyFromOperations(e){let t=e[0];if("get"in t){let n=t.get.blockIds[0];return n?new TextEncoder().encode(n):void 0}if("pend"in t){let n=Object.keys(t.pend.transforms)[0];return n?new TextEncoder().encode(n):void 0}if("commit"in t)return new TextEncoder().encode(t.commit.tailId)}recordCoordinatorForOpsIfSupported(e,t){let n=this.extractKeyFromOperations(e),s=this.peerNetwork;n!=null&&typeof s?.recordCoordinator=="function"&&s.recordCoordinator(n,t)}};ke();var re=Sr("cluster"),ml=class{keyNetwork;createClusterClient;cfg;localCluster;fretService;transactions=new Map;retryInitialIntervalMs=2e3;retryBackoffFactor=2;retryMaxIntervalMs=3e4;retryMaxAttempts=5;constructor(e,t,n,s,o){this.keyNetwork=e,this.createClusterClient=t,this.cfg=n,this.localCluster=s,this.fretService=o}async createMessageHash(e){let t=new TextEncoder().encode(JSON.stringify(e)),n=await nn.digest(t);return wd.encode(n.digest)}async getClusterForBlock(e){let t=new TextEncoder().encode(e);try{let n=await this.keyNetwork.findCluster(t),s=Object.keys(n??{});return re("cluster-tx:cluster-members",{blockId:e,peerIds:s}),n}catch(n){return re("WARN findCluster failed for %s: %o",e,n),{}}}makeRecord(e,t,n){let s=Object.keys(e??{}).length,o={messageHash:t,peers:e,message:n,coordinatingBlockIds:n.coordinatingBlockIds,promises:{},commits:{},suggestedClusterSize:s||void 0,minRequiredSize:this.cfg.allowClusterDownsize?void 0:this.cfg.clusterSize};if(this.fretService)try{let i=this.fretService.getNetworkSizeEstimate();i.size_estimate>0&&(o.networkSizeHint=i.size_estimate,o.networkSizeConfidence=i.confidence)}catch{}return o}async executeClusterTransaction(e,t,n){let s=await this.getClusterForBlock(e),o=await this.createMessageHash(t),i=this.makeRecord(s,o,t);re("cluster-tx:start",{messageHash:o,blockId:e,peerCount:Object.keys(s??{}).length,allowDownsize:this.cfg.allowClusterDownsize,configuredSize:this.cfg.clusterSize,suggestedSize:i.suggestedClusterSize,minRequiredSize:i.minRequiredSize});let a=this.executeTransaction(s,i),c=new so(a),l={messageHash:o,record:i,pending:c,lastUpdate:Date.now()};this.transactions.set(o,l),re("cluster-tx:transaction-store",{messageHash:o,transactionKeys:Array.from(this.transactions.keys())});try{let u=await c.result(),h=this.localCluster?.wasTransactionExecuted?.(o)??!1;return{record:u,localExecuted:h}}finally{let u=this.transactions.get(o),h=u?.retry?{attempt:u.retry.attempt,pending:Array.from(u.retry.pendingPeers??[])}:void 0;re("cluster-tx:complete",{messageHash:o,finalPromises:u?Object.keys(u.record.promises??{}):void 0,finalCommits:u?Object.keys(u.record.commits??{}):void 0,retry:h}),u?.retry||setTimeout(()=>{this.transactions.delete(o),re("cluster-tx:transaction-remove",{messageHash:o,remaining:Array.from(this.transactions.keys())})},100)}}async executeTransaction(e,t){let n=Object.keys(e).length;if(n<this.cfg.minAbsoluteClusterSize){if(!await this.validateSmallCluster(n,e))throw re("cluster-tx:reject-too-small",{peerCount:n,minRequired:this.cfg.minAbsoluteClusterSize}),new Error(`Cluster size ${n} below minimum ${this.cfg.minAbsoluteClusterSize} and not validated`);re("cluster-tx:small-cluster-validated",{peerCount:n})}if(!this.cfg.allowClusterDownsize&&n<this.cfg.clusterSize)throw re("cluster-tx:reject-downsize",{peerCount:n,required:this.cfg.clusterSize}),new Error(`Cluster size ${n} below configured minimum ${this.cfg.clusterSize}`);let s=await this.collectPromises(e,t),o=Math.ceil(n*this.cfg.superMajorityThreshold),i=s.record.promises,a=Object.values(i).filter(u=>u.type==="approve").length,c=Object.values(i).filter(u=>u.type==="reject").length,l=n-o;if(c>l){let u=Object.entries(i).filter(([h,p])=>p.type==="reject").map(([h,p])=>`${h}: ${p.rejectReason??"unknown"}`).join("; ");throw re("cluster-tx:rejected-by-validators",{messageHash:t.messageHash,peerCount:n,rejections:c,maxAllowed:l,reasons:u}),this.updateTransactionRecord(s.record,"rejected-by-validators"),new Error(`Transaction rejected by validators (${c}/${n} rejected): ${u}`)}if(n>1&&a<o)throw re("cluster-tx:supermajority-failed",{messageHash:t.messageHash,peerCount:n,approvals:a,rejections:c,superMajority:o,threshold:this.cfg.superMajorityThreshold}),this.updateTransactionRecord(s.record,"supermajority-failed"),new Error(`Failed to get super-majority: ${a}/${n} approvals (needed ${o}, ${c} rejections)`);return await this.commitTransaction(s.record)}async getClusterSize(e){let t=await this.getClusterForBlock(e);return Object.keys(t??{}).length}async validateSmallCluster(e,t){if(this.fretService)try{let n=this.fretService.getNetworkSizeEstimate();if(n.confidence>.5){let s=Math.floor(Math.log10(n.size_estimate+1)),o=Math.floor(Math.log10(e+1));if(Math.abs(s-o)<=1)return re("cluster-tx:small-cluster-validated-by-fret",{localSize:e,fretEstimate:n.size_estimate,confidence:n.confidence,sources:n.sources}),!0}}catch{}return re("cluster-tx:small-cluster-accepted-without-validation",{localSize:e,reason:"no-confident-network-size-estimate"}),!0}async collectPromises(e,t){let n=Object.keys(e),s=[],o=n.map(l=>{let u=this.localCluster&&l===this.localCluster.peerId.toString();re("cluster-tx:promise-request",{messageHash:t.messageHash,peerId:l,isLocal:u});let h=u?this.localCluster.update(t):this.createClusterClient(de(l)).update(t);return new so(h)}),i=await Promise.all(o.map((l,u)=>l.result().then(h=>{let p=n[u];return re("cluster-tx:promise-response",{messageHash:t.messageHash,peerId:p,success:!0,returnedPromises:Object.keys(h.promises??{}),returnedCommits:Object.keys(h.commits??{})}),s.push({peerId:p,success:!0}),h}).catch(h=>{let p=n[u];return re("cluster-tx:promise-response",{messageHash:t.messageHash,peerId:p,success:!1,error:h}),s.push({peerId:p,success:!1,error:h instanceof Error?h.message:String(h)}),null}))),a=s.filter(l=>l.success).map(l=>l.peerId),c=s.filter(l=>!l.success);re("cluster-tx:promise-summary",{messageHash:t.messageHash,successes:a,failures:c}),re("cluster-tx:promise-merge-begin",{messageHash:t.messageHash,initialPromises:Object.keys(t.promises??{}),transactionsKeys:Array.from(this.transactions.keys()),hasTransaction:this.transactions.has(t.messageHash)});for(let l of i.filter(Boolean)){re("cluster-tx:promise-merge-input",{messageHash:t.messageHash,resultFrom:Object.keys(l.promises??{}),recordBefore:Object.keys(t.promises??{})});let u=Object.keys(l.promises??{});if(re("cluster-tx:promise-merge-result",{messageHash:t.messageHash,peerPromises:u}),typeof t.suggestedClusterSize=="number"&&typeof l.suggestedClusterSize=="number"){let h=l.suggestedClusterSize,p=Object.keys(e).length,f=Math.ceil(Math.max(1,h*this.cfg.clusterSizeTolerance));Math.abs(p-h)>f&&re("cluster-tx:size-variance",{expected:h,actual:p,tolerance:this.cfg.clusterSizeTolerance})}t.promises={...t.promises,...l.promises},re("cluster-tx:promise-merge-after",{messageHash:t.messageHash,mergedPromises:Object.keys(t.promises??{})})}return re("cluster-tx:promise-merge",{messageHash:t.messageHash,mergedPromises:Object.keys(t.promises??{})}),re("cluster-tx:promise-merge-end",{messageHash:t.messageHash,finalPromises:Object.keys(t.promises??{}),transactionsEntry:this.transactions.get(t.messageHash)}),this.updateTransactionRecord(t,"after-promises"),{record:t}}async commitTransaction(e){let t=Object.keys(e.peers),n=[],s={...e},o=t.map(f=>{let d=this.localCluster&&f===this.localCluster.peerId.toString();re("cluster-tx:commit-request",{messageHash:e.messageHash,peerId:f,isLocal:d});let m=d?this.localCluster.update(s):this.createClusterClient(de(f)).update(s);return new so(m)}),i=await Promise.all(o.map((f,d)=>f.result().then(m=>{let g=t[d];return re("cluster-tx:commit-response",{messageHash:e.messageHash,peerId:g,success:!0}),n.push({peerId:g,success:!0}),m}).catch(m=>{let g=t[d];return re("cluster-tx:commit-response",{messageHash:e.messageHash,peerId:g,success:!1,error:m}),n.push({peerId:g,success:!1,error:m instanceof Error?m.message:String(m)}),null}))),a=n.filter(f=>f.success).map(f=>f.peerId),c=n.filter(f=>!f.success);re("cluster-tx:commit-summary",{messageHash:e.messageHash,successes:a,failures:c}),re("cluster-tx:commit-merge-begin",{messageHash:e.messageHash,initialCommits:Object.keys(e.commits??{}),transactionsEntry:this.transactions.get(e.messageHash)});for(let f of i.filter(Boolean))re("cluster-tx:commit-merge-input",{messageHash:e.messageHash,resultFrom:Object.keys(f.commits??{}),recordBefore:Object.keys(e.commits??{})}),re("cluster-tx:commit-merge-result",{messageHash:e.messageHash,peerCommits:Object.keys(f.commits??{})}),e.commits={...e.commits,...f.commits},re("cluster-tx:commit-merge-after",{messageHash:e.messageHash,mergedCommits:Object.keys(e.commits??{})});re("cluster-tx:commit-merge",{messageHash:e.messageHash,mergedCommits:Object.keys(e.commits??{})}),re("cluster-tx:commit-merge-end",{messageHash:e.messageHash,finalCommits:Object.keys(e.commits??{}),transactionsEntry:this.transactions.get(e.messageHash)}),this.updateTransactionRecord(e,"after-commit");let l=Object.keys(e.peers).length,u=Math.floor(l*this.cfg.simpleMajorityThreshold)+1,h=Object.keys(e.commits).length;if(h>=u&&(re("cluster-tx:commit-majority-reached",{messageHash:e.messageHash,commitCount:h,simpleMajority:u,peerCount:l,threshold:this.cfg.simpleMajorityThreshold}),this.localCluster))try{await this.localCluster.update(e)}catch(f){re("cluster-tx:local-execution-error",{messageHash:e.messageHash,error:f instanceof Error?f.message:String(f)})}let p=c.map(f=>f.peerId);return p.length>0?this.scheduleCommitRetry(e.messageHash,e,p):this.clearRetry(e.messageHash),e}updateTransactionRecord(e,t){let n=this.transactions.get(e.messageHash);if(!n){re("cluster-tx:transaction-update-miss",{messageHash:e.messageHash,stage:t});return}n.record={...e},n.lastUpdate=Date.now(),re("cluster-tx:transaction-update",{messageHash:e.messageHash,stage:t,promises:Object.keys(e.promises??{}),commits:Object.keys(e.commits??{})})}scheduleCommitRetry(e,t,n){let s=this.transactions.get(e);if(!s)return;let o=s.retry,i=(o?.attempt??0)+1;if(i>this.retryMaxAttempts){re("cluster-tx:retry-abort",{messageHash:e,missingPeers:n});return}if(n.length===0){this.clearRetry(e);return}let a=new Set(n),c=o?Math.min(o.intervalMs*this.retryBackoffFactor,this.retryMaxIntervalMs):this.retryInitialIntervalMs;o?.timer&&clearTimeout(o.timer);let l=setTimeout(()=>{this.retryCommits(e)},c);s.retry={pendingPeers:a,attempt:i,intervalMs:c,timer:l},re("cluster-tx:retry-scheduled",{messageHash:e,attempt:i,missingPeers:n,delayMs:c})}async retryCommits(e){let t=this.transactions.get(e);if(!t?.retry)return;let{pendingPeers:n,attempt:s}=t.retry;if(n.size===0){this.clearRetry(e);return}let o=Array.from(n),i=t.record;re("cluster-tx:retry-start",{messageHash:e,attempt:s,peerIds:o});let a=await Promise.all(o.map(async u=>{let h=this.localCluster&&u===this.localCluster.peerId.toString(),p={...i,commits:i.commits};try{let f=h?await this.localCluster.update(p):await this.createClusterClient(de(u)).update(p);return t.record.commits={...t.record.commits,...f.commits},{peerId:u,success:!0}}catch(f){return{peerId:u,success:!1,error:f instanceof Error?f.message:String(f)}}})),c=a.filter(u=>u.success).map(u=>u.peerId),l=a.filter(u=>!u.success);for(let u of c)n.delete(u);if(re("cluster-tx:retry-complete",{messageHash:e,attempt:s,successes:c,failures:l}),n.size===0){re("cluster-tx:retry-finished",{messageHash:e}),this.clearRetry(e);return}this.transactions.has(e)&&this.scheduleCommitRetry(e,t.record,Array.from(n))}clearRetry(e){let t=this.transactions.get(e);t?.retry&&(t.retry.timer&&clearTimeout(t.retry.timer),t.retry=void 0,setTimeout(()=>{this.transactions.delete(e),re("cluster-tx:transaction-remove",{messageHash:e,remaining:Array.from(this.transactions.keys())})},100))}};ke();var io=Sr("coordinator-repo");function Qg(r,e,t,n){return s=>new _d(r,e,s.storageRepo,t,s.localCluster,s.localPeerId,n,s.clusterLatestCallback)}var _d=class{keyNetwork;createClusterClient;storageRepo;clusterLatestCallback;coordinator;DEFAULT_TIMEOUT=3e4;constructor(e,t,n,s,o,i,a,c){this.keyNetwork=e,this.createClusterClient=t,this.storageRepo=n,this.clusterLatestCallback=c;let l={clusterSize:s?.clusterSize??10,superMajorityThreshold:s?.superMajorityThreshold??.75,simpleMajorityThreshold:s?.simpleMajorityThreshold??.51,minAbsoluteClusterSize:s?.minAbsoluteClusterSize??3,allowClusterDownsize:s?.allowClusterDownsize??!0,clusterSizeTolerance:s?.clusterSizeTolerance??.5,partitionDetectionWindow:s?.partitionDetectionWindow??6e4},u=o&&i?{update:o.update.bind(o),peerId:i,wasTransactionExecuted:o.wasTransactionExecuted?.bind(o)}:void 0;this.coordinator=new ml(e,t,l,u,a)}async get(e,t){let n=await this.storageRepo.get(e,t),s=t?.skipClusterFetch;if(this.clusterLatestCallback&&!s){for(let o of e.blockIds)if(!n[o]?.state?.latest)try{await this.fetchBlockFromCluster(o);let a=await this.storageRepo.get({blockIds:[o],context:e.context},t);a[o]&&(n[o]=a[o])}catch(a){io("cluster-fetch:error",{blockId:o,error:a.message})}}return n}async fetchBlockFromCluster(e){if(!this.clusterLatestCallback)return;let t=await this.queryClusterForLatest(e);t&&(await this.storageRepo.get({blockIds:[e],context:{committed:[t],rev:t.rev}}),io("cluster-fetch:synced",{blockId:e,rev:t.rev}))}async queryClusterForLatest(e){let t=new TextEncoder().encode(e),n=await this.keyNetwork.findCluster(t);if(!n||Object.keys(n).length===0)return;let s=Object.keys(n),o,i=(c,l)=>Promise.race([c,new Promise(u=>setTimeout(()=>u(void 0),l))]),a=await Promise.allSettled(s.map(c=>{let l=de(c);return i(this.clusterLatestCallback(l,e),3e3)}));for(let c of a)if(c.status==="fulfilled"&&c.value){let l=c.value;(!o||l.rev>o.rev)&&(o=l)}return o}async pend(e,t){let n=Object.keys(e.transforms),s=t?.coordinatingBlockIds??n;if(await this.coordinator.getClusterSize(s[0])<=1)return await this.storageRepo.pend(e,t);let i={operations:[{pend:e}],expiration:t?.expiration??Date.now()+this.DEFAULT_TIMEOUT,coordinatingBlockIds:s};try{let{localExecuted:a}=await this.coordinator.executeClusterTransaction(s[0],i,t);if(io("coordinator-repo:pend-cluster-complete",{actionId:e.actionId,localExecuted:a}),!a){let c=await this.storageRepo.pend(e,t);return io("coordinator-repo:pend-fallback-result",{actionId:e.actionId,success:c.success,hasMissing:!!c.missing?.length,hasPending:!!c.pending?.length}),c}return{success:!0,pending:[],blockIds:Object.keys(e.transforms)}}catch(a){throw io("coordinator-repo:pend-error",{actionId:e.actionId,error:a.message}),a}}async cancel(e,t){let n=e.blockIds,s={operations:[{cancel:{actionRef:e}}],expiration:t?.expiration??Date.now()+this.DEFAULT_TIMEOUT};try{let o=n.map(c=>this.coordinator.executeClusterTransaction(c,s,t));(await Promise.all(o)).some(c=>c.localExecuted)||await this.storageRepo.cancel(e,t)}catch(o){throw io("coordinator-repo:cancel-error",{actionId:e.actionId,error:o.message}),o}}async commit(e,t){let n=e.blockIds;if(await this.coordinator.getClusterSize(n[0])<=1)return await this.storageRepo.commit(e,t);let o={operations:[{commit:e}],expiration:t?.expiration??Date.now()+this.DEFAULT_TIMEOUT};try{let{localExecuted:i}=await this.coordinator.executeClusterTransaction(n[0],o,t);return i?{success:!0}:await this.storageRepo.commit(e,t)}catch(i){throw io("coordinator-repo:commit-error",{actionId:e.actionId,error:i.message}),i}}};function BS(r){try{if(r==null)return null;if(typeof r?.toString=="function")return r.toString();let e=r.id;return e&&typeof e.toString=="function"?e.toString():typeof e=="string"?e:typeof r=="string"?r:null}catch{return null}}function ao(r,e){let t=BS(r),n=BS(e);return t!=null&&n!=null&&t===n}function Pd(r){return{redirect:{peers:r,reason:"not_in_cluster"}}}function Jg(r={}){return e=>new Dd(e,r)}var Dd=class{protocol;maxInboundStreams;maxOutboundStreams;log;repo;components;running;k;responsibilityK;constructor(e,t={}){this.components=e;let n=t.protocol??(t.protocolPrefix??"/db-p2p")+"/repo/1.0.0";this.protocol=n,this.maxInboundStreams=t.maxInboundStreams??32,this.maxOutboundStreams=t.maxOutboundStreams??64,this.log=e.logger.forComponent(t.logPrefix??"db-p2p:repo-service"),this.repo=e.repo,this.running=!1,this.k=t.kBucketSize??10,this.responsibilityK=t.responsibilityK??1}[Symbol.toStringTag]="@libp2p/repo-service";async start(){this.running||(await this.components.registrar.handle(this.protocol,this.handleIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.running=!0)}async stop(){this.running&&(await this.components.registrar.unhandle(this.protocol),this.running=!1)}handleIncomingStream(e,t){let n=t.remotePeer,s=async function*(o){for await(let i of o){let a=new TextDecoder().decode(i.subarray()),c=JSON.parse(a),l=c.operations[0],u;if("get"in l){let p=(await nn.digest(new TextEncoder().encode(l.get.blockIds[0]))).digest,f=this.components.libp2p?.services?.networkManager;if(f?.getCluster){let d=await f.getCluster(p);c.cluster=d.map(b=>b.toString?.()??String(b));let m=this.components.libp2p.peerId,g=d.some(b=>ao(b,m));if(!(d.length<this.responsibilityK)&&!g){let b=d.filter(w=>!ao(w,m));console.debug("repo-service:redirect",{peerId:m.toString(),reason:"not-cluster-member",operation:"get",blockId:l.get.blockIds[0],cluster:d.map(w=>w.toString?.()??String(w))}),u=Pd(b.map(w=>({id:w.toString(),addrs:[]})))}else u=await this.repo.get(l.get,{expiration:c.expiration,skipClusterFetch:!0})}else u=await this.repo.get(l.get,{expiration:c.expiration,skipClusterFetch:!0})}else if("pend"in l){let h=Object.keys(l.pend.transforms)[0],f=(await nn.digest(new TextEncoder().encode(h))).digest,d=this.components.libp2p?.services?.networkManager;if(d?.getCluster){let m=await d.getCluster(f);c.cluster=m.map(w=>w.toString?.()??String(w));let g=this.components.libp2p.peerId,y=m.some(w=>ao(w,g));if(!(m.length<this.responsibilityK)&&!y){let w=m.filter(x=>!ao(x,g));console.debug("repo-service:redirect",{peerId:g.toString(),reason:"not-cluster-member",operation:"pend",blockId:h,cluster:m.map(x=>x.toString?.()??String(x))}),u=Pd(w.map(x=>({id:x.toString(),addrs:[]})))}else u=await this.repo.pend(l.pend,{expiration:c.expiration})}else u=await this.repo.pend(l.pend,{expiration:c.expiration})}else if("cancel"in l)u=await this.repo.cancel(l.cancel.actionRef,{expiration:c.expiration});else if("commit"in l){let p=(await nn.digest(new TextEncoder().encode(l.commit.tailId))).digest,f=this.components.libp2p?.services?.networkManager;if(f?.getCluster){let d=await f.getCluster(p);c.cluster=d.map(b=>b.toString?.()??String(b));let m=this.components.libp2p.peerId,g=d.some(b=>ao(b,m));if(!(d.length<this.responsibilityK)&&!g){let b=d.filter(w=>!ao(w,m));console.debug("repo-service:redirect",{peerId:m.toString(),reason:"not-cluster-member",operation:"commit",tailId:l.commit.tailId,cluster:d.map(w=>w.toString?.()??String(w))}),u=Pd(b.map(w=>({id:w.toString(),addrs:[]})))}else u=await this.repo.commit(l.commit,{expiration:c.expiration})}else u=await this.repo.commit(l.commit,{expiration:c.expiration})}yield new TextEncoder().encode(JSON.stringify(u))}};(async()=>{try{let o=ht(e,i=>Pr(i),s.bind(this),i=>yr(i));for await(let i of o)e.send(i);await e.close()}catch(o){this.log.error("error handling repo protocol message from %p - %e",n,o),e.abort(o instanceof Error?o:new Error(String(o)))}})()}};function US(r){if(r.length<=1)return r;r.sort((t,n)=>t[0]-n[0]);let e=[r[0]];for(let t of r.slice(1)){let n=e[e.length-1];n[1]!==void 0&&(t[0]<=n[1]?t[1]===void 0?n[1]=void 0:n[1]=Math.max(n[1],t[1]):e.push(t))}return e}var Bi=class{blockId;storage;restoreCallback;constructor(e,t,n){this.blockId=e,this.storage=t,this.restoreCallback=n}async getLatest(){return(await this.storage.getMetadata(this.blockId))?.latest}async getBlock(e){let t=await this.storage.getMetadata(this.blockId);if(!t)return;let n=e??t.latest?.rev;if(n===void 0)throw new Error(`No revision specified and no latest revision exists for block ${this.blockId}`);return await this.ensureRevision(t,n),await this.materializeBlock(t,n)}async getTransaction(e){return await this.storage.getTransaction(this.blockId,e)}async getPendingTransaction(e){return await this.storage.getPendingTransaction(this.blockId,e)}async*listPendingTransactions(){yield*this.storage.listPendingTransactions(this.blockId)}async savePendingTransaction(e,t){let n=await this.storage.getMetadata(this.blockId);n||(n={latest:void 0,ranges:[[0]]},await this.storage.saveMetadata(this.blockId,n)),await this.storage.savePendingTransaction(this.blockId,e,t)}async deletePendingTransaction(e){await this.storage.deletePendingTransaction(this.blockId,e)}async*listRevisions(e,t){yield*this.storage.listRevisions(this.blockId,e,t)}async saveMaterializedBlock(e,t){await this.storage.saveMaterializedBlock(this.blockId,e,t)}async saveRevision(e,t){await this.storage.saveRevision(this.blockId,e,t)}async promotePendingTransaction(e){await this.storage.promotePendingTransaction(this.blockId,e)}async setLatest(e){let t=await this.storage.getMetadata(this.blockId);if(!t)throw new Error(`Block ${this.blockId} not found`);t.latest=e,await this.storage.saveMetadata(this.blockId,t)}async ensureRevision(e,t){if(this.inRanges(t,e.ranges))return;let n=`BlockStorage.ensureRevision:${this.blockId}`,s=await no.acquire(n);try{let o=await this.storage.getMetadata(this.blockId);if(!o)throw new Error(`Block ${this.blockId} metadata disappeared unexpectedly.`);if(this.inRanges(t,o.ranges))return;let i=await this.restoreBlock(t);if(!i)throw new Error(`Block ${this.blockId} revision ${t} not found during restore attempt.`);await this.saveRestored(i),o.ranges.unshift(i.range),o.ranges=US(o.ranges),await this.storage.saveMetadata(this.blockId,o)}finally{s()}}async materializeBlock(e,t){let n,s,o=[];for await(let i of this.storage.listRevisions(this.blockId,t,1)){let a=await this.storage.getMaterializedBlock(this.blockId,i.actionId);if(a){n=a,s=i;break}else o.push(i)}if(!n||!s)throw new Error(`Failed to find materialized block ${this.blockId} for revision ${t}`);for(let i=o.length-1;i>=0;--i){let{actionId:a}=o[i],c=await this.storage.getTransaction(this.blockId,a);if(!c)throw new Error(`Missing action ${a} for block ${this.blockId}`);n=cl(n,c)}if(!n)throw new Error(`Block ${this.blockId} has been deleted`);return o.length?(await this.storage.saveMaterializedBlock(this.blockId,o[0].actionId,n),{block:n,actionRev:o[0]}):{block:n,actionRev:s}}async restoreBlock(e){if(this.restoreCallback)return await this.restoreCallback(this.blockId,e)}async saveRestored(e){let t=Object.entries(e.revisions).map(([n,s])=>({rev:Number(n),data:s}));for(let{rev:n,data:{action:s,block:o}}of t)await Promise.all([this.storage.saveRevision(this.blockId,n,s.actionId),this.storage.saveTransaction(this.blockId,s.actionId,s.transform),o?this.storage.saveMaterializedBlock(this.blockId,s.actionId,o):Promise.resolve()])}inRanges(e,t){return t.some(n=>e>=n[0]&&(n[1]===void 0||e<n[1]))}};var gl=class{metadata=new Map;revisions=new Map;pendingActions=new Map;actions=new Map;materializedBlocks=new Map;getRevisionKey(e,t){return`${e}:${t}`}getActionKey(e,t){return`${e}:${t}`}async getMetadata(e){return this.metadata.get(e)}async saveMetadata(e,t){this.metadata.set(e,t)}async getRevision(e,t){return this.revisions.get(this.getRevisionKey(e,t))}async saveRevision(e,t,n){this.revisions.set(this.getRevisionKey(e,t),n)}async*listRevisions(e,t,n){let s=t<=n,o=s?t:n,i=s?n:t,a=[];for(let c=o;c<=i;c++){let l=this.revisions.get(this.getRevisionKey(e,c));l&&a.push({rev:c,actionId:l})}s||a.reverse();for(let c of a)yield c}async getPendingTransaction(e,t){return this.pendingActions.get(this.getActionKey(e,t))}async savePendingTransaction(e,t,n){this.pendingActions.set(this.getActionKey(e,t),structuredClone(n))}async deletePendingTransaction(e,t){this.pendingActions.delete(this.getActionKey(e,t))}async*listPendingTransactions(e){let t=`${e}:`;for(let[n]of Array.from(this.pendingActions.entries()))n.startsWith(t)&&(yield n.substring(t.length))}async getTransaction(e,t){return this.actions.get(this.getActionKey(e,t))}async saveTransaction(e,t,n){this.actions.set(this.getActionKey(e,t),n)}async getMaterializedBlock(e,t){let n=this.materializedBlocks.get(this.getActionKey(e,t));return n?structuredClone(n):void 0}async saveMaterializedBlock(e,t,n){let s=this.getActionKey(e,t);n?this.materializedBlocks.set(s,structuredClone(n)):this.materializedBlocks.delete(s)}async promotePendingTransaction(e,t){let n=this.getActionKey(e,t),s=this.pendingActions.get(n);s&&(this.actions.set(n,s),this.pendingActions.delete(n))}};var yl=class{createBlockStorage;validatePend;constructor(e,t){this.createBlockStorage=e,this.validatePend=t?.validatePend}async get({blockIds:e,context:t},n){let s=Array.from(new Set(e)),o=await Promise.all(s.map(async i=>{let a=this.createBlockStorage(i);if(t){let u=await a.getLatest(),h=u?t.committed.filter(p=>p.rev>u.rev):t.committed;for(let{actionId:p,rev:f}of h.sort((d,m)=>d.rev-m.rev))await a.getPendingTransaction(p)&&await this.internalCommit(i,p,f,a)}let c=await a.getBlock(t?.rev);if(!c)return[i,{state:{}}];if(t?.actionId!==void 0){let u=await a.getPendingTransaction(t.actionId);if(!u)throw new Error(`Pending action ${t.actionId} not found`);let h=cl(c.block,u);return[i,{block:h,state:{latest:await a.getLatest(),pendings:[t.actionId]}}]}let l=await uc(a.listPendingTransactions());return[i,{block:c.block,state:{latest:await a.getLatest(),pendings:l}}]}));return Object.fromEntries(o)}async pend(e,t){if(this.validatePend&&e.transaction&&e.operationsHash){let i=await this.validatePend(e.transaction,e.operationsHash);if(!i.valid)return{success:!1,reason:i.reason??"Transaction validation failed"}}let n=gs(e.transforms),s=[],o=[];for(let i of n){let a=this.createBlockStorage(i),c=md(e.transforms,i),l=await uc(a.listPendingTransactions());if(s.push(...l.map(u=>({blockId:i,actionId:u}))),e.rev!==void 0||c.insert){let u=await a.getLatest();if(u&&u.rev>=(e.rev??0)){let h=await uc(a.listRevisions(e.rev??0,u.rev));for(let p of h){let f=await a.getTransaction(p.actionId);if(!f)throw new Error(`Missing action ${p.actionId} for block ${i}`);o.push({actionId:p.actionId,rev:p.rev,transforms:j2(f,i)})}}}}if(o.length)return{success:!1,missing:o};if(s.length>0){if(e.policy==="f")return{success:!1,pending:s};if(e.policy==="r")return{success:!1,pending:await Promise.all(s.map(async i=>{let a=this.createBlockStorage(i.blockId);return{blockId:i.blockId,actionId:i.actionId,transform:await a.getPendingTransaction(i.actionId)??await a.getTransaction(i.actionId)}}))}}return await Promise.all(n.map(i=>{let a=this.createBlockStorage(i),c=md(e.transforms,i);return a.savePendingTransaction(e.actionId,c)})),{success:!0,pending:s,blockIds:n}}async cancel(e,t){await Promise.all(e.blockIds.map(n=>this.createBlockStorage(n).deletePendingTransaction(e.actionId)))}async commit(e,t){let n=Array.from(new Set(e.blockIds)).sort(),s=[];try{for(let c of n){let l=`StorageRepo.commit:${c}`,u=await no.acquire(l);s.push(u)}let o=e.blockIds.map(c=>({blockId:c,storage:this.createBlockStorage(c)})),i=[];for(let{blockId:c,storage:l}of o){let u=await l.getLatest();if(u&&u.rev>=e.rev){let h=[];for await(let p of l.listRevisions(e.rev,u.rev)){let f=await l.getTransaction(p.actionId);if(!f)throw new Error(`Missing action ${p.actionId} for block ${c}`);h.push({actionId:p.actionId,rev:p.rev,transform:f})}i.push({blockId:c,transforms:h})}}if(i.length)return{success:!1,missing:y9(i)};let a=[];for(let{blockId:c,storage:l}of o)await l.getPendingTransaction(e.actionId)||a.push({blockId:c,actionId:e.actionId});if(a.length)throw new Error(`Pending action ${e.actionId} not found for block(s): ${a.map(c=>c.blockId).join(", ")}`);for(let{blockId:c,storage:l}of o)try{await this.internalCommit(c,e.actionId,e.rev,l)}catch(u){return{success:!1,reason:u instanceof Error?u.message:"Unknown error during commit"}}}finally{s.reverse().forEach(o=>o())}return{success:!0}}async internalCommit(e,t,n,s){let o=await s.getPendingTransaction(t);if(!o)throw new Error(`Consistency Error: Pending action ${t} disappeared for block ${e} within critical section.`);let i=await s.getLatest(),a=i?(await s.getBlock(i.rev))?.block:void 0,c=cl(a,o);c&&await s.saveMaterializedBlock(t,c),await s.saveRevision(n,t),await s.promotePendingTransaction(t),await s.setLatest({actionId:t,rev:n})}};function y9(r){let e=r.flatMap(({blockId:n,transforms:s})=>s.map(o=>({blockId:n,transform:o}))),t=_g(e,({transform:n})=>n.actionId);return Object.entries(t).map(([n,s])=>s.reduce((o,{blockId:i,transform:a})=>(Y2(o.transforms,i,a.transform),o),{actionId:n,rev:s[0].transform.rev,transforms:W2()}))}var sn=class{entries;constructor(e){this.entries=e}},bl=class{partitions;nodes;constructor(e,t){this.partitions=e,this.nodes=t}};var Rn=class r{node;index;constructor(e,t){this.node=e,this.index=t}clone(){return new r(this.node,this.index)}},Ui=class r{branches;leafNode;leafIndex;on;version;constructor(e,t,n,s,o){this.branches=e,this.leafNode=t,this.leafIndex=n,this.on=s,this.version=o}isEqual(e){return this.leafNode===e.leafNode&&this.leafIndex===e.leafIndex&&this.on===e.on&&this.version===e.version}clone(){return new r(this.branches.map(e=>e.clone()),this.leafNode,this.leafIndex,this.on,this.version)}};var Ir=64,kd=class{keyFromEntry;compare;_root;_version=0;constructor(e=n=>n,t=(n,s)=>n<s?-1:n>s?1:0){this.keyFromEntry=e,this.compare=t,this._root=new sn([])}first(){return this.getFirst(this._root)}last(){return this.getLast(this._root)}find(e){return this.getPath(this._root,e)}get(e){return this.at(this.find(e))}at(e){return this.validatePath(e),e.on?e.leafNode.entries[e.leafIndex]:void 0}*range(e){let t=e.first?this.findFirst(e):e.isAscending?this.first():this.last(),n=e.last?this.findLast(e):e.isAscending?this.last():this.first(),s=this.keyFromEntry(n.leafNode.entries[n.leafIndex]),o=e.isAscending?this.internalAscending(t):this.internalDescending(t),i=e.isAscending?1:-1;for(let a of o){if(!a.on||!n.on||this.compareKeys(this.keyFromEntry(a.leafNode.entries[a.leafIndex]),s)*i>0)break;yield a}}isValid(e){return e.version===this._version}insert(e){Object.freeze(e);let t=this.internalInsert(e);return t.on&&(t.version=++this._version),t}updateAt(e,t){this.validatePath(e),e.on&&Object.freeze(t);let n=this.internalUpdate(e,t);return n[0].on&&(n[0].version=++this._version),n}upsert(e){let t=this.find(this.keyFromEntry(e));return Object.freeze(e),t.on?t.leafNode.entries[t.leafIndex]=e:this.internalInsertAt(t,e),t.version=++this._version,t}merge(e,t){let n=this.keyFromEntry(e),s=this.find(n);if(s.on){let o=this.updateAt(s,t(s.leafNode.entries[s.leafIndex]));return o[0].on&&(o[0].version=++this._version),o}else return this.internalInsertAt(s,Object.freeze(e)),s.on=!0,s.version=++this._version,[s,!1]}deleteAt(e){this.validatePath(e);let t=this.internalDelete(e);return t&&++this._version,t}ascending(e){return this.validatePath(e),this.internalAscending(e.clone())}descending(e){return this.validatePath(e),this.internalDescending(e.clone())}getCount(e){let t=0,n=e?e.path.clone():this.first();if(e?.ascending??!0)for(;n.on;)t+=n.leafNode.entries.length-n.leafIndex,n.leafIndex=n.leafNode.entries.length-1,this.internalNext(n);else for(;n.on;)t+=n.leafIndex+1,n.leafIndex=0,this.internalPrior(n);return t}next(e){let t=e.clone();return this.moveNext(t),t}moveNext(e){this.validatePath(e),this.internalNext(e)}prior(e){let t=e.clone();return this.movePrior(t),t}movePrior(e){this.validatePath(e),this.internalPrior(e)}compareKeys(e,t){let n=this.compare(e,t);if(n!==0&&n===this.compare(t,e))throw new Error("Inconsistent comparison function for given values");return n}*internalAscending(e){for(this.validatePath(e);e.on;)yield e,this.moveNext(e)}*internalDescending(e){for(this.validatePath(e);e.on;)yield e,this.movePrior(e)}findFirst(e){let t=this.find(e.first.key);return(!t.on||e.first&&!e.first.inclusive)&&(e.isAscending?this.internalNext(t):this.internalPrior(t)),t}findLast(e){let t=this.find(e.last.key);return(!t.on||e.last&&!e.last.inclusive)&&(e.isAscending?this.internalPrior(t):this.internalNext(t)),t}getPath(e,t){if(e instanceof sn){let n=e,[s,o]=this.indexOfEntry(n.entries,t);return new Ui([],n,o,s,this._version)}else{let n=e,s=this.indexOfKey(n.partitions,t),o=this.getPath(n.nodes[s],t);return o.branches.unshift(new Rn(n,s)),o}}indexOfEntry(e,t){let n=0,s=e.length-1,o=0,i=-1;for(;n<=s;){if(o=n+s>>>1,i=this.compareKeys(t,this.keyFromEntry(e[o])),i===0)return[!0,o];i<0?s=o-1:n=o+1}return[!1,n]}indexOfKey(e,t){let n=0,s=e.length-1,o=0,i=-1;for(;n<=s;){if(o=n+s>>>1,i=this.compareKeys(t,e[o]),i===0)return o+1;i<0?s=o-1:n=o+1}return n}internalNext(e){if(e.on)if(e.leafIndex>=e.leafNode.entries.length-1){let t=0,n=!1,s=e.branches.length-1;for(;t<=s&&!n;){let o=e.branches[s-t];o.index===o.node.partitions.length?++t:n=!0}if(!n)e.leafIndex=e.leafNode.entries.length,e.on=!1;else{e.branches.splice(-t,t);let o=e.branches.at(-1);++o.index,this.moveToFirst(o.node.nodes[o.index],e)}}else++e.leafIndex,e.on=!0;else if(e.on=e.branches.every(t=>t.index>=0&&t.index<t.node.nodes.length)&&e.leafIndex>=0&&e.leafIndex<e.leafNode.entries.length,e.on)return}internalPrior(e){if(this.validatePath(e),e.leafIndex<=0){let t=0,n=!1,s=e.branches.length-1;for(;t<=s&&!n;)e.branches[s-t].index===0?++t:n=!0;if(!n)e.leafIndex=0,e.on=!1;else{e.branches.splice(-t,t);let o=e.branches.at(-1);--o.index,this.moveToLast(o.node.nodes[o.index],e)}}else--e.leafIndex,e.on=!0}internalUpdate(e,t){if(e.on){let n=this.keyFromEntry(e.leafNode.entries[e.leafIndex]),s=this.keyFromEntry(t);if(this.compareKeys(n,s)!==0){let o=this.internalInsert(t);return o.on&&(this.internalDelete(this.find(n)),o=this.find(s)),[o,!1]}else e.leafNode.entries[e.leafIndex]=t}return[e,!0]}internalDelete(e){if(e.on){if(e.leafNode.entries.splice(e.leafIndex,1),e.branches.length>0){if(e.leafIndex===0){let n=e.branches.at(-1);this.updatePartition(n.index,e,e.branches.length-1,this.keyFromEntry(e.leafNode.entries[e.leafIndex]))}let t=this.rebalanceLeaf(e);t&&(this._root=t)}return e.on=!1,!0}else return!1}internalInsert(e){let t=this.find(this.keyFromEntry(e));return t.on?(t.on=!1,t):(this.internalInsertAt(t,e),t.on=!0,t)}internalInsertAt(e,t){let n=this.leafInsert(e,t),s=e.branches.length-1;for(;n&&s>=0;)n=this.branchInsert(e,s,n),--s;if(n){let o=new bl([n.key],[this._root,n.right]);this._root=o,e.branches.unshift(new Rn(o,n.indexDelta))}}moveToFirst(e,t){if(e instanceof sn){let n=e;t.leafNode=n,t.leafIndex=0,t.on=n.entries.length>0}else t.branches.push(new Rn(e,0)),this.moveToFirst(e.nodes[0],t)}moveToLast(e,t){if(e instanceof sn){let n=e,s=n.entries.length;t.leafNode=n,t.on=s>0,t.leafIndex=s>0?s-1:0}else{let n=e,s=new Rn(n,n.partitions.length);t.branches.push(s),this.moveToLast(n.nodes[s.index],t)}}getFirst(e){if(e instanceof sn){let t=e;return new Ui([],t,0,t.entries.length>0,this._version)}else{let t=e,n=this.getFirst(t.nodes[0]);return n.branches.unshift(new Rn(t,0)),n}}getLast(e){if(e instanceof sn){let t=e,n=t.entries.length;return new Ui([],t,n>0?n-1:0,n>0,this._version)}else{let t=e,n=t.nodes.length-1,s=this.getLast(t.nodes[n]);return s.branches.unshift(new Rn(t,n)),s}}leafInsert(e,t){let{leafNode:n,leafIndex:s}=e;if(n.entries.length<Ir){n.entries.splice(s,0,t);return}let o=n.entries.length+1>>>1,i=n.entries.splice(o),a=new sn(i),c=s<o?0:1;return c?(e.leafNode=a,e.leafIndex-=n.entries.length,a.entries.splice(e.leafIndex,0,t)):n.entries.splice(s,0,t),new Ld(this.keyFromEntry(i[0]),a,c)}branchInsert(e,t,n){let s=e.branches[t],{index:o,node:i}=s;if(s.index+=n.indexDelta,i.partitions.splice(o,0,n.key),i.nodes.splice(o+1,0,n.right),i.nodes.length<=Ir)return;let a=i.nodes.length>>>1,c=i.partitions.splice(a),l=i.partitions.pop(),u=i.nodes.splice(a),h=new bl(c,u),p=s.index<a?0:1;return p&&(s.index-=a,s.node=h),new Ld(l,h,p)}rebalanceLeaf(e){if(e.leafNode.entries.length>=Ir>>>1)return;let t=e.leafNode,n=e.branches.at(-1),s=e.branches.length-1,o=n.index,i=n.node,a=i.nodes[o+1];if(a&&a.entries.length>Ir>>>1){let l=a.entries.shift();t.entries.push(l),this.updatePartition(o+1,e,s,this.keyFromEntry(a.entries[0]));return}let c=i.nodes[o-1];if(c&&c.entries.length>Ir>>>1){let l=c.entries.pop();t.entries.unshift(l),this.updatePartition(o,e,s,this.keyFromEntry(l)),e.leafIndex+=1;return}if(a&&a.entries.length+t.entries.length<=Ir)return t.entries.push(...a.entries),i.partitions.splice(o,1),i.nodes.splice(o+1,1),o===0&&this.updatePartition(o,e,s,this.keyFromEntry(t.entries[0])),this.rebalanceBranch(e,s);if(c&&c.entries.length+t.entries.length<=Ir)return e.leafNode=c,e.leafIndex+=c.entries.length,c.entries.push(...t.entries),i.partitions.splice(o-1,1),i.nodes.splice(o,1),this.rebalanceBranch(e,s)}rebalanceBranch(e,t){let n=e.branches[t],s=n.node;if(t===0&&s.partitions.length===0)return e.branches[t+1]?.node??e.leafNode;if(t===0||s.nodes.length>=Ir<<1)return;let o=e.branches.at(t-1),i=o.index,a=o.node,c=a.nodes[i+1];if(c&&c.nodes.length>Ir>>>1){s.partitions.push(a.partitions[i]);let u=c.nodes.shift();s.nodes.push(u);let h=c.partitions.shift();this.updatePartition(i+1,e,t-1,h);return}let l=a.nodes[i-1];if(l&&l.nodes.length>Ir>>>1){s.partitions.unshift(a.partitions[i-1]);let u=l.nodes.pop();s.nodes.unshift(u);let h=l.partitions.pop();n.index+=1,this.updatePartition(i,e,t-1,h);return}if(c&&c.nodes.length+s.nodes.length<=Ir){let u=a.partitions.splice(i,1)[0];return s.partitions.push(u),s.partitions.push(...c.partitions),s.nodes.push(...c.nodes),a.nodes.splice(i+1,1),i===0&&a.partitions.length>0&&this.updatePartition(i,e,t-1,a.partitions[0]),this.rebalanceBranch(e,t-1)}if(l&&l.nodes.length+s.nodes.length<=Ir){n.node=l,n.index+=l.nodes.length;let u=a.partitions.splice(i-1,1)[0];return l.partitions.push(u),l.partitions.push(...s.partitions),l.nodes.push(...s.nodes),a.nodes.splice(i,1),this.rebalanceBranch(e,t-1)}}updatePartition(e,t,n,s){let o=t.branches[n];e>0?o.node.partitions[e-1]=s:n!==0&&this.updatePartition(t.branches[n-1].index,t,n-1,s)}validatePath(e){if(!this.isValid(e))throw new Error("Path is invalid due to mutation of the tree")}},Ld=class{key;right;indexDelta;constructor(e,t,n){this.key=e,this.right=t,this.indexDelta=n}};function wl(r){let e="";for(let t=0;t<r.length;t++)e+=r[t].toString(16).padStart(2,"0");return e}function Md(r){return`${wl(r.coord)}|${r.id}`}var Od=class{byKey;byId;constructor(){this.byKey=new kd(e=>Md(e)),this.byId=new Map}insert(e){let t=Md(e);this.byKey.insert(e),this.byId.set(e.id,t)}upsert(e,t){let n=Date.now(),s=this.byId.get(e);if(s){let i=this.byKey.find(s);i.on&&this.byKey.deleteAt(i),this.byId.delete(e)}let o={id:e,coord:t,relevance:0,lastAccess:n,state:"disconnected",accessCount:0,successCount:0,failureCount:0,avgLatencyMs:0};return this.insert(o),o}update(e,t){let n=this.byId.get(e);if(!n)return;let s=this.byKey.find(n),o=this.byKey.at(s);if(!o)return;let i={...o,...t};this.byKey.updateAt(s,i),Md(o)!==Md(i)&&(this.byKey.deleteAt(s),this.insert(i))}getById(e){let t=this.byId.get(e);if(!t)return;let n=this.byKey.find(t);return n.on?this.byKey.at(n):void 0}remove(e){let t=this.byId.get(e);if(!t)return;let n=this.byKey.find(t);n.on&&this.byKey.deleteAt(n),this.byId.delete(e)}list(){let e=[];for(let t of this.byKey.ascending(this.byKey.first()))e.push(this.byKey.at(t));return e}size(){return this.byId.size}setState(e,t){this.update(e,{state:t})}protectedIdsAround(e,t){let n=new Set;for(let s of this.neighborsRight(e,t))n.add(s);for(let s of this.neighborsLeft(e,t))n.add(s);return n}ceilPath(e){let t=`${e}|\0`,n=this.byKey.find(t);return n.on||(n=this.byKey.next(n)),n}floorPath(e){let t=`${e}|\uFFFF`,n=this.byKey.find(t);return n.on||(n=this.byKey.prior(n)),n}successorOfCoord(e){let t=wl(e),n=this.ceilPath(t);if(n.on)return this.byKey.at(n);let s=this.byKey.first();return s.on?this.byKey.at(s):void 0}predecessorOfCoord(e){let t=wl(e),n=this.floorPath(t);if(n.on)return this.byKey.at(n);let s=this.byKey.last();return s.on?this.byKey.at(s):void 0}neighborsRight(e,t){let n=[],s=wl(e),o=this.ceilPath(s);o=o.on?o:this.byKey.first();let i=0;for(;i<t&&!(!o.on&&(o=this.byKey.first(),!o.on));)n.push(this.byKey.at(o).id),o=this.byKey.next(o),i++;return Array.from(new Set(n))}neighborsLeft(e,t){let n=[],s=wl(e),o=this.floorPath(s);o=o.on?o:this.byKey.last();let i=0;for(;i<t&&!(!o.on&&(o=this.byKey.last(),!o.on));)n.push(this.byKey.at(o).id),o=this.byKey.prior(o),i++;return Array.from(new Set(n))}};var ny={};z(ny,{sha256:()=>qi,sha512:()=>B9});var ry=ie(ee("crypto"),1);var Nae=new Uint8Array(0);function KS(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Ar(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function FS(r){return new TextEncoder().encode(r)}function zS(r){return new TextDecoder().decode(r)}var b9=VS,HS=128,w9=127,x9=~w9,v9=Math.pow(2,31);function VS(r,e,t){e=e||[],t=t||0;for(var n=t;r>=v9;)e[t++]=r&255|HS,r/=128;for(;r&x9;)e[t++]=r&255|HS,r>>>=7;return e[t]=r|0,VS.bytes=t-n+1,e}var E9=Zg,S9=128,qS=127;function Zg(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Zg.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&qS)<<s:(i&qS)*Math.pow(2,s),s+=7}while(i>=S9);return Zg.bytes=o-n,t}var I9=Math.pow(2,7),A9=Math.pow(2,14),C9=Math.pow(2,21),T9=Math.pow(2,28),_9=Math.pow(2,35),P9=Math.pow(2,42),D9=Math.pow(2,49),k9=Math.pow(2,56),L9=Math.pow(2,63),M9=function(r){return r<I9?1:r<A9?2:r<C9?3:r<T9?4:r<_9?5:r<P9?6:r<D9?7:r<k9?8:r<L9?9:10},O9={encode:b9,decode:E9,encodingLength:M9},R9=O9,xl=R9;function vl(r,e=0){return[xl.decode(r,e),xl.decode.bytes]}function Ki(r,e,t=0){return xl.encode(r,e,t),e}function Fi(r){return xl.encodingLength(r)}function $i(r,e){let t=e.byteLength,n=Fi(r),s=n+Fi(t),o=new Uint8Array(s+t);return Ki(r,o,0),Ki(t,o,n),o.set(e,s),new zi(r,t,e,o)}function El(r){let e=Ar(r),[t,n]=vl(e),[s,o]=vl(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new zi(t,s,i,e)}function GS(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&KS(r.bytes,t.bytes)}}var zi=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var N9=20;function ty({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new ey(r,e,t,n,s)}var ey=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??N9,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?WS(n,this.code,t?.truncate):n.then(s=>WS(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function WS(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return $i(e,r)}var qi=ty({name:"sha2-256",code:18,encode:r=>Ar(ry.default.createHash("sha256").update(r).digest())}),B9=ty({name:"sha2-512",code:19,encode:r=>Ar(ry.default.createHash("sha512").update(r).digest())});ce();te();async function qe(r){let e=r.toMultihash().bytes;return await qi.encode(e)}async function ir(r){return await qi.encode(r)}function YS(r){return P(r,"base64url")}function XS(r="default"){let e=`/optimystic/${r}/fret/1.0.0`;return{PROTOCOL_NEIGHBORS:`${e}/neighbors`,PROTOCOL_NEIGHBORS_ANNOUNCE:`${e}/neighbors/announce`,PROTOCOL_MAYBE_ACT:`${e}/maybeAct`,PROTOCOL_LEAVE:`${e}/leave`,PROTOCOL_PING:`${e}/ping`}}var sy="/optimystic/default/fret/1.0.0/neighbors",oy="/optimystic/default/fret/1.0.0/neighbors/announce",iy="/optimystic/default/fret/1.0.0/maybeAct",ay="/optimystic/default/fret/1.0.0/leave",cy="/optimystic/default/fret/1.0.0/ping";async function Cr(r){let e=JSON.stringify(r);return new TextEncoder().encode(e)}async function on(r){if(r.byteLength===0)throw new Error("empty response");let e=0,t=r.byteLength;for(;e<t&&(r[e]===0||r[e]===9||r[e]===10||r[e]===13||r[e]===32);)e++;for(;t>e&&(r[t-1]===0||r[t-1]===9||r[t-1]===10||r[t-1]===13||r[t-1]===32);)t--;if(t<=e)throw new Error("whitespace response");let n=new TextDecoder().decode(r.subarray(e,t));return JSON.parse(n)}var bs=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Nd=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Bd=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var fy={};z(fy,{base58btc:()=>Ge,base58flickr:()=>q9});function U9(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var v=d[y],S=0,E=w-1;(v!==0||S<g)&&E!==-1;E--,S++)v+=256*x[E]>>>0,x[E]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var A=c.repeat(m);I<w;++I)A+=r.charAt(x[I]);return A}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*w[S]>>>0,w[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(d[m]!==" "){for(var E=b-y;E!==b&&w[E]===0;)E++;for(var I=new Uint8Array(g+(b-E)),A=g;E!==b;)I[A++]=w[E++];return I}}}function f(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:f}}var K9=U9,F9=K9,QS=F9;var ly=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},uy=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return JS(this,e)}},hy=class{decoders;constructor(e){this.decoders=e}or(e){return JS(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function JS(r,e){return new hy({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var dy=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new ly(e,t,n),this.decoder=new uy(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Vi({name:r,prefix:e,encode:t,decode:n}){return new dy(r,e,t,n)}function ws({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=QS(t,r);return Vi({prefix:e,name:r,encode:n,decode:o=>Ar(s(o))})}function z9(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function $9(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function H9(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Ve({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=H9(n);return Vi({prefix:e,name:r,encode(o){return $9(o,n,t)},decode(o){return z9(o,s,t,r)}})}var Ge=ws({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),q9=ws({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var py={};z(py,{base32:()=>xs,base32hex:()=>j9,base32hexpad:()=>X9,base32hexpadupper:()=>Q9,base32hexupper:()=>Y9,base32pad:()=>G9,base32padupper:()=>W9,base32upper:()=>V9,base32z:()=>J9});var xs=Ve({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),V9=Ve({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),G9=Ve({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),W9=Ve({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),j9=Ve({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Y9=Ve({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),X9=Ve({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Q9=Ve({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),J9=Ve({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var my={};z(my,{base36:()=>Sl,base36upper:()=>Z9});var Sl=ws({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Z9=ws({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});function ZS(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return tN(t,gy(r),e??Ge.encoder);default:return rN(t,gy(r),e??xs.encoder)}}var eI=new WeakMap;function gy(r){let e=eI.get(r);if(e==null){let t=new Map;return eI.set(r,t),t}return e}var ot=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Il)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==nN)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=$i(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&GS(e.multihash,n.multihash)}toString(e){return ZS(this,e)}toJSON(){return{"/":ZS(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??tI(n,s,o.bytes))}else if(t[sN]===!0){let{version:n,multihash:s,code:o}=t,i=El(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Il)throw new Error(`Version 0 CID must use dag-pb (code: ${Il}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=tI(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Il,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=Ar(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new zi(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,p]=vl(e.subarray(t));return t+=p,h},s=n(),o=Il;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=eN(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return gy(o).set(n,e),o}};function eN(r,e){switch(r[0]){case"Q":{let t=e??Ge;return[Ge.prefix,t.decode(`${Ge.prefix}${r}`)]}case Ge.prefix:{let t=e??Ge;return[Ge.prefix,t.decode(r)]}case xs.prefix:{let t=e??xs;return[xs.prefix,t.decode(r)]}case Sl.prefix:{let t=e??Sl;return[Sl.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function tN(r,e,t){let{prefix:n}=t;if(n!==Ge.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function rN(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var Il=112,nN=18;function tI(r,e,t){let n=Fi(r),s=n+Fi(e),o=new Uint8Array(s+t.byteLength);return Ki(r,o,0),Ki(e,o,n),o.set(t,s),o}var sN=Symbol.for("@ipld/js-cid/CID");var yy={};z(yy,{identity:()=>Ur});var rI=0,oN="identity",nI=Ar;function iN(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return $i(rI,nI(r))}var Ur={code:rI,name:oN,encode:nI,digest:iN};Ne();Be();te();ce();Be();var aN=parseInt("11111",2),by=parseInt("10000000",2),cN=parseInt("01111111",2),sI={0:Al,1:Al,2:lN,3:dN,4:fN,5:hN,6:uN,16:Al,22:Al,48:Al};function wy(r,e={offset:0}){let t=r[e.offset]&aN;if(e.offset++,sI[t]!=null)return sI[t](r,e);throw new Error("No decoder for tag "+t)}function Cl(r,e){let t=0;if((r[e.offset]&by)===by){let n=r[e.offset]&cN,s="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)s+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(s,16)}else t=r[e.offset],e.offset++;return t}function Al(r,e){Cl(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=wy(r,e);if(n===null)break;t.push(n)}return t}function lN(r,e){let t=Cl(r,e),n=e.offset,s=e.offset+t,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function uN(r,e){let t=Cl(r,e),n=e.offset+t,s=r[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let h=0;h<c.length;h++)u+=c[h]<<h*7;a+=`.${u}`,c=[]}}return a}function hN(r,e){return e.offset++,null}function dN(r,e){let t=Cl(r,e),n=r[e.offset];e.offset++;let s=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function fN(r,e){let t=Cl(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function pN(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new U;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function xy(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=pN(r.byteLength);return new U(Uint8Array.from([e.byteLength|by]),e)}function oI(r){let e=new U,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new U(Uint8Array.from([2]),xy(e),e)}function iI(r){let e=Uint8Array.from([0]),t=new U(e,r);return new U(Uint8Array.from([3]),xy(t),t)}function Ud(r,e=48){let t=new U;for(let n of r)t.append(n);return new U(Uint8Array.from([e]),xy(t),t)}async function aI(r,e,t,n){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,e,t.subarray());return n?.signal?.throwIfAborted(),o}var mN=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),gN=Uint8Array.from([6,5,43,129,4,0,34]),yN=Uint8Array.from([6,5,43,129,4,0,35]),bN={ext:!0,kty:"EC",crv:"P-256"},wN={ext:!0,kty:"EC",crv:"P-384"},xN={ext:!0,kty:"EC",crv:"P-521"},vy=32,Ey=48,Sy=66;function cI(r){let e=wy(r);return lI(e)}function lI(r){let e=r[1][1][0],t=1,n,s;if(e.byteLength===vy*2+1)return n=P(e.subarray(t,t+vy),"base64url"),s=P(e.subarray(t+vy),"base64url"),new Gi({...bN,key_ops:["verify"],x:n,y:s});if(e.byteLength===Ey*2+1)return n=P(e.subarray(t,t+Ey),"base64url"),s=P(e.subarray(t+Ey),"base64url"),new Gi({...wN,key_ops:["verify"],x:n,y:s});if(e.byteLength===Sy*2+1)return n=P(e.subarray(t,t+Sy),"base64url"),s=P(e.subarray(t+Sy),"base64url"),new Gi({...xN,key_ops:["verify"],x:n,y:s});throw new bs(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function uI(r){return Ud([oI(Uint8Array.from([1])),Ud([vN(r.crv)],160),Ud([iI(new U(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function vN(r){if(r==="P-256")return mN;if(r==="P-384")return gN;if(r==="P-521")return yN;throw new bs(`Invalid curve ${r}`)}var Gi=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=uI(this.jwk)),this._raw}toMultihash(){return Ur.digest(Wi(this))}toCID(){return ot.createV1(114,this.toMultihash())}toString(){return Ge.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}async verify(e,t,n){return aI(this.jwk,t,e,n)}};var Kd=ie(ee("crypto"),1);bt();te();ce();var Mce=Kd.default.generateKeyPairSync,Tl=32;var EN=64;function hI(r,e,t){if(r.byteLength!==Tl)throw new TypeError('"key" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');if(e.byteLength!==EN)throw new TypeError('"sig" must be 64 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"sig" must be a node.js Buffer, or Uint8Array.');let n=Kd.default.createPublicKey({format:"jwk",key:{crv:"Ed25519",x:P(r,"base64url"),kty:"OKP"}});return Kd.default.verify(null,t instanceof Uint8Array?t:t.subarray(),n,e)}Ne();bt();te();function fI(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Fd=class{type="Ed25519";raw;constructor(e){this.raw=Iy(e,Tl)}toMultihash(){return Ur.digest(Wi(this))}toCID(){return ot.createV1(114,this.toMultihash())}toString(){return Ge.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let s=hI(this.raw,t,e);return fI(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}};function pI(r){return r=Iy(r,Tl),new Fd(r)}function Iy(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new bs(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}wr();var ar;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ar||(ar={}));var Ay;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Ay||(Ay={}));(function(r){r.codec=()=>sr(Ay)})(ar||(ar={}));var _l;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ar.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=ar.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(_l||(_l={}));var Cy;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ar.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=ar.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(Cy||(Cy={}));var mI=ie(ee("node:crypto"),1);eo();var zd=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}};function gI(r,e,t,n){n?.signal?.throwIfAborted();let s=mI.default.createHash("sha256");if(t instanceof Uint8Array)s.update(t);else for(let i of t)s.update(i);let o=s.digest();try{return st.verify(e,o,r,{prehash:!1,format:"der"})}catch(i){throw new zd(String(i))}}eo();Ne();var $d=class{type="secp256k1";raw;_key;constructor(e){this._key=bI(e),this.raw=yI(this._key)}toMultihash(){return Ur.digest(Wi(this))}toCID(){return ot.createV1(114,this.toMultihash())}toString(){return Ge.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){return gI(this._key,t,e,n)}};function wI(r){return new $d(r)}function yI(r){return st.Point.fromBytes(r).toBytes()}function bI(r){try{return st.Point.fromBytes(r),r}catch(e){throw new Nd(String(e))}}function xI(r){let{Type:e,Data:t}=_l.decode(r.digest),n=t??new Uint8Array;switch(e){case ar.Ed25519:return pI(n);case ar.secp256k1:return wI(n);case ar.ECDSA:return cI(n);default:throw new Bd}}function Wi(r){return _l.encode({Type:ar[r.type],Data:r.raw})}var Ty=Symbol.for("@libp2p/peer-id");var Hd=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var qd=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Vd=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};ce();Ne();te();ce();var vI=Symbol.for("nodejs.util.inspect.custom"),AN=114,Pl=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Ty]=!0;toString(){return this.string==null&&(this.string=Ge.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ot.createV1(AN,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return W(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return W(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[vI](){return`PeerId(${this.toString()})`}},Gd=class extends Pl{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Wd=class extends Pl{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},jd=class extends Pl{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},CN=2336,Dl=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ur.digest(D(this.url))}[vI](){return`PeerId(${this.url})`}[Ty]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ot.createV1(CN,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=P(e)),e.toString()===this.toString())}};var TN=114,EI=2336;function Oe(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=El(Ge.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return _N(ot.parse(r));if(e==null)throw new Hd('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=El(e.decode(r))}return SI(t)}function SI(r){if(DN(r))return new Gd({multihash:r});if(PN(r))try{let e=xI(r);if(e.type==="Ed25519")return new Wd({multihash:r,publicKey:e});if(e.type==="secp256k1")return new jd({multihash:r,publicKey:e})}catch{let t=P(r.digest);return new Dl(new URL(t))}throw new Vd("Supplied PeerID Multihash is invalid")}function _N(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==TN&&r.code!==EI)throw new qd("Supplied PeerID CID is invalid");if(r.code===EI){let e=P(r.multihash.digest);return new Dl(new URL(e))}return SI(r.multihash)}function PN(r){return r.code===Ur.code}function DN(r){return r.code===qi.code}var II=ie(Wg(),1),kN="optimystic:fret";function vs(r){return(0,II.default)(`${kN}:${r}`)}var _y=vs("rpc:neighbors");function AI(r,e,t,n={PROTOCOL_NEIGHBORS:sy,PROTOCOL_NEIGHBORS_ANNOUNCE:oy}){r.handle(n.PROTOCOL_NEIGHBORS,async({stream:s})=>{try{let o=await e();await s.sink((async function*(){yield await Cr(o)})());try{s.close?.()}catch{}}catch(o){console.error("neighbors handler error:",o)}}),t&&r.handle(n.PROTOCOL_NEIGHBORS_ANNOUNCE,async({stream:s})=>{try{let o=await TI(s),i=await on(o);t(i.from,i),await s.sink((async function*(){yield await Cr({ok:!0})})());try{s.close?.()}catch{}}catch(o){console.error("neighbors announce handler error:",o)}})}async function CI(r,e,t=sy){let n=Oe(e),s=r.getConnections?.(n)??[];if(!Array.isArray(s)||s.length===0||typeof s[0]?.newStream!="function")return{v:1,from:e,timestamp:Date.now(),successors:[],predecessors:[],sig:""};let o;try{o=await s[0].newStream([t]);let i=await TI(o);return await on(i)}catch(i){return _y("fetchNeighbors decode failed for %s - %o",e,i),{v:1,from:e,timestamp:Date.now(),successors:[],predecessors:[],sig:""}}finally{if(o)try{await o.close()}catch{}}}async function Py(r,e,t,n=oy){let s=Oe(e),o=r.getConnections?.(s)??[];if(!Array.isArray(o)||o.length===0||typeof o[0]?.newStream!="function")return;let i;try{i=await o[0].newStream([n]),await i.sink((async function*(){yield await Cr(t)})())}catch(a){_y("announceNeighbors failed to %s - %o",e,a)}finally{if(i)try{await i.close()}catch{}}}function LN(r){if(r instanceof Uint8Array)return r;let e=r;if(typeof e?.subarray=="function")try{return e.subarray(0)}catch(t){_y("toBytes subarray failed - %o",t)}if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unsupported chunk type in neighbors read")}async function TI(r){let e=[];for await(let o of r.source)e.push(LN(o));let t=0;for(let o of e)t+=o.length;let n=new Uint8Array(t),s=0;for(let o of e)n.set(o,s),s+=o.length;return n}function _I(r,e,t=iy){r.handle(t,async({stream:n})=>{try{let s=await DI(n),o=await on(s),i=await e(o);await n.sink((async function*(){yield await Cr(i)})())}catch(s){console.error("maybeAct handler error:",s)}})}async function PI(r,e,t,n=iy){let s=Oe(e),o=r.getConnections?.(s)??[],i;try{Array.isArray(o)&&o.length>0&&typeof o[0]?.newStream=="function"?i=await o[0].newStream([n]):i=await r.dialProtocol(s,[n]),await i.sink((async function*(){yield await Cr(t)})());let a=await DI(i);return await on(a)}finally{if(i)try{await i.close()}catch{}}}function MN(r){if(r instanceof Uint8Array)return r;let e=r;if(typeof e?.subarray=="function")return e.subarray(0);throw new Error("Unsupported chunk type in maybeAct read")}async function DI(r){let e=[];for await(let o of r.source)e.push(MN(o));let t=0;for(let o of e)t+=o.length;let n=new Uint8Array(t),s=0;for(let o of e)n.set(o,s),s+=o.length;return n}function kI(r,e,t=ay){r.handle(t,async({stream:n})=>{try{let s=await RN(n),o=await on(s);await e(o),await n.sink((async function*(){yield await Cr({ok:!0})})())}catch(s){console.error("leave handler error:",s)}})}async function LI(r,e,t,n=ay){let s=Oe(e),o=r.getConnections?.(s)??[],i;try{Array.isArray(o)&&o.length>0&&typeof o[0]?.newStream=="function"?i=await o[0].newStream([n]):i=await r.dialProtocol(s,[n]),await i.sink((async function*(){yield await Cr(t)})())}finally{if(i)try{await i.close()}catch{}}}function ON(r){if(r instanceof Uint8Array)return r;let e=r;if(typeof e?.subarray=="function")return e.subarray(0);throw new Error("Unsupported chunk type in leave read")}async function RN(r){let e=[];for await(let o of r.source)e.push(ON(o));let t=0;for(let o of e)t+=o.length;let n=new Uint8Array(t),s=0;for(let o of e)n.set(o,s),s+=o.length;return n}var Dy=vs("rpc:ping");function MI(r,e=cy,t){r.handle(e,async({stream:n})=>{let s={ok:!0,ts:Date.now()};if(t)try{let o=await t();o.size_estimate!==void 0&&(s.size_estimate=o.size_estimate,s.confidence=o.confidence)}catch(o){Dy("getSizeEstimate failed - %o",o)}await n.sink((async function*(){yield await Cr(s)})())})}async function kl(r,e,t=cy){let n=Date.now(),s=Oe(e),o;try{try{let l=r.getConnections?.(s)??[];if(Array.isArray(l)&&l.length>0&&typeof l[0]?.newStream=="function")o=await l[0].newStream([t]);else{let u=await r.dialProtocol(s,[t]);o=u.stream??u}}catch{let u=await r.dialProtocol(s,[t]);o=u.stream??u}let i=null;for await(let l of o.source)if(l!=null)try{if(l instanceof Uint8Array){i=l;break}if(typeof l.subarray=="function"){let u=l.subarray();if(u instanceof Uint8Array){i=u;break}if(ArrayBuffer.isView(u)){i=new Uint8Array(u.buffer,u.byteOffset,u.byteLength);break}}if(ArrayBuffer.isView(l)){i=new Uint8Array(l.buffer,l.byteOffset,l.byteLength);break}}catch(u){Dy("sendPing chunk handling failed - %o",u)}let a=Math.max(0,Date.now()-n);if(!i||i.length===0)return{ok:!1,rttMs:a};let c=new TextDecoder().decode(i).trim();if(!c||c[0]!=="{"||!c.endsWith("}"))return{ok:!1,rttMs:a};try{let l=await on(i);return{ok:!!l.ok,rttMs:a,size_estimate:l.size_estimate,confidence:l.confidence}}catch(l){return Dy("sendPing decode failed - %o",l),{ok:!1,rttMs:a}}}finally{if(o)try{await o.close()}catch{}}}te();function NN(r){let e=0n;for(let t=0;t<r.length;t++)e=e<<8n|BigInt(r[t]);return e}function BN(r){if(r.length===0)return 0n;let e=[...r].sort((n,s)=>n<s?-1:n>s?1:0),t=Math.floor(e.length/2);return e.length%2===0?(e[t-1]+e[t])/2n:e[t]}function Yd(r,e){let t=r.list(),n=t.length;if(n===0)return{n:0,confidence:0};if(n===1)return{n:1,confidence:.2};let s=1n<<256n,o=t.map(g=>NN(g.coord)).sort((g,y)=>g<y?-1:g>y?1:0),i=[];for(let g=1;g<o.length;g++)i.push(o[g]-o[g-1]);i.push(o[0]+s-o[o.length-1]);let a=BN(i),c=a>0n?a:s/BigInt(Math.max(1,n)),l=s/c,u=Math.max(1,Math.min(Number(l),1e9)),h=i[0],p=i[0];for(let g of i)g<h&&(h=g),g>p&&(p=g);let f=Math.min(1,n/Math.max(1,e*2)),d=p===0n?0:Number(h)/Number(p),m=Math.max(.05,Math.min(1,.5*f+.5*d));return{n:u,confidence:m}}var ji=class{capacity;refillPerSec;tokens;last;constructor(e,t){this.capacity=e,this.refillPerSec=t,this.tokens=e,this.last=Date.now()}tryTake(e=1){return this.refill(),this.tokens>=e?(this.tokens-=e,!0):!1}retryAfterMs(e=1){if(this.refill(),this.tokens>=e)return 0;let n=(e-this.tokens)/this.refillPerSec;return Math.ceil(n*1e3)}refill(){let e=Date.now(),t=(e-this.last)/1e3;t>0&&(this.tokens=Math.min(this.capacity,this.tokens+t*this.refillPerSec),this.last=e)}};ce();var vt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Nn=class extends Error{static name="ValidationError";name="ValidationError"},Ll=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Xd=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};Ne();te();ce();gr();bt();te();ce();var fe=ee("node:net");var Ly={};z(Ly,{base64:()=>UN,base64pad:()=>KN,base64url:()=>ky,base64urlpad:()=>FN});var UN=Ve({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),KN=Ve({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ky=Ve({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),FN=Ve({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var My={};z(My,{base10:()=>zN});var zN=ws({prefix:"9",name:"base10",alphabet:"0123456789"});var Oy={};z(Oy,{base16:()=>$N,base16upper:()=>HN});var $N=Ve({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),HN=Ve({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ry={};z(Ry,{base2:()=>qN});var qN=Ve({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ny={};z(Ny,{base256emoji:()=>YN});var OI=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),VN=OI.reduce((r,e,t)=>(r[t]=e,r),[]),GN=OI.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function WN(r){return r.reduce((e,t)=>(e+=VN[t],e),"")}function jN(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=GN[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var YN=Vi({prefix:"\u{1F680}",name:"base256emoji",encode:WN,decode:jN});var By={};z(By,{base8:()=>XN});var XN=Ve({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Uy={};z(Uy,{identity:()=>QN});var QN=Vi({prefix:"\0",name:"identity",encode:r=>zS(r),decode:r=>FS(r)});var Nue=new TextEncoder,Bue=new TextDecoder;var RI={...Uy,...Ry,...By,...My,...Oy,...py,...my,...fy,...Ly,...Ny},Fue={...ny,...yy};bt();te();ce();function Fy(r){return e=>P(e,r)}function zy(r){return e=>D(e,r)}function Yi(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function co(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function NI(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=D(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=co(n);return Ee([t,s],t.length+s.length)}function BI(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=xs.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=co(n);return Ee([t,s],t.length+s.length)}function $y(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=P(e,"base32"),s=Yi(t);return`${n}:${s}`}var Hy=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let s=parseInt(t,10);if(isNaN(s)||s<0||s>255)throw new vt("Invalid byte value in IP address");e[n]=s}),e},UI=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=(0,fe.isIPv4)(t[n]),i;o&&(i=Hy(t[n]),t[n]=P(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,P(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new vt("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},KI=function(r){if(r.byteLength!==4)throw new vt("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},FI=function(r){if(r.byteLength!==16)throw new vt("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new vt(`Invalid IPv6 address "${t}"`)}};function zI(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new vt(`Invalid IPv6 address "${r}"`)}}var Ky=Object.values(RI).map(r=>r.decoder),eB=(function(){let r=Ky[0].or(Ky[1]);return Ky.slice(2).forEach(e=>r=r.or(e)),r})();function $I(r){return eB.decode(r)}function HI(r){return e=>r.encoder.encode(e)}function tB(r){if(parseInt(r).toString()!==r)throw new Nn("Value must be an integer")}function rB(r){if(r<0)throw new Nn("Value must be a positive integer, or zero")}function nB(r){return e=>{if(e>r)throw new Nn(`Value must be smaller than or equal to ${r}`)}}function sB(...r){return e=>{for(let t of r)t(e)}}var Ml=sB(tB,rB,nB(65535));var pt=-1,qy=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new Xd(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},cr=new qy,OB=[{code:4,name:"ip4",size:32,valueToBytes:Hy,bytesToValue:KI,validate:r=>{if(!(0,fe.isIPv4)(r))throw new Nn(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:co,bytesToValue:Yi,validate:Ml},{code:273,name:"udp",size:16,valueToBytes:co,bytesToValue:Yi,validate:Ml},{code:33,name:"dccp",size:16,valueToBytes:co,bytesToValue:Yi,validate:Ml},{code:41,name:"ip6",size:128,valueToBytes:UI,bytesToValue:FI,stringToValue:zI,validate:r=>{if(!(0,fe.isIPv6)(r))throw new Nn(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:pt},{code:43,name:"ipcidr",size:8,bytesToValue:Fy("base10"),valueToBytes:zy("base10")},{code:53,name:"dns",size:pt,resolvable:!0},{code:54,name:"dns4",size:pt,resolvable:!0},{code:55,name:"dns6",size:pt,resolvable:!0},{code:56,name:"dnsaddr",size:pt,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:co,bytesToValue:Yi,validate:Ml},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:pt,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:pt,bytesToValue:Fy("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?zy("base58btc")(r):ot.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:$y,valueToBytes:NI},{code:445,name:"onion3",size:296,bytesToValue:$y,valueToBytes:BI},{code:446,name:"garlic64",size:pt},{code:447,name:"garlic32",size:pt},{code:448,name:"tls"},{code:449,name:"sni",size:pt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:pt,bytesToValue:HI(ky),valueToBytes:$I},{code:480,name:"http"},{code:481,name:"http-path",size:pt,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:pt}];OB.forEach(r=>{cr.addProtocol(r)});function qI(r){let e=[],t=0;for(;t<r.length;){let n=jt(r,t),s=cr.getProtocol(n),o=Ae(n),i=RB(s,r,t+o),a=0;i>0&&s.size===pt&&(a=Ae(i));let c=o+a+i,l={code:n,name:s.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+o+a,h=r.subarray(u,u+i);l.value=s.bytesToValue?.(h)??P(h)}e.push(l),t+=c}return e}function VI(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let s=cr.getProtocol(n.code),o=Ae(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??D(n.value),a=i.byteLength,s.size===pt&&(c=Ae(a)));let l=new Uint8Array(o+c+a),u=0;In(n.code,l,u),u+=o,i!=null&&(s.size===pt&&(In(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Ee(t,e)}function GI(r){if(r.charAt(0)!=="/")throw new vt('String multiaddr must start with "/"');let e=[],t="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(t==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=cr.getProtocol(s);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",s="",t="protocol";continue}else if(a)throw new vt(`Component ${s} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new vt(`Component ${s} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",s="",t="protocol"}}}if(s!==""&&n!=="")throw new vt("Incomplete multiaddr");return e}function WI(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=cr.getProtocol(e.code);if(t==null)throw new vt(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function RB(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:jt(e,t)}var NB=Symbol.for("nodejs.util.inspect.custom"),Jy=Symbol.for("@multiformats/multiaddr"),BB=[53,54,55,56],Qy=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}};function UB(r){if(r==null&&(r="/"),YI(r))return r.getComponents();if(r instanceof Uint8Array)return qI(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),GI(r);if(Array.isArray(r))return r;throw new vt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var tf=class r{[Jy]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=UB(e),t.validate!==!1&&KB(this)}get bytes(){return this.#r==null&&(this.#r=VI(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=WI(this.#e)),this.#t}toJSON(){return this.toString()}toOptions(){let e,t,n,s,o="";for(let{code:a,name:c,value:l}of this.#e)a===42&&(o=`%${l??""}`),BB.includes(a)&&(t="tcp",s=443,n=`${l??""}${o}`,e=a===55?6:4),(a===6||a===273)&&(t=c==="tcp"?"tcp":"udp",s=parseInt(l??"")),(a===4||a===41)&&(t="tcp",n=`${l??""}${o}`,e=a===41?6:4);if(e==null||t==null||n==null||s==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:s}}getComponents(){return[...this.#e]}protos(){return this.#e.map(({code:e,value:t})=>{let n=cr.getProtocol(e);return{code:e,size:n.size??0,name:n.name,resolvable:!!n.resolvable,path:!!n.path}})}protoCodes(){return this.#e.map(({code:e})=>e)}protoNames(){return this.#e.map(({name:e})=>e)}tuples(){return this.#e.map(({code:e,value:t})=>{if(t==null)return[e];let n=cr.getProtocol(e),s=[e];return t!=null&&s.push(n.valueToBytes?.(t)??D(t)),s})}stringTuples(){return this.#e.map(({code:e,value:t})=>t==null?[e]:[e,t])}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new Ll(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,s),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}getPeerId(){try{let e=[];this.#e.forEach(({code:n,value:s})=>{n===421&&e.push([n,s]),n===290&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?P(Ge.decode(`z${n}`),"base58btc"):P(ot.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(let e of this.#e)if(cr.getProtocol(e.code).path)return e.value??null;return null}equals(e){return W(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(o=>o.resolvable);if(t==null)return[this];let n=jI.get(t.name);if(n==null)throw new Qy(`no available resolver for ${t.name}`);return(await n(this,e)).map(o=>Rl(o))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(){return!(this.#e.length!==2||this.#e[0].code!==4&&this.#e[0].code!==41||this.#e[1].code!==6&&this.#e[1].code!==273)}[NB](){return`Multiaddr(${this.toString()})`}};function KB(r){r.getComponents().forEach(e=>{let t=cr.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}var rf=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let p=Number.parseInt(h,e);if(!Number.isNaN(p))return p});if(u===void 0)break;if(o*=e,o+=u,o>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let s=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2],t[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];t[s]=o>>8,t[s+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,s]=e(t);if(n===16)return t;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=e(o.subarray(0,i));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var XI=45,FB=15,Xi=new rf;function QI(r){if(!(r.length>FB))return Xi.new(r).parseWith(()=>Xi.readIPv4Addr())}function JI(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>XI))return Xi.new(r).parseWith(()=>Xi.readIPv6Addr())}function Nl(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>XI)return;let t=Xi.new(r).parseWith(()=>Xi.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function ZI(r,e,t){let n=0;for(let s of r)if(!(n<e)){if(n>t)break;if(s!==255)return!1;n++}return!0}function eA(r,e,t,n){let s=0;for(let o of r)if(!(s<t)){if(s>n)break;if(o!==e[s])return!1;s++}return!0}function Zy(r){switch(r.length){case lo:return r.join(".");case uo:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function tA(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let s=t+1;s<r.length;s++)if(r[s]!=0)return-1;break}return e}function rA(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var lo=4,uo=16,Dhe=parseInt("0xFFFF",16),zB=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Bl(r,e){e.length===uo&&r.length===lo&&ZI(e,0,11)&&(e=e.slice(12)),e.length===lo&&r.length===uo&&eA(r,zB,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=r[s]&e[s];return n}function nA(r,e){if(typeof e=="string"&&(e=Nl(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function e3(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=lo,s=QI(e);if(s==null&&(n=uo,s=JI(e),s==null))throw new Error("Failed to parse given CIDR: "+r);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=t3(o,8*n);return{network:Bl(s,i),mask:i}}function t3(r,e){if(e!==8*lo&&e!==8*uo)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let s=0;s<t;s++){if(r>=8){n[s]=255,r-=8;continue}n[s]=255-(255>>r),r=0}return n}var Bn=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=e3(e));else{let n=Nl(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n.length*8){let o=Nl(t);if(o==null)throw new Error("Failed to parse mask");this.mask=o}else this.mask=t3(s,8*n.length);this.network=Bl(n,this.mask)}}contains(e){return nA({network:this.network,mask:this.mask},e)}toString(){let e=tA(this.mask),t=e!==-1?String(e):rA(this.mask);return Zy(this.network)+"/"+t}};function sA(r,e){return new Bn(r).contains(e)}te();ce();var jI=new Map;function YI(r){return!!r?.[Jy]}function Rl(r){return new tf(r)}function nf(r,e){let t=Math.max(r.length,e.length),n=new Uint8Array(t);for(let s=0;s<t;s++){let o=r[r.length-1-s]??0,i=e[e.length-1-s]??0;n[t-1-s]=o^i}return n}function r3(r,e){let t=Math.max(r.length,e.length);for(let n=0;n<t;n++){let s=r[n]??0,o=e[n]??0;if(s<o)return!0;if(s>o)return!1}return!1}function oA(r){for(let e=0;e<r.length;e++)if(r[e]!==0)return e;return Number.POSITIVE_INFINITY}function $B(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}function iA(r,e,t,n){return r3(e,n)?!0:r3(n,e)?!1:r<t}function sf(r,e,t,n,s,o=1){let i,a=[];for(let u of t){let h=r.getById(u);if(!h)continue;let p=nf(h.coord,e),f=n(u),d=(f?1:0)+.25*s(u);a.push({id:u,dist:p,connected:f,score:d}),(!i||iA(u,p,i.id,i.dist))&&(i={id:u,dist:p})}if(!i)return;let c=oA(i.dist),l;for(let u of a){if(!u.connected)continue;if(oA(u.dist)<=c+o){if(!l){l={id:u.id,dist:u.dist,score:u.score};continue}iA(u.id,u.dist,l.id,l.dist)?l={id:u.id,dist:u.dist,score:u.score}:$B(u.dist,l.dist)&&(u.score>l.score||u.score===l.score&&u.id<l.id)&&(l={id:u.id,dist:u.dist,score:u.score})}}return l?.id??i.id}function aA(r=12,e=.08,t=.03,n=.6,s=.7,o=1.8,i=1e-6){let a=[];for(let c=0;c<r;c++)a.push((c+.5)/r);return{centers:a,occupancy:new Float64Array(r),alpha:t,sigma:e,beta:n,sMin:s,sMax:o,eps:i}}function of(r,e){let t=nf(r,e),n=0;for(let o=0;o<t.length;o++){let i=t[o]??0;if(i===0){n+=8;continue}let a=7-Math.floor(Math.log2(i));n+=a;break}return 1-Math.min(256,n)/256}function cA(r,e){let t=r/Math.max(1e-9,e);return Math.exp(-.5*t*t)}function n3(r,e){for(let t=0;t<r.centers.length;t++){let n=cA(Math.abs(e-r.centers[t]),r.sigma);r.occupancy[t]=(1-r.alpha)*r.occupancy[t]+r.alpha*n}}function s3(r,e){let t=0,n=0;for(let i=0;i<r.centers.length;i++){let a=cA(Math.abs(e-r.centers[i]),r.sigma);t+=r.occupancy[i]*a,n+=1*a}let s=(n+r.eps)/(t+r.eps),o=Math.pow(s,r.beta);return Math.max(r.sMin,Math.min(r.sMax,o))}function HB(r,e){let t=Math.max(0,e-r.lastAccess),s=Math.log(2)/Math.max(1,6e4);return Math.exp(-s*t)}function qB(r){return Math.log1p(r.accessCount)/5}function VB(r){let e=r.successCount+r.failureCount,t=e>0?r.successCount/e:.5,n=r.avgLatencyMs>0?Math.min(1,r.avgLatencyMs/1e3):.5,s=.5*t+.5*(1-n);return Math.max(0,s)}function o3(r,e){return .4*HB(r,e)+.2*qB(r)+.4*VB(r)}function i3(r,e){return{...r,...e}}function lA(r,e,t,n=Date.now()){n3(t,e);let s=o3(r,n),o=s3(t,e),i=s*o;return i3(r,{lastAccess:n,relevance:i,accessCount:r.accessCount+1})}function uA(r,e,t,n,s=Date.now()){n3(n,t);let o=.2,i=r.avgLatencyMs>0?(1-o)*r.avgLatencyMs+o*e:e,a=o3({...r,avgLatencyMs:i,successCount:r.successCount+1},s),c=s3(n,t),l=a*c;return i3(r,{lastAccess:s,relevance:l,successCount:r.successCount+1,avgLatencyMs:i})}function hA(r,e,t,n=Date.now()){n3(t,e);let s=o3({...r,failureCount:r.failureCount+1},n)*.7,o=s3(t,e),i=s*o;return i3(r,{lastAccess:n,relevance:i,failureCount:r.failureCount+1})}var Kr=vs("service:fret"),Qi=class{mode="passive";store=new Od;cfg;node;stabilizing=!1;inflightAct=0;bucketNeighbors;bucketMaybeAct;bucketDiscovery;announcedIds=new Map;postBootstrapAnnounced=!1;sparsity=aA();cachedSelfCoord=null;preconnectRunning=!1;protocols;metadata;diag={peersDiscovered:0,snapshotsFetched:0,announcementsSent:0,pingsSent:0,pingsOk:0,pingsFail:0,maybeActForwarded:0,evictions:0};networkObservations=[];maxObservations=100;observationWindowMs=3e5;constructor(e,t){this.node=e,this.cfg={k:t?.k??15,m:t?.m??Math.ceil((t?.k??15)/2),capacity:t?.capacity??2048,profile:t?.profile??"core",bootstraps:t?.bootstraps??[],networkName:t?.networkName??"default"},this.protocols=XS(this.cfg.networkName),this.bucketDiscovery=new ji(this.cfg.profile==="core"?50:10,this.cfg.profile==="core"?25:3),this.bucketNeighbors=new ji(this.cfg.profile==="core"?20:8,this.cfg.profile==="core"?10:4),this.bucketMaybeAct=new ji(this.cfg.profile==="core"?32:8,this.cfg.profile==="core"?16:4)}getDiagnostics(){return this.diag}async selfCoord(){return this.cachedSelfCoord?this.cachedSelfCoord:(this.cachedSelfCoord=await qe(this.node.peerId),this.cachedSelfCoord)}enforceCapacity(){let e=Math.max(1,this.cfg.capacity);if(this.store.size()<=e)return;let t=this.cachedSelfCoord;if(!t)return;let n=this.store.protectedIdsAround(t,Math.max(2,this.cfg.m)),s=this.store.list();s.sort((o,i)=>o.relevance-i.relevance);for(let o of s){if(this.store.size()<=e)break;n.has(o.id)||this.store.remove(o.id)}}async applyTouch(e,t){let n=this.store.getById(e)??this.store.upsert(e,t),s=of(await this.selfCoord(),t),o=lA(n,s,this.sparsity);this.store.update(e,{lastAccess:o.lastAccess,relevance:o.relevance,accessCount:o.accessCount})}async applySuccess(e,t,n){let s=this.store.getById(e)??this.store.upsert(e,t),o=of(await this.selfCoord(),t),i=uA(s,n,o,this.sparsity);this.store.update(e,{lastAccess:i.lastAccess,relevance:i.relevance,successCount:i.successCount,avgLatencyMs:i.avgLatencyMs})}async applyFailure(e,t){let n=this.store.getById(e)??this.store.upsert(e,t),s=of(await this.selfCoord(),t),o=hA(n,s,this.sparsity);this.store.update(e,{lastAccess:o.lastAccess,relevance:o.relevance,failureCount:o.failureCount})}async start(){await this.seedFromPeerStore(),this.registerRpcHandlers(),await this.proactiveAnnounceOnStart(),this.startStabilizationLoop(),this.mode==="active"&&this.preconnectNeighbors(),this.node.addEventListener("peer:connect",async e=>{if(!this.postBootstrapAnnounced){this.postBootstrapAnnounced=!0;try{await this.announceNeighborsBounded(8)}catch(t){Kr("postBootstrap announce failed - %o",t)}}}),this.node.addEventListener("peer:connect",async e=>{try{let t=e?.detail?.id?.toString?.();if(!t)return;let n=this.store.getById(t)?.coord??await qe(Oe(t));this.store.setState(t,"connected"),await this.applyTouch(t,n)}catch(t){Kr("peer:connect handler failed - %o",t)}}),this.node.addEventListener("peer:disconnect",async e=>{try{let t=e?.detail?.id?.toString?.();if(!t)return;let n=this.store.getById(t)?.coord??await qe(Oe(t));this.store.setState(t,"disconnected"),await this.applyFailure(t,n)}catch(t){Kr("peer:disconnect handler failed - %o",t)}})}async stop(){this.stabilizing=!1;try{await this.sendLeaveToNeighbors()}catch(e){console.warn("sendLeaveToNeighbors failed",e)}}setMode(e){this.mode=e,e==="active"&&!this.preconnectRunning&&this.startActivePreconnectLoop()}async ready(){}registerRpcHandlers(){AI(this.node,async()=>this.handleNeighborsRequest(),(e,t)=>{this.mergeAnnounceSnapshot(e,t)},this.protocols),_I(this.node,async e=>this.handleMaybeAct(e),this.protocols.PROTOCOL_MAYBE_ACT),kI(this.node,async e=>this.handleLeave(e.from),this.protocols.PROTOCOL_LEAVE),MI(this.node,this.protocols.PROTOCOL_PING,()=>this.getNetworkSizeEstimate())}async handleNeighborsRequest(){return this.bucketNeighbors.tryTake()?await this.snapshot():{v:1,from:this.node.peerId.toString(),timestamp:Date.now(),successors:[],predecessors:[],sig:""}}async handleMaybeAct(e){if(e.ttl<=0)return await this.nearAnchorOnly(e);if(e.activity&&e.activity.length>128*1024)return await this.nearAnchorOnly(e);if(!this.bucketMaybeAct.tryTake())return await this.nearAnchorOnly(e);let t=this.cfg.profile==="core"?16:4;if(this.inflightAct>=t)return this.nearAnchorOnly(e);this.inflightAct++;try{return await this.routeAct(e)}catch(n){return console.error("routeAct failed:",n),await this.nearAnchorOnly(e)}finally{this.inflightAct--}}isConnected(e){try{return this.node.getConnections(Oe(e)).length>0}catch{return!1}}hasAddresses(e){try{let t=this.node.getMultiaddrsForPeer?.(Oe(e))??[];return Array.isArray(t)&&t.length>0}catch{return!1}}async proactiveAnnounceOnStart(){try{await this.announceNeighborsBounded(8)}catch(e){console.warn("proactiveAnnounceOnStart failed",e)}}async announceNeighborsBounded(e){let t=await qe(this.node.peerId),n=this.node.peerId.toString(),s=Array.from(new Set([...this.getNeighbors(t,"right",this.cfg.m),...this.getNeighbors(t,"left",this.cfg.m)])).filter(i=>i!==n).slice(0,e),o=await this.snapshot();for(let i of s)if(this.isConnected(i)||this.hasAddresses(i))try{await Py(this.node,i,o,this.protocols.PROTOCOL_NEIGHBORS_ANNOUNCE),this.diag.announcementsSent++}catch(a){console.warn("announce failed",i,a)}}async preconnectNeighbors(){try{let e=await qe(this.node.peerId),t=this.node.peerId.toString(),n=Array.from(new Set([...this.getNeighbors(e,"right",Math.min(6,this.cfg.m)),...this.getNeighbors(e,"left",Math.min(6,this.cfg.m))])).filter(s=>s!==t);for(let s of n)if(this.isConnected(s)||this.hasAddresses(s))try{await kl(this.node,s,this.protocols.PROTOCOL_PING),this.diag.pingsSent++}catch(o){Kr("preconnectNeighbors ping failed for %s - %o",s,o)}}catch(e){Kr("preconnectNeighbors outer failed - %o",e)}}startActivePreconnectLoop(){if(this.preconnectRunning)return;this.preconnectRunning=!0;let e=async()=>{if(!this.preconnectRunning||this.mode!=="active"){this.preconnectRunning=!1;return}try{let t=await this.selfCoord(),n=this.node.peerId.toString(),s=this.cfg.profile==="core"?6:3,o=Array.from(new Set([...this.getNeighbors(t,"right",Math.min(12,this.cfg.m)),...this.getNeighbors(t,"left",Math.min(12,this.cfg.m))])).filter(i=>i!==n).slice(0,s);for(let i of o)if(this.isConnected(i)||this.hasAddresses(i))try{await kl(this.node,i,this.protocols.PROTOCOL_PING),this.diag.pingsSent++}catch(a){Kr("active preconnect ping failed for %s - %o",i,a)}}catch(t){Kr("active preconnect tick failed - %o",t)}setTimeout(e,1e3)};e()}async sendLeaveToNeighbors(){try{let e=await qe(this.node.peerId),t=this.node.peerId.toString(),n=Array.from(new Set([...this.getNeighbors(e,"right",this.cfg.m),...this.getNeighbors(e,"left",this.cfg.m)])).filter(o=>o!==t).slice(0,8),s={v:1,from:this.node.peerId.toString(),timestamp:Date.now()};for(let o of n)try{await LI(this.node,o,s,this.protocols.PROTOCOL_LEAVE)}catch(i){Kr("sendLeave failed for %s - %o",o,i)}}catch(e){Kr("sendLeaveToNeighbors outer failed - %o",e)}}async handleLeave(e){try{let t=null,n=this.store.getById(e);if(n)t=n.coord;else try{t=await qe(Oe(e))}catch(l){console.warn("handleLeave: could not hash departing peer id",e,l)}if(this.store.remove(e),t)try{await this.applyFailure(e,t)}catch{}if(!t)return;let s=Array.from(new Set([...this.store.neighborsRight(t,this.cfg.m),...this.store.neighborsLeft(t,this.cfg.m)])),o=this.expandCohort(s,t,Math.max(2,Math.ceil(this.cfg.m/2))),i=new Set(s),a=o.filter(l=>!i.has(l)),c=a.slice(0,Math.min(a.length,6));for(let l of c)try{if(await kl(this.node,l,this.protocols.PROTOCOL_PING),!this.isConnected(l)){let u=await this.snapshot();await Py(this.node,l,u,this.protocols.PROTOCOL_NEIGHBORS_ANNOUNCE)}}catch(u){console.warn("warm/announce failed for",l,u)}await this.mergeNeighborSnapshots(c.slice(0,4))}catch(t){console.error("handleLeave failed for",e,t)}}async mergeAnnounceSnapshot(e,t){try{let n=Oe(e),s=await qe(n),o=[];this.store.getById(e)||o.push(e),this.store.upsert(e,s),await this.applyTouch(e,s),t.metadata&&this.store.update(e,{metadata:t.metadata});for(let i of[...t.successors??[],...t.predecessors??[]])try{let a=await qe(Oe(i));this.store.getById(i)||o.push(i),this.store.upsert(i,a),await this.applyTouch(i,a)}catch(a){console.warn("mergeAnnounceSnapshot: failed for",i,a)}for(let i of t.sample??[])try{let a=D(i.coord,"base64url");this.store.getById(i.id)||o.push(i.id),this.store.upsert(i.id,a),await this.applyTouch(i.id,a)}catch(a){Kr("mergeAnnounceSnapshot sample upsert failed for %s - %o",i.id,a)}this.enforceCapacity(),this.emitDiscovered(o)}catch(n){console.warn("mergeAnnounceSnapshot failed for",e,n)}}async seedFromPeerStore(){try{let e=this.node.peerStore?.getPeers?.()??[],t=[];for(let n of e)try{let s=await qe(n.id),o=n.id.toString();this.store.getById(o)||t.push(o),this.store.upsert(o,s)}catch(s){console.warn("failed to add peer from peerStore",n?.id?.toString?.(),s)}try{let n=await qe(this.node.peerId),s=this.node.peerId.toString();this.store.getById(s)||t.push(s),this.store.upsert(s,n)}catch(n){console.error("failed to add self to store",n)}this.enforceCapacity(),this.emitDiscovered(t)}catch(e){console.error("seedFromPeerStore failed:",e)}}startStabilizationLoop(){if(this.stabilizing)return;this.stabilizing=!0;let e=async()=>{if(this.stabilizing)try{await this.seedFromPeerStore(),await this.seedFromBootstraps(),await this.stabilizeOnce()}catch(t){console.error("stabilize tick failed:",t)}finally{let t=this.mode==="active"?300:1500;setTimeout(e,t)}};e()}async seedFromBootstraps(){if(!this.cfg.bootstraps||this.cfg.bootstraps.length===0)return;let e=[];for(let t of this.cfg.bootstraps.slice(0,8))try{let n=t;if(t.startsWith("/"))try{let a=Rl(t).getPeerId();a&&(n=a)}catch{}let s=Oe(n),o=await qe(s);this.store.getById(n)||e.push(n),this.store.upsert(n,o),await this.applyTouch(n,o)}catch(n){console.warn("seedFromBootstraps failed for",t,n)}this.enforceCapacity(),this.emitDiscovered(e)}async stabilizeOnce(){let e=await qe(this.node.peerId),t=this.node.peerId.toString(),s=this.getNeighbors(e,"both",Math.max(2,this.cfg.m)).filter(o=>o!==t&&(this.isConnected(o)||this.hasAddresses(o)));await this.probeNeighborsLatency(s.slice(0,4)),await this.mergeNeighborSnapshots(s.slice(0,4))}async probeNeighborsLatency(e){for(let t of e)try{let n=await kl(this.node,t,this.protocols.PROTOCOL_PING);if(this.diag.pingsSent++,n.ok){let s=this.store.getById(t)?.coord??await qe(Oe(t));await this.applySuccess(t,s,n.rttMs),this.diag.pingsOk++}else{let s=this.store.getById(t)?.coord??await qe(Oe(t));await this.applyFailure(t,s),this.diag.pingsFail++}}catch{try{let s=this.store.getById(t)?.coord??await qe(Oe(t));await this.applyFailure(t,s),this.diag.pingsFail++}catch{}}}async mergeNeighborSnapshots(e){let t=[];for(let n of e)try{let s=await CI(this.node,n,this.protocols.PROTOCOL_NEIGHBORS);this.diag.snapshotsFetched++;let o=this.cfg.profile==="core"?16:8,i=this.cfg.profile==="core"?16:8,a=(s.successors??[]).slice(0,o),c=(s.predecessors??[]).slice(0,i);for(let u of[...a,...c])try{let h=await qe(Oe(u));this.store.getById(u)||t.push(u),this.store.upsert(u,h),await this.applyTouch(u,h)}catch(h){console.warn("failed to merge neighbor",u,h)}let l=this.cfg.profile==="core"?8:6;for(let u of(s.sample??[]).slice(0,l))try{let h=D(u.coord,"base64url");this.store.getById(u.id)||t.push(u.id),this.store.upsert(u.id,h),await this.applyTouch(u.id,h)}catch(h){Kr("mergeNeighborSnapshots sample upsert failed for %s - %o",u.id,h)}}catch(s){console.warn("fetchNeighbors failed for",n,s)}this.enforceCapacity(),this.emitDiscovered(t)}async snapshot(){let e=await qe(this.node.peerId),{n:t,confidence:n}=Yd(this.store,this.cfg.m),s=this.cfg.profile==="core"?12:6,o=this.cfg.profile==="core"?12:6,i=this.cfg.profile==="core"?8:6,a=this.getNeighbors(e,"right",this.cfg.m),c=this.getNeighbors(e,"left",this.cfg.m),l=a.slice(0,s),u=c.slice(0,o),h=Array.from(new Set([...l.slice(0,4),...u.slice(0,4)])).slice(0,i),p=await Promise.all(h.map(async f=>{let d=this.store.getById(f);return d?{id:f,coord:YS(d.coord),relevance:d.relevance}:{id:f,coord:"",relevance:0}}));return{v:1,from:this.node.peerId.toString(),timestamp:Date.now(),successors:l,predecessors:u,sample:p,size_estimate:t,confidence:n,sig:"",metadata:this.metadata}}neighborDistance(e,t,n){let s=new Set,o=Math.max(1,n),a=this.assembleCohort(t,o,s).findIndex(c=>c===e);return a>=0?a:Number.POSITIVE_INFINITY}getNeighbors(e,t,n){let s=[];return(t==="right"||t==="both")&&s.push(...this.store.neighborsRight(e,n)),(t==="left"||t==="both")&&s.push(...this.store.neighborsLeft(e,n)),Array.from(new Set(s)).slice(0,n)}nextSuccessor(e,t){let n=t.findIndex(s=>s.id===e.id);return t[(n+1)%t.length]}nextPredecessor(e,t){let n=t.findIndex(s=>s.id===e.id);return t[(n-1+t.length)%t.length]}assembleCohort(e,t,n){let s=[],o=n??new Set,i=this.store.neighborsRight(e,t*2),a=this.store.neighborsLeft(e,t*2),c=0,l=0;for(;s.length<t&&(c<i.length||l<a.length);)if(s.length%2===0){let u=i[c++];u&&!o.has(u)&&s.push(u)}else{let u=a[l++];u&&!o.has(u)&&s.push(u)}return Array.from(new Set(s)).slice(0,t)}expandCohort(e,t,n,s){let o=new Set(e),i=this.assembleCohort(t,e.length+n,s);for(let a of i)o.add(a);return Array.from(o)}async nearAnchorOnly(e){let t=D(e.key,"base64url"),n=await ir(t),s=this.getNeighbors(n,"right",this.cfg.m),o=this.getNeighbors(n,"left",this.cfg.m);return{v:1,anchors:this.pickAnchors([...s.slice(0,3),...o.slice(0,3)]),cohort_hint:Array.from(new Set([...s.slice(0,2),...o.slice(0,2)])),estimated_cluster_size:this.cfg.k,confidence:.5}}emitDiscovered(e){if(e.length===0)return;let t=Date.now(),n=this.cfg.profile==="core"?10*6e4:30*6e4,s=this.node,o=0;for(let i of Array.from(new Set(e)))if(!((this.announcedIds.get(i)??0)>t)){if(!this.bucketDiscovery.tryTake())break;try{let c=Oe(i);s.dispatchEvent?.(new CustomEvent("peer:discovery",{detail:{id:c,multiaddrs:[]}})),this.announcedIds.set(i,t+n),o++}catch(c){console.warn("emitDiscovered failed for",i,c)}}if(o>0&&this.announcedIds.size>4096)for(let[i,a]of this.announcedIds)a<=t&&this.announcedIds.delete(i)}pickAnchors(e){let t=Array.from(new Set(e));if(t.length===0)return[];let n=c=>.5,s=new Uint8Array(32),o=sf(this.store,s,t,c=>this.isConnected(c),n),i=t.filter(c=>c!==o),a=sf(this.store,s,i,c=>this.isConnected(c),n);return[o,a].filter(c=>!!c)}async routeAct(e){let t=D(e.key,"base64url"),n=await ir(t),s=this.node.peerId.toString();if(this.neighborDistance(s,n,2)>1&&e.ttl>0){let h=new Set([...e.breadcrumbs??[],s]),p=this.assembleCohort(n,Math.max(4,this.cfg.m)).filter(m=>!h.has(m)),f=m=>.5,d=sf(this.store,n,p,m=>this.isConnected(m),f);if(d){let m={...e,ttl:e.ttl-1,breadcrumbs:[...e.breadcrumbs??[],s]};try{return await PI(this.node,d,m,this.protocols.PROTOCOL_MAYBE_ACT)}catch(g){console.warn("forward maybeAct failed to",d,g)}}}let{n:i,confidence:a}=Yd(this.store,this.cfg.m),c=this.getNeighbors(n,"right",this.cfg.m),l=this.getNeighbors(n,"left",this.cfg.m);return{v:1,anchors:this.pickAnchors([...c.slice(0,4),...l.slice(0,4)]),cohort_hint:Array.from(new Set([...c.slice(0,4),...l.slice(0,4)])),estimated_cluster_size:Math.max(this.cfg.k,i),confidence:a}}report(e){}reportNetworkSize(e,t,n="external"){let s=Date.now();this.networkObservations.push({estimate:e,confidence:t,timestamp:s,source:n});let o=s-this.observationWindowMs;this.networkObservations=this.networkObservations.filter(i=>i.timestamp>o),this.networkObservations.length>this.maxObservations&&(this.networkObservations=this.networkObservations.slice(-this.maxObservations))}getNetworkSizeEstimate(){let e=Yd(this.store,this.cfg.m),t=Date.now(),n=[{estimate:e.n,confidence:e.confidence,timestamp:t,source:"fret"},...this.networkObservations];if(n.length===0)return{size_estimate:0,confidence:0,sources:0};let s=0,o=0,i=0;for(let l of n){let u=t-l.timestamp,h=Math.exp(-u/(this.observationWindowMs/3)),p=h*l.confidence;o+=l.estimate*p,i+=l.confidence*h,s+=p}if(s===0)return{size_estimate:0,confidence:0,sources:0};let a=Math.round(o/s),c=i/n.length;return{size_estimate:a,confidence:Math.min(1,c),sources:n.length}}getNetworkChurn(){if(this.networkObservations.length<2)return 0;let e=Date.now(),t=this.observationWindowMs/2,n=e-t,s=this.networkObservations.filter(l=>l.timestamp>n),o=this.networkObservations.filter(l=>l.timestamp<=n);if(s.length===0||o.length===0)return 0;let i=s.reduce((l,u)=>l+u.estimate,0)/s.length,a=o.reduce((l,u)=>l+u.estimate,0)/o.length;return(i-a)/t*6e4}detectPartition(){if(this.networkObservations.length<10)return!1;let e=this.getNetworkSizeEstimate();if(e.confidence<.3)return!1;let t=Date.now()-3e4,n=this.networkObservations.filter(c=>c.timestamp<t);if(n.length<3)return!1;let s=n.slice(-5).reduce((c,l)=>c+l.estimate,0)/Math.min(5,n.length);if(e.size_estimate/s<.5)return!0;let i=Math.abs(this.getNetworkChurn()),a=e.size_estimate*.1;return i>a}setMetadata(e){this.metadata=e}getMetadata(e){return this.store.getById(e)?.metadata}listPeers(){return this.store.list().map(e=>({id:e.id,metadata:e.metadata}))}};var GB=vs("service:discovery");function a3(r,e){let t=r;for(let n of e.list())try{let s=Oe(n.id);t.dispatchEvent?.(new CustomEvent("peer:discovery",{detail:{id:s,multiaddrs:[]}}))}catch(s){GB("seedDiscovery failed for %s - %o",n.id,s)}}var af=class{components;cfg;inner=null;nodeRef=null;constructor(e,t){this.components=e,this.cfg=t}get[Symbol.toStringTag](){return"@optimystic/fret"}setLibp2p(e){this.nodeRef=e}ensure(){if(!this.inner){if(!this.nodeRef)throw new Error("Libp2pFretService: libp2p node not injected");this.inner=new Qi(this.nodeRef,this.cfg)}return this.inner}async start(){if(this.ensure(),!this.nodeRef)throw new Error("Libp2pFretService.start: libp2p node not injected");a3(this.nodeRef,this.inner?.store??{}),await this.ensure().start()}async stop(){await this.inner?.stop()}async routeAct(e){return await this.ensure().routeAct(e)}getNeighborsForKey(e,t,n){return this.ensure().getNeighbors(e,t,n)}assembleCohortForKey(e,t){return this.ensure().assembleCohort(e,t)}getDiagnostics(){return this.ensure().getDiagnostics?.()}neighborDistance(e,t,n){return this.ensure().neighborDistance(e,t,n)}getNeighbors(e,t,n){return this.ensure().getNeighbors(e,t,n)}assembleCohort(e,t,n){return this.ensure().assembleCohort(e,t,n)}expandCohort(e,t,n,s){return this.ensure().expandCohort(e,t,n,s)}async ready(){await this.ensure().ready()}setMode(e){this.ensure().setMode(e)}setMetadata(e){this.ensure().setMetadata(e)}report(e){this.ensure().report(e)}getMetadata(e){return this.ensure().getMetadata(e)}listPeers(){return this.ensure().listPeers()}};function c3(r){return e=>new af(e,r)}ke();var dA="/db-p2p/sync/",fA="1.0.0",Ul=(r="")=>`${r}${dA}${fA}`;var ho=class extends Cn{protocol;constructor(e,t,n=""){super(e,t),this.protocol=Ul(n)}async requestBlock(e){return await this.processMessage(e,this.protocol)}getProtocol(){return this.protocol}};var Kl=class{fretAdapter;peerNetwork;protocolPrefix;metrics={totalRequests:0,successByRing:new Map,failureByRing:new Map,averageDurationMs:0};constructor(e,t,n){this.fretAdapter=e,this.peerNetwork=t,this.protocolPrefix=n}log=Sr("storage:restoration");async restore(e,t){let n=Date.now();this.metrics.totalRequests++;let s=await this.getMyRingPeers(e),o=this.getMyRingDepth();for(let a of s){let c=await this.queryPeer(a,e,t);if(c)return this.recordSuccess(o,e,Date.now()-n),c}for(let a=o-1;a>=0;a--){let c=this.fretAdapter.findPeersAtRing(a),l=this.filterByPartition(c,e,a);for(let u of l){let h=await this.queryPeer(u,e,t);if(h)return this.recordSuccess(a,e,Date.now()-n),h}}let i=Date.now()-n;this.log("restore failed for block %s after %dms",e,i)}createRestoreCallback(){return async(e,t)=>await this.restore(e,t)}async getMyRingPeers(e){let t=new TextEncoder().encode(e),n=await ir(t);return this.fretAdapter.getFret().assembleCohort(n,10)}getMyRingDepth(){return this.fretAdapter.getMyArachnodeInfo()?.ringDepth??8}filterByPartition(e,t,n){if(n===0)return e;let s=this.extractBlockPrefix(t,n);return e.filter(o=>{let i=this.fretAdapter.getArachnodeInfo(o);return!i||!i.partition?!1:i.partition.prefixValue===s})}extractBlockPrefix(e,t){let n=new TextEncoder().encode(e),s=new Uint8Array(32);for(let i=0;i<Math.min(n.length,s.length);i++)s[i]=n[i];let o=0;for(let i=0;i<t;i++){let a=Math.floor(i/8),c=7-i%8,l=s[a]>>c&1;o=o<<1|l}return o}async queryPeer(e,t,n){try{let s=de(e),i=await new ho(s,this.peerNetwork,this.protocolPrefix).requestBlock({blockId:t,rev:n});return i.success?i.archive:void 0}catch(s){this.log("queryPeer failed for %s - %o",e,s);return}}recordSuccess(e,t,n){let s=this.metrics.successByRing.get(e)??0;this.metrics.successByRing.set(e,s+1);let o=Array.from(this.metrics.successByRing.values()).reduce((a,c)=>a+c,0),i=this.metrics.averageDurationMs*(o-1);this.metrics.averageDurationMs=(i+n)/o,console.log(`[Ring ${e}] Successfully restored block ${t} in ${n}ms`)}getMetrics(){return{...this.metrics}}};var Fl=class{fretAdapter;storageMonitor;config;constructor(e,t,n){this.fretAdapter=e,this.storageMonitor=t,this.config=n}async determineRing(){let e=await this.storageMonitor.getCapacity();if(e.available<this.config.minCapacity)return-1;let s=1e3*(100*1024),o=e.available/s,i=Math.max(0,Math.ceil(-Math.log2(Math.max(.001,o))));return Math.min(i,16)}async calculatePartition(e,t){if(e===0)return;let n=await qe({toString:()=>t}),s=e,o=this.extractPrefix(n,s);return{prefixBits:s,prefixValue:o}}async createArachnodeInfo(e){let t=await this.storageMonitor.getCapacity(),n=await this.determineRing(),s=n>=0?await this.calculatePartition(n,e):void 0;return{ringDepth:Math.max(0,n),partition:s,capacity:{total:t.total,used:t.used,available:t.available},status:"active"}}async shouldTransition(){let e=await this.storageMonitor.getCapacity(),t=e.used/e.total;if(t>this.config.thresholds.moveOut)return{shouldMove:!0,direction:"out",newRingDepth:await this.determineRing()+1};if(t<this.config.thresholds.moveIn){let n=await this.determineRing();if(n>0)return{shouldMove:!0,direction:"in",newRingDepth:n-1}}return{shouldMove:!1}}extractPrefix(e,t){let n=0;for(let s=0;s<t;s++){let o=Math.floor(s/8),i=7-s%8,a=e[o]>>i&1;n=n<<1|a}return n}};var zl=class{storage;config;constructor(e,t={}){this.storage=e,this.config=t}async getCapacity(){let t=this.config.totalBytes??10737418240,n=this.config.usedBytes,s=this.config.availableBytes;if(n!==void 0||s!==void 0||this.config.totalBytes!==void 0){let a=n??Math.max(0,t-(s??t)),c=s??Math.max(0,t-a);return{total:t,used:Math.min(t,Math.max(0,a)),available:Math.max(0,Math.min(t,c))}}let o=await this.estimateUsedSpace(),i=Math.max(0,t-o);return{total:t,used:o,available:i}}async estimateUsedSpace(){return 0}};var $l=class r{fret;static ARACHNODE_KEY="arachnode";constructor(e){this.fret=e}setArachnodeInfo(e){this.fret.setMetadata({[r.ARACHNODE_KEY]:e})}getArachnodeInfo(e){return this.fret.getMetadata(e)?.[r.ARACHNODE_KEY]}getMyArachnodeInfo(){let e=this.fret.node?.peerId?.toString();if(e)return this.getArachnodeInfo(e)}findPeersAtRing(e){return this.fret.listPeers().filter(n=>n.metadata?.[r.ARACHNODE_KEY]?.ringDepth===e).map(n=>n.id)}getKnownRings(){let e=this.fret.listPeers(),t=new Set;for(let n of e){let s=n.metadata?.[r.ARACHNODE_KEY];s?.ringDepth!==void 0&&t.add(s.ringDepth)}return Array.from(t).sort((n,s)=>n-s)}getRingStats(){let e=this.fret.listPeers(),t=new Map;for(let n of e){let s=n.metadata?.[r.ARACHNODE_KEY];if(s){let o=t.get(s.ringDepth)??{count:0,totalCapacity:0};t.set(s.ringDepth,{count:o.count+1,totalCapacity:o.totalCapacity+s.capacity.available})}}return Array.from(t.entries()).map(([n,s])=>({ringDepth:n,peerCount:s.count,avgCapacity:s.totalCapacity/s.count})).sort((n,s)=>n.ringDepth-s.ringDepth)}getFret(){return this.fret}};te();ce();var cf=class{components;running=!1;log;protocol;repo;registrar;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("db-p2p:sync-service"),this.protocol=Ul(t.protocolPrefix??""),this.repo=e.repo,this.registrar=e.registrar}async start(){this.running||(await this.registrar.handle(this.protocol,async e=>{await this.handleSyncRequest(e.stream)}),this.running=!0,this.log("Sync service started on protocol %s",this.protocol))}async stop(){this.running&&(await this.registrar.unhandle(this.protocol),this.running=!1,this.log("Sync service stopped"))}async handleSyncRequest(e){try{let t=await this.readRequest(e);this.log("[Ring Zulu] Received sync request for block %s revision %s",t.blockId,t.rev??"latest");let n=await this.buildArchive(t.blockId,t.rev,t.includePending,t.maxRevisions),s=n?{success:!0,archive:n,responderId:e.id}:{success:!1,error:"Block not found in local storage"};await this.sendResponse(e,s),this.log("[Ring Zulu] %s sync request for block %s",s.success?"Fulfilled":"Failed",t.blockId)}catch(t){this.log.error("Error handling sync request:",t);try{let n={success:!1,error:t instanceof Error?t.message:"Unknown error"};await this.sendResponse(e,n)}catch(n){this.log.error("Failed to send error response:",n)}}finally{try{await e.close()}catch{}}}async readRequest(e){let t=[];if(await ht(e,Pr,async s=>{for await(let o of s)t.push(o.subarray())}),t.length===0)throw new Error("No request received");let n=P(t[0],"utf8");return JSON.parse(n)}async sendResponse(e,t){let n=JSON.stringify(t),s=D(n,"utf8"),o=ht([s],yr);for await(let i of o)e.send(i)}async buildArchive(e,t,n,s){try{let o=t!==void 0?{rev:t,committed:[],pending:[]}:void 0,a=(await this.repo.get({blockIds:[e],context:o}))[e];if(!a||!a.state.latest)return;let c=a.state.latest;return{blockId:e,revisions:{[c.rev]:{action:{actionId:c.actionId,transform:{insert:a.block}},block:a.block}},range:[c.rev,c.rev+1]}}catch(o){this.log.error("Error building archive for block %s:",e,o);return}}},l3=(r={})=>e=>new cf(e,r);ce();ke();Ne();gr();bt();te();ce();var Et=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Un=class extends Error{static name="ValidationError";name="ValidationError"},lf=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},uf=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var lfe=new Uint8Array(0);function pA(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Tr(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function mA(r){return new TextEncoder().encode(r)}function gA(r){return new TextDecoder().decode(r)}var p3={};z(p3,{base32:()=>Ss,base32hex:()=>rU,base32hexpad:()=>sU,base32hexpadupper:()=>oU,base32hexupper:()=>nU,base32pad:()=>eU,base32padupper:()=>tU,base32upper:()=>ZB,base32z:()=>iU});function WB(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var v=d[y],S=0,E=w-1;(v!==0||S<g)&&E!==-1;E--,S++)v+=256*x[E]>>>0,x[E]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var A=c.repeat(m);I<w;++I)A+=r.charAt(x[I]);return A}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*w[S]>>>0,w[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(d[m]!==" "){for(var E=b-y;E!==b&&w[E]===0;)E++;for(var I=new Uint8Array(g+(b-E)),A=g;E!==b;)I[A++]=w[E++];return I}}}function f(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:f}}var jB=WB,YB=jB,bA=YB;var u3=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},h3=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return wA(this,e)}},d3=class{decoders;constructor(e){this.decoders=e}or(e){return wA(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function wA(r,e){return new d3({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var f3=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new u3(e,t,n),this.decoder=new h3(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ji({name:r,prefix:e,encode:t,decode:n}){return new f3(r,e,t,n)}function Es({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=bA(t,r);return Ji({prefix:e,name:r,encode:n,decode:o=>Tr(s(o))})}function XB(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function QB(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function JB(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function We({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=JB(n);return Ji({prefix:e,name:r,encode(o){return QB(o,n,t)},decode(o){return XB(o,s,t,r)}})}var Ss=We({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ZB=We({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),eU=We({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),tU=We({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),rU=We({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),nU=We({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),sU=We({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),oU=We({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),iU=We({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var m3={};z(m3,{base36:()=>Hl,base36upper:()=>aU});var Hl=Es({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),aU=Es({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var g3={};z(g3,{base58btc:()=>an,base58flickr:()=>cU});var an=Es({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),cU=Es({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var lU=EA,xA=128,uU=127,hU=~uU,dU=Math.pow(2,31);function EA(r,e,t){e=e||[],t=t||0;for(var n=t;r>=dU;)e[t++]=r&255|xA,r/=128;for(;r&hU;)e[t++]=r&255|xA,r>>>=7;return e[t]=r|0,EA.bytes=t-n+1,e}var fU=y3,pU=128,vA=127;function y3(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw y3.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&vA)<<s:(i&vA)*Math.pow(2,s),s+=7}while(i>=pU);return y3.bytes=o-n,t}var mU=Math.pow(2,7),gU=Math.pow(2,14),yU=Math.pow(2,21),bU=Math.pow(2,28),wU=Math.pow(2,35),xU=Math.pow(2,42),vU=Math.pow(2,49),EU=Math.pow(2,56),SU=Math.pow(2,63),IU=function(r){return r<mU?1:r<gU?2:r<yU?3:r<bU?4:r<wU?5:r<xU?6:r<vU?7:r<EU?8:r<SU?9:10},AU={encode:lU,decode:fU,encodingLength:IU},CU=AU,ql=CU;function Vl(r,e=0){return[ql.decode(r,e),ql.decode.bytes]}function Zi(r,e,t=0){return ql.encode(r,e,t),e}function ea(r){return ql.encodingLength(r)}function ra(r,e){let t=e.byteLength,n=ea(r),s=n+ea(t),o=new Uint8Array(s+t);return Zi(r,o,0),Zi(t,o,n),o.set(e,s),new ta(r,t,e,o)}function SA(r){let e=Tr(r),[t,n]=Vl(e),[s,o]=Vl(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new ta(t,s,i,e)}function IA(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&pA(r.bytes,t.bytes)}}var ta=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function AA(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return _U(t,b3(r),e??an.encoder);default:return PU(t,b3(r),e??Ss.encoder)}}var CA=new WeakMap;function b3(r){let e=CA.get(r);if(e==null){let t=new Map;return CA.set(r,t),t}return e}var na=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Wl)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==DU)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=ra(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&IA(e.multihash,n.multihash)}toString(e){return AA(this,e)}toJSON(){return{"/":AA(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??TA(n,s,o.bytes))}else if(t[kU]===!0){let{version:n,multihash:s,code:o}=t,i=SA(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Wl)throw new Error(`Version 0 CID must use dag-pb (code: ${Wl}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=TA(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Wl,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=Tr(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new ta(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,p]=Vl(e.subarray(t));return t+=p,h},s=n(),o=Wl;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=TU(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return b3(o).set(n,e),o}};function TU(r,e){switch(r[0]){case"Q":{let t=e??an;return[an.prefix,t.decode(`${an.prefix}${r}`)]}case an.prefix:{let t=e??an;return[an.prefix,t.decode(r)]}case Ss.prefix:{let t=e??Ss;return[Ss.prefix,t.decode(r)]}case Hl.prefix:{let t=e??Hl;return[Hl.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function _U(r,e,t){let{prefix:n}=t;if(n!==an.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function PU(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var Wl=112,DU=18;function TA(r,e,t){let n=ea(r),s=n+ea(e),o=new Uint8Array(s+t.byteLength);return Zi(r,o,0),Zi(e,o,n),o.set(t,s),o}var kU=Symbol.for("@ipld/js-cid/CID");var LU=20;function x3({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new w3(r,e,t,n,s)}var w3=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??LU,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?_A(n,this.code,t?.truncate):n.then(s=>_A(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function _A(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return ra(e,r)}var E3={};z(E3,{base64:()=>MU,base64pad:()=>OU,base64url:()=>v3,base64urlpad:()=>RU});var MU=We({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),OU=We({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),v3=We({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),RU=We({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var S3={};z(S3,{base10:()=>NU});var NU=Es({prefix:"9",name:"base10",alphabet:"0123456789"});var I3={};z(I3,{base16:()=>BU,base16upper:()=>UU});var BU=We({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),UU=We({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var A3={};z(A3,{base2:()=>KU});var KU=We({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var C3={};z(C3,{base256emoji:()=>qU});var DA=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),FU=DA.reduce((r,e,t)=>(r[t]=e,r),[]),zU=DA.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function $U(r){return r.reduce((e,t)=>(e+=FU[t],e),"")}function HU(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=zU[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var qU=Ji({prefix:"\u{1F680}",name:"base256emoji",encode:$U,decode:HU});var T3={};z(T3,{base8:()=>VU});var VU=We({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var _3={};z(_3,{identity:()=>GU});var GU=Ji({prefix:"\0",name:"identity",encode:r=>gA(r),decode:r=>mA(r)});var Hfe=new TextEncoder,qfe=new TextDecoder;var P3={};z(P3,{identity:()=>QU});var kA=0,YU="identity",LA=Tr;function XU(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return ra(kA,LA(r))}var QU={code:kA,name:YU,encode:LA,digest:XU};var k3={};z(k3,{sha256:()=>JU,sha512:()=>ZU});var D3=ie(ee("crypto"),1);var JU=x3({name:"sha2-256",code:18,encode:r=>Tr(D3.default.createHash("sha256").update(r).digest())}),ZU=x3({name:"sha2-512",code:19,encode:r=>Tr(D3.default.createHash("sha512").update(r).digest())});var MA={..._3,...A3,...T3,...S3,...I3,...p3,...m3,...g3,...E3,...C3},Xfe={...k3,...P3};bt();te();ce();function M3(r){return e=>P(e,r)}function O3(r){return e=>D(e,r)}function sa(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function fo(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function OA(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=D(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=fo(n);return Ee([t,s],t.length+s.length)}function RA(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=Ss.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=fo(n);return Ee([t,s],t.length+s.length)}function R3(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=P(e,"base32"),s=sa(t);return`${n}:${s}`}var N3=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let s=parseInt(t,10);if(isNaN(s)||s<0||s>255)throw new Et("Invalid byte value in IP address");e[n]=s}),e},NA=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=(0,fe.isIPv4)(t[n]),i;o&&(i=N3(t[n]),t[n]=P(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,P(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new Et("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},BA=function(r){if(r.byteLength!==4)throw new Et("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},UA=function(r){if(r.byteLength!==16)throw new Et("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Et(`Invalid IPv6 address "${t}"`)}};function KA(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Et(`Invalid IPv6 address "${r}"`)}}var L3=Object.values(MA).map(r=>r.decoder),eK=(function(){let r=L3[0].or(L3[1]);return L3.slice(2).forEach(e=>r=r.or(e)),r})();function FA(r){return eK.decode(r)}function zA(r){return e=>r.encoder.encode(e)}function tK(r){if(parseInt(r).toString()!==r)throw new Un("Value must be an integer")}function rK(r){if(r<0)throw new Un("Value must be a positive integer, or zero")}function nK(r){return e=>{if(e>r)throw new Un(`Value must be smaller than or equal to ${r}`)}}function sK(...r){return e=>{for(let t of r)t(e)}}var jl=sK(tK,rK,nK(65535));var mt=-1,B3=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new uf(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Kn=new B3,wK=[{code:4,name:"ip4",size:32,valueToBytes:N3,bytesToValue:BA,validate:r=>{if(!(0,fe.isIPv4)(r))throw new Un(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:fo,bytesToValue:sa,validate:jl},{code:273,name:"udp",size:16,valueToBytes:fo,bytesToValue:sa,validate:jl},{code:33,name:"dccp",size:16,valueToBytes:fo,bytesToValue:sa,validate:jl},{code:41,name:"ip6",size:128,valueToBytes:NA,bytesToValue:UA,stringToValue:KA,validate:r=>{if(!(0,fe.isIPv6)(r))throw new Un(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:mt},{code:43,name:"ipcidr",size:8,bytesToValue:M3("base10"),valueToBytes:O3("base10")},{code:53,name:"dns",size:mt},{code:54,name:"dns4",size:mt},{code:55,name:"dns6",size:mt},{code:56,name:"dnsaddr",size:mt},{code:132,name:"sctp",size:16,valueToBytes:fo,bytesToValue:sa,validate:jl},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:mt,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:mt,bytesToValue:M3("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?O3("base58btc")(r):na.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:R3,valueToBytes:OA},{code:445,name:"onion3",size:296,bytesToValue:R3,valueToBytes:RA},{code:446,name:"garlic64",size:mt},{code:447,name:"garlic32",size:mt},{code:448,name:"tls"},{code:449,name:"sni",size:mt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:mt,bytesToValue:zA(v3),valueToBytes:FA},{code:480,name:"http"},{code:481,name:"http-path",size:mt,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:mt}];wK.forEach(r=>{Kn.addProtocol(r)});function $A(r){let e=[],t=0;for(;t<r.length;){let n=jt(r,t),s=Kn.getProtocol(n),o=Ae(n),i=xK(s,r,t+o),a=0;i>0&&s.size===mt&&(a=Ae(i));let c=o+a+i,l={code:n,name:s.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+o+a,h=r.subarray(u,u+i);l.value=s.bytesToValue?.(h)??P(h)}e.push(l),t+=c}return e}function HA(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let s=Kn.getProtocol(n.code),o=Ae(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??D(n.value),a=i.byteLength,s.size===mt&&(c=Ae(a)));let l=new Uint8Array(o+c+a),u=0;In(n.code,l,u),u+=o,i!=null&&(s.size===mt&&(In(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Ee(t,e)}function qA(r){if(r.charAt(0)!=="/")throw new Et('String multiaddr must start with "/"');let e=[],t="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(t==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=Kn.getProtocol(s);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",s="",t="protocol";continue}else if(a)throw new Et(`Component ${s} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Et(`Component ${s} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",s="",t="protocol"}}}if(s!==""&&n!=="")throw new Et("Incomplete multiaddr");return e}function VA(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Kn.getProtocol(e.code);if(t==null)throw new Et(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function xK(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:jt(e,t)}var vK=Symbol.for("nodejs.util.inspect.custom"),Y3=Symbol.for("@multiformats/multiaddr");function EK(r){if(r==null&&(r="/"),As(r))return r.getComponents();if(r instanceof Uint8Array)return $A(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),qA(r);if(Array.isArray(r))return r;throw new Et("Must be a string, Uint8Array, Component[], or another Multiaddr")}var mf=class r{[Y3]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=EK(e),t.validate!==!1&&SK(this)}get bytes(){return this.#r==null&&(this.#r=HA(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=VA(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new lf(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,s),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return W(this.bytes,e.bytes)}[vK](){return`Multiaddr(${this.toString()})`}};function SK(r){r.getComponents().forEach(e=>{let t=Kn.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function As(r){return!!r?.[Y3]}function q(r){return new mf(r)}var Xl=class r{libp2p;clusterSize;selfCoordinationConfig;networkHighWaterMark=1;lastConnectedTime=Date.now();constructor(e,t=16,n){this.libp2p=e,this.clusterSize=t,this.selfCoordinationConfig={gracePeriodMs:n?.gracePeriodMs??3e4,shrinkageThreshold:n?.shrinkageThreshold??.5,allowSelfCoordination:n?.allowSelfCoordination??!0},this.setupConnectionTracking()}coordinatorCache=new Map;static MAX_CACHE_ENTRIES=1e3;log=Sr("libp2p-key-network");toCacheKey(e){return P(e,"base64url")}setupConnectionTracking(){this.libp2p.addEventListener("connection:open",()=>{this.updateNetworkObservations()})}updateNetworkObservations(){(this.libp2p.getConnections?.()??[]).length>0&&(this.lastConnectedTime=Date.now());try{let n=this.getFret().getNetworkSizeEstimate();n.size_estimate>this.networkHighWaterMark&&(this.networkHighWaterMark=n.size_estimate,this.log("network-hwm-updated mark=%d confidence=%f",this.networkHighWaterMark,n.confidence))}catch{let n=(this.libp2p.getConnections?.().length??0)+1;n>this.networkHighWaterMark&&(this.networkHighWaterMark=n,this.log("network-hwm-updated mark=%d (from connections)",this.networkHighWaterMark))}}shouldAllowSelfCoordination(){if(!this.selfCoordinationConfig.allowSelfCoordination)return{allow:!1,reason:"disabled"};if(this.networkHighWaterMark<=1)return{allow:!0,reason:"bootstrap-node"};try{let t=this.getFret();if(t.detectPartition())return this.log("self-coord-blocked: partition-detected"),{allow:!1,reason:"partition-detected"};let n=t.getNetworkSizeEstimate(),s=1-n.size_estimate/this.networkHighWaterMark;if(s>this.selfCoordinationConfig.shrinkageThreshold)return this.log("self-coord-blocked: suspicious-shrinkage current=%d hwm=%d shrinkage=%f",n.size_estimate,this.networkHighWaterMark,s),{allow:!1,reason:"suspicious-shrinkage"}}catch{let t=this.libp2p.getConnections?.()??[];if(this.networkHighWaterMark>1&&t.length===0){let n=Date.now()-this.lastConnectedTime;if(n<this.selfCoordinationConfig.gracePeriodMs)return this.log("self-coord-blocked: grace-period-not-elapsed since=%dms",n),{allow:!1,reason:"grace-period-not-elapsed"}}}let e=Date.now()-this.lastConnectedTime;return e<this.selfCoordinationConfig.gracePeriodMs&&(this.libp2p.getConnections?.()??[]).length===0?(this.log("self-coord-blocked: grace-period-not-elapsed since=%dms",e),{allow:!1,reason:"grace-period-not-elapsed"}):(this.log("self-coord-allowed: extended-isolation (warn)"),{allow:!0,reason:"extended-isolation",warn:!0})}recordCoordinator(e,t,n=1800*1e3){let s=this.toCacheKey(e),o=Date.now();for(let[i,a]of this.coordinatorCache)a.expires<=o&&this.coordinatorCache.delete(i);for(this.coordinatorCache.set(s,{id:t,expires:o+n});this.coordinatorCache.size>r.MAX_CACHE_ENTRIES;){let i=this.coordinatorCache.keys().next().value;if(i==null)break;this.coordinatorCache.delete(i)}}getCachedCoordinator(e){let t=this.toCacheKey(e),n=this.coordinatorCache.get(t);if(n&&n.expires>Date.now())return n.id;n&&this.coordinatorCache.delete(t)}connect(e,t,n){let s=this.libp2p.getConnections?.(e)??[];if(Array.isArray(s)&&s.length>0&&typeof s[0]?.newStream=="function")return s[0].newStream([t]);let o={runOnLimitedConnection:!0,negotiateFully:!1};return this.libp2p.dialProtocol(e,[t],o)}getFret(){let e=this.libp2p.services?.fret;if(e==null)throw new Error("FRET service is not registered on this libp2p node");return e}async getNeighborIdsForKey(e,t){let n=this.getFret(),s=await ir(e),o=n.getNeighbors(s,"both",t);return Array.from(new Set(o)).slice(0,t)}async findCoordinator(e,t){let n=new Set((t?.excludedPeers??[]).map(l=>l.toString())),s=this.toCacheKey(e).substring(0,12);this.log("findCoordinator:start key=%s excluded=%o",s,Array.from(n).map(l=>l.substring(0,12)));let o=this.getCachedCoordinator(e);if(o!=null&&!n.has(o.toString()))return this.log("findCoordinator:cached-hit key=%s coordinator=%s",s,o.toString().substring(0,12)),o;let i=3,a=500;for(let l=0;l<i;l++){let u=(this.libp2p.getConnections?.()??[]).map(f=>f.remotePeer),h=new Set(u.map(f=>f.toString()));this.log("findCoordinator:connected-peers key=%s count=%d peers=%o attempt=%d",s,u.length,u.map(f=>f.toString().substring(0,12)),l);try{let f=await this.getNeighborIdsForKey(e,this.clusterSize);this.log("findCoordinator:fret-neighbors key=%s candidates=%o",s,f.map(g=>g.substring(0,12)));let d=f.filter(g=>h.has(g)||g===this.libp2p.peerId.toString());this.log("findCoordinator:fret-connected key=%s count=%d peers=%o",s,d.length,d.map(g=>g.substring(0,12)));let m=d.find(g=>!n.has(g));if(m){let g=de(m);return this.recordCoordinator(e,g),this.log("findCoordinator:fret-selected key=%s coordinator=%s",s,m.substring(0,12)),g}}catch(f){this.log("findCoordinator getNeighborIdsForKey failed - %o",f)}let p=u.find(f=>!n.has(f.toString()));if(p)return this.recordCoordinator(e,p),this.log("findCoordinator:connected-fallback key=%s coordinator=%s",s,p.toString().substring(0,12)),p;if(u.length===0&&l<i-1){this.log("findCoordinator:no-connections-retry key=%s attempt=%d delay=%dms",s,l,a),await new Promise(f=>setTimeout(f,a));continue}}let c=this.libp2p.peerId;if(!n.has(c.toString())){let l=this.shouldAllowSelfCoordination();if(!l.allow)throw this.log("findCoordinator:self-coord-blocked key=%s reason=%s",s,l.reason),new Error(`Self-coordination blocked: ${l.reason}. No coordinator available for key.`);return l.warn?this.log("findCoordinator:self-selected-warn key=%s coordinator=%s reason=%s",s,c.toString().substring(0,12),l.reason):this.log("findCoordinator:self-selected key=%s coordinator=%s reason=%s",s,c.toString().substring(0,12),l.reason),c}throw this.log("findCoordinator:all-excluded key=%s self=%s",s,c.toString().substring(0,12)),new Error("No coordinator available for key (all candidates excluded)")}getConnectedAddrsByPeer(){let e=this.libp2p.getConnections(),t={};for(let n of e){let s=n.remotePeer.toString(),o=n.remoteAddr?.toString?.();o&&(t[s]??=[]).push(o)}return t}parseMultiaddrs(e){let t=[];for(let n of e)try{t.push(q(n))}catch(s){console.warn("invalid multiaddr from connection",n,s)}return t}async findCluster(e){let t=this.getFret(),n=await ir(e),s=t.assembleCohort(n,this.clusterSize),o=this.toCacheKey(e).substring(0,12),i=Array.from(new Set([...s,this.libp2p.peerId.toString()])),a=this.getConnectedAddrsByPeer(),c=Object.keys(a);this.log("findCluster key=%s fretCohort=%d connected=%d cohortPeers=%o",o,s.length,c.length,i.map(u=>u.substring(0,12)));let l={};for(let u of i){if(u===this.libp2p.peerId.toString()){l[u]={multiaddrs:this.libp2p.getMultiaddrs(),publicKey:this.libp2p.peerId.publicKey?.raw??new Uint8Array};continue}let h=a[u]??[],p=this.parseMultiaddrs(h);l[u]={multiaddrs:p,publicKey:new Uint8Array}}return this.log("findCluster:result key=%s clusterSize=%d withAddrs=%d connectedInCohort=%d",o,Object.keys(l).length,Object.values(l).filter(u=>u.multiaddrs.length>0).length,i.filter(u=>c.includes(u)||u===this.libp2p.peerId.toString()).length),l}};Bt();ke();V();async function GA(r){if(r.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new R("Private network is enforced, but no protector was provided");return r}Bt();V();var Fpe=new Uint8Array(0);function WA(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function IK(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var v=d[y],S=0,E=w-1;(v!==0||S<g)&&E!==-1;E--,S++)v+=256*x[E]>>>0,x[E]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var A=c.repeat(m);I<w;++I)A+=r.charAt(x[I]);return A}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*w[S]>>>0,w[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(d[m]!==" "){for(var E=b-y;E!==b&&w[E]===0;)E++;for(var I=new Uint8Array(g+(b-E)),A=g;E!==b;)I[A++]=w[E++];return I}}}function f(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:f}}var AK=IK,CK=AK,jA=CK;var X3=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Q3=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return YA(this,e)}},J3=class{decoders;constructor(e){this.decoders=e}or(e){return YA(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function YA(r,e){return new J3({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Z3=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new X3(e,t,n),this.decoder=new Q3(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function XA({name:r,prefix:e,encode:t,decode:n}){return new Z3(r,e,t,n)}function eb({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=jA(t,r);return XA({prefix:e,name:r,encode:n,decode:o=>WA(s(o))})}function TK(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function _K(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function PK(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function zt({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=PK(n);return XA({prefix:e,name:r,encode(o){return _K(o,n,t)},decode(o){return TK(o,s,t,r)}})}var QA=zt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Wpe=zt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),jpe=zt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ype=zt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Xpe=zt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Qpe=zt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Jpe=zt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Zpe=zt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),e1e=zt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var JA=eb({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),n1e=eb({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ZA=zt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),i1e=zt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),a1e=zt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),c1e=zt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var e8=ie(ee("node:tty"),1),yf=ie(ee("node:util"),1);function DK(r,e){if(typeof r=="string")return kK(r);if(typeof r=="number")return OK(r,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}var gf=DK;function kK(r){if(typeof r!="string"||r.length===0||r.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,s=parseFloat(t),o=n.toLowerCase();switch(o){case"years":case"year":case"yrs":case"yr":case"y":return s*315576e5;case"months":case"month":case"mo":return s*26298e5;case"weeks":case"week":case"w":return s*6048e5;case"days":case"day":case"d":return s*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return s*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return s*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return s*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return s;default:throw Error(`Unknown unit "${o}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function LK(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function MK(r){let e=Math.abs(r);return e>=315576e5?bo(r,e,315576e5,"year"):e>=26298e5?bo(r,e,26298e5,"month"):e>=6048e5?bo(r,e,6048e5,"week"):e>=864e5?bo(r,e,864e5,"day"):e>=36e5?bo(r,e,36e5,"hour"):e>=6e4?bo(r,e,6e4,"minute"):e>=1e3?bo(r,e,1e3,"second"):`${r} ms`}function OK(r,e){if(typeof r!="number"||!Number.isFinite(r))throw Error("Value provided to ms.format() must be of type number.");return e?.long?MK(r):LK(r)}function bo(r,e,t,n){let s=e>=t*1.5;return`${Math.round(r/t)} ${n}${s?"s":""}`}Vg();function tb(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=s,t.enabled=i,t.humanize=gf,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let h=0;for(let p=0;p<u.length;p++)h=(h<<5)-h+u.charCodeAt(p),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(u,h){let p,f=null,d,m;function g(...y){if(!g.enabled)return;let b=g,w=Number(new Date),x=w-(p||w);b.diff=x,b.prev=p,b.curr=w,p=w,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let v=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(E,I)=>{if(E==="%%")return"%";v++;let A=t.formatters[I];if(typeof A=="function"){let X=y[v];E=A.call(b,X),y.splice(v,1),v--}return E}),t.formatArgs.call(b,y),h?.onLog!=null&&h.onLog(...y),(b.log||t.log).apply(b,y)}return g.namespace=u,g.useColors=t.useColors(),g.color=t.selectColor(u),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(d!==t.namespaces&&(d=t.namespaces,m=t.enabled(u)),m),set:y=>{f=y}}),typeof t.init=="function"&&t.init(g),g}function n(u,h){let p=t(this.namespace+(typeof h>"u"?":":h)+u);return p.log=this.log,p}function s(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let h,p=(typeof u=="string"?u:"").split(/[\s,]+/),f=p.length;for(h=0;h<f;h++)p[h]&&(u=p[h].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function o(){let u=[...t.names.map(a),...t.skips.map(a).map(h=>"-"+h)].join(",");return t.enable(""),u}function i(u){if(u[u.length-1]==="*")return!0;let h,p;for(h=0,p=t.skips.length;h<p;h++)if(t.skips[h].test(u))return!1;for(h=0,p=t.names.length;h<p;h++)if(t.names[h].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var t8=[6,2,3,4,5,1];pl.stderr!==!1&&(pl.stderr??pl).level>=2&&(t8=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]);var la=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,o)=>o.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),r[t]=n,r},{});function RK(){return"colors"in la?!!la.colors:e8.default.isatty(process.stderr.fd)}function NK(r){let{namespace:e,useColors:t}=this;if(t===!0){let n=this.color,s="\x1B[3"+(n<8?n:"8;5;"+n),o=` ${s};1m${e} \x1B[0m`;r[0]=o+r[0].split(`
|
|
6
|
+
`).map(e=>e.trim()).join(" ")};OS.O=function(r){return this.inspectOpts.colors=this.useColors,Id.inspect(r,this.inspectOpts)}});var Wg=At((Bie,Gg)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Gg.exports=kS():Gg.exports=RS()});var x8=At(eu=>{(function(){var r,e,t,n,s,o,i,a;a=function(c){var l,u,h,p;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,h=(c&65280)>>>8,p=c&255,[l,u,h,p].join(".")},i=function(c){var l,u,h,p,f,d;for(l=[],h=p=0;p<=3&&c.length!==0;h=++p){if(h>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}d=e(c),f=d[0],u=d[1],c=c.substring(u),l.push(f)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),o=t("a"),s=t("A"),e=function(c){var l,u,h,p,f;for(p=0,l=10,u="9",h=0,c.length>1&&c[h]==="0"&&(c[h+1]==="x"||c[h+1]==="X"?(h+=2,l=16):"0"<=c[h+1]&&c[h+1]<="9"&&(h++,l=8,u="7")),f=h;h<c.length;){if("0"<=c[h]&&c[h]<=u)p=p*l+(t(c[h])-n)>>>0;else if(l===16)if("a"<=c[h]&&c[h]<="f")p=p*l+(10+t(c[h])-o)>>>0;else if("A"<=c[h]&&c[h]<="F")p=p*l+(10+t(c[h])-s)>>>0;else break;else break;if(p>4294967295)throw new Error("too large");h++}if(h===f)throw new Error("empty octet");return[p,h]},r=(function(){function c(l,u){var h,p,f,d;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(d=l.split("/",2),l=d[0],u=d[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=i(u)}catch(m){throw h=m,new Error("Invalid mask: "+u)}for(p=f=32;f>=0;p=--f)if(this.maskLong===4294967295<<32-p>>>0){this.bitmask=p;break}}else if(u||u===0)this.bitmask=parseInt(u,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(m){throw h=m,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+u);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var u,h,p;for(p=i(this.first),h=i(this.last),u=0;p<=h;)l(a(p),p,u),u++,p++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c})(),eu.ip2long=i,eu.long2ip=a,eu.Netmask=r}).call(eu)});var HC=At((twe,$C)=>{$C.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function s(o,i){t[o]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(o){return t[o]!==void 0||n[o]!==void 0},remove:function(o){t[o]!==void 0&&(t[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var i=t[o];if(i!==void 0)return i;if((i=n[o])!==void 0)return s(o,i),i},set:function(o,i){t[o]!==void 0?t[o]=i:s(o,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Tw=At(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.TAG_LENGTH=dn.DATA_CHUNK_LENGTH=dn.NONCE_LENGTH=dn.KEY_LENGTH=void 0;dn.KEY_LENGTH=32;dn.NONCE_LENGTH=12;dn.DATA_CHUNK_LENGTH=65536;dn.TAG_LENGTH=16});var cT=At(Zp=>{"use strict";Object.defineProperty(Zp,"__esModule",{value:!0});Zp.ChaCha20Poly1305=void 0;var je=Tw(),_w=class{constructor(e){this.ctx=e;let t=e.cpKey.value;this.wasmKeyArr=new Uint8Array(e.memory.buffer,t,je.KEY_LENGTH);let n=e.cpNonce.value;this.wasmNonceArr=new Uint8Array(e.memory.buffer,n,je.NONCE_LENGTH);let s=e.cpAssociatedData.value;this.wasmAdArr=new Uint8Array(e.memory.buffer,s,je.KEY_LENGTH);let o=e.cpInput.value;this.wasmInputArr=new Uint8Array(e.memory.buffer,o,je.DATA_CHUNK_LENGTH);let i=e.chacha20Output.value;this.wasmChacha20OutputArr=new Uint8Array(e.memory.buffer,i,je.DATA_CHUNK_LENGTH);let a=e.poly1305Output.value;this.wasmPoly1305OutputArr=new Uint8Array(e.memory.buffer,a,je.TAG_LENGTH);let c=e.debug.value;this.wasmDebugArr=new Uint32Array(e.memory.buffer,c,64)}seal(e,t,n,s,o){this.init(e,t,s);let i=n.length+je.TAG_LENGTH,a;if(o){if(o.length!==i)throw new Error("ChaCha20Poly1305: incorrect destination length");a=o}else a=new Uint8Array(i);let c=s?.length??0;return this.sealUpdate(n,c,a),a.set(this.wasmPoly1305OutputArr,n.length),a}open(e,t,n,s,o){this.init(e,t,s);let i=n.subarray(0,n.length-je.TAG_LENGTH),a;if(o){if(o.length!==i.length)throw new Error("ChaCha20Poly1305: incorrect destination length");a=o}else a=new Uint8Array(i.length);let c=s?.length??0;this.openUpdate(i,c,a);let l=n.subarray(n.length-je.TAG_LENGTH,n.length);return this.isSameTag(l)?a:null}init(e,t,n=new Uint8Array(0)){if(e.length!=je.KEY_LENGTH)throw Error(`Invalid chacha20poly1305 key length ${e.length}, expect ${je.KEY_LENGTH}`);if(n.length>je.KEY_LENGTH)throw Error(`Invalid ad length ${n.length}, expect <= ${je.KEY_LENGTH}`);if(t.length!==je.NONCE_LENGTH)throw Error(`Invalid nonce length ${t.length}, expect ${je.NONCE_LENGTH}`);this.wasmKeyArr.set(e),this.wasmNonceArr.set(t),this.wasmAdArr.set(n)}openUpdate(e,t,n){this.commonUpdate(e,this.ctx.openUpdate,t,n)}sealUpdate(e,t,n){this.commonUpdate(e,this.ctx.sealUpdate,t,n)}commonUpdate(e,t,n,s){let o=e.length;if(e.length<=je.DATA_CHUNK_LENGTH){this.wasmInputArr.set(e),t(!0,!0,o,o,n),s.set(o===je.DATA_CHUNK_LENGTH?this.wasmChacha20OutputArr:this.wasmChacha20OutputArr.subarray(0,o));return}for(let i=0;i<o;i+=je.DATA_CHUNK_LENGTH){let a=Math.min(o,i+je.DATA_CHUNK_LENGTH);this.wasmInputArr.set(e.subarray(i,a));let c=i===0,l=i+je.DATA_CHUNK_LENGTH>=o;t(c,l,a-i,o,n),s.set(a-i===je.DATA_CHUNK_LENGTH?this.wasmChacha20OutputArr:this.wasmChacha20OutputArr.subarray(0,a-i),i)}}isSameTag(e){let t=!0;for(let n=0;n<je.TAG_LENGTH;n++)if(this.wasmPoly1305OutputArr[n]!==e[n]){t=!1;break}return t}};Zp.ChaCha20Poly1305=_w});var lT=At(e1=>{"use strict";Object.defineProperty(e1,"__esModule",{value:!0});e1.Poly1305=void 0;var Vn=Tw(),Pw=class{constructor(e){this.ctx=e;let t=e.poly1305Key.value;this.wasmKeyArr=new Uint8Array(e.memory.buffer,t,Vn.KEY_LENGTH);let n=e.poly1305Input.value;this.wasmInputArr=new Uint8Array(e.memory.buffer,n,Vn.DATA_CHUNK_LENGTH);let s=e.poly1305Output.value;this.wasmOutputArr=new Uint8Array(e.memory.buffer,s,Vn.TAG_LENGTH);let o=e.debug.value;this.wasmDebugArr=new Uint32Array(e.memory.buffer,o,64)}init(e){if(e.length!=Vn.KEY_LENGTH)throw Error(`Invalid poly1305 key length ${e.length}, expect ${Vn.KEY_LENGTH}`);this.wasmKeyArr.set(e),this.ctx.poly1305Init()}update(e){if(e.length<=Vn.DATA_CHUNK_LENGTH){this.wasmInputArr.set(e),this.ctx.poly1305Update(e.length);return}for(let t=0;t<e.length;t+=Vn.DATA_CHUNK_LENGTH){let n=Math.min(e.length,t+Vn.DATA_CHUNK_LENGTH);this.wasmInputArr.set(e.subarray(t,n)),this.ctx.poly1305Update(n-t)}}digest(){this.ctx.poly1305Digest();let e=new Uint8Array(Vn.TAG_LENGTH);return e.set(this.wasmOutputArr),e}};e1.Poly1305=Pw});var uT=At(t1=>{"use strict";Object.defineProperty(t1,"__esModule",{value:!0});t1.wasmCode=void 0;t1.wasmCode=Uint8Array.from([0,97,115,109,1,0,0,0,1,58,10,96,0,0,96,2,127,127,0,96,1,127,0,96,3,127,127,127,0,96,1,127,1,127,96,4,127,127,127,127,0,96,5,127,127,127,127,127,0,96,0,1,127,96,2,127,127,1,127,96,5,127,127,127,127,127,1,127,2,13,1,3,101,110,118,5,97,98,111,114,116,0,5,3,34,33,2,8,1,4,0,4,7,0,0,3,3,2,1,9,4,2,0,3,1,2,2,1,0,0,0,5,1,1,1,6,1,6,0,5,3,1,0,1,6,238,1,47,127,0,65,32,11,127,0,65,16,11,127,0,65,128,128,4,11,127,0,65,16,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,7,226,2,23,6,109,101,109,111,114,121,2,0,21,67,72,65,67,72,65,50,48,95,73,78,80,85,84,95,76,69,78,71,84,72,3,2,23,67,72,65,67,72,65,50,48,95,67,79,85,78,84,69,82,95,76,69,78,71,84,72,3,3,13,99,104,97,99,104,97,50,48,73,110,112,117,116,3,6,11,99,104,97,99,104,97,50,48,75,101,121,3,8,15,99,104,97,99,104,97,50,48,67,111,117,110,116,101,114,3,10,14,99,104,97,99,104,97,50,48,79,117,116,112,117,116,3,12,23,99,104,97,99,104,97,50,48,83,116,114,101,97,109,88,79,82,85,112,100,97,116,101,0,15,10,75,69,89,95,76,69,78,71,84,72,3,0,10,84,65,71,95,76,69,78,71,84,72,3,1,12,112,111,108,121,49,51,48,53,73,110,105,116,0,17,14,112,111,108,121,49,51,48,53,85,112,100,97,116,101,0,20,14,112,111,108,121,49,51,48,53,68,105,103,101,115,116,0,24,13,112,111,108,121,49,51,48,53,73,110,112,117,116,3,19,11,112,111,108,121,49,51,48,53,75,101,121,3,18,14,112,111,108,121,49,51,48,53,79,117,116,112,117,116,3,20,10,111,112,101,110,85,112,100,97,116,101,0,30,10,115,101,97,108,85,112,100,97,116,101,0,32,5,99,112,75,101,121,3,37,7,99,112,78,111,110,99,101,3,39,7,99,112,73,110,112,117,116,3,43,16,99,112,65,115,115,111,99,105,97,116,101,100,68,97,116,97,3,41,5,100,101,98,117,103,3,46,8,1,33,10,195,47,33,70,1,2,127,32,0,63,0,34,2,65,16,116,34,1,75,4,64,32,2,32,0,32,1,107,65,255,255,3,106,65,128,128,124,113,65,16,118,34,1,32,2,32,1,74,27,64,0,65,0,72,4,64,32,1,64,0,65,0,72,4,64,0,11,11,11,32,0,36,5,11,82,1,3,127,32,0,65,240,255,255,255,3,75,4,64,0,11,35,5,65,16,106,34,3,32,0,65,15,106,65,112,113,34,2,65,16,32,2,65,16,75,27,34,4,106,16,1,32,3,65,16,107,34,2,32,4,54,2,0,32,2,65,1,54,2,4,32,2,32,1,54,2,8,32,2,32,0,54,2,12,32,3,11,37,1,1,127,3,64,32,1,4,64,32,0,34,2,65,1,106,33,0,32,2,65,0,58,0,0,32,1,65,1,107,33,1,12,1,11,11,11,42,1,1,127,32,0,65,240,255,255,255,3,75,4,64,65,32,65,208,0,65,54,65,42,16,0,0,11,32,0,65,0,16,2,34,1,32,0,16,3,32,1,11,67,0,65,128,3,36,4,65,128,3,36,5,65,128,128,4,16,4,36,6,35,6,36,7,65,32,16,4,36,8,35,8,36,9,65,16,16,4,36,10,35,10,36,11,65,128,128,4,16,4,36,12,35,12,36,13,65,192,0,16,4,36,14,35,14,36,15,11,83,1,1,127,65,128,2,65,0,16,2,34,1,65,128,2,16,3,32,0,69,4,64,65,12,65,2,16,2,33,0,11,32,0,65,0,54,2,0,32,0,65,0,54,2,4,32,0,65,0,54,2,8,32,0,40,2,0,26,32,0,32,1,54,2,0,32,0,32,1,54,2,4,32,0,65,128,2,54,2,8,32,0,11,10,0,65,12,65,3,16,2,16,6,11,95,0,16,7,36,16,35,16,40,2,0,36,17,65,32,16,4,36,18,65,128,128,4,16,4,36,19,65,16,16,4,36,20,35,18,36,21,35,19,36,22,35,20,36,23,65,16,16,4,36,24,35,24,36,25,65,20,16,4,36,26,35,26,36,27,65,20,16,4,36,28,35,28,36,29,65,16,16,4,36,30,35,30,36,31,65,20,16,4,36,35,35,35,36,36,11,55,0,65,32,16,4,36,37,35,37,36,38,65,12,16,4,36,39,35,39,36,40,65,32,16,4,36,41,35,41,36,42,65,128,128,4,16,4,36,43,35,43,36,44,16,7,36,45,35,45,40,2,0,36,46,11,22,0,32,1,32,2,65,255,1,113,65,4,110,65,2,116,106,32,0,54,2,0,11,188,6,1,31,127,65,229,240,193,139,6,33,5,65,238,200,129,153,3,33,6,65,178,218,136,203,7,33,14,65,244,202,129,217,6,33,7,32,2,40,2,0,34,19,33,4,32,2,65,4,106,40,2,0,34,20,33,8,32,2,65,8,106,40,2,0,34,21,33,3,32,2,65,12,106,40,2,0,34,22,33,13,32,2,65,16,106,40,2,0,34,23,33,15,32,2,65,20,106,40,2,0,34,24,33,9,32,2,65,24,106,40,2,0,34,25,33,10,32,2,65,28,106,40,2,0,34,26,33,2,32,1,40,2,0,34,27,33,11,32,1,65,4,106,40,2,0,34,28,33,16,32,1,65,8,106,40,2,0,34,29,33,12,32,1,65,12,106,40,2,0,34,30,33,1,3,64,32,18,65,20,72,4,64,32,3,32,10,32,12,32,3,32,14,106,34,3,115,65,16,119,34,14,106,34,10,115,65,12,119,34,12,32,10,32,14,32,3,32,12,106,34,3,115,65,8,119,34,14,106,34,10,115,33,12,32,13,32,2,32,1,32,7,32,13,106,34,1,115,65,16,119,34,2,106,34,13,115,65,12,119,34,7,32,13,32,2,32,1,32,7,106,34,13,115,65,8,119,34,1,106,34,2,115,33,7,32,4,32,15,32,11,32,4,32,5,106,34,4,115,65,16,119,34,5,106,34,15,115,65,12,119,34,11,32,15,32,5,32,4,32,11,106,34,4,115,65,8,119,34,5,106,34,15,115,33,11,32,10,32,1,32,8,32,9,32,16,32,6,32,8,106,34,1,115,65,16,119,34,8,106,34,6,115,65,12,119,34,9,32,6,32,8,32,1,32,9,106,34,1,115,65,8,119,34,6,106,34,9,115,65,7,119,34,10,32,4,106,34,17,115,65,16,119,34,31,106,33,8,32,2,32,5,32,12,65,7,119,34,5,32,1,106,34,32,115,65,16,119,34,33,106,33,1,32,9,32,14,32,13,32,11,65,7,119,34,9,106,34,11,115,65,16,119,34,12,106,33,4,32,15,32,6,32,3,32,7,65,7,119,34,3,106,34,6,115,65,16,119,34,7,106,34,2,32,6,32,2,32,3,115,65,12,119,34,3,106,34,14,32,7,115,65,8,119,34,16,106,34,15,32,3,115,65,7,119,33,13,32,11,32,4,32,9,115,65,12,119,34,2,106,34,7,32,12,115,65,8,119,34,12,32,4,106,34,9,32,2,115,65,7,119,33,4,32,32,32,1,32,5,115,65,12,119,34,3,106,34,6,32,33,115,65,8,119,34,11,32,1,106,34,2,32,3,115,65,7,119,33,3,32,17,32,8,32,10,115,65,12,119,34,17,106,34,5,32,31,115,65,8,119,34,1,32,8,106,34,10,32,17,115,65,7,119,33,8,32,18,65,2,106,33,18,12,1,11,11,32,5,65,229,240,193,139,6,106,32,0,65,0,16,10,32,6,65,238,200,129,153,3,106,32,0,65,4,16,10,32,14,65,178,218,136,203,7,106,32,0,65,8,16,10,32,7,65,244,202,129,217,6,106,32,0,65,12,16,10,32,4,32,19,106,32,0,65,16,16,10,32,8,32,20,106,32,0,65,20,16,10,32,3,32,21,106,32,0,65,24,16,10,32,13,32,22,106,32,0,65,28,16,10,32,15,32,23,106,32,0,65,32,16,10,32,9,32,24,106,32,0,65,36,16,10,32,10,32,25,106,32,0,65,40,16,10,32,2,32,26,106,32,0,65,44,16,10,32,11,32,27,106,32,0,65,48,16,10,32,16,32,28,106,32,0,65,52,16,10,32,12,32,29,106,32,0,65,56,16,10,32,1,32,30,106,32,0,65,60,16,10,11,97,1,4,127,65,4,33,3,65,1,33,1,3,64,32,3,34,2,65,1,107,33,3,32,2,65,255,1,113,4,64,32,1,32,0,32,4,65,255,1,113,106,34,2,45,0,0,106,33,1,32,2,32,1,58,0,0,32,1,65,8,118,33,1,32,4,65,1,106,33,4,12,1,11,11,32,1,65,0,74,4,64,65,144,1,65,208,1,65,135,2,65,4,16,0,0,11,11,8,0,32,0,32,1,16,3,11,108,1,2,127,3,64,32,6,32,1,73,4,64,35,15,32,3,32,2,16,11,32,6,33,5,3,64,32,5,32,1,73,65,0,32,5,32,6,65,64,107,73,27,4,64,32,4,32,5,106,32,0,32,5,106,45,0,0,35,15,32,5,32,6,107,106,45,0,0,115,58,0,0,32,5,65,1,106,33,5,12,1,11,11,32,3,16,12,32,6,65,64,107,33,6,12,1,11,11,35,15,65,192,0,16,13,32,1,11,14,0,35,7,32,0,35,9,35,11,35,13,16,14,11,204,4,1,1,127,35,27,32,0,45,0,0,32,0,65,1,106,45,0,0,65,8,116,114,34,1,65,255,63,113,59,1,0,35,27,65,2,106,32,1,65,13,118,32,0,65,2,106,45,0,0,32,0,65,3,106,45,0,0,65,8,116,114,34,1,65,3,116,114,65,255,63,113,59,1,0,35,27,65,4,106,32,1,65,10,118,32,0,65,4,106,45,0,0,32,0,65,5,106,45,0,0,65,8,116,114,34,1,65,6,116,114,65,131,62,113,59,1,0,35,27,65,6,106,32,1,65,7,118,32,0,65,6,106,45,0,0,32,0,65,7,106,45,0,0,65,8,116,114,34,1,65,9,116,114,65,255,63,113,59,1,0,35,27,65,8,106,32,1,65,4,118,32,0,65,8,106,45,0,0,32,0,65,9,106,45,0,0,65,8,116,114,34,1,65,12,116,114,65,255,1,113,59,1,0,35,27,65,10,106,32,1,65,1,118,65,254,63,113,59,1,0,35,27,65,12,106,32,1,65,14,118,32,0,65,10,106,45,0,0,32,0,65,11,106,45,0,0,65,8,116,114,34,1,65,2,116,114,65,255,63,113,59,1,0,35,27,65,14,106,32,1,65,11,118,32,0,65,12,106,45,0,0,32,0,65,13,106,45,0,0,65,8,116,114,34,1,65,5,116,114,65,129,63,113,59,1,0,35,27,65,16,106,32,1,65,8,118,32,0,65,14,106,45,0,0,32,0,65,15,106,45,0,0,65,8,116,114,34,1,65,8,116,114,65,255,63,113,59,1,0,35,27,65,18,106,32,1,65,5,118,65,255,0,113,59,1,0,35,31,32,0,65,16,106,45,0,0,32,0,65,17,106,45,0,0,65,8,116,114,59,1,0,35,31,65,2,106,32,0,65,18,106,45,0,0,32,0,65,19,106,45,0,0,65,8,116,114,59,1,0,35,31,65,4,106,32,0,65,20,106,45,0,0,32,0,65,21,106,45,0,0,65,8,116,114,59,1,0,35,31,65,6,106,32,0,65,22,106,45,0,0,32,0,65,23,106,45,0,0,65,8,116,114,59,1,0,35,31,65,8,106,32,0,65,24,106,45,0,0,32,0,65,25,106,45,0,0,65,8,116,114,59,1,0,35,31,65,10,106,32,0,65,26,106,45,0,0,32,0,65,27,106,45,0,0,65,8,116,114,59,1,0,35,31,65,12,106,32,0,65,28,106,45,0,0,32,0,65,29,106,45,0,0,65,8,116,114,59,1,0,35,31,65,14,106,32,0,65,30,106,45,0,0,32,0,65,31,106,45,0,0,65,8,116,114,59,1,0,11,6,0,35,21,16,16,11,166,13,1,32,127,65,0,65,128,16,35,33,27,33,34,35,29,47,1,0,33,3,35,29,65,2,106,47,1,0,33,4,35,29,65,4,106,47,1,0,33,8,35,29,65,6,106,47,1,0,33,9,35,29,65,8,106,47,1,0,33,10,35,29,65,10,106,47,1,0,33,11,35,29,65,12,106,47,1,0,33,12,35,29,65,14,106,47,1,0,33,13,35,29,65,16,106,47,1,0,33,14,35,29,65,18,106,47,1,0,33,6,35,27,47,1,0,33,17,35,27,65,2,106,47,1,0,33,18,35,27,65,4,106,47,1,0,33,20,35,27,65,6,106,47,1,0,33,22,35,27,65,8,106,47,1,0,33,24,35,27,65,10,106,47,1,0,33,26,35,27,65,12,106,47,1,0,33,29,35,27,65,14,106,47,1,0,33,30,35,27,65,16,106,47,1,0,33,31,35,27,65,18,106,47,1,0,33,33,3,64,32,2,65,16,79,4,64,32,3,32,0,32,1,106,45,0,0,32,0,32,1,65,1,106,106,45,0,0,65,8,116,114,34,15,65,255,63,113,106,34,3,32,17,108,32,4,32,0,32,1,65,2,106,106,45,0,0,32,0,32,1,65,3,106,106,45,0,0,65,8,116,114,34,16,65,3,116,32,15,65,255,255,3,113,65,13,118,114,65,255,63,113,106,34,4,32,33,65,5,108,34,15,108,106,32,8,32,0,32,1,65,4,106,106,45,0,0,32,0,32,1,65,5,106,106,45,0,0,65,8,116,114,34,19,65,6,116,32,16,65,255,255,3,113,65,10,118,114,65,255,63,113,106,34,8,32,31,65,5,108,34,16,108,106,32,9,32,0,32,1,65,6,106,106,45,0,0,32,0,32,1,65,7,106,106,45,0,0,65,8,116,114,34,21,65,9,116,32,19,65,255,255,3,113,65,7,118,114,65,255,63,113,106,34,9,32,30,65,5,108,34,19,108,106,32,10,32,0,32,1,65,8,106,106,45,0,0,32,0,32,1,65,9,106,106,45,0,0,65,8,116,114,34,23,65,12,116,32,21,65,255,255,3,113,65,4,118,114,65,255,63,113,106,34,10,32,29,65,5,108,34,21,108,106,34,32,65,255,63,113,32,11,32,23,65,255,255,3,113,65,1,118,65,255,63,113,106,34,11,32,26,65,5,108,34,27,108,106,32,12,32,0,32,1,65,10,106,106,45,0,0,32,0,32,1,65,11,106,106,45,0,0,65,8,116,114,34,28,65,2,116,32,23,65,255,255,3,113,65,14,118,114,65,255,63,113,106,34,12,32,24,65,5,108,34,23,108,106,32,13,32,0,32,1,65,12,106,106,45,0,0,32,0,32,1,65,13,106,106,45,0,0,65,8,116,114,34,25,65,5,116,32,28,65,255,255,3,113,65,11,118,114,65,255,63,113,106,34,13,32,22,65,5,108,34,28,108,106,32,14,32,25,65,255,255,3,113,65,8,118,32,0,32,1,65,14,106,106,45,0,0,32,0,32,1,65,15,106,106,45,0,0,65,8,116,114,34,25,65,8,116,114,65,255,63,113,106,34,14,32,20,65,5,108,34,7,108,106,33,5,32,11,32,21,108,32,32,65,13,118,32,5,32,6,32,34,32,25,65,255,255,3,113,65,5,118,114,65,255,255,3,113,106,34,6,32,18,65,5,108,108,106,34,32,65,13,118,106,32,3,32,18,108,106,32,4,32,17,108,106,32,8,32,15,108,106,32,9,32,16,108,106,32,10,32,19,108,106,34,25,65,255,63,113,106,32,12,32,27,108,106,32,13,32,23,108,106,32,14,32,28,108,106,33,5,32,11,32,19,108,32,25,65,13,118,32,5,32,6,32,7,108,106,34,25,65,13,118,106,32,3,32,20,108,106,32,4,32,18,108,106,32,8,32,17,108,106,32,9,32,15,108,106,32,10,32,16,108,106,34,7,65,255,63,113,106,32,12,32,21,108,106,32,13,32,27,108,106,32,14,32,23,108,106,33,5,32,11,32,16,108,32,7,65,13,118,32,5,32,6,32,28,108,106,34,28,65,13,118,106,32,3,32,22,108,106,32,4,32,20,108,106,32,8,32,18,108,106,32,9,32,17,108,106,32,10,32,15,108,106,34,7,65,255,63,113,106,32,12,32,19,108,106,32,13,32,21,108,106,32,14,32,27,108,106,33,5,32,11,32,15,108,32,7,65,13,118,32,5,32,6,32,23,108,106,34,23,65,13,118,106,32,3,32,24,108,106,32,4,32,22,108,106,32,8,32,20,108,106,32,9,32,18,108,106,32,10,32,17,108,106,34,7,65,255,63,113,106,32,12,32,16,108,106,32,13,32,19,108,106,32,14,32,21,108,106,33,5,32,11,32,17,108,32,7,65,13,118,32,5,32,6,32,27,108,106,34,27,65,13,118,106,32,3,32,26,108,106,32,4,32,24,108,106,32,8,32,22,108,106,32,9,32,20,108,106,32,10,32,18,108,106,34,7,65,255,63,113,106,32,12,32,15,108,106,32,13,32,16,108,106,32,14,32,19,108,106,33,5,32,11,32,18,108,32,7,65,13,118,32,5,32,6,32,21,108,106,34,21,65,13,118,106,32,3,32,29,108,106,32,4,32,26,108,106,32,8,32,24,108,106,32,9,32,22,108,106,32,10,32,20,108,106,34,7,65,255,63,113,106,32,12,32,17,108,106,32,13,32,15,108,106,32,14,32,16,108,106,33,5,32,11,32,20,108,32,7,65,13,118,32,5,32,6,32,19,108,106,34,19,65,13,118,106,32,3,32,30,108,106,32,4,32,29,108,106,32,8,32,26,108,106,32,9,32,24,108,106,32,10,32,22,108,106,34,7,65,255,63,113,106,32,12,32,18,108,106,32,13,32,17,108,106,32,14,32,15,108,106,33,5,32,11,32,22,108,32,7,65,13,118,32,5,32,6,32,16,108,106,34,16,65,13,118,106,32,3,32,31,108,106,32,4,32,30,108,106,32,8,32,29,108,106,32,9,32,26,108,106,32,10,32,24,108,106,34,7,65,255,63,113,106,32,12,32,20,108,106,32,13,32,18,108,106,32,14,32,17,108,106,33,5,32,11,32,24,108,32,7,65,13,118,32,5,32,6,32,15,108,106,34,15,65,13,118,106,32,3,32,33,108,106,32,4,32,31,108,106,32,8,32,30,108,106,32,9,32,29,108,106,32,10,32,26,108,106,34,3,65,255,63,113,106,32,12,32,22,108,106,32,13,32,20,108,106,32,14,32,18,108,106,33,4,32,3,65,13,118,32,4,32,6,32,17,108,106,34,6,65,13,118,106,34,3,32,3,65,2,116,106,32,32,65,255,63,113,106,34,3,65,13,118,33,4,32,3,65,255,63,113,33,3,32,25,65,255,63,113,32,4,106,33,4,32,28,65,255,63,113,33,8,32,23,65,255,63,113,33,9,32,27,65,255,63,113,33,10,32,21,65,255,63,113,33,11,32,19,65,255,63,113,33,12,32,16,65,255,63,113,33,13,32,15,65,255,63,113,33,14,32,6,65,255,63,113,33,6,32,1,65,16,106,33,1,32,2,65,16,107,33,2,12,1,11,11,35,29,32,3,59,1,0,35,29,65,2,106,32,4,59,1,0,35,29,65,4,106,32,8,59,1,0,35,29,65,6,106,32,9,59,1,0,35,29,65,8,106,32,10,59,1,0,35,29,65,10,106,32,11,59,1,0,35,29,65,12,106,32,12,59,1,0,35,29,65,14,106,32,13,59,1,0,35,29,65,16,106,32,14,59,1,0,35,29,65,18,106,32,6,59,1,0,11,203,1,1,3,127,35,32,4,64,65,16,35,32,107,34,3,32,1,75,4,64,32,1,33,3,11,3,64,32,2,32,3,73,4,64,35,25,32,2,35,32,106,106,32,0,32,2,106,45,0,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,1,32,3,107,33,1,32,3,33,4,32,3,35,32,106,36,32,35,32,65,16,73,4,64,15,11,35,25,65,0,65,16,16,18,65,0,36,32,11,2,127,32,1,65,16,79,4,64,32,0,32,4,32,1,32,1,65,15,113,107,34,3,16,18,32,3,32,4,106,33,4,32,1,32,3,107,33,1,11,32,1,11,4,64,65,0,33,2,3,64,32,2,32,1,73,4,64,35,25,32,2,35,32,106,106,32,0,32,2,32,4,106,106,45,0,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,1,35,32,106,36,32,11,11,8,0,35,22,32,0,16,19,11,149,9,1,3,127,35,32,4,64,35,32,34,1,35,25,106,65,1,58,0,0,32,1,65,1,106,33,1,3,64,32,1,65,16,73,4,64,32,1,35,25,106,65,0,58,0,0,32,1,65,1,106,33,1,12,1,11,11,65,1,36,33,35,25,65,0,65,16,16,18,11,35,29,65,2,106,47,1,0,65,13,118,33,2,35,29,65,2,106,35,29,65,2,106,47,1,0,65,255,63,113,59,1,0,65,2,33,1,3,64,32,1,65,10,73,4,64,32,1,65,1,116,34,3,35,29,106,32,2,32,3,35,29,106,47,1,0,106,59,1,0,32,3,35,29,106,47,1,0,65,13,118,33,2,32,3,35,29,106,32,3,35,29,106,47,1,0,65,255,63,113,59,1,0,32,1,65,1,106,33,1,12,1,11,11,35,29,35,29,47,1,0,32,2,65,5,108,106,59,1,0,35,29,47,1,0,33,1,35,29,35,29,47,1,0,65,255,63,113,59,1,0,35,29,65,2,106,35,29,65,2,106,47,1,0,32,1,65,255,255,3,113,65,13,118,106,59,1,0,35,29,65,2,106,47,1,0,33,1,35,29,65,2,106,35,29,65,2,106,47,1,0,65,255,63,113,59,1,0,35,29,65,4,106,35,29,65,4,106,47,1,0,32,1,65,255,255,3,113,65,13,118,106,59,1,0,35,36,35,29,47,1,0,65,5,106,59,1,0,35,36,47,1,0,65,13,118,33,2,35,36,35,36,47,1,0,65,255,63,113,59,1,0,65,1,33,1,3,64,32,1,65,10,73,4,64,32,1,65,1,116,34,3,35,36,106,32,2,32,3,35,29,106,47,1,0,106,59,1,0,32,3,35,36,106,47,1,0,65,13,118,33,2,32,3,35,36,106,32,3,35,36,106,47,1,0,65,255,63,113,59,1,0,32,1,65,1,106,33,1,12,1,11,11,35,36,65,18,106,35,36,65,18,106,47,1,0,65,128,64,106,59,1,0,32,2,65,1,115,65,1,107,33,2,65,0,33,1,3,64,32,1,65,10,73,4,64,32,1,65,1,116,34,3,35,36,106,32,2,32,3,35,36,106,47,1,0,113,59,1,0,32,1,65,1,106,33,1,12,1,11,11,32,2,65,127,115,33,3,65,0,33,1,3,64,32,1,65,10,73,4,64,32,1,65,1,116,34,2,35,29,106,32,2,35,36,106,47,1,0,32,3,32,2,35,29,106,47,1,0,113,114,59,1,0,32,1,65,1,106,33,1,12,1,11,11,35,29,35,29,47,1,0,35,29,65,2,106,47,1,0,65,13,116,114,59,1,0,35,29,65,2,106,35,29,65,4,106,47,1,0,65,10,116,35,29,65,2,106,47,1,0,65,3,118,114,59,1,0,35,29,65,4,106,35,29,65,6,106,47,1,0,65,7,116,35,29,65,4,106,47,1,0,65,6,118,114,59,1,0,35,29,65,6,106,35,29,65,8,106,47,1,0,65,4,116,35,29,65,6,106,47,1,0,65,9,118,114,59,1,0,35,29,65,8,106,35,29,65,10,106,47,1,0,65,1,116,35,29,65,8,106,47,1,0,65,12,118,114,35,29,65,12,106,47,1,0,65,14,116,114,59,1,0,35,29,65,10,106,35,29,65,14,106,47,1,0,65,11,116,35,29,65,12,106,47,1,0,65,2,118,114,59,1,0,35,29,65,12,106,35,29,65,16,106,47,1,0,65,8,116,35,29,65,14,106,47,1,0,65,5,118,114,59,1,0,35,29,65,14,106,35,29,65,18,106,47,1,0,65,5,116,35,29,65,16,106,47,1,0,65,8,118,114,59,1,0,35,29,35,29,47,1,0,35,31,47,1,0,106,34,2,59,1,0,65,1,33,1,3,64,32,1,65,8,73,4,64,32,1,65,1,116,34,3,35,29,106,47,1,0,32,3,35,31,106,47,1,0,106,32,2,65,16,118,106,33,2,35,29,32,3,106,32,2,59,1,0,32,1,65,1,106,33,1,12,1,11,11,32,0,35,29,47,1,0,58,0,0,32,0,65,1,106,35,29,47,1,0,65,8,118,58,0,0,32,0,65,2,106,35,29,65,2,106,47,1,0,58,0,0,32,0,65,3,106,35,29,65,2,106,47,1,0,65,8,118,58,0,0,32,0,65,4,106,35,29,65,4,106,47,1,0,58,0,0,32,0,65,5,106,35,29,65,4,106,47,1,0,65,8,118,58,0,0,32,0,65,6,106,35,29,65,6,106,47,1,0,58,0,0,32,0,65,7,106,35,29,65,6,106,47,1,0,65,8,118,58,0,0,32,0,65,8,106,35,29,65,8,106,47,1,0,58,0,0,32,0,65,9,106,35,29,65,8,106,47,1,0,65,8,118,58,0,0,32,0,65,10,106,35,29,65,10,106,47,1,0,58,0,0,32,0,65,11,106,35,29,65,10,106,47,1,0,65,8,118,58,0,0,32,0,65,12,106,35,29,65,12,106,47,1,0,58,0,0,32,0,65,13,106,35,29,65,12,106,47,1,0,65,8,118,58,0,0,32,0,65,14,106,35,29,65,14,106,47,1,0,58,0,0,32,0,65,15,106,35,29,65,14,106,47,1,0,65,8,118,58,0,0,65,1,36,34,11,11,0,32,0,32,1,65,1,116,16,3,11,38,0,35,25,65,16,16,13,35,27,65,10,16,22,35,29,65,10,16,22,35,31,65,8,16,22,65,0,36,32,65,0,36,33,65,0,36,34,11,33,1,1,127,35,23,33,0,35,34,4,64,65,144,2,65,208,2,65,226,3,65,4,16,0,0,11,32,0,16,21,16,23,11,39,1,1,127,3,64,32,0,65,32,73,4,64,32,0,35,7,106,65,0,58,0,0,32,0,65,1,106,33,0,12,1,11,11,65,32,16,15,26,11,152,2,1,1,127,3,64,32,4,65,32,72,4,64,32,4,35,9,106,32,0,32,4,106,45,0,0,58,0,0,32,4,65,1,106,33,4,12,1,11,11,65,0,33,4,3,64,32,4,65,4,72,4,64,32,4,35,11,106,65,0,58,0,0,32,4,65,1,106,33,4,12,1,11,11,65,4,33,4,3,64,32,4,65,16,72,4,64,32,4,35,11,106,32,1,32,4,65,4,107,106,45,0,0,58,0,0,32,4,65,1,106,33,4,12,1,11,11,16,25,65,0,33,4,3,64,32,4,65,32,72,4,64,32,4,35,21,106,32,4,35,13,106,45,0,0,58,0,0,32,4,65,1,106,33,4,12,1,11,11,35,21,16,16,32,3,65,0,75,4,64,65,0,33,4,3,64,32,4,32,3,73,4,64,32,4,35,22,106,32,2,32,4,106,45,0,0,58,0,0,32,4,65,1,106,33,4,12,1,11,11,32,3,16,20,32,3,65,15,113,65,0,75,4,64,65,16,32,3,65,15,113,107,34,1,65,0,74,4,64,65,0,33,0,3,64,32,0,32,1,72,4,64,32,0,35,22,106,65,0,58,0,0,32,0,65,1,106,33,0,12,1,11,11,32,1,16,20,11,11,11,11,65,1,1,127,3,64,32,2,32,1,73,4,64,35,22,32,2,106,32,0,32,2,106,45,0,0,58,0,0,35,7,32,2,106,32,0,32,2,106,45,0,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,1,16,20,32,1,16,15,26,11,27,0,32,0,32,1,65,0,16,10,32,0,173,66,128,128,128,128,16,127,167,32,1,65,4,16,10,11,87,1,2,127,32,0,65,15,113,65,0,75,4,64,65,16,32,0,65,15,113,107,34,3,65,0,74,4,64,3,64,32,2,32,3,72,4,64,32,2,35,22,106,65,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,3,16,20,11,11,32,1,35,22,16,28,65,8,16,20,32,0,35,22,16,28,65,8,16,20,16,24,11,34,0,32,0,4,64,35,38,35,40,35,42,32,4,16,26,11,35,44,32,2,16,27,32,1,4,64,32,3,32,4,16,29,11,11,89,1,1,127,3,64,32,2,32,1,73,4,64,35,7,32,2,106,32,0,32,2,106,45,0,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,1,16,15,26,65,0,33,2,3,64,32,2,32,1,73,4,64,35,22,32,2,106,32,2,35,13,106,45,0,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,1,16,20,11,34,0,32,0,4,64,35,38,35,40,35,42,32,4,16,26,11,35,44,32,2,16,31,32,1,4,64,32,3,32,4,16,29,11,11,8,0,16,5,16,8,16,9,11,11,234,2,6,0,65,16,11,43,28,0,0,0,1,0,0,0,1,0,0,0,28,0,0,0,73,0,110,0,118,0,97,0,108,0,105,0,100,0,32,0,108,0,101,0,110,0,103,0,116,0,104,0,65,192,0,11,53,38,0,0,0,1,0,0,0,1,0,0,0,38,0,0,0,126,0,108,0,105,0,98,0,47,0,97,0,114,0,114,0,97,0,121,0,98,0,117,0,102,0,102,0,101,0,114,0,46,0,116,0,115,0,65,128,1,11,63,48,0,0,0,1,0,0,0,1,0,0,0,48,0,0,0,67,0,104,0,97,0,67,0,104,0,97,0,58,0,32,0,99,0,111,0,117,0,110,0,116,0,101,0,114,0,32,0,111,0,118,0,101,0,114,0,102,0,108,0,111,0,119,0,65,192,1,11,55,40,0,0,0,1,0,0,0,1,0,0,0,40,0,0,0,97,0,115,0,115,0,101,0,109,0,98,0,108,0,121,0,47,0,99,0,104,0,97,0,99,0,104,0,97,0,50,0,48,0,46,0,116,0,115,0,65,128,2,11,57,42,0,0,0,1,0,0,0,1,0,0,0,42,0,0,0,80,0,111,0,108,0,121,0,49,0,51,0,48,0,53,0,32,0,119,0,97,0,115,0,32,0,102,0,105,0,110,0,105,0,115,0,104,0,101,0,100,0,65,192,2,11,55,40,0,0,0,1,0,0,0,1,0,0,0,40,0,0,0,97,0,115,0,115,0,101,0,109,0,98,0,108,0,121,0,47,0,112,0,111,0,108,0,121,0,49,0,51,0,48,0,53,0,46,0,116,0,115])});var Dw=At(r1=>{"use strict";Object.defineProperty(r1,"__esModule",{value:!0});r1.newInstance=void 0;var aH=uT(),cH=new WebAssembly.Module(aH.wasmCode),lH={env:{abort:function(r,e,t,n){throw Error(`abort: ${r}:${e}:${t}:${n}`)}}};function uH(){return new WebAssembly.Instance(cH,lH).exports}r1.newInstance=uH});var fT=At(n1=>{"use strict";Object.defineProperty(n1,"__esModule",{value:!0});n1.chacha20StreamXOR=void 0;var hH=Dw(),fn=hH.newInstance(),dH=fn.chacha20Input.value,fH=fn.chacha20Output.value,pH=fn.chacha20Key.value,mH=fn.chacha20Counter.value,{CHACHA20_INPUT_LENGTH:Ia,KEY_LENGTH:kw,CHACHA20_COUNTER_LENGTH:dT}=fn,gH=new Uint8Array(fn.memory.buffer,dH,Ia),hT=new Uint8Array(fn.memory.buffer,fH,Ia),yH=new Uint8Array(fn.memory.buffer,pH,kw),bH=new Uint8Array(fn.memory.buffer,mH,dT);function wH(r,e,t){if(r.length!=kw)throw new Error("ChaCha: key size must be 32 bytes, expected "+kw+" got "+r.length);if(e.length!=dT)throw new Error("ChaCha nonce with counter must be 16 bytes");yH.set(r),bH.set(e);let n=new Uint8Array(t.length),s=Math.floor(t.length/Ia);for(let o=0;o<=s;o++){let i=o*Ia,a=Math.min((o+1)*Ia,t.length);gH.set(s===0?t:t.subarray(i,a));let c=a-i,l=fn.chacha20StreamXORUpdate(c);n.set(l===Ia?hT:hT.subarray(0,l),i)}return n}n1.chacha20StreamXOR=wH});var pT=At(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.newInstance=pn.chacha20StreamXOR=pn.Poly1305=pn.ChaCha20Poly1305=void 0;var xH=cT();Object.defineProperty(pn,"ChaCha20Poly1305",{enumerable:!0,get:function(){return xH.ChaCha20Poly1305}});var vH=lT();Object.defineProperty(pn,"Poly1305",{enumerable:!0,get:function(){return vH.Poly1305}});var EH=fT();Object.defineProperty(pn,"chacha20StreamXOR",{enumerable:!0,get:function(){return EH.chacha20StreamXOR}});var SH=Dw();Object.defineProperty(pn,"newInstance",{enumerable:!0,get:function(){return SH.newInstance}})});var vT=At((n4e,xT)=>{function OH(){return!!(typeof window<"u"&&typeof window.process=="object"&&window.process.type==="renderer"||typeof process<"u"&&typeof process.versions=="object"&&process.versions.electron||typeof navigator=="object"&&typeof navigator.userAgent=="string"&&navigator.userAgent.indexOf("Electron")>=0)}xT.exports=OH});var wP=At((tCe,bP)=>{"use strict";function ze(r,t){var t=t||{};this._capacity=t.capacity,this._head=0,this._tail=0,Array.isArray(r)?this._fromArray(r):(this._capacityMask=3,this._list=new Array(4))}ze.prototype.peekAt=function(e){var t=e;if(t===(t|0)){var n=this.size();if(!(t>=n||t<-n))return t<0&&(t+=n),t=this._head+t&this._capacityMask,this._list[t]}};ze.prototype.get=function(e){return this.peekAt(e)};ze.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]};ze.prototype.peekFront=function(){return this.peek()};ze.prototype.peekBack=function(){return this.peekAt(-1)};Object.defineProperty(ze.prototype,"length",{get:function(){return this.size()}});ze.prototype.size=function(){return this._head===this._tail?0:this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};ze.prototype.unshift=function(e){if(arguments.length===0)return this.size();var t=this._list.length;return this._head=this._head-1+t&this._capacityMask,this._list[this._head]=e,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.pop(),this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};ze.prototype.shift=function(){var e=this._head;if(e!==this._tail){var t=this._list[e];return this._list[e]=void 0,this._head=e+1&this._capacityMask,e<2&&this._tail>1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}};ze.prototype.push=function(e){if(arguments.length===0)return this.size();var t=this._tail;return this._list[t]=e,this._tail=t+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.shift(),this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};ze.prototype.pop=function(){var e=this._tail;if(e!==this._head){var t=this._list.length;this._tail=e-1+t&this._capacityMask;var n=this._list[this._tail];return this._list[this._tail]=void 0,this._head<2&&e>1e4&&e<=t>>>2&&this._shrinkArray(),n}};ze.prototype.removeOne=function(e){var t=e;if(t===(t|0)&&this._head!==this._tail){var n=this.size(),s=this._list.length;if(!(t>=n||t<-n)){t<0&&(t+=n),t=this._head+t&this._capacityMask;var o=this._list[t],i;if(e<n/2){for(i=e;i>0;i--)this._list[t]=this._list[t=t-1+s&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+s&this._capacityMask}else{for(i=n-1-e;i>0;i--)this._list[t]=this._list[t=t+1+s&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+s&this._capacityMask}return o}}};ze.prototype.remove=function(e,t){var n=e,s,o=t;if(n===(n|0)&&this._head!==this._tail){var i=this.size(),a=this._list.length;if(!(n>=i||n<-i||t<1)){if(n<0&&(n+=i),t===1||!t)return s=new Array(1),s[0]=this.removeOne(n),s;if(n===0&&n+t>=i)return s=this.toArray(),this.clear(),s;n+t>i&&(t=i-n);var c;for(s=new Array(t),c=0;c<t;c++)s[c]=this._list[this._head+n+c&this._capacityMask];if(n=this._head+n&this._capacityMask,e+t===i){for(this._tail=this._tail-t+a&this._capacityMask,c=t;c>0;c--)this._list[n=n+1+a&this._capacityMask]=void 0;return s}if(e===0){for(this._head=this._head+t+a&this._capacityMask,c=t-1;c>0;c--)this._list[n=n+1+a&this._capacityMask]=void 0;return s}if(n<i/2){for(this._head=this._head+e+t+a&this._capacityMask,c=e;c>0;c--)this.unshift(this._list[n=n-1+a&this._capacityMask]);for(n=this._head-1+a&this._capacityMask;o>0;)this._list[n=n-1+a&this._capacityMask]=void 0,o--;e<0&&(this._tail=n)}else{for(this._tail=n,n=n+t+a&this._capacityMask,c=i-(t+e);c>0;c--)this.push(this._list[n++]);for(n=this._tail;o>0;)this._list[n=n+1+a&this._capacityMask]=void 0,o--}return this._head<2&&this._tail>1e4&&this._tail<=a>>>2&&this._shrinkArray(),s}}};ze.prototype.splice=function(e,t){var n=e;if(n===(n|0)){var s=this.size();if(n<0&&(n+=s),!(n>s))if(arguments.length>2){var o,i,a,c=arguments.length,l=this._list.length,u=2;if(!s||n<s/2){for(i=new Array(n),o=0;o<n;o++)i[o]=this._list[this._head+o&this._capacityMask];for(t===0?(a=[],n>0&&(this._head=this._head+n+l&this._capacityMask)):(a=this.remove(n,t),this._head=this._head+n+l&this._capacityMask);c>u;)this.unshift(arguments[--c]);for(o=n;o>0;o--)this.unshift(i[o-1])}else{i=new Array(s-(n+t));var h=i.length;for(o=0;o<h;o++)i[o]=this._list[this._head+n+t+o&this._capacityMask];for(t===0?(a=[],n!=s&&(this._tail=this._head+n+l&this._capacityMask)):(a=this.remove(n,t),this._tail=this._tail-h+l&this._capacityMask);u<c;)this.push(arguments[u++]);for(o=0;o<h;o++)this.push(i[o])}return a}else return this.remove(n,t)}};ze.prototype.clear=function(){this._list=new Array(this._list.length),this._head=0,this._tail=0};ze.prototype.isEmpty=function(){return this._head===this._tail};ze.prototype.toArray=function(){return this._copyArray(!1)};ze.prototype._fromArray=function(e){var t=e.length,n=this._nextPowerOf2(t);this._list=new Array(n),this._capacityMask=n-1,this._tail=t;for(var s=0;s<t;s++)this._list[s]=e[s]};ze.prototype._copyArray=function(e,t){var n=this._list,s=n.length,o=this.length;if(t=t|o,t==o&&this._head<this._tail)return this._list.slice(this._head,this._tail);var i=new Array(t),a=0,c;if(e||this._head>this._tail){for(c=this._head;c<s;c++)i[a++]=n[c];for(c=0;c<this._tail;c++)i[a++]=n[c]}else for(c=this._head;c<this._tail;c++)i[a++]=n[c];return i};ze.prototype._growArray=function(){if(this._head!=0){var e=this._copyArray(!0,this._list.length<<1);this._tail=this._list.length,this._head=0,this._list=e}else this._tail=this._list.length,this._list.length<<=1;this._capacityMask=this._capacityMask<<1|1};ze.prototype._shrinkArray=function(){this._list.length>>>=1,this._capacityMask>>>=1};ze.prototype._nextPowerOf2=function(e){var t=Math.log(e)/Math.log(2),n=1<<t+1;return Math.max(n,4)};bP.exports=ze});var zj={};z(zj,{ArachnodeFretAdapter:()=>$l,BlockStorage:()=>Bi,ClusterClient:()=>ro,ClusterCoordinator:()=>ml,ClusterMember:()=>Cd,ClusterService:()=>Td,CoordinatorRepo:()=>_d,Libp2pKeyPeerNetwork:()=>Xl,MemoryRawStorage:()=>gl,NetworkManagerService:()=>xm,ProtocolClient:()=>Cn,RepoClient:()=>Xg,RepoService:()=>Dd,RestorationCoordinator:()=>Kl,RingSelector:()=>Fl,SYNC_PROTOCOL_PREFIX:()=>dA,SYNC_PROTOCOL_VERSION:()=>fA,StorageMonitor:()=>zl,StorageRepo:()=>yl,SyncClient:()=>ho,SyncService:()=>cf,asyncIteratorToArray:()=>uc,buildKnownPeers:()=>Uj,buildSyncProtocol:()=>Ul,clusterMember:()=>jg,clusterService:()=>Yg,computeResponsibility:()=>Bj,coordinatorRepo:()=>Qg,createLibp2pNode:()=>Nj,first:()=>Lm,getNetworkManager:()=>Fj,lessThanLex:()=>LD,networkManagerService:()=>B5,reduce:()=>ek,repoService:()=>Jg,sortPeersByDistance:()=>MD,syncService:()=>l3,xorDistanceBytes:()=>kD});function ut(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var ch=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},jo=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new ch(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new ch(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Em=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Ot(r={}){return KD(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function KD(r,e){e=e??{};let t=e.onEnd,n=new jo,s,o,i,a=ut(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,y)=>{o=b=>{o=null,n.push(b);try{g(r(n))}catch(w){y(w)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ut()})}},l=g=>o!=null?o(g):(n.push(g),s),u=g=>(n=new jo,o!=null?o({error:g}):(n.push({error:g}),s)),h=g=>{if(i)return s;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:g})},p=g=>i?s:(i=!0,g!=null?u(g):l({done:!0})),f=()=>(n=new jo,p(),{done:!0}),d=g=>(p(g),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:f,throw:d,push:h,end:p,get readableLength(){return n.size},onEmpty:async g=>{let y=g?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let b,w;y!=null&&(b=new Promise((x,v)=>{w=()=>{v(new Em)},y.addEventListener("abort",w)}));try{await Promise.race([a.promise,b])}finally{w!=null&&y!=null&&y?.removeEventListener("abort",w)}}},t==null)return s;let m=s;return s={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(g){return m.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:h,end(g){return m.end(g),t!=null&&(t(g),t=void 0),s},get readableLength(){return m.readableLength},onEmpty:g=>m.onEmpty(g)},s}var lh=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function uh(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new lh(t?.errorMessage,t?.errorCode,t?.errorName));let n,s=new lh(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((o,i)=>{n=()=>{i(s)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Sm=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ut(),this.haveNext=ut()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ut(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ut(),await uh(this.readNext.promise,t?.signal,t)}};function H5(){return new Sm}function FD(r){return r[Symbol.asyncIterator]!=null}async function zD(r,e,t){try{await Promise.all(r.map(async n=>{for await(let s of n)await e.push(s,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*$D(r){let e=new AbortController,t=H5();zD(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*HD(r){for(let e of r)yield*e}function qD(...r){let e=[];for(let t of r)FD(t)||e.push(t);return e.length===r.length?HD(e):$D(r)}var Ks=qD;function ht(r,...e){if(r==null)throw new Error("Empty pipeline");if(Im(r)){let n=r;r=()=>n.source}else if(V5(r)||q5(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&Im(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)Im(t[n])&&(t[n]=GD(t[n]));return VD(...t)}var VD=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},q5=r=>r?.[Symbol.asyncIterator]!=null,V5=r=>r?.[Symbol.iterator]!=null,Im=r=>r==null?!1:r.sink!=null&&r.source!=null,GD=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=Ot({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(q5(o))s=async function*(){yield*o,n.end()};else if(V5(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Ks(n,s())}return r.source};gr();Be();rt();var dh=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Yo=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},fh=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},lc=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function ph(r){return r[Symbol.asyncIterator]!=null}function Y5(r,e){if(r.byteLength>e)throw new Yo("Message length too long")}var gh=r=>{let e=Ae(r),t=tt(e);return Vr(r,t),gh.bytes=e,t};gh.bytes=0;function yr(r,e){e=e??{};let t=e.lengthEncoder??gh,n=e?.maxDataLength??4194304;function*s(o){Y5(o,n);let i=t(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return ph(r)?(async function*(){for await(let o of r)yield*s(o)})():(function*(){for(let o of r)yield*s(o)})()}yr.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??gh,n=e?.maxDataLength??4194304;return Y5(r,n),new U(t(r.byteLength),r)};gr();Be();var Fs;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Fs||(Fs={}));var km=r=>{let e=jt(r);return km.bytes=Ae(e),e};km.bytes=0;function Pr(r,e){let t=new U,n=Fs.LENGTH,s=-1,o=e?.lengthDecoder??km,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Fs.LENGTH)try{if(s=o(t),s<0)throw new dh("Invalid message length");if(s>a)throw new Yo("Message length too long");let l=o.bytes;t.consume(l),e?.onLength!=null&&e.onLength(s),n=Fs.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new fh("Message length length too long");break}throw l}if(n===Fs.DATA){if(t.byteLength<s)break;let l=t.sublist(0,s);t.consume(s),e?.onData!=null&&e.onData(l),yield l,n=Fs.LENGTH}}}return ph(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new lc("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new lc("Unexpected end of input")})()}Pr.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:o,value:i}=await r.next(t);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}})();return Pr(n,{...e??{},onLength:o=>{t=o}})};async function Lm(r,e=()=>{throw new Error("No items found")},t){let n=new AbortController,s=typeof t=="number"?setTimeout(()=>n.abort(),t):void 0;try{for await(let o of r(n.signal))return o;return e()}finally{s!==void 0&&clearTimeout(s),n.abort()}}async function uc(r){let e=[];for await(let t of r)e.push(t);return e}function ek(r,e,t){let n=t,s=0;for(let o of r)n=e(n,o,s),++s;return n}var Cn=class{peerId;peerNetwork;constructor(e,t){this.peerId=e,this.peerNetwork=t}async processMessage(e,t,n){let s=await this.peerNetwork.connect(this.peerId,t,{signal:n?.signal});try{let o=ht([new TextEncoder().encode(JSON.stringify(e))],yr);for await(let a of o)s.send(a);let i=ht(s,Pr,async function*(a){for await(let c of a){let l=new TextDecoder().decode(c.subarray());yield JSON.parse(l)}});return await Lm(()=>i,()=>{throw new Error("No response received")})}finally{await s.close()}}};ke();var ro=class r extends Cn{protocolPrefix;constructor(e,t,n){super(e,t),this.protocolPrefix=n}static create(e,t,n){return new r(e,t,n)}async update(e,t=0){let n={operation:"update",record:e},s=(this.protocolPrefix??"/db-p2p")+"/cluster/1.0.0",o;try{o=await this.processMessage(n,s)}catch(i){if(s!=="/db-p2p/cluster/1.0.0")o=await this.processMessage(n,"/db-p2p/cluster/1.0.0");else throw i}if(o?.redirect?.peers?.length){if(t>=2)throw new Error("Redirect loop detected in ClusterClient (max hops reached)");let i=this.peerId.toString(),a=o.redirect.peers.find(u=>u.id!==i)??o.redirect.peers[0],c=de(a.id);if(a.id===i)throw new Error("Redirect loop detected in ClusterClient (same peer)");return this.recordCoordinatorForRecordIfSupported(e,c),await r.create(c,this.peerNetwork,this.protocolPrefix).update(e,t+1)}return o}recordCoordinatorForRecordIfSupported(e,t){let n=e?.message,s;if(n?.commit?.tailId)s=n.commit.tailId;else if(n?.pend?.transforms){let o=Object.keys(n.pend.transforms);o.length>0&&(s=o[0])}if(s){let o=new TextEncoder().encode(s),i=this.peerNetwork;typeof i?.recordCoordinator=="function"&&i.recordCoordinator(o,t)}}};var G2=new Map;function tn(r,e){if(G2.has(r))throw new Error(`Block type ${r} (${e}) already registered (${G2.get(r)})`);return G2.set(r,e),r}function pd(r,[e,t,n,s]){Array.isArray(s)?r[e].splice(t,n,...structuredClone(s)):r[e]=structuredClone(s)}function EM(r,e){for(let t of e)pd(r,t)}function gs(r){if(!r)return[];let e=Object.keys(r.inserts??{}),t=Object.keys(r.updates??{}),n=r.deletes??[];return[...new Set([...e,...t,...n])]}function W2(){return{inserts:{},updates:{},deletes:[]}}function md(r,e){return{...r.inserts&&e in r.inserts?{insert:r.inserts[e]}:{},...r.updates&&e in r.updates?{updates:structuredClone(r.updates[e])}:{},...r.deletes?.includes(e)?{delete:!0}:{}}}function j2(r,e){return{inserts:r.insert?{[e]:r.insert}:{},updates:r.updates?{[e]:r.updates}:{},deletes:r.delete?[e]:[]}}function cl(r,e){if(e.insert&&(r=e.insert),r&&e.updates&&EM(r,e.updates),!e.delete)return r}function Y2(r,e,t){return{inserts:{...r.inserts,...t.insert?{[e]:t.insert}:{}},updates:{...r.updates,...t.updates?{[e]:t.updates}:{}},deletes:[...r.deletes??[],...t.delete?[e]:[]]}}function Xt(r,e){return e??r}var SM=tn("TL","TreeLeaf"),IM=tn("TB","TreeBranch"),AM=Xt("entries"),CM=Xt("partitions"),TM=Xt("nodes");var DM=Xt("entries"),kM=Xt("priorId"),LM=Xt("nextId"),MM=tn("CHD","ChainDataBlock"),OM=Xt("headId"),RM=Xt("tailId"),NM=tn("CHH","ChainHeaderBlock");var $E=ee("node:buffer");function zE(r){return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}function HE(r=0){return zE($E.Buffer.allocUnsafe(r))}var eg={};z(eg,{base10:()=>qM});var Ire=new Uint8Array(0);function qE(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function vr(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function VE(r){return new TextEncoder().encode(r)}function GE(r){return new TextDecoder().decode(r)}function UM(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var v=d[y],S=0,E=w-1;(v!==0||S<g)&&E!==-1;E--,S++)v+=256*x[E]>>>0,x[E]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var A=c.repeat(m);I<w;++I)A+=r.charAt(x[I]);return A}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*w[S]>>>0,w[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(d[m]!==" "){for(var E=b-y;E!==b&&w[E]===0;)E++;for(var I=new Uint8Array(g+(b-E)),A=g;E!==b;)I[A++]=w[E++];return I}}}function f(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:f}}var KM=UM,FM=KM,jE=FM;var X2=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Q2=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return YE(this,e)}},J2=class{decoders;constructor(e){this.decoders=e}or(e){return YE(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function YE(r,e){return new J2({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Z2=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new X2(e,t,n),this.decoder=new Q2(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ti({name:r,prefix:e,encode:t,decode:n}){return new Z2(r,e,t,n)}function ys({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=jE(t,r);return Ti({prefix:e,name:r,encode:n,decode:o=>vr(s(o))})}function zM(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function $M(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function HM(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function He({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=HM(n);return Ti({prefix:e,name:r,encode(o){return $M(o,n,t)},decode(o){return zM(o,s,t,r)}})}var qM=ys({prefix:"9",name:"base10",alphabet:"0123456789"});var tg={};z(tg,{base16:()=>VM,base16upper:()=>GM});var VM=He({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),GM=He({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var rg={};z(rg,{base2:()=>WM});var WM=He({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ng={};z(ng,{base256emoji:()=>JM});var XE=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),jM=XE.reduce((r,e,t)=>(r[t]=e,r),[]),YM=XE.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function XM(r){return r.reduce((e,t)=>(e+=jM[t],e),"")}function QM(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=YM[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var JM=Ti({prefix:"\u{1F680}",name:"base256emoji",encode:XM,decode:QM});var sg={};z(sg,{base32:()=>_i,base32hex:()=>rO,base32hexpad:()=>sO,base32hexpadupper:()=>oO,base32hexupper:()=>nO,base32pad:()=>eO,base32padupper:()=>tO,base32upper:()=>ZM,base32z:()=>iO});var _i=He({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ZM=He({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),eO=He({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),tO=He({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),rO=He({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),nO=He({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),sO=He({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),oO=He({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),iO=He({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var og={};z(og,{base36:()=>ll,base36upper:()=>aO});var ll=ys({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),aO=ys({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ig={};z(ig,{base58btc:()=>rn,base58flickr:()=>cO});var rn=ys({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),cO=ys({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ag={};z(ag,{base64:()=>lO,base64pad:()=>uO,base64url:()=>hO,base64urlpad:()=>dO});var lO=He({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),uO=He({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),hO=He({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),dO=He({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var cg={};z(cg,{base8:()=>fO});var fO=He({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var lg={};z(lg,{identity:()=>pO});var pO=Ti({prefix:"\0",name:"identity",encode:r=>GE(r),decode:r=>VE(r)});var Fre=new TextEncoder,zre=new TextDecoder;var hg={};z(hg,{identity:()=>BO});var yO=ZE,QE=128,bO=127,wO=~bO,xO=Math.pow(2,31);function ZE(r,e,t){e=e||[],t=t||0;for(var n=t;r>=xO;)e[t++]=r&255|QE,r/=128;for(;r&wO;)e[t++]=r&255|QE,r>>>=7;return e[t]=r|0,ZE.bytes=t-n+1,e}var vO=ug,EO=128,JE=127;function ug(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw ug.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&JE)<<s:(i&JE)*Math.pow(2,s),s+=7}while(i>=EO);return ug.bytes=o-n,t}var SO=Math.pow(2,7),IO=Math.pow(2,14),AO=Math.pow(2,21),CO=Math.pow(2,28),TO=Math.pow(2,35),_O=Math.pow(2,42),PO=Math.pow(2,49),DO=Math.pow(2,56),kO=Math.pow(2,63),LO=function(r){return r<SO?1:r<IO?2:r<AO?3:r<CO?4:r<TO?5:r<_O?6:r<PO?7:r<DO?8:r<kO?9:10},MO={encode:yO,decode:vO,encodingLength:LO},OO=MO,ul=OO;function hl(r,e=0){return[ul.decode(r,e),ul.decode.bytes]}function Pi(r,e,t=0){return ul.encode(r,e,t),e}function Di(r){return ul.encodingLength(r)}function Li(r,e){let t=e.byteLength,n=Di(r),s=n+Di(t),o=new Uint8Array(s+t);return Pi(r,o,0),Pi(t,o,n),o.set(e,s),new ki(r,t,e,o)}function eS(r){let e=vr(r),[t,n]=hl(e),[s,o]=hl(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new ki(t,s,i,e)}function tS(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&qE(r.bytes,t.bytes)}}var ki=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var rS=0,RO="identity",nS=vr;function NO(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Li(rS,nS(r))}var BO={code:rS,name:RO,encode:nS,digest:NO};var mg={};z(mg,{sha256:()=>KO,sha512:()=>FO});var pg=ie(ee("crypto"),1);var UO=20;function fg({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new dg(r,e,t,n,s)}var dg=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??UO,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?sS(n,this.code,t?.truncate):n.then(s=>sS(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function sS(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Li(e,r)}var KO=fg({name:"sha2-256",code:18,encode:r=>vr(pg.default.createHash("sha256").update(r).digest())}),FO=fg({name:"sha2-512",code:19,encode:r=>vr(pg.default.createHash("sha512").update(r).digest())});function iS(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return $O(t,gg(r),e??rn.encoder);default:return HO(t,gg(r),e??_i.encoder)}}var aS=new WeakMap;function gg(r){let e=aS.get(r);if(e==null){let t=new Map;return aS.set(r,t),t}return e}var yd=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==fl)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==qO)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Li(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&tS(e.multihash,n.multihash)}toString(e){return iS(this,e)}toJSON(){return{"/":iS(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??cS(n,s,o.bytes))}else if(t[VO]===!0){let{version:n,multihash:s,code:o}=t,i=eS(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==fl)throw new Error(`Version 0 CID must use dag-pb (code: ${fl}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=cS(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,fl,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=vr(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new ki(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,p]=hl(e.subarray(t));return t+=p,h},s=n(),o=fl;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=zO(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return gg(o).set(n,e),o}};function zO(r,e){switch(r[0]){case"Q":{let t=e??rn;return[rn.prefix,t.decode(`${rn.prefix}${r}`)]}case rn.prefix:{let t=e??rn;return[rn.prefix,t.decode(r)]}case _i.prefix:{let t=e??_i;return[_i.prefix,t.decode(r)]}case ll.prefix:{let t=e??ll;return[ll.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function $O(r,e,t){let{prefix:n}=t;if(n!==rn.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function HO(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var fl=112,qO=18;function cS(r,e,t){let n=Di(r),s=n+Di(e),o=new Uint8Array(s+t.byteLength);return Pi(r,o,0),Pi(e,o,n),o.set(t,s),o}var VO=Symbol.for("@ipld/js-cid/CID");var yg={...lg,...rg,...cg,...eg,...tg,...sg,...og,...ig,...ag,...ng},une={...mg,...hg};function uS(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var lS=uS("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),bg=uS("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=HE(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),pne={utf8:lS,"utf-8":lS,hex:yg.base16,latin1:bg,ascii:bg,binary:bg,...yg};var no=class{static lockQueues=new Map;static async acquire(e){let t=this.lockQueues.get(e)??Promise.resolve(),n,s=new Promise(i=>{n=i});return this.lockQueues.set(e,s),await t,()=>{n(),this.lockQueues.get(e)===s&&this.lockQueues.delete(e)}}};var YO=tn("DIH","DiaryHeaderBlock");var XO=tn("TRE","TreeHeaderBlock"),QO=Xt("rootId");var Cg=ie(ee("crypto"),1);var sse=new Uint8Array(0);function bd(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var JO=pS,dS=128,ZO=127,eR=~ZO,tR=Math.pow(2,31);function pS(r,e,t){e=e||[],t=t||0;for(var n=t;r>=tR;)e[t++]=r&255|dS,r/=128;for(;r&eR;)e[t++]=r&255|dS,r>>>=7;return e[t]=r|0,pS.bytes=t-n+1,e}var rR=wg,nR=128,fS=127;function wg(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw wg.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&fS)<<s:(i&fS)*Math.pow(2,s),s+=7}while(i>=nR);return wg.bytes=o-n,t}var sR=Math.pow(2,7),oR=Math.pow(2,14),iR=Math.pow(2,21),aR=Math.pow(2,28),cR=Math.pow(2,35),lR=Math.pow(2,42),uR=Math.pow(2,49),hR=Math.pow(2,56),dR=Math.pow(2,63),fR=function(r){return r<sR?1:r<oR?2:r<iR?3:r<aR?4:r<cR?5:r<lR?6:r<uR?7:r<hR?8:r<dR?9:10},pR={encode:JO,decode:rR,encodingLength:fR},mR=pR,xg=mR;function vg(r,e,t=0){return xg.encode(r,e,t),e}function Eg(r){return xg.encodingLength(r)}function mS(r,e){let t=e.byteLength,n=Eg(r),s=n+Eg(t),o=new Uint8Array(s+t);return vg(r,o,0),vg(t,o,n),o.set(e,s),new Sg(r,t,e,o)}var Sg=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var bR=20;function Ag({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new Ig(r,e,t,n,s)}var Ig=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??bR,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?gS(n,this.code,t?.truncate):n.then(s=>gS(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function gS(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return mS(e,r)}var yS=Ag({name:"sha2-256",code:18,encode:r=>bd(Cg.default.createHash("sha256").update(r).digest())}),pse=Ag({name:"sha2-512",code:19,encode:r=>bd(Cg.default.createHash("sha512").update(r).digest())});var Ese=Xt("priorHash");Tg();Tg();var so=class{promise;response;error;t1=Date.now();duration;get isResponse(){return this.response!==void 0}get isError(){return this.error!==void 0}get isComplete(){return this.isResponse||this.isError}async result(){if(this.isResponse)return this.response;if(this.isError)throw this.error;return await this.promise}constructor(e){this.promise=e,e.then(t=>(this.duration=Date.now()-this.t1,this.response=t,t),t=>{this.duration=Date.now()-this.t1,this.error=t})}};function _g(r,e){return r.reduce((t,n)=>{let s=e(n);return(t[s]??=[]).push(n),t},{})}ke();var Ng=ie(ee("crypto"),1);var gie=new Uint8Array(0);function Mi(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var xR=SS,vS=128,vR=127,ER=~vR,SR=Math.pow(2,31);function SS(r,e,t){e=e||[],t=t||0;for(var n=t;r>=SR;)e[t++]=r&255|vS,r/=128;for(;r&ER;)e[t++]=r&255|vS,r>>>=7;return e[t]=r|0,SS.bytes=t-n+1,e}var IR=Pg,AR=128,ES=127;function Pg(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Pg.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&ES)<<s:(i&ES)*Math.pow(2,s),s+=7}while(i>=AR);return Pg.bytes=o-n,t}var CR=Math.pow(2,7),TR=Math.pow(2,14),_R=Math.pow(2,21),PR=Math.pow(2,28),DR=Math.pow(2,35),kR=Math.pow(2,42),LR=Math.pow(2,49),MR=Math.pow(2,56),OR=Math.pow(2,63),RR=function(r){return r<CR?1:r<TR?2:r<_R?3:r<PR?4:r<DR?5:r<kR?6:r<LR?7:r<MR?8:r<OR?9:10},NR={encode:xR,decode:IR,encodingLength:RR},BR=NR,Dg=BR;function kg(r,e,t=0){return Dg.encode(r,e,t),e}function Lg(r){return Dg.encodingLength(r)}function IS(r,e){let t=e.byteLength,n=Lg(r),s=n+Lg(t),o=new Uint8Array(s+t);return kg(r,o,0),kg(t,o,n),o.set(e,s),new Mg(r,t,e,o)}var Mg=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var FR=20;function Rg({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new Og(r,e,t,n,s)}var Og=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??FR,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?AS(n,this.code,t?.truncate):n.then(s=>AS(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function AS(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return IS(e,r)}var nn=Rg({name:"sha2-256",code:18,encode:r=>Mi(Ng.default.createHash("sha256").update(r).digest())}),Cie=Rg({name:"sha2-512",code:19,encode:r=>Mi(Ng.default.createHash("sha512").update(r).digest())});function zR(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var v=d[y],S=0,E=w-1;(v!==0||S<g)&&E!==-1;E--,S++)v+=256*x[E]>>>0,x[E]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var A=c.repeat(m);I<w;++I)A+=r.charAt(x[I]);return A}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*w[S]>>>0,w[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(d[m]!==" "){for(var E=b-y;E!==b&&w[E]===0;)E++;for(var I=new Uint8Array(g+(b-E)),A=g;E!==b;)I[A++]=w[E++];return I}}}function f(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:f}}var $R=zR,HR=$R,CS=HR;var Bg=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Ug=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return TS(this,e)}},Kg=class{decoders;constructor(e){this.decoders=e}or(e){return TS(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function TS(r,e){return new Kg({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Fg=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new Bg(e,t,n),this.decoder=new Ug(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function qR({name:r,prefix:e,encode:t,decode:n}){return new Fg(r,e,t,n)}function zg({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=CS(t,r);return qR({prefix:e,name:r,encode:n,decode:o=>Mi(s(o))})}var wd=zg({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Mie=zg({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});ce();var NS=ie(Wg(),1),m9="optimystic:db-p2p";function Sr(r){return(0,NS.default)(`${m9}:${r}`)}var ye=Sr("cluster-member"),xt;(function(r){r[r.Promising=0]="Promising",r[r.OurPromiseNeeded=1]="OurPromiseNeeded",r[r.OurCommitNeeded=2]="OurCommitNeeded",r[r.Consensus=3]="Consensus",r[r.Rejected=4]="Rejected",r[r.Propagating=5]="Propagating"})(xt||(xt={}));function jg(r){return new Cd(r.storageRepo,r.peerNetwork,r.peerId,r.protocolPrefix,r.partitionDetector,r.fretService,r.validator)}var g9=600*1e3,Cd=class{storageRepo;peerNetwork;peerId;protocolPrefix;partitionDetector;fretService;validator;activeTransactions=new Map;executedTransactions=new Map;cleanupQueue=[];pendingUpdates=new Map;constructor(e,t,n,s,o,i,a){this.storageRepo=e,this.peerNetwork=t,this.peerId=n,this.protocolPrefix=s,this.partitionDetector=o,this.fretService=i,this.validator=a,setInterval(()=>this.queueExpiredTransactions(),6e4),setInterval(()=>this.processCleanupQueue(),1e3)}wasTransactionExecuted(e){return this.executedTransactions.has(e)}async update(e){let t=this.pendingUpdates.get(e.messageHash);t&&(ye("cluster-member:concurrent-update-wait",{messageHash:e.messageHash}),await t);let n=this.processUpdate(e);this.pendingUpdates.set(e.messageHash,n);try{return await n}finally{setTimeout(()=>{this.pendingUpdates.delete(e.messageHash)},100)}}async processUpdate(e){let t=this.peerId.toString(),n=e.commits[t]?"commit":e.promises[t]?"promise":"initial";if(ye("cluster-member:incoming",{messageHash:e.messageHash,phase:n,peerCount:Object.keys(e.peers).length,promiseCount:Object.keys(e.promises).length,commitCount:Object.keys(e.commits).length,existingTransaction:this.activeTransactions.has(e.messageHash)}),this.fretService&&e.networkSizeHint&&e.networkSizeConfidence)try{this.fretService.reportNetworkSize(e.networkSizeHint,e.networkSizeConfidence,"cluster")}catch{}await this.validateRecord(e);let s=this.activeTransactions.get(e.messageHash),o=s?.record||e;s&&ye("cluster-member:merge-start",{messageHash:e.messageHash,existingPromises:Object.keys(s.record.promises??{}),existingCommits:Object.keys(s.record.commits??{}),incomingPromises:Object.keys(e.promises??{}),incomingCommits:Object.keys(e.commits??{})}),s&&(o=await this.mergeRecords(s.record,e),ye("cluster-member:merge-complete",{messageHash:e.messageHash,mergedPromises:Object.keys(o.promises??{}),mergedCommits:Object.keys(o.commits??{})}));let i=await this.getTransactionPhase(o);ye("cluster-member:phase",{messageHash:e.messageHash,phase:i,promises:Object.keys(o.promises??{}),commits:Object.keys(o.commits??{})});let a=!0;switch(i){case xt.OurPromiseNeeded:ye("cluster-member:action-promise",{messageHash:e.messageHash}),o=await this.handlePromiseNeeded(o),ye("cluster-member:action-promise-complete",{messageHash:e.messageHash,promises:Object.keys(o.promises??{})});break;case xt.OurCommitNeeded:ye("cluster-member:action-commit",{messageHash:e.messageHash}),o=await this.handleCommitNeeded(o),ye("cluster-member:action-commit-complete",{messageHash:e.messageHash,commits:Object.keys(o.commits??{})}),await this.getTransactionPhase(o)===xt.Consensus&&(ye("cluster-member:action-consensus-after-commit",{messageHash:e.messageHash}),await this.handleConsensus(o)),a=!1;break;case xt.Consensus:ye("cluster-member:action-consensus",{messageHash:e.messageHash}),n!=="commit"?await this.handleConsensus(o):ye("cluster-member:consensus-skip-already-committed",{messageHash:e.messageHash}),a=!1;break;case xt.Rejected:ye("cluster-member:action-rejected",{messageHash:e.messageHash}),await this.handleRejection(o),a=!1;break;case xt.Propagating:ye("cluster-member:phase-propagating",{messageHash:e.messageHash}),a=!1;break;case xt.Promising:ye("cluster-member:phase-promising-blocked",{messageHash:e.messageHash});break}if(a){let c=this.setupTimeouts(o);this.activeTransactions.set(e.messageHash,{record:o,lastUpdate:Date.now(),promiseTimeout:c.promiseTimeout,resolutionTimeout:c.resolutionTimeout}),ye("cluster-member:state-persist",{messageHash:e.messageHash,storedPromises:Object.keys(o.promises??{}),storedCommits:Object.keys(o.commits??{})})}else ye("cluster-member:state-clear",{messageHash:e.messageHash}),this.clearTransaction(e.messageHash);return ye("cluster-member:update-complete",{messageHash:e.messageHash,promiseCount:Object.keys(o.promises).length,commitCount:Object.keys(o.commits).length}),o}async mergeRecords(e,t){if(ye("cluster-member:merge-records",{messageHash:e.messageHash,existingPromises:Object.keys(e.promises??{}),existingCommits:Object.keys(e.commits??{}),incomingPromises:Object.keys(t.promises??{}),incomingCommits:Object.keys(t.commits??{})}),e.messageHash!==t.messageHash)throw new Error("Message hash mismatch");if(JSON.stringify(e.message)!==JSON.stringify(t.message))throw new Error("Message content mismatch");if(JSON.stringify(e.peers)!==JSON.stringify(t.peers))throw new Error("Peers mismatch");return{...e,promises:{...e.promises,...t.promises},commits:{...e.commits,...t.commits}}}async validateRecord(e){let t=await this.computeMessageHash(e.message);if(t!==e.messageHash)throw new Error(`Message hash mismatch: expected=${t}, received=${e.messageHash}`);if(await this.validateSignatures(e),e.message.expiration&&e.message.expiration<Date.now())throw new Error("Transaction expired")}async computeMessageHash(e){let t=new TextEncoder().encode(JSON.stringify(e)),n=await nn.digest(t);return wd.encode(n.digest)}async validateSignatures(e){let t=await this.computePromiseHash(e);for(let[s,o]of Object.entries(e.promises))if(!await this.verifySignature(s,t,o))throw new Error(`Invalid promise signature from ${s}`);let n=await this.computeCommitHash(e);for(let[s,o]of Object.entries(e.commits))if(!await this.verifySignature(s,n,o))throw new Error(`Invalid commit signature from ${s}`)}async computePromiseHash(e){let t=new TextEncoder().encode(e.messageHash+JSON.stringify(e.message)),n=await nn.digest(t);return P(n.digest,"base64url")}async computeCommitHash(e){let t=new TextEncoder().encode(e.messageHash+JSON.stringify(e.message)+JSON.stringify(e.promises)),n=await nn.digest(t);return P(n.digest,"base64url")}async verifySignature(e,t,n){return!0}async getTransactionPhase(e){let t=Object.keys(e.peers).length,n=Object.keys(e.promises).length,s=Object.keys(e.commits).length,o=this.peerId.toString(),i=Object.values(e.promises).filter(l=>l.type==="reject"),a=Object.values(e.commits).filter(l=>l.type==="reject");if(i.length>0||this.hasMajority(a.length,t))return xt.Rejected;if(!e.promises[o]&&!this.hasConflict(e))return xt.OurPromiseNeeded;if(n<t)return xt.Promising;if(n===t&&!e.commits[o])return xt.OurCommitNeeded;let c=Object.values(e.commits).filter(l=>l.type==="approve");return this.hasMajority(c.length,t)?xt.Consensus:xt.Propagating}hasMajority(e,t){return e>t/2}async handlePromiseNeeded(e){let t=await this.validatePendOperations(e),n=t.valid?{type:"approve",signature:"approved"}:{type:"reject",signature:"rejected",rejectReason:t.reason};return t.valid||ye("cluster-member:validation-rejected",{messageHash:e.messageHash,reason:t.reason}),{...e,promises:{...e.promises,[this.peerId.toString()]:n}}}async validatePendOperations(e){for(let t of e.message.operations)if("pend"in t){let n=t.pend;if(n.rev!==void 0){let s=gs(n.transforms),o=await this.storageRepo.get({blockIds:s});for(let i of s){let c=o[i]?.state?.latest?.rev;if(c!==void 0&&c>=n.rev)return ye("cluster-member:validation-stale-revision",{messageHash:e.messageHash,blockId:i,requestedRev:n.rev,latestRev:c}),{valid:!1,reason:`stale revision: block ${i} at rev ${c}, requested rev ${n.rev}`}}}if(this.validator&&n.transaction&&n.operationsHash){let s=await this.validator.validate(n.transaction,n.operationsHash);if(!s.valid)return{valid:!1,reason:s.reason}}}return{valid:!0}}async handleCommitNeeded(e){if(this.hasLocalCommit(e))return e;let t={type:"approve",signature:"committed"};return{...e,commits:{...e.commits,[this.peerId.toString()]:t}}}async handleConsensus(e){if(this.executedTransactions.has(e.messageHash)){ye("cluster-member:consensus-already-executed",{messageHash:e.messageHash});return}this.executedTransactions.set(e.messageHash,Date.now());try{for(let t of e.message.operations)if("get"in t)await this.storageRepo.get(t.get);else if("pend"in t){let n=await this.storageRepo.pend(t.pend);if(!n.success)throw ye("cluster-member:consensus-pend-failed",{messageHash:e.messageHash,actionId:t.pend.actionId,reason:n.reason,hasMissing:!!n.missing?.length,hasPending:!!n.pending?.length}),new Error(`Consensus pend failed for action ${t.pend.actionId}: ${n.reason??"stale revision"}`)}else if("commit"in t){let n=await this.storageRepo.commit(t.commit);if(!n.success)throw ye("cluster-member:consensus-commit-failed",{messageHash:e.messageHash,actionId:t.commit.actionId,reason:n.reason,hasMissing:!!n.missing?.length}),new Error(`Consensus commit failed for action ${t.commit.actionId}: ${n.reason??"stale revision"}`)}else"cancel"in t&&await this.storageRepo.cancel(t.cancel.actionRef)}catch(t){throw this.executedTransactions.delete(e.messageHash),t}}async handleRejection(e){}setupTimeouts(e){return e.message.expiration?{promiseTimeout:setTimeout(()=>this.handleExpiration(e.messageHash),e.message.expiration-Date.now()),resolutionTimeout:setTimeout(()=>this.resolveWithPeers(e.messageHash),e.message.expiration+5e3-Date.now())}:{}}hasConflict(e){let t=Date.now(),n=2e3,s=this.getAffectedBlockIds(e.message.operations);ye("cluster-member:hasConflict-check",{messageHash:e.messageHash,activeCount:this.activeTransactions.size,incomingBlockIds:s});for(let[o,i]of Array.from(this.activeTransactions.entries())){if(o===e.messageHash)continue;let a=this.getAffectedBlockIds(i.record.message.operations);if(ye("cluster-member:hasConflict-compare",{existing:o,incoming:e.messageHash,existingBlockIds:a,incomingBlockIds:s}),t-i.lastUpdate>n){ye("cluster-member:stale-cleanup",{messageHash:o,age:t-i.lastUpdate}),this.clearTransaction(o);continue}if(this.operationsConflict(i.record.message.operations,e.message.operations)){if(this.resolveRace(i.record,e)==="keep-existing")return ye("cluster-member:race-keep-existing",{existing:o,incoming:e.messageHash}),!0;ye("cluster-member:race-accept-incoming",{existing:o,incoming:e.messageHash}),this.clearTransaction(o);continue}}return!1}resolveRace(e,t){let n=Object.keys(e.promises).length,s=Object.keys(t.promises).length;return n>s?"keep-existing":s>n?"accept-incoming":e.messageHash>t.messageHash?"keep-existing":"accept-incoming"}operationsConflict(e,t){let n=this.getActionId(e),s=this.getActionId(t);if(n&&s&&n===s)return!1;let o=new Set(this.getAffectedBlockIds(e)),i=new Set(this.getAffectedBlockIds(t));for(let a of Array.from(o))if(i.has(a))return ye("cluster-member:conflict-detected",{blocks1:Array.from(o),blocks2:Array.from(i),conflictingBlock:a}),!0;return!1}getActionId(e){for(let t of e){if("pend"in t)return t.pend.actionId;if("commit"in t)return t.commit.actionId;if("cancel"in t)return t.cancel.actionRef.actionId}}getAffectedBlockIds(e){let t=new Set;for(let n of e)"get"in n?n.get.blockIds.forEach(s=>t.add(s)):"pend"in n?gs(n.pend.transforms).forEach(s=>t.add(s)):"commit"in n?n.commit.blockIds.forEach(s=>t.add(s)):"cancel"in n&&n.cancel.actionRef.blockIds.forEach(s=>t.add(s));return Array.from(t)}async propagateIfNeeded(e){let t=[];for(let[n,s]of Object.entries(e.peers))if(n!==this.peerId.toString())try{let o=ro.create(de(n),this.peerNetwork,this.protocolPrefix);t.push(o.update(e))}catch(o){console.error(`Failed to propagate to peer ${n}:`,o)}await Promise.allSettled(t)}async handleExpiration(e){let t=this.activeTransactions.get(e);if(t&&!t.record.promises[this.peerId.toString()]){let n={type:"reject",signature:"rejected",rejectReason:"Transaction expired"},s={...t.record,promises:{...t.record.promises,[this.peerId.toString()]:n}};this.activeTransactions.set(e,{...t,record:s}),await this.propagateIfNeeded(s)}}async resolveWithPeers(e){ye("cluster-member:resolve-skipped",{messageHash:e,reason:"coordinator-handles-retry"})}queueExpiredTransactions(){let e=Date.now();for(let[n,s]of Array.from(this.activeTransactions.entries()))s.record.message.expiration&&s.record.message.expiration<e&&this.cleanupQueue.push(n);let t=e-g9;for(let[n,s]of Array.from(this.executedTransactions.entries()))s<t&&this.executedTransactions.delete(n)}async processCleanupQueue(){for(;this.cleanupQueue.length>0;){let e=this.cleanupQueue.shift();if(!e)continue;let t=this.activeTransactions.get(e);if(!t)continue;let n=await this.getTransactionPhase(t.record);n!==xt.Consensus&&n!==xt.Rejected&&this.activeTransactions.delete(e)}}hasLocalCommit(e){let t=this.peerId.toString();return!!e.commits[t]}clearTransaction(e){let t=this.activeTransactions.get(e);if(!t){ye("cluster-member:clear-miss",{messageHash:e});return}t.promiseTimeout&&clearTimeout(t.promiseTimeout),t.resolutionTimeout&&clearTimeout(t.resolutionTimeout),this.activeTransactions.delete(e),ye("cluster-member:clear-done",{messageHash:e,remaining:Array.from(this.activeTransactions.keys())})}};function Yg(r={}){return e=>new Td(e,r)}var Td=class{protocol;maxInboundStreams;maxOutboundStreams;log;cluster;components;running;k;configuredClusterSize;allowDownsize;sizeTolerance;responsibilityK;constructor(e,t={}){this.components=e,this.protocol=t.protocol??(t.protocolPrefix??"/db-p2p")+"/cluster/1.0.0",this.maxInboundStreams=t.maxInboundStreams??32,this.maxOutboundStreams=t.maxOutboundStreams??64,this.log=e.logger.forComponent(t.logPrefix??"db-p2p:cluster"),this.cluster=e.cluster,this.running=!1,this.k=t.kBucketSize??10,this.configuredClusterSize=t.configuredClusterSize??10,this.allowDownsize=t.allowClusterDownsize??!0,this.sizeTolerance=t.clusterSizeTolerance??.5,this.responsibilityK=t.responsibilityK??1}[Symbol.toStringTag]="@libp2p/cluster";async start(){this.running||(await this.components.registrar.handle(this.protocol,this.handleIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.running=!0)}async stop(){this.running&&(await this.components.registrar.unhandle(this.protocol),this.running=!1)}handleIncomingStream(e,t){let n=t.remotePeer,s=async function*(o){for await(let i of o){let a=new TextDecoder().decode(i.subarray()),c=JSON.parse(a),l;if(c.operation==="update"){let h=c.record?.message?.commit?.tailId??c.record?.message?.pend?Object.keys(c.record.message.pend.transforms)[0]:void 0;l=await this.cluster.update(c.record)}else throw new Error(`Unknown operation: ${c.operation}`);if(c.operation==="update"){let h=l;this.log("cluster-service:pre-serialize",{messageHash:h?.messageHash,responseType:typeof l,hasPromises:"promises"in(h??{}),hasCommits:"commits"in(h??{}),promiseKeys:Object.keys(h?.promises??{}),commitKeys:Object.keys(h?.commits??{}),promiseValues:h?.promises,commitValues:h?.commits})}let u=JSON.stringify(l);if(c.operation==="update"){let h=JSON.parse(u);this.log("cluster-service:post-serialize",{messageHash:h?.messageHash,promiseKeys:Object.keys(h?.promises??{}),commitKeys:Object.keys(h?.commits??{})})}yield new TextEncoder().encode(u)}};(async()=>{try{let o=ht(e,i=>Pr(i),s.bind(this),i=>yr(i));for await(let i of o)e.send(i);await e.close()}catch(o){this.log.error("error handling cluster protocol message from %p - %e",n,o),e.abort(o instanceof Error?o:new Error(String(o)))}})()}};ke();var Xg=class r extends Cn{protocolPrefix;constructor(e,t,n){super(e,t),this.protocolPrefix=n}static create(e,t,n){return new r(e,t,n)}async get(e,t){return this.processRepoMessage([{get:e}],t)}async pend(e,t){return this.processRepoMessage([{pend:e}],t)}async cancel(e,t){return this.processRepoMessage([{cancel:{actionRef:e}}],t)}async commit(e,t){return this.processRepoMessage([{commit:e}],t)}async processRepoMessage(e,t,n=0){let s={operations:e,expiration:t.expiration},o=t.expiration??Date.now()+3e4,i=Math.max(1,o-Date.now()),a=async u=>await Promise.race([u(),new Promise((h,p)=>setTimeout(()=>p(new Error("RepoClient timeout")),i))]),c,l=(this.protocolPrefix??"/db-p2p")+"/repo/1.0.0";if(c=await a(()=>super.processMessage(s,l,{signal:t?.signal})),c?.redirect?.peers?.length){if(n>=2)throw new Error("Redirect loop detected in RepoClient (max hops reached)");let u=this.peerId.toString(),h=c.redirect.peers.find(d=>d.id!==u)??c.redirect.peers[0],p=de(h.id);if(h.id===u)throw new Error("Redirect loop detected in RepoClient (same peer)");return this.recordCoordinatorForOpsIfSupported(e,p),await r.create(p,this.peerNetwork,this.protocolPrefix).processRepoMessage(e,t,n+1)}return c}extractKeyFromOperations(e){let t=e[0];if("get"in t){let n=t.get.blockIds[0];return n?new TextEncoder().encode(n):void 0}if("pend"in t){let n=Object.keys(t.pend.transforms)[0];return n?new TextEncoder().encode(n):void 0}if("commit"in t)return new TextEncoder().encode(t.commit.tailId)}recordCoordinatorForOpsIfSupported(e,t){let n=this.extractKeyFromOperations(e),s=this.peerNetwork;n!=null&&typeof s?.recordCoordinator=="function"&&s.recordCoordinator(n,t)}};ke();var re=Sr("cluster"),ml=class{keyNetwork;createClusterClient;cfg;localCluster;fretService;transactions=new Map;retryInitialIntervalMs=2e3;retryBackoffFactor=2;retryMaxIntervalMs=3e4;retryMaxAttempts=5;constructor(e,t,n,s,o){this.keyNetwork=e,this.createClusterClient=t,this.cfg=n,this.localCluster=s,this.fretService=o}async createMessageHash(e){let t=new TextEncoder().encode(JSON.stringify(e)),n=await nn.digest(t);return wd.encode(n.digest)}async getClusterForBlock(e){let t=new TextEncoder().encode(e);try{let n=await this.keyNetwork.findCluster(t),s=Object.keys(n??{});return re("cluster-tx:cluster-members",{blockId:e,peerIds:s}),n}catch(n){return re("WARN findCluster failed for %s: %o",e,n),{}}}makeRecord(e,t,n){let s=Object.keys(e??{}).length,o={messageHash:t,peers:e,message:n,coordinatingBlockIds:n.coordinatingBlockIds,promises:{},commits:{},suggestedClusterSize:s||void 0,minRequiredSize:this.cfg.allowClusterDownsize?void 0:this.cfg.clusterSize};if(this.fretService)try{let i=this.fretService.getNetworkSizeEstimate();i.size_estimate>0&&(o.networkSizeHint=i.size_estimate,o.networkSizeConfidence=i.confidence)}catch{}return o}async executeClusterTransaction(e,t,n){let s=await this.getClusterForBlock(e),o=await this.createMessageHash(t),i=this.makeRecord(s,o,t);re("cluster-tx:start",{messageHash:o,blockId:e,peerCount:Object.keys(s??{}).length,allowDownsize:this.cfg.allowClusterDownsize,configuredSize:this.cfg.clusterSize,suggestedSize:i.suggestedClusterSize,minRequiredSize:i.minRequiredSize});let a=this.executeTransaction(s,i),c=new so(a),l={messageHash:o,record:i,pending:c,lastUpdate:Date.now()};this.transactions.set(o,l),re("cluster-tx:transaction-store",{messageHash:o,transactionKeys:Array.from(this.transactions.keys())});try{let u=await c.result(),h=this.localCluster?.wasTransactionExecuted?.(o)??!1;return{record:u,localExecuted:h}}finally{let u=this.transactions.get(o),h=u?.retry?{attempt:u.retry.attempt,pending:Array.from(u.retry.pendingPeers??[])}:void 0;re("cluster-tx:complete",{messageHash:o,finalPromises:u?Object.keys(u.record.promises??{}):void 0,finalCommits:u?Object.keys(u.record.commits??{}):void 0,retry:h}),u?.retry||setTimeout(()=>{this.transactions.delete(o),re("cluster-tx:transaction-remove",{messageHash:o,remaining:Array.from(this.transactions.keys())})},100)}}async executeTransaction(e,t){let n=Object.keys(e).length;if(n<this.cfg.minAbsoluteClusterSize){if(!await this.validateSmallCluster(n,e))throw re("cluster-tx:reject-too-small",{peerCount:n,minRequired:this.cfg.minAbsoluteClusterSize}),new Error(`Cluster size ${n} below minimum ${this.cfg.minAbsoluteClusterSize} and not validated`);re("cluster-tx:small-cluster-validated",{peerCount:n})}if(!this.cfg.allowClusterDownsize&&n<this.cfg.clusterSize)throw re("cluster-tx:reject-downsize",{peerCount:n,required:this.cfg.clusterSize}),new Error(`Cluster size ${n} below configured minimum ${this.cfg.clusterSize}`);let s=await this.collectPromises(e,t),o=Math.ceil(n*this.cfg.superMajorityThreshold),i=s.record.promises,a=Object.values(i).filter(u=>u.type==="approve").length,c=Object.values(i).filter(u=>u.type==="reject").length,l=n-o;if(c>l){let u=Object.entries(i).filter(([h,p])=>p.type==="reject").map(([h,p])=>`${h}: ${p.rejectReason??"unknown"}`).join("; ");throw re("cluster-tx:rejected-by-validators",{messageHash:t.messageHash,peerCount:n,rejections:c,maxAllowed:l,reasons:u}),this.updateTransactionRecord(s.record,"rejected-by-validators"),new Error(`Transaction rejected by validators (${c}/${n} rejected): ${u}`)}if(n>1&&a<o)throw re("cluster-tx:supermajority-failed",{messageHash:t.messageHash,peerCount:n,approvals:a,rejections:c,superMajority:o,threshold:this.cfg.superMajorityThreshold}),this.updateTransactionRecord(s.record,"supermajority-failed"),new Error(`Failed to get super-majority: ${a}/${n} approvals (needed ${o}, ${c} rejections)`);return await this.commitTransaction(s.record)}async getClusterSize(e){let t=await this.getClusterForBlock(e);return Object.keys(t??{}).length}async validateSmallCluster(e,t){if(this.fretService)try{let n=this.fretService.getNetworkSizeEstimate();if(n.confidence>.5){let s=Math.floor(Math.log10(n.size_estimate+1)),o=Math.floor(Math.log10(e+1));if(Math.abs(s-o)<=1)return re("cluster-tx:small-cluster-validated-by-fret",{localSize:e,fretEstimate:n.size_estimate,confidence:n.confidence,sources:n.sources}),!0}}catch{}return re("cluster-tx:small-cluster-accepted-without-validation",{localSize:e,reason:"no-confident-network-size-estimate"}),!0}async collectPromises(e,t){let n=Object.keys(e),s=[],o=n.map(l=>{let u=this.localCluster&&l===this.localCluster.peerId.toString();re("cluster-tx:promise-request",{messageHash:t.messageHash,peerId:l,isLocal:u});let h=u?this.localCluster.update(t):this.createClusterClient(de(l)).update(t);return new so(h)}),i=await Promise.all(o.map((l,u)=>l.result().then(h=>{let p=n[u];return re("cluster-tx:promise-response",{messageHash:t.messageHash,peerId:p,success:!0,returnedPromises:Object.keys(h.promises??{}),returnedCommits:Object.keys(h.commits??{})}),s.push({peerId:p,success:!0}),h}).catch(h=>{let p=n[u];return re("cluster-tx:promise-response",{messageHash:t.messageHash,peerId:p,success:!1,error:h}),s.push({peerId:p,success:!1,error:h instanceof Error?h.message:String(h)}),null}))),a=s.filter(l=>l.success).map(l=>l.peerId),c=s.filter(l=>!l.success);re("cluster-tx:promise-summary",{messageHash:t.messageHash,successes:a,failures:c}),re("cluster-tx:promise-merge-begin",{messageHash:t.messageHash,initialPromises:Object.keys(t.promises??{}),transactionsKeys:Array.from(this.transactions.keys()),hasTransaction:this.transactions.has(t.messageHash)});for(let l of i.filter(Boolean)){re("cluster-tx:promise-merge-input",{messageHash:t.messageHash,resultFrom:Object.keys(l.promises??{}),recordBefore:Object.keys(t.promises??{})});let u=Object.keys(l.promises??{});if(re("cluster-tx:promise-merge-result",{messageHash:t.messageHash,peerPromises:u}),typeof t.suggestedClusterSize=="number"&&typeof l.suggestedClusterSize=="number"){let h=l.suggestedClusterSize,p=Object.keys(e).length,f=Math.ceil(Math.max(1,h*this.cfg.clusterSizeTolerance));Math.abs(p-h)>f&&re("cluster-tx:size-variance",{expected:h,actual:p,tolerance:this.cfg.clusterSizeTolerance})}t.promises={...t.promises,...l.promises},re("cluster-tx:promise-merge-after",{messageHash:t.messageHash,mergedPromises:Object.keys(t.promises??{})})}return re("cluster-tx:promise-merge",{messageHash:t.messageHash,mergedPromises:Object.keys(t.promises??{})}),re("cluster-tx:promise-merge-end",{messageHash:t.messageHash,finalPromises:Object.keys(t.promises??{}),transactionsEntry:this.transactions.get(t.messageHash)}),this.updateTransactionRecord(t,"after-promises"),{record:t}}async commitTransaction(e){let t=Object.keys(e.peers),n=[],s={...e},o=t.map(f=>{let d=this.localCluster&&f===this.localCluster.peerId.toString();re("cluster-tx:commit-request",{messageHash:e.messageHash,peerId:f,isLocal:d});let m=d?this.localCluster.update(s):this.createClusterClient(de(f)).update(s);return new so(m)}),i=await Promise.all(o.map((f,d)=>f.result().then(m=>{let g=t[d];return re("cluster-tx:commit-response",{messageHash:e.messageHash,peerId:g,success:!0}),n.push({peerId:g,success:!0}),m}).catch(m=>{let g=t[d];return re("cluster-tx:commit-response",{messageHash:e.messageHash,peerId:g,success:!1,error:m}),n.push({peerId:g,success:!1,error:m instanceof Error?m.message:String(m)}),null}))),a=n.filter(f=>f.success).map(f=>f.peerId),c=n.filter(f=>!f.success);re("cluster-tx:commit-summary",{messageHash:e.messageHash,successes:a,failures:c}),re("cluster-tx:commit-merge-begin",{messageHash:e.messageHash,initialCommits:Object.keys(e.commits??{}),transactionsEntry:this.transactions.get(e.messageHash)});for(let f of i.filter(Boolean))re("cluster-tx:commit-merge-input",{messageHash:e.messageHash,resultFrom:Object.keys(f.commits??{}),recordBefore:Object.keys(e.commits??{})}),re("cluster-tx:commit-merge-result",{messageHash:e.messageHash,peerCommits:Object.keys(f.commits??{})}),e.commits={...e.commits,...f.commits},re("cluster-tx:commit-merge-after",{messageHash:e.messageHash,mergedCommits:Object.keys(e.commits??{})});re("cluster-tx:commit-merge",{messageHash:e.messageHash,mergedCommits:Object.keys(e.commits??{})}),re("cluster-tx:commit-merge-end",{messageHash:e.messageHash,finalCommits:Object.keys(e.commits??{}),transactionsEntry:this.transactions.get(e.messageHash)}),this.updateTransactionRecord(e,"after-commit");let l=Object.keys(e.peers).length,u=Math.floor(l*this.cfg.simpleMajorityThreshold)+1,h=Object.keys(e.commits).length;if(h>=u&&(re("cluster-tx:commit-majority-reached",{messageHash:e.messageHash,commitCount:h,simpleMajority:u,peerCount:l,threshold:this.cfg.simpleMajorityThreshold}),this.localCluster))try{await this.localCluster.update(e)}catch(f){re("cluster-tx:local-execution-error",{messageHash:e.messageHash,error:f instanceof Error?f.message:String(f)})}let p=c.map(f=>f.peerId);return p.length>0?this.scheduleCommitRetry(e.messageHash,e,p):this.clearRetry(e.messageHash),e}updateTransactionRecord(e,t){let n=this.transactions.get(e.messageHash);if(!n){re("cluster-tx:transaction-update-miss",{messageHash:e.messageHash,stage:t});return}n.record={...e},n.lastUpdate=Date.now(),re("cluster-tx:transaction-update",{messageHash:e.messageHash,stage:t,promises:Object.keys(e.promises??{}),commits:Object.keys(e.commits??{})})}scheduleCommitRetry(e,t,n){let s=this.transactions.get(e);if(!s)return;let o=s.retry,i=(o?.attempt??0)+1;if(i>this.retryMaxAttempts){re("cluster-tx:retry-abort",{messageHash:e,missingPeers:n});return}if(n.length===0){this.clearRetry(e);return}let a=new Set(n),c=o?Math.min(o.intervalMs*this.retryBackoffFactor,this.retryMaxIntervalMs):this.retryInitialIntervalMs;o?.timer&&clearTimeout(o.timer);let l=setTimeout(()=>{this.retryCommits(e)},c);s.retry={pendingPeers:a,attempt:i,intervalMs:c,timer:l},re("cluster-tx:retry-scheduled",{messageHash:e,attempt:i,missingPeers:n,delayMs:c})}async retryCommits(e){let t=this.transactions.get(e);if(!t?.retry)return;let{pendingPeers:n,attempt:s}=t.retry;if(n.size===0){this.clearRetry(e);return}let o=Array.from(n),i=t.record;re("cluster-tx:retry-start",{messageHash:e,attempt:s,peerIds:o});let a=await Promise.all(o.map(async u=>{let h=this.localCluster&&u===this.localCluster.peerId.toString(),p={...i,commits:i.commits};try{let f=h?await this.localCluster.update(p):await this.createClusterClient(de(u)).update(p);return t.record.commits={...t.record.commits,...f.commits},{peerId:u,success:!0}}catch(f){return{peerId:u,success:!1,error:f instanceof Error?f.message:String(f)}}})),c=a.filter(u=>u.success).map(u=>u.peerId),l=a.filter(u=>!u.success);for(let u of c)n.delete(u);if(re("cluster-tx:retry-complete",{messageHash:e,attempt:s,successes:c,failures:l}),n.size===0){re("cluster-tx:retry-finished",{messageHash:e}),this.clearRetry(e);return}this.transactions.has(e)&&this.scheduleCommitRetry(e,t.record,Array.from(n))}clearRetry(e){let t=this.transactions.get(e);t?.retry&&(t.retry.timer&&clearTimeout(t.retry.timer),t.retry=void 0,setTimeout(()=>{this.transactions.delete(e),re("cluster-tx:transaction-remove",{messageHash:e,remaining:Array.from(this.transactions.keys())})},100))}};ke();var io=Sr("coordinator-repo");function Qg(r,e,t,n){return s=>new _d(r,e,s.storageRepo,t,s.localCluster,s.localPeerId,n,s.clusterLatestCallback)}var _d=class{keyNetwork;createClusterClient;storageRepo;clusterLatestCallback;coordinator;DEFAULT_TIMEOUT=3e4;constructor(e,t,n,s,o,i,a,c){this.keyNetwork=e,this.createClusterClient=t,this.storageRepo=n,this.clusterLatestCallback=c;let l={clusterSize:s?.clusterSize??10,superMajorityThreshold:s?.superMajorityThreshold??.75,simpleMajorityThreshold:s?.simpleMajorityThreshold??.51,minAbsoluteClusterSize:s?.minAbsoluteClusterSize??3,allowClusterDownsize:s?.allowClusterDownsize??!0,clusterSizeTolerance:s?.clusterSizeTolerance??.5,partitionDetectionWindow:s?.partitionDetectionWindow??6e4},u=o&&i?{update:o.update.bind(o),peerId:i,wasTransactionExecuted:o.wasTransactionExecuted?.bind(o)}:void 0;this.coordinator=new ml(e,t,l,u,a)}async get(e,t){let n=await this.storageRepo.get(e,t),s=t?.skipClusterFetch;if(this.clusterLatestCallback&&!s){for(let o of e.blockIds)if(!n[o]?.state?.latest)try{await this.fetchBlockFromCluster(o);let a=await this.storageRepo.get({blockIds:[o],context:e.context},t);a[o]&&(n[o]=a[o])}catch(a){io("cluster-fetch:error",{blockId:o,error:a.message})}}return n}async fetchBlockFromCluster(e){if(!this.clusterLatestCallback)return;let t=await this.queryClusterForLatest(e);t&&(await this.storageRepo.get({blockIds:[e],context:{committed:[t],rev:t.rev}}),io("cluster-fetch:synced",{blockId:e,rev:t.rev}))}async queryClusterForLatest(e){let t=new TextEncoder().encode(e),n=await this.keyNetwork.findCluster(t);if(!n||Object.keys(n).length===0)return;let s=Object.keys(n),o,i=(c,l)=>Promise.race([c,new Promise(u=>setTimeout(()=>u(void 0),l))]),a=await Promise.allSettled(s.map(c=>{let l=de(c);return i(this.clusterLatestCallback(l,e),3e3)}));for(let c of a)if(c.status==="fulfilled"&&c.value){let l=c.value;(!o||l.rev>o.rev)&&(o=l)}return o}async pend(e,t){let n=Object.keys(e.transforms),s=t?.coordinatingBlockIds??n;if(await this.coordinator.getClusterSize(s[0])<=1)return await this.storageRepo.pend(e,t);let i={operations:[{pend:e}],expiration:t?.expiration??Date.now()+this.DEFAULT_TIMEOUT,coordinatingBlockIds:s};try{let{localExecuted:a}=await this.coordinator.executeClusterTransaction(s[0],i,t);if(io("coordinator-repo:pend-cluster-complete",{actionId:e.actionId,localExecuted:a}),!a){let c=await this.storageRepo.pend(e,t);return io("coordinator-repo:pend-fallback-result",{actionId:e.actionId,success:c.success,hasMissing:!!c.missing?.length,hasPending:!!c.pending?.length}),c}return{success:!0,pending:[],blockIds:Object.keys(e.transforms)}}catch(a){throw io("coordinator-repo:pend-error",{actionId:e.actionId,error:a.message}),a}}async cancel(e,t){let n=e.blockIds,s={operations:[{cancel:{actionRef:e}}],expiration:t?.expiration??Date.now()+this.DEFAULT_TIMEOUT};try{let o=n.map(c=>this.coordinator.executeClusterTransaction(c,s,t));(await Promise.all(o)).some(c=>c.localExecuted)||await this.storageRepo.cancel(e,t)}catch(o){throw io("coordinator-repo:cancel-error",{actionId:e.actionId,error:o.message}),o}}async commit(e,t){let n=e.blockIds;if(await this.coordinator.getClusterSize(n[0])<=1)return await this.storageRepo.commit(e,t);let o={operations:[{commit:e}],expiration:t?.expiration??Date.now()+this.DEFAULT_TIMEOUT};try{let{localExecuted:i}=await this.coordinator.executeClusterTransaction(n[0],o,t);return i?{success:!0}:await this.storageRepo.commit(e,t)}catch(i){throw io("coordinator-repo:commit-error",{actionId:e.actionId,error:i.message}),i}}};function BS(r){try{if(r==null)return null;if(typeof r?.toString=="function")return r.toString();let e=r.id;return e&&typeof e.toString=="function"?e.toString():typeof e=="string"?e:typeof r=="string"?r:null}catch{return null}}function ao(r,e){let t=BS(r),n=BS(e);return t!=null&&n!=null&&t===n}function Pd(r){return{redirect:{peers:r,reason:"not_in_cluster"}}}function Jg(r={}){return e=>new Dd(e,r)}var Dd=class{protocol;maxInboundStreams;maxOutboundStreams;log;repo;components;running;k;responsibilityK;constructor(e,t={}){this.components=e;let n=t.protocol??(t.protocolPrefix??"/db-p2p")+"/repo/1.0.0";this.protocol=n,this.maxInboundStreams=t.maxInboundStreams??32,this.maxOutboundStreams=t.maxOutboundStreams??64,this.log=e.logger.forComponent(t.logPrefix??"db-p2p:repo-service"),this.repo=e.repo,this.running=!1,this.k=t.kBucketSize??10,this.responsibilityK=t.responsibilityK??1}[Symbol.toStringTag]="@libp2p/repo-service";async start(){this.running||(await this.components.registrar.handle(this.protocol,this.handleIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.running=!0)}async stop(){this.running&&(await this.components.registrar.unhandle(this.protocol),this.running=!1)}handleIncomingStream(e,t){let n=t.remotePeer,s=async function*(o){for await(let i of o){let a=new TextDecoder().decode(i.subarray()),c=JSON.parse(a),l=c.operations[0],u;if("get"in l){let p=(await nn.digest(new TextEncoder().encode(l.get.blockIds[0]))).digest,f=this.components.libp2p?.services?.networkManager;if(f?.getCluster){let d=await f.getCluster(p);c.cluster=d.map(b=>b.toString?.()??String(b));let m=this.components.libp2p.peerId,g=d.some(b=>ao(b,m));if(!(d.length<this.responsibilityK)&&!g){let b=d.filter(w=>!ao(w,m));console.debug("repo-service:redirect",{peerId:m.toString(),reason:"not-cluster-member",operation:"get",blockId:l.get.blockIds[0],cluster:d.map(w=>w.toString?.()??String(w))}),u=Pd(b.map(w=>({id:w.toString(),addrs:[]})))}else u=await this.repo.get(l.get,{expiration:c.expiration,skipClusterFetch:!0})}else u=await this.repo.get(l.get,{expiration:c.expiration,skipClusterFetch:!0})}else if("pend"in l){let h=Object.keys(l.pend.transforms)[0],f=(await nn.digest(new TextEncoder().encode(h))).digest,d=this.components.libp2p?.services?.networkManager;if(d?.getCluster){let m=await d.getCluster(f);c.cluster=m.map(w=>w.toString?.()??String(w));let g=this.components.libp2p.peerId,y=m.some(w=>ao(w,g));if(!(m.length<this.responsibilityK)&&!y){let w=m.filter(x=>!ao(x,g));console.debug("repo-service:redirect",{peerId:g.toString(),reason:"not-cluster-member",operation:"pend",blockId:h,cluster:m.map(x=>x.toString?.()??String(x))}),u=Pd(w.map(x=>({id:x.toString(),addrs:[]})))}else u=await this.repo.pend(l.pend,{expiration:c.expiration})}else u=await this.repo.pend(l.pend,{expiration:c.expiration})}else if("cancel"in l)u=await this.repo.cancel(l.cancel.actionRef,{expiration:c.expiration});else if("commit"in l){let p=(await nn.digest(new TextEncoder().encode(l.commit.tailId))).digest,f=this.components.libp2p?.services?.networkManager;if(f?.getCluster){let d=await f.getCluster(p);c.cluster=d.map(b=>b.toString?.()??String(b));let m=this.components.libp2p.peerId,g=d.some(b=>ao(b,m));if(!(d.length<this.responsibilityK)&&!g){let b=d.filter(w=>!ao(w,m));console.debug("repo-service:redirect",{peerId:m.toString(),reason:"not-cluster-member",operation:"commit",tailId:l.commit.tailId,cluster:d.map(w=>w.toString?.()??String(w))}),u=Pd(b.map(w=>({id:w.toString(),addrs:[]})))}else u=await this.repo.commit(l.commit,{expiration:c.expiration})}else u=await this.repo.commit(l.commit,{expiration:c.expiration})}yield new TextEncoder().encode(JSON.stringify(u))}};(async()=>{try{let o=ht(e,i=>Pr(i),s.bind(this),i=>yr(i));for await(let i of o)e.send(i);await e.close()}catch(o){this.log.error("error handling repo protocol message from %p - %e",n,o),e.abort(o instanceof Error?o:new Error(String(o)))}})()}};function US(r){if(r.length<=1)return r;r.sort((t,n)=>t[0]-n[0]);let e=[r[0]];for(let t of r.slice(1)){let n=e[e.length-1];n[1]!==void 0&&(t[0]<=n[1]?t[1]===void 0?n[1]=void 0:n[1]=Math.max(n[1],t[1]):e.push(t))}return e}var Bi=class{blockId;storage;restoreCallback;constructor(e,t,n){this.blockId=e,this.storage=t,this.restoreCallback=n}async getLatest(){return(await this.storage.getMetadata(this.blockId))?.latest}async getBlock(e){let t=await this.storage.getMetadata(this.blockId);if(!t)return;let n=e??t.latest?.rev;if(n===void 0)throw new Error(`No revision specified and no latest revision exists for block ${this.blockId}`);return await this.ensureRevision(t,n),await this.materializeBlock(t,n)}async getTransaction(e){return await this.storage.getTransaction(this.blockId,e)}async getPendingTransaction(e){return await this.storage.getPendingTransaction(this.blockId,e)}async*listPendingTransactions(){yield*this.storage.listPendingTransactions(this.blockId)}async savePendingTransaction(e,t){let n=await this.storage.getMetadata(this.blockId);n||(n={latest:void 0,ranges:[[0]]},await this.storage.saveMetadata(this.blockId,n)),await this.storage.savePendingTransaction(this.blockId,e,t)}async deletePendingTransaction(e){await this.storage.deletePendingTransaction(this.blockId,e)}async*listRevisions(e,t){yield*this.storage.listRevisions(this.blockId,e,t)}async saveMaterializedBlock(e,t){await this.storage.saveMaterializedBlock(this.blockId,e,t)}async saveRevision(e,t){await this.storage.saveRevision(this.blockId,e,t)}async promotePendingTransaction(e){await this.storage.promotePendingTransaction(this.blockId,e)}async setLatest(e){let t=await this.storage.getMetadata(this.blockId);if(!t)throw new Error(`Block ${this.blockId} not found`);t.latest=e,await this.storage.saveMetadata(this.blockId,t)}async ensureRevision(e,t){if(this.inRanges(t,e.ranges))return;let n=`BlockStorage.ensureRevision:${this.blockId}`,s=await no.acquire(n);try{let o=await this.storage.getMetadata(this.blockId);if(!o)throw new Error(`Block ${this.blockId} metadata disappeared unexpectedly.`);if(this.inRanges(t,o.ranges))return;let i=await this.restoreBlock(t);if(!i)throw new Error(`Block ${this.blockId} revision ${t} not found during restore attempt.`);await this.saveRestored(i),o.ranges.unshift(i.range),o.ranges=US(o.ranges),await this.storage.saveMetadata(this.blockId,o)}finally{s()}}async materializeBlock(e,t){let n,s,o=[];for await(let i of this.storage.listRevisions(this.blockId,t,1)){let a=await this.storage.getMaterializedBlock(this.blockId,i.actionId);if(a){n=a,s=i;break}else o.push(i)}if(!n||!s)throw new Error(`Failed to find materialized block ${this.blockId} for revision ${t}`);for(let i=o.length-1;i>=0;--i){let{actionId:a}=o[i],c=await this.storage.getTransaction(this.blockId,a);if(!c)throw new Error(`Missing action ${a} for block ${this.blockId}`);n=cl(n,c)}if(!n)throw new Error(`Block ${this.blockId} has been deleted`);return o.length?(await this.storage.saveMaterializedBlock(this.blockId,o[0].actionId,n),{block:n,actionRev:o[0]}):{block:n,actionRev:s}}async restoreBlock(e){if(this.restoreCallback)return await this.restoreCallback(this.blockId,e)}async saveRestored(e){let t=Object.entries(e.revisions).map(([n,s])=>({rev:Number(n),data:s}));for(let{rev:n,data:{action:s,block:o}}of t)await Promise.all([this.storage.saveRevision(this.blockId,n,s.actionId),this.storage.saveTransaction(this.blockId,s.actionId,s.transform),o?this.storage.saveMaterializedBlock(this.blockId,s.actionId,o):Promise.resolve()])}inRanges(e,t){return t.some(n=>e>=n[0]&&(n[1]===void 0||e<n[1]))}};var gl=class{metadata=new Map;revisions=new Map;pendingActions=new Map;actions=new Map;materializedBlocks=new Map;getRevisionKey(e,t){return`${e}:${t}`}getActionKey(e,t){return`${e}:${t}`}async getMetadata(e){return this.metadata.get(e)}async saveMetadata(e,t){this.metadata.set(e,t)}async getRevision(e,t){return this.revisions.get(this.getRevisionKey(e,t))}async saveRevision(e,t,n){this.revisions.set(this.getRevisionKey(e,t),n)}async*listRevisions(e,t,n){let s=t<=n,o=s?t:n,i=s?n:t,a=[];for(let c=o;c<=i;c++){let l=this.revisions.get(this.getRevisionKey(e,c));l&&a.push({rev:c,actionId:l})}s||a.reverse();for(let c of a)yield c}async getPendingTransaction(e,t){return this.pendingActions.get(this.getActionKey(e,t))}async savePendingTransaction(e,t,n){this.pendingActions.set(this.getActionKey(e,t),structuredClone(n))}async deletePendingTransaction(e,t){this.pendingActions.delete(this.getActionKey(e,t))}async*listPendingTransactions(e){let t=`${e}:`;for(let[n]of Array.from(this.pendingActions.entries()))n.startsWith(t)&&(yield n.substring(t.length))}async getTransaction(e,t){return this.actions.get(this.getActionKey(e,t))}async saveTransaction(e,t,n){this.actions.set(this.getActionKey(e,t),n)}async getMaterializedBlock(e,t){let n=this.materializedBlocks.get(this.getActionKey(e,t));return n?structuredClone(n):void 0}async saveMaterializedBlock(e,t,n){let s=this.getActionKey(e,t);n?this.materializedBlocks.set(s,structuredClone(n)):this.materializedBlocks.delete(s)}async promotePendingTransaction(e,t){let n=this.getActionKey(e,t),s=this.pendingActions.get(n);s&&(this.actions.set(n,s),this.pendingActions.delete(n))}};var yl=class{createBlockStorage;validatePend;constructor(e,t){this.createBlockStorage=e,this.validatePend=t?.validatePend}async get({blockIds:e,context:t},n){let s=Array.from(new Set(e)),o=await Promise.all(s.map(async i=>{let a=this.createBlockStorage(i);if(t){let u=await a.getLatest(),h=u?t.committed.filter(p=>p.rev>u.rev):t.committed;for(let{actionId:p,rev:f}of h.sort((d,m)=>d.rev-m.rev))await a.getPendingTransaction(p)&&await this.internalCommit(i,p,f,a)}let c=await a.getBlock(t?.rev);if(!c)return[i,{state:{}}];if(t?.actionId!==void 0){let u=await a.getPendingTransaction(t.actionId);if(!u)throw new Error(`Pending action ${t.actionId} not found`);let h=cl(c.block,u);return[i,{block:h,state:{latest:await a.getLatest(),pendings:[t.actionId]}}]}let l=await uc(a.listPendingTransactions());return[i,{block:c.block,state:{latest:await a.getLatest(),pendings:l}}]}));return Object.fromEntries(o)}async pend(e,t){if(this.validatePend&&e.transaction&&e.operationsHash){let i=await this.validatePend(e.transaction,e.operationsHash);if(!i.valid)return{success:!1,reason:i.reason??"Transaction validation failed"}}let n=gs(e.transforms),s=[],o=[];for(let i of n){let a=this.createBlockStorage(i),c=md(e.transforms,i),l=await uc(a.listPendingTransactions());if(s.push(...l.map(u=>({blockId:i,actionId:u}))),e.rev!==void 0||c.insert){let u=await a.getLatest();if(u&&u.rev>=(e.rev??0)){let h=await uc(a.listRevisions(e.rev??0,u.rev));for(let p of h){let f=await a.getTransaction(p.actionId);if(!f)throw new Error(`Missing action ${p.actionId} for block ${i}`);o.push({actionId:p.actionId,rev:p.rev,transforms:j2(f,i)})}}}}if(o.length)return{success:!1,missing:o};if(s.length>0){if(e.policy==="f")return{success:!1,pending:s};if(e.policy==="r")return{success:!1,pending:await Promise.all(s.map(async i=>{let a=this.createBlockStorage(i.blockId);return{blockId:i.blockId,actionId:i.actionId,transform:await a.getPendingTransaction(i.actionId)??await a.getTransaction(i.actionId)}}))}}return await Promise.all(n.map(i=>{let a=this.createBlockStorage(i),c=md(e.transforms,i);return a.savePendingTransaction(e.actionId,c)})),{success:!0,pending:s,blockIds:n}}async cancel(e,t){await Promise.all(e.blockIds.map(n=>this.createBlockStorage(n).deletePendingTransaction(e.actionId)))}async commit(e,t){let n=Array.from(new Set(e.blockIds)).sort(),s=[];try{for(let c of n){let l=`StorageRepo.commit:${c}`,u=await no.acquire(l);s.push(u)}let o=e.blockIds.map(c=>({blockId:c,storage:this.createBlockStorage(c)})),i=[];for(let{blockId:c,storage:l}of o){let u=await l.getLatest();if(u&&u.rev>=e.rev){let h=[];for await(let p of l.listRevisions(e.rev,u.rev)){let f=await l.getTransaction(p.actionId);if(!f)throw new Error(`Missing action ${p.actionId} for block ${c}`);h.push({actionId:p.actionId,rev:p.rev,transform:f})}i.push({blockId:c,transforms:h})}}if(i.length)return{success:!1,missing:y9(i)};let a=[];for(let{blockId:c,storage:l}of o)await l.getPendingTransaction(e.actionId)||a.push({blockId:c,actionId:e.actionId});if(a.length)throw new Error(`Pending action ${e.actionId} not found for block(s): ${a.map(c=>c.blockId).join(", ")}`);for(let{blockId:c,storage:l}of o)try{await this.internalCommit(c,e.actionId,e.rev,l)}catch(u){return{success:!1,reason:u instanceof Error?u.message:"Unknown error during commit"}}}finally{s.reverse().forEach(o=>o())}return{success:!0}}async internalCommit(e,t,n,s){let o=await s.getPendingTransaction(t);if(!o)throw new Error(`Consistency Error: Pending action ${t} disappeared for block ${e} within critical section.`);let i=await s.getLatest(),a=i?(await s.getBlock(i.rev))?.block:void 0,c=cl(a,o);c&&await s.saveMaterializedBlock(t,c),await s.saveRevision(n,t),await s.promotePendingTransaction(t),await s.setLatest({actionId:t,rev:n})}};function y9(r){let e=r.flatMap(({blockId:n,transforms:s})=>s.map(o=>({blockId:n,transform:o}))),t=_g(e,({transform:n})=>n.actionId);return Object.entries(t).map(([n,s])=>s.reduce((o,{blockId:i,transform:a})=>(Y2(o.transforms,i,a.transform),o),{actionId:n,rev:s[0].transform.rev,transforms:W2()}))}var sn=class{entries;constructor(e){this.entries=e}},bl=class{partitions;nodes;constructor(e,t){this.partitions=e,this.nodes=t}};var Rn=class r{node;index;constructor(e,t){this.node=e,this.index=t}clone(){return new r(this.node,this.index)}},Ui=class r{branches;leafNode;leafIndex;on;version;constructor(e,t,n,s,o){this.branches=e,this.leafNode=t,this.leafIndex=n,this.on=s,this.version=o}isEqual(e){return this.leafNode===e.leafNode&&this.leafIndex===e.leafIndex&&this.on===e.on&&this.version===e.version}clone(){return new r(this.branches.map(e=>e.clone()),this.leafNode,this.leafIndex,this.on,this.version)}};var Ir=64,kd=class{keyFromEntry;compare;_root;_version=0;constructor(e=n=>n,t=(n,s)=>n<s?-1:n>s?1:0){this.keyFromEntry=e,this.compare=t,this._root=new sn([])}first(){return this.getFirst(this._root)}last(){return this.getLast(this._root)}find(e){return this.getPath(this._root,e)}get(e){return this.at(this.find(e))}at(e){return this.validatePath(e),e.on?e.leafNode.entries[e.leafIndex]:void 0}*range(e){let t=e.first?this.findFirst(e):e.isAscending?this.first():this.last(),n=e.last?this.findLast(e):e.isAscending?this.last():this.first(),s=this.keyFromEntry(n.leafNode.entries[n.leafIndex]),o=e.isAscending?this.internalAscending(t):this.internalDescending(t),i=e.isAscending?1:-1;for(let a of o){if(!a.on||!n.on||this.compareKeys(this.keyFromEntry(a.leafNode.entries[a.leafIndex]),s)*i>0)break;yield a}}isValid(e){return e.version===this._version}insert(e){Object.freeze(e);let t=this.internalInsert(e);return t.on&&(t.version=++this._version),t}updateAt(e,t){this.validatePath(e),e.on&&Object.freeze(t);let n=this.internalUpdate(e,t);return n[0].on&&(n[0].version=++this._version),n}upsert(e){let t=this.find(this.keyFromEntry(e));return Object.freeze(e),t.on?t.leafNode.entries[t.leafIndex]=e:this.internalInsertAt(t,e),t.version=++this._version,t}merge(e,t){let n=this.keyFromEntry(e),s=this.find(n);if(s.on){let o=this.updateAt(s,t(s.leafNode.entries[s.leafIndex]));return o[0].on&&(o[0].version=++this._version),o}else return this.internalInsertAt(s,Object.freeze(e)),s.on=!0,s.version=++this._version,[s,!1]}deleteAt(e){this.validatePath(e);let t=this.internalDelete(e);return t&&++this._version,t}ascending(e){return this.validatePath(e),this.internalAscending(e.clone())}descending(e){return this.validatePath(e),this.internalDescending(e.clone())}getCount(e){let t=0,n=e?e.path.clone():this.first();if(e?.ascending??!0)for(;n.on;)t+=n.leafNode.entries.length-n.leafIndex,n.leafIndex=n.leafNode.entries.length-1,this.internalNext(n);else for(;n.on;)t+=n.leafIndex+1,n.leafIndex=0,this.internalPrior(n);return t}next(e){let t=e.clone();return this.moveNext(t),t}moveNext(e){this.validatePath(e),this.internalNext(e)}prior(e){let t=e.clone();return this.movePrior(t),t}movePrior(e){this.validatePath(e),this.internalPrior(e)}compareKeys(e,t){let n=this.compare(e,t);if(n!==0&&n===this.compare(t,e))throw new Error("Inconsistent comparison function for given values");return n}*internalAscending(e){for(this.validatePath(e);e.on;)yield e,this.moveNext(e)}*internalDescending(e){for(this.validatePath(e);e.on;)yield e,this.movePrior(e)}findFirst(e){let t=this.find(e.first.key);return(!t.on||e.first&&!e.first.inclusive)&&(e.isAscending?this.internalNext(t):this.internalPrior(t)),t}findLast(e){let t=this.find(e.last.key);return(!t.on||e.last&&!e.last.inclusive)&&(e.isAscending?this.internalPrior(t):this.internalNext(t)),t}getPath(e,t){if(e instanceof sn){let n=e,[s,o]=this.indexOfEntry(n.entries,t);return new Ui([],n,o,s,this._version)}else{let n=e,s=this.indexOfKey(n.partitions,t),o=this.getPath(n.nodes[s],t);return o.branches.unshift(new Rn(n,s)),o}}indexOfEntry(e,t){let n=0,s=e.length-1,o=0,i=-1;for(;n<=s;){if(o=n+s>>>1,i=this.compareKeys(t,this.keyFromEntry(e[o])),i===0)return[!0,o];i<0?s=o-1:n=o+1}return[!1,n]}indexOfKey(e,t){let n=0,s=e.length-1,o=0,i=-1;for(;n<=s;){if(o=n+s>>>1,i=this.compareKeys(t,e[o]),i===0)return o+1;i<0?s=o-1:n=o+1}return n}internalNext(e){if(e.on)if(e.leafIndex>=e.leafNode.entries.length-1){let t=0,n=!1,s=e.branches.length-1;for(;t<=s&&!n;){let o=e.branches[s-t];o.index===o.node.partitions.length?++t:n=!0}if(!n)e.leafIndex=e.leafNode.entries.length,e.on=!1;else{e.branches.splice(-t,t);let o=e.branches.at(-1);++o.index,this.moveToFirst(o.node.nodes[o.index],e)}}else++e.leafIndex,e.on=!0;else if(e.on=e.branches.every(t=>t.index>=0&&t.index<t.node.nodes.length)&&e.leafIndex>=0&&e.leafIndex<e.leafNode.entries.length,e.on)return}internalPrior(e){if(this.validatePath(e),e.leafIndex<=0){let t=0,n=!1,s=e.branches.length-1;for(;t<=s&&!n;)e.branches[s-t].index===0?++t:n=!0;if(!n)e.leafIndex=0,e.on=!1;else{e.branches.splice(-t,t);let o=e.branches.at(-1);--o.index,this.moveToLast(o.node.nodes[o.index],e)}}else--e.leafIndex,e.on=!0}internalUpdate(e,t){if(e.on){let n=this.keyFromEntry(e.leafNode.entries[e.leafIndex]),s=this.keyFromEntry(t);if(this.compareKeys(n,s)!==0){let o=this.internalInsert(t);return o.on&&(this.internalDelete(this.find(n)),o=this.find(s)),[o,!1]}else e.leafNode.entries[e.leafIndex]=t}return[e,!0]}internalDelete(e){if(e.on){if(e.leafNode.entries.splice(e.leafIndex,1),e.branches.length>0){if(e.leafIndex===0){let n=e.branches.at(-1);this.updatePartition(n.index,e,e.branches.length-1,this.keyFromEntry(e.leafNode.entries[e.leafIndex]))}let t=this.rebalanceLeaf(e);t&&(this._root=t)}return e.on=!1,!0}else return!1}internalInsert(e){let t=this.find(this.keyFromEntry(e));return t.on?(t.on=!1,t):(this.internalInsertAt(t,e),t.on=!0,t)}internalInsertAt(e,t){let n=this.leafInsert(e,t),s=e.branches.length-1;for(;n&&s>=0;)n=this.branchInsert(e,s,n),--s;if(n){let o=new bl([n.key],[this._root,n.right]);this._root=o,e.branches.unshift(new Rn(o,n.indexDelta))}}moveToFirst(e,t){if(e instanceof sn){let n=e;t.leafNode=n,t.leafIndex=0,t.on=n.entries.length>0}else t.branches.push(new Rn(e,0)),this.moveToFirst(e.nodes[0],t)}moveToLast(e,t){if(e instanceof sn){let n=e,s=n.entries.length;t.leafNode=n,t.on=s>0,t.leafIndex=s>0?s-1:0}else{let n=e,s=new Rn(n,n.partitions.length);t.branches.push(s),this.moveToLast(n.nodes[s.index],t)}}getFirst(e){if(e instanceof sn){let t=e;return new Ui([],t,0,t.entries.length>0,this._version)}else{let t=e,n=this.getFirst(t.nodes[0]);return n.branches.unshift(new Rn(t,0)),n}}getLast(e){if(e instanceof sn){let t=e,n=t.entries.length;return new Ui([],t,n>0?n-1:0,n>0,this._version)}else{let t=e,n=t.nodes.length-1,s=this.getLast(t.nodes[n]);return s.branches.unshift(new Rn(t,n)),s}}leafInsert(e,t){let{leafNode:n,leafIndex:s}=e;if(n.entries.length<Ir){n.entries.splice(s,0,t);return}let o=n.entries.length+1>>>1,i=n.entries.splice(o),a=new sn(i),c=s<o?0:1;return c?(e.leafNode=a,e.leafIndex-=n.entries.length,a.entries.splice(e.leafIndex,0,t)):n.entries.splice(s,0,t),new Ld(this.keyFromEntry(i[0]),a,c)}branchInsert(e,t,n){let s=e.branches[t],{index:o,node:i}=s;if(s.index+=n.indexDelta,i.partitions.splice(o,0,n.key),i.nodes.splice(o+1,0,n.right),i.nodes.length<=Ir)return;let a=i.nodes.length>>>1,c=i.partitions.splice(a),l=i.partitions.pop(),u=i.nodes.splice(a),h=new bl(c,u),p=s.index<a?0:1;return p&&(s.index-=a,s.node=h),new Ld(l,h,p)}rebalanceLeaf(e){if(e.leafNode.entries.length>=Ir>>>1)return;let t=e.leafNode,n=e.branches.at(-1),s=e.branches.length-1,o=n.index,i=n.node,a=i.nodes[o+1];if(a&&a.entries.length>Ir>>>1){let l=a.entries.shift();t.entries.push(l),this.updatePartition(o+1,e,s,this.keyFromEntry(a.entries[0]));return}let c=i.nodes[o-1];if(c&&c.entries.length>Ir>>>1){let l=c.entries.pop();t.entries.unshift(l),this.updatePartition(o,e,s,this.keyFromEntry(l)),e.leafIndex+=1;return}if(a&&a.entries.length+t.entries.length<=Ir)return t.entries.push(...a.entries),i.partitions.splice(o,1),i.nodes.splice(o+1,1),o===0&&this.updatePartition(o,e,s,this.keyFromEntry(t.entries[0])),this.rebalanceBranch(e,s);if(c&&c.entries.length+t.entries.length<=Ir)return e.leafNode=c,e.leafIndex+=c.entries.length,c.entries.push(...t.entries),i.partitions.splice(o-1,1),i.nodes.splice(o,1),this.rebalanceBranch(e,s)}rebalanceBranch(e,t){let n=e.branches[t],s=n.node;if(t===0&&s.partitions.length===0)return e.branches[t+1]?.node??e.leafNode;if(t===0||s.nodes.length>=Ir<<1)return;let o=e.branches.at(t-1),i=o.index,a=o.node,c=a.nodes[i+1];if(c&&c.nodes.length>Ir>>>1){s.partitions.push(a.partitions[i]);let u=c.nodes.shift();s.nodes.push(u);let h=c.partitions.shift();this.updatePartition(i+1,e,t-1,h);return}let l=a.nodes[i-1];if(l&&l.nodes.length>Ir>>>1){s.partitions.unshift(a.partitions[i-1]);let u=l.nodes.pop();s.nodes.unshift(u);let h=l.partitions.pop();n.index+=1,this.updatePartition(i,e,t-1,h);return}if(c&&c.nodes.length+s.nodes.length<=Ir){let u=a.partitions.splice(i,1)[0];return s.partitions.push(u),s.partitions.push(...c.partitions),s.nodes.push(...c.nodes),a.nodes.splice(i+1,1),i===0&&a.partitions.length>0&&this.updatePartition(i,e,t-1,a.partitions[0]),this.rebalanceBranch(e,t-1)}if(l&&l.nodes.length+s.nodes.length<=Ir){n.node=l,n.index+=l.nodes.length;let u=a.partitions.splice(i-1,1)[0];return l.partitions.push(u),l.partitions.push(...s.partitions),l.nodes.push(...s.nodes),a.nodes.splice(i,1),this.rebalanceBranch(e,t-1)}}updatePartition(e,t,n,s){let o=t.branches[n];e>0?o.node.partitions[e-1]=s:n!==0&&this.updatePartition(t.branches[n-1].index,t,n-1,s)}validatePath(e){if(!this.isValid(e))throw new Error("Path is invalid due to mutation of the tree")}},Ld=class{key;right;indexDelta;constructor(e,t,n){this.key=e,this.right=t,this.indexDelta=n}};function wl(r){let e="";for(let t=0;t<r.length;t++)e+=r[t].toString(16).padStart(2,"0");return e}function Md(r){return`${wl(r.coord)}|${r.id}`}var Od=class{byKey;byId;constructor(){this.byKey=new kd(e=>Md(e)),this.byId=new Map}insert(e){let t=Md(e);this.byKey.insert(e),this.byId.set(e.id,t)}upsert(e,t){let n=Date.now(),s=this.byId.get(e);if(s){let i=this.byKey.find(s);i.on&&this.byKey.deleteAt(i),this.byId.delete(e)}let o={id:e,coord:t,relevance:0,lastAccess:n,state:"disconnected",accessCount:0,successCount:0,failureCount:0,avgLatencyMs:0};return this.insert(o),o}update(e,t){let n=this.byId.get(e);if(!n)return;let s=this.byKey.find(n),o=this.byKey.at(s);if(!o)return;let i={...o,...t};this.byKey.updateAt(s,i),Md(o)!==Md(i)&&(this.byKey.deleteAt(s),this.insert(i))}getById(e){let t=this.byId.get(e);if(!t)return;let n=this.byKey.find(t);return n.on?this.byKey.at(n):void 0}remove(e){let t=this.byId.get(e);if(!t)return;let n=this.byKey.find(t);n.on&&this.byKey.deleteAt(n),this.byId.delete(e)}list(){let e=[];for(let t of this.byKey.ascending(this.byKey.first()))e.push(this.byKey.at(t));return e}size(){return this.byId.size}setState(e,t){this.update(e,{state:t})}protectedIdsAround(e,t){let n=new Set;for(let s of this.neighborsRight(e,t))n.add(s);for(let s of this.neighborsLeft(e,t))n.add(s);return n}ceilPath(e){let t=`${e}|\0`,n=this.byKey.find(t);return n.on||(n=this.byKey.next(n)),n}floorPath(e){let t=`${e}|\uFFFF`,n=this.byKey.find(t);return n.on||(n=this.byKey.prior(n)),n}successorOfCoord(e){let t=wl(e),n=this.ceilPath(t);if(n.on)return this.byKey.at(n);let s=this.byKey.first();return s.on?this.byKey.at(s):void 0}predecessorOfCoord(e){let t=wl(e),n=this.floorPath(t);if(n.on)return this.byKey.at(n);let s=this.byKey.last();return s.on?this.byKey.at(s):void 0}neighborsRight(e,t){let n=[],s=wl(e),o=this.ceilPath(s);o=o.on?o:this.byKey.first();let i=0;for(;i<t&&!(!o.on&&(o=this.byKey.first(),!o.on));)n.push(this.byKey.at(o).id),o=this.byKey.next(o),i++;return Array.from(new Set(n))}neighborsLeft(e,t){let n=[],s=wl(e),o=this.floorPath(s);o=o.on?o:this.byKey.last();let i=0;for(;i<t&&!(!o.on&&(o=this.byKey.last(),!o.on));)n.push(this.byKey.at(o).id),o=this.byKey.prior(o),i++;return Array.from(new Set(n))}};var ny={};z(ny,{sha256:()=>qi,sha512:()=>B9});var ry=ie(ee("crypto"),1);var Bae=new Uint8Array(0);function KS(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Ar(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function FS(r){return new TextEncoder().encode(r)}function zS(r){return new TextDecoder().decode(r)}var b9=VS,HS=128,w9=127,x9=~w9,v9=Math.pow(2,31);function VS(r,e,t){e=e||[],t=t||0;for(var n=t;r>=v9;)e[t++]=r&255|HS,r/=128;for(;r&x9;)e[t++]=r&255|HS,r>>>=7;return e[t]=r|0,VS.bytes=t-n+1,e}var E9=Zg,S9=128,qS=127;function Zg(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Zg.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&qS)<<s:(i&qS)*Math.pow(2,s),s+=7}while(i>=S9);return Zg.bytes=o-n,t}var I9=Math.pow(2,7),A9=Math.pow(2,14),C9=Math.pow(2,21),T9=Math.pow(2,28),_9=Math.pow(2,35),P9=Math.pow(2,42),D9=Math.pow(2,49),k9=Math.pow(2,56),L9=Math.pow(2,63),M9=function(r){return r<I9?1:r<A9?2:r<C9?3:r<T9?4:r<_9?5:r<P9?6:r<D9?7:r<k9?8:r<L9?9:10},O9={encode:b9,decode:E9,encodingLength:M9},R9=O9,xl=R9;function vl(r,e=0){return[xl.decode(r,e),xl.decode.bytes]}function Ki(r,e,t=0){return xl.encode(r,e,t),e}function Fi(r){return xl.encodingLength(r)}function $i(r,e){let t=e.byteLength,n=Fi(r),s=n+Fi(t),o=new Uint8Array(s+t);return Ki(r,o,0),Ki(t,o,n),o.set(e,s),new zi(r,t,e,o)}function El(r){let e=Ar(r),[t,n]=vl(e),[s,o]=vl(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new zi(t,s,i,e)}function GS(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&KS(r.bytes,t.bytes)}}var zi=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var N9=20;function ty({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new ey(r,e,t,n,s)}var ey=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??N9,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?WS(n,this.code,t?.truncate):n.then(s=>WS(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function WS(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return $i(e,r)}var qi=ty({name:"sha2-256",code:18,encode:r=>Ar(ry.default.createHash("sha256").update(r).digest())}),B9=ty({name:"sha2-512",code:19,encode:r=>Ar(ry.default.createHash("sha512").update(r).digest())});ce();te();async function qe(r){let e=r.toMultihash().bytes;return await qi.encode(e)}async function ir(r){return await qi.encode(r)}function YS(r){return P(r,"base64url")}function XS(r="default"){let e=`/optimystic/${r}/fret/1.0.0`;return{PROTOCOL_NEIGHBORS:`${e}/neighbors`,PROTOCOL_NEIGHBORS_ANNOUNCE:`${e}/neighbors/announce`,PROTOCOL_MAYBE_ACT:`${e}/maybeAct`,PROTOCOL_LEAVE:`${e}/leave`,PROTOCOL_PING:`${e}/ping`}}var sy="/optimystic/default/fret/1.0.0/neighbors",oy="/optimystic/default/fret/1.0.0/neighbors/announce",iy="/optimystic/default/fret/1.0.0/maybeAct",ay="/optimystic/default/fret/1.0.0/leave",cy="/optimystic/default/fret/1.0.0/ping";async function Cr(r){let e=JSON.stringify(r);return new TextEncoder().encode(e)}async function on(r){if(r.byteLength===0)throw new Error("empty response");let e=0,t=r.byteLength;for(;e<t&&(r[e]===0||r[e]===9||r[e]===10||r[e]===13||r[e]===32);)e++;for(;t>e&&(r[t-1]===0||r[t-1]===9||r[t-1]===10||r[t-1]===13||r[t-1]===32);)t--;if(t<=e)throw new Error("whitespace response");let n=new TextDecoder().decode(r.subarray(e,t));return JSON.parse(n)}var bs=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Nd=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Bd=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var fy={};z(fy,{base58btc:()=>Ge,base58flickr:()=>q9});function U9(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var v=d[y],S=0,E=w-1;(v!==0||S<g)&&E!==-1;E--,S++)v+=256*x[E]>>>0,x[E]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var A=c.repeat(m);I<w;++I)A+=r.charAt(x[I]);return A}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*w[S]>>>0,w[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(d[m]!==" "){for(var E=b-y;E!==b&&w[E]===0;)E++;for(var I=new Uint8Array(g+(b-E)),A=g;E!==b;)I[A++]=w[E++];return I}}}function f(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:f}}var K9=U9,F9=K9,QS=F9;var ly=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},uy=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return JS(this,e)}},hy=class{decoders;constructor(e){this.decoders=e}or(e){return JS(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function JS(r,e){return new hy({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var dy=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new ly(e,t,n),this.decoder=new uy(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Vi({name:r,prefix:e,encode:t,decode:n}){return new dy(r,e,t,n)}function ws({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=QS(t,r);return Vi({prefix:e,name:r,encode:n,decode:o=>Ar(s(o))})}function z9(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function $9(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function H9(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Ve({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=H9(n);return Vi({prefix:e,name:r,encode(o){return $9(o,n,t)},decode(o){return z9(o,s,t,r)}})}var Ge=ws({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),q9=ws({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var py={};z(py,{base32:()=>xs,base32hex:()=>j9,base32hexpad:()=>X9,base32hexpadupper:()=>Q9,base32hexupper:()=>Y9,base32pad:()=>G9,base32padupper:()=>W9,base32upper:()=>V9,base32z:()=>J9});var xs=Ve({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),V9=Ve({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),G9=Ve({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),W9=Ve({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),j9=Ve({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Y9=Ve({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),X9=Ve({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Q9=Ve({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),J9=Ve({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var my={};z(my,{base36:()=>Sl,base36upper:()=>Z9});var Sl=ws({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Z9=ws({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});function ZS(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return tN(t,gy(r),e??Ge.encoder);default:return rN(t,gy(r),e??xs.encoder)}}var eI=new WeakMap;function gy(r){let e=eI.get(r);if(e==null){let t=new Map;return eI.set(r,t),t}return e}var ot=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Il)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==nN)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=$i(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&GS(e.multihash,n.multihash)}toString(e){return ZS(this,e)}toJSON(){return{"/":ZS(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??tI(n,s,o.bytes))}else if(t[sN]===!0){let{version:n,multihash:s,code:o}=t,i=El(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Il)throw new Error(`Version 0 CID must use dag-pb (code: ${Il}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=tI(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Il,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=Ar(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new zi(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,p]=vl(e.subarray(t));return t+=p,h},s=n(),o=Il;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=eN(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return gy(o).set(n,e),o}};function eN(r,e){switch(r[0]){case"Q":{let t=e??Ge;return[Ge.prefix,t.decode(`${Ge.prefix}${r}`)]}case Ge.prefix:{let t=e??Ge;return[Ge.prefix,t.decode(r)]}case xs.prefix:{let t=e??xs;return[xs.prefix,t.decode(r)]}case Sl.prefix:{let t=e??Sl;return[Sl.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function tN(r,e,t){let{prefix:n}=t;if(n!==Ge.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function rN(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var Il=112,nN=18;function tI(r,e,t){let n=Fi(r),s=n+Fi(e),o=new Uint8Array(s+t.byteLength);return Ki(r,o,0),Ki(e,o,n),o.set(t,s),o}var sN=Symbol.for("@ipld/js-cid/CID");var yy={};z(yy,{identity:()=>Ur});var rI=0,oN="identity",nI=Ar;function iN(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return $i(rI,nI(r))}var Ur={code:rI,name:oN,encode:nI,digest:iN};Ne();Be();te();ce();Be();var aN=parseInt("11111",2),by=parseInt("10000000",2),cN=parseInt("01111111",2),sI={0:Al,1:Al,2:lN,3:dN,4:fN,5:hN,6:uN,16:Al,22:Al,48:Al};function wy(r,e={offset:0}){let t=r[e.offset]&aN;if(e.offset++,sI[t]!=null)return sI[t](r,e);throw new Error("No decoder for tag "+t)}function Cl(r,e){let t=0;if((r[e.offset]&by)===by){let n=r[e.offset]&cN,s="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)s+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(s,16)}else t=r[e.offset],e.offset++;return t}function Al(r,e){Cl(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=wy(r,e);if(n===null)break;t.push(n)}return t}function lN(r,e){let t=Cl(r,e),n=e.offset,s=e.offset+t,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function uN(r,e){let t=Cl(r,e),n=e.offset+t,s=r[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let h=0;h<c.length;h++)u+=c[h]<<h*7;a+=`.${u}`,c=[]}}return a}function hN(r,e){return e.offset++,null}function dN(r,e){let t=Cl(r,e),n=r[e.offset];e.offset++;let s=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function fN(r,e){let t=Cl(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function pN(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new U;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function xy(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=pN(r.byteLength);return new U(Uint8Array.from([e.byteLength|by]),e)}function oI(r){let e=new U,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new U(Uint8Array.from([2]),xy(e),e)}function iI(r){let e=Uint8Array.from([0]),t=new U(e,r);return new U(Uint8Array.from([3]),xy(t),t)}function Ud(r,e=48){let t=new U;for(let n of r)t.append(n);return new U(Uint8Array.from([e]),xy(t),t)}async function aI(r,e,t,n){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,e,t.subarray());return n?.signal?.throwIfAborted(),o}var mN=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),gN=Uint8Array.from([6,5,43,129,4,0,34]),yN=Uint8Array.from([6,5,43,129,4,0,35]),bN={ext:!0,kty:"EC",crv:"P-256"},wN={ext:!0,kty:"EC",crv:"P-384"},xN={ext:!0,kty:"EC",crv:"P-521"},vy=32,Ey=48,Sy=66;function cI(r){let e=wy(r);return lI(e)}function lI(r){let e=r[1][1][0],t=1,n,s;if(e.byteLength===vy*2+1)return n=P(e.subarray(t,t+vy),"base64url"),s=P(e.subarray(t+vy),"base64url"),new Gi({...bN,key_ops:["verify"],x:n,y:s});if(e.byteLength===Ey*2+1)return n=P(e.subarray(t,t+Ey),"base64url"),s=P(e.subarray(t+Ey),"base64url"),new Gi({...wN,key_ops:["verify"],x:n,y:s});if(e.byteLength===Sy*2+1)return n=P(e.subarray(t,t+Sy),"base64url"),s=P(e.subarray(t+Sy),"base64url"),new Gi({...xN,key_ops:["verify"],x:n,y:s});throw new bs(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function uI(r){return Ud([oI(Uint8Array.from([1])),Ud([vN(r.crv)],160),Ud([iI(new U(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function vN(r){if(r==="P-256")return mN;if(r==="P-384")return gN;if(r==="P-521")return yN;throw new bs(`Invalid curve ${r}`)}var Gi=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=uI(this.jwk)),this._raw}toMultihash(){return Ur.digest(Wi(this))}toCID(){return ot.createV1(114,this.toMultihash())}toString(){return Ge.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}async verify(e,t,n){return aI(this.jwk,t,e,n)}};var Kd=ie(ee("crypto"),1);bt();te();ce();var Oce=Kd.default.generateKeyPairSync,Tl=32;var EN=64;function hI(r,e,t){if(r.byteLength!==Tl)throw new TypeError('"key" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');if(e.byteLength!==EN)throw new TypeError('"sig" must be 64 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"sig" must be a node.js Buffer, or Uint8Array.');let n=Kd.default.createPublicKey({format:"jwk",key:{crv:"Ed25519",x:P(r,"base64url"),kty:"OKP"}});return Kd.default.verify(null,t instanceof Uint8Array?t:t.subarray(),n,e)}Ne();bt();te();function fI(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Fd=class{type="Ed25519";raw;constructor(e){this.raw=Iy(e,Tl)}toMultihash(){return Ur.digest(Wi(this))}toCID(){return ot.createV1(114,this.toMultihash())}toString(){return Ge.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let s=hI(this.raw,t,e);return fI(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}};function pI(r){return r=Iy(r,Tl),new Fd(r)}function Iy(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new bs(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}wr();var ar;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ar||(ar={}));var Ay;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Ay||(Ay={}));(function(r){r.codec=()=>sr(Ay)})(ar||(ar={}));var _l;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ar.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=ar.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(_l||(_l={}));var Cy;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ar.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=ar.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(Cy||(Cy={}));var mI=ie(ee("node:crypto"),1);eo();var zd=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}};function gI(r,e,t,n){n?.signal?.throwIfAborted();let s=mI.default.createHash("sha256");if(t instanceof Uint8Array)s.update(t);else for(let i of t)s.update(i);let o=s.digest();try{return st.verify(e,o,r,{prehash:!1,format:"der"})}catch(i){throw new zd(String(i))}}eo();Ne();var $d=class{type="secp256k1";raw;_key;constructor(e){this._key=bI(e),this.raw=yI(this._key)}toMultihash(){return Ur.digest(Wi(this))}toCID(){return ot.createV1(114,this.toMultihash())}toString(){return Ge.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){return gI(this._key,t,e,n)}};function wI(r){return new $d(r)}function yI(r){return st.Point.fromBytes(r).toBytes()}function bI(r){try{return st.Point.fromBytes(r),r}catch(e){throw new Nd(String(e))}}function xI(r){let{Type:e,Data:t}=_l.decode(r.digest),n=t??new Uint8Array;switch(e){case ar.Ed25519:return pI(n);case ar.secp256k1:return wI(n);case ar.ECDSA:return cI(n);default:throw new Bd}}function Wi(r){return _l.encode({Type:ar[r.type],Data:r.raw})}var Ty=Symbol.for("@libp2p/peer-id");var Hd=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var qd=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Vd=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};ce();Ne();te();ce();var vI=Symbol.for("nodejs.util.inspect.custom"),AN=114,Pl=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Ty]=!0;toString(){return this.string==null&&(this.string=Ge.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ot.createV1(AN,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return W(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return W(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[vI](){return`PeerId(${this.toString()})`}},Gd=class extends Pl{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Wd=class extends Pl{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},jd=class extends Pl{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},CN=2336,Dl=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ur.digest(D(this.url))}[vI](){return`PeerId(${this.url})`}[Ty]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ot.createV1(CN,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=P(e)),e.toString()===this.toString())}};var TN=114,EI=2336;function Oe(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=El(Ge.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return _N(ot.parse(r));if(e==null)throw new Hd('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=El(e.decode(r))}return SI(t)}function SI(r){if(DN(r))return new Gd({multihash:r});if(PN(r))try{let e=xI(r);if(e.type==="Ed25519")return new Wd({multihash:r,publicKey:e});if(e.type==="secp256k1")return new jd({multihash:r,publicKey:e})}catch{let t=P(r.digest);return new Dl(new URL(t))}throw new Vd("Supplied PeerID Multihash is invalid")}function _N(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==TN&&r.code!==EI)throw new qd("Supplied PeerID CID is invalid");if(r.code===EI){let e=P(r.multihash.digest);return new Dl(new URL(e))}return SI(r.multihash)}function PN(r){return r.code===Ur.code}function DN(r){return r.code===qi.code}var II=ie(Wg(),1),kN="optimystic:fret";function vs(r){return(0,II.default)(`${kN}:${r}`)}var _y=vs("rpc:neighbors");function AI(r,e,t,n={PROTOCOL_NEIGHBORS:sy,PROTOCOL_NEIGHBORS_ANNOUNCE:oy}){r.handle(n.PROTOCOL_NEIGHBORS,async({stream:s})=>{try{let o=await e();await s.sink((async function*(){yield await Cr(o)})());try{s.close?.()}catch{}}catch(o){console.error("neighbors handler error:",o)}}),t&&r.handle(n.PROTOCOL_NEIGHBORS_ANNOUNCE,async({stream:s})=>{try{let o=await TI(s),i=await on(o);t(i.from,i),await s.sink((async function*(){yield await Cr({ok:!0})})());try{s.close?.()}catch{}}catch(o){console.error("neighbors announce handler error:",o)}})}async function CI(r,e,t=sy){let n=Oe(e),s=r.getConnections?.(n)??[];if(!Array.isArray(s)||s.length===0||typeof s[0]?.newStream!="function")return{v:1,from:e,timestamp:Date.now(),successors:[],predecessors:[],sig:""};let o;try{o=await s[0].newStream([t]);let i=await TI(o);return await on(i)}catch(i){return _y("fetchNeighbors decode failed for %s - %o",e,i),{v:1,from:e,timestamp:Date.now(),successors:[],predecessors:[],sig:""}}finally{if(o)try{await o.close()}catch{}}}async function Py(r,e,t,n=oy){let s=Oe(e),o=r.getConnections?.(s)??[];if(!Array.isArray(o)||o.length===0||typeof o[0]?.newStream!="function")return;let i;try{i=await o[0].newStream([n]),await i.sink((async function*(){yield await Cr(t)})())}catch(a){_y("announceNeighbors failed to %s - %o",e,a)}finally{if(i)try{await i.close()}catch{}}}function LN(r){if(r instanceof Uint8Array)return r;let e=r;if(typeof e?.subarray=="function")try{return e.subarray(0)}catch(t){_y("toBytes subarray failed - %o",t)}if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unsupported chunk type in neighbors read")}async function TI(r){let e=[];for await(let o of r.source)e.push(LN(o));let t=0;for(let o of e)t+=o.length;let n=new Uint8Array(t),s=0;for(let o of e)n.set(o,s),s+=o.length;return n}function _I(r,e,t=iy){r.handle(t,async({stream:n})=>{try{let s=await DI(n),o=await on(s),i=await e(o);await n.sink((async function*(){yield await Cr(i)})())}catch(s){console.error("maybeAct handler error:",s)}})}async function PI(r,e,t,n=iy){let s=Oe(e),o=r.getConnections?.(s)??[],i;try{Array.isArray(o)&&o.length>0&&typeof o[0]?.newStream=="function"?i=await o[0].newStream([n]):i=await r.dialProtocol(s,[n]),await i.sink((async function*(){yield await Cr(t)})());let a=await DI(i);return await on(a)}finally{if(i)try{await i.close()}catch{}}}function MN(r){if(r instanceof Uint8Array)return r;let e=r;if(typeof e?.subarray=="function")return e.subarray(0);throw new Error("Unsupported chunk type in maybeAct read")}async function DI(r){let e=[];for await(let o of r.source)e.push(MN(o));let t=0;for(let o of e)t+=o.length;let n=new Uint8Array(t),s=0;for(let o of e)n.set(o,s),s+=o.length;return n}function kI(r,e,t=ay){r.handle(t,async({stream:n})=>{try{let s=await RN(n),o=await on(s);await e(o),await n.sink((async function*(){yield await Cr({ok:!0})})())}catch(s){console.error("leave handler error:",s)}})}async function LI(r,e,t,n=ay){let s=Oe(e),o=r.getConnections?.(s)??[],i;try{Array.isArray(o)&&o.length>0&&typeof o[0]?.newStream=="function"?i=await o[0].newStream([n]):i=await r.dialProtocol(s,[n]),await i.sink((async function*(){yield await Cr(t)})())}finally{if(i)try{await i.close()}catch{}}}function ON(r){if(r instanceof Uint8Array)return r;let e=r;if(typeof e?.subarray=="function")return e.subarray(0);throw new Error("Unsupported chunk type in leave read")}async function RN(r){let e=[];for await(let o of r.source)e.push(ON(o));let t=0;for(let o of e)t+=o.length;let n=new Uint8Array(t),s=0;for(let o of e)n.set(o,s),s+=o.length;return n}var Dy=vs("rpc:ping");function MI(r,e=cy,t){r.handle(e,async({stream:n})=>{let s={ok:!0,ts:Date.now()};if(t)try{let o=await t();o.size_estimate!==void 0&&(s.size_estimate=o.size_estimate,s.confidence=o.confidence)}catch(o){Dy("getSizeEstimate failed - %o",o)}await n.sink((async function*(){yield await Cr(s)})())})}async function kl(r,e,t=cy){let n=Date.now(),s=Oe(e),o;try{try{let l=r.getConnections?.(s)??[];if(Array.isArray(l)&&l.length>0&&typeof l[0]?.newStream=="function")o=await l[0].newStream([t]);else{let u=await r.dialProtocol(s,[t]);o=u.stream??u}}catch{let u=await r.dialProtocol(s,[t]);o=u.stream??u}let i=null;for await(let l of o.source)if(l!=null)try{if(l instanceof Uint8Array){i=l;break}if(typeof l.subarray=="function"){let u=l.subarray();if(u instanceof Uint8Array){i=u;break}if(ArrayBuffer.isView(u)){i=new Uint8Array(u.buffer,u.byteOffset,u.byteLength);break}}if(ArrayBuffer.isView(l)){i=new Uint8Array(l.buffer,l.byteOffset,l.byteLength);break}}catch(u){Dy("sendPing chunk handling failed - %o",u)}let a=Math.max(0,Date.now()-n);if(!i||i.length===0)return{ok:!1,rttMs:a};let c=new TextDecoder().decode(i).trim();if(!c||c[0]!=="{"||!c.endsWith("}"))return{ok:!1,rttMs:a};try{let l=await on(i);return{ok:!!l.ok,rttMs:a,size_estimate:l.size_estimate,confidence:l.confidence}}catch(l){return Dy("sendPing decode failed - %o",l),{ok:!1,rttMs:a}}}finally{if(o)try{await o.close()}catch{}}}te();function NN(r){let e=0n;for(let t=0;t<r.length;t++)e=e<<8n|BigInt(r[t]);return e}function BN(r){if(r.length===0)return 0n;let e=[...r].sort((n,s)=>n<s?-1:n>s?1:0),t=Math.floor(e.length/2);return e.length%2===0?(e[t-1]+e[t])/2n:e[t]}function Yd(r,e){let t=r.list(),n=t.length;if(n===0)return{n:0,confidence:0};if(n===1)return{n:1,confidence:.2};let s=1n<<256n,o=t.map(g=>NN(g.coord)).sort((g,y)=>g<y?-1:g>y?1:0),i=[];for(let g=1;g<o.length;g++)i.push(o[g]-o[g-1]);i.push(o[0]+s-o[o.length-1]);let a=BN(i),c=a>0n?a:s/BigInt(Math.max(1,n)),l=s/c,u=Math.max(1,Math.min(Number(l),1e9)),h=i[0],p=i[0];for(let g of i)g<h&&(h=g),g>p&&(p=g);let f=Math.min(1,n/Math.max(1,e*2)),d=p===0n?0:Number(h)/Number(p),m=Math.max(.05,Math.min(1,.5*f+.5*d));return{n:u,confidence:m}}var ji=class{capacity;refillPerSec;tokens;last;constructor(e,t){this.capacity=e,this.refillPerSec=t,this.tokens=e,this.last=Date.now()}tryTake(e=1){return this.refill(),this.tokens>=e?(this.tokens-=e,!0):!1}retryAfterMs(e=1){if(this.refill(),this.tokens>=e)return 0;let n=(e-this.tokens)/this.refillPerSec;return Math.ceil(n*1e3)}refill(){let e=Date.now(),t=(e-this.last)/1e3;t>0&&(this.tokens=Math.min(this.capacity,this.tokens+t*this.refillPerSec),this.last=e)}};ce();var vt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Nn=class extends Error{static name="ValidationError";name="ValidationError"},Ll=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Xd=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};Ne();te();ce();gr();bt();te();ce();var fe=ee("node:net");var Ly={};z(Ly,{base64:()=>UN,base64pad:()=>KN,base64url:()=>ky,base64urlpad:()=>FN});var UN=Ve({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),KN=Ve({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ky=Ve({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),FN=Ve({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var My={};z(My,{base10:()=>zN});var zN=ws({prefix:"9",name:"base10",alphabet:"0123456789"});var Oy={};z(Oy,{base16:()=>$N,base16upper:()=>HN});var $N=Ve({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),HN=Ve({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ry={};z(Ry,{base2:()=>qN});var qN=Ve({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ny={};z(Ny,{base256emoji:()=>YN});var OI=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),VN=OI.reduce((r,e,t)=>(r[t]=e,r),[]),GN=OI.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function WN(r){return r.reduce((e,t)=>(e+=VN[t],e),"")}function jN(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=GN[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var YN=Vi({prefix:"\u{1F680}",name:"base256emoji",encode:WN,decode:jN});var By={};z(By,{base8:()=>XN});var XN=Ve({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Uy={};z(Uy,{identity:()=>QN});var QN=Vi({prefix:"\0",name:"identity",encode:r=>zS(r),decode:r=>FS(r)});var Bue=new TextEncoder,Uue=new TextDecoder;var RI={...Uy,...Ry,...By,...My,...Oy,...py,...my,...fy,...Ly,...Ny},zue={...ny,...yy};bt();te();ce();function Fy(r){return e=>P(e,r)}function zy(r){return e=>D(e,r)}function Yi(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function co(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function NI(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=D(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=co(n);return Ee([t,s],t.length+s.length)}function BI(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=xs.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=co(n);return Ee([t,s],t.length+s.length)}function $y(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=P(e,"base32"),s=Yi(t);return`${n}:${s}`}var Hy=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let s=parseInt(t,10);if(isNaN(s)||s<0||s>255)throw new vt("Invalid byte value in IP address");e[n]=s}),e},UI=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=(0,fe.isIPv4)(t[n]),i;o&&(i=Hy(t[n]),t[n]=P(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,P(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new vt("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},KI=function(r){if(r.byteLength!==4)throw new vt("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},FI=function(r){if(r.byteLength!==16)throw new vt("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new vt(`Invalid IPv6 address "${t}"`)}};function zI(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new vt(`Invalid IPv6 address "${r}"`)}}var Ky=Object.values(RI).map(r=>r.decoder),eB=(function(){let r=Ky[0].or(Ky[1]);return Ky.slice(2).forEach(e=>r=r.or(e)),r})();function $I(r){return eB.decode(r)}function HI(r){return e=>r.encoder.encode(e)}function tB(r){if(parseInt(r).toString()!==r)throw new Nn("Value must be an integer")}function rB(r){if(r<0)throw new Nn("Value must be a positive integer, or zero")}function nB(r){return e=>{if(e>r)throw new Nn(`Value must be smaller than or equal to ${r}`)}}function sB(...r){return e=>{for(let t of r)t(e)}}var Ml=sB(tB,rB,nB(65535));var pt=-1,qy=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new Xd(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},cr=new qy,OB=[{code:4,name:"ip4",size:32,valueToBytes:Hy,bytesToValue:KI,validate:r=>{if(!(0,fe.isIPv4)(r))throw new Nn(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:co,bytesToValue:Yi,validate:Ml},{code:273,name:"udp",size:16,valueToBytes:co,bytesToValue:Yi,validate:Ml},{code:33,name:"dccp",size:16,valueToBytes:co,bytesToValue:Yi,validate:Ml},{code:41,name:"ip6",size:128,valueToBytes:UI,bytesToValue:FI,stringToValue:zI,validate:r=>{if(!(0,fe.isIPv6)(r))throw new Nn(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:pt},{code:43,name:"ipcidr",size:8,bytesToValue:Fy("base10"),valueToBytes:zy("base10")},{code:53,name:"dns",size:pt,resolvable:!0},{code:54,name:"dns4",size:pt,resolvable:!0},{code:55,name:"dns6",size:pt,resolvable:!0},{code:56,name:"dnsaddr",size:pt,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:co,bytesToValue:Yi,validate:Ml},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:pt,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:pt,bytesToValue:Fy("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?zy("base58btc")(r):ot.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:$y,valueToBytes:NI},{code:445,name:"onion3",size:296,bytesToValue:$y,valueToBytes:BI},{code:446,name:"garlic64",size:pt},{code:447,name:"garlic32",size:pt},{code:448,name:"tls"},{code:449,name:"sni",size:pt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:pt,bytesToValue:HI(ky),valueToBytes:$I},{code:480,name:"http"},{code:481,name:"http-path",size:pt,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:pt}];OB.forEach(r=>{cr.addProtocol(r)});function qI(r){let e=[],t=0;for(;t<r.length;){let n=jt(r,t),s=cr.getProtocol(n),o=Ae(n),i=RB(s,r,t+o),a=0;i>0&&s.size===pt&&(a=Ae(i));let c=o+a+i,l={code:n,name:s.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+o+a,h=r.subarray(u,u+i);l.value=s.bytesToValue?.(h)??P(h)}e.push(l),t+=c}return e}function VI(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let s=cr.getProtocol(n.code),o=Ae(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??D(n.value),a=i.byteLength,s.size===pt&&(c=Ae(a)));let l=new Uint8Array(o+c+a),u=0;In(n.code,l,u),u+=o,i!=null&&(s.size===pt&&(In(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Ee(t,e)}function GI(r){if(r.charAt(0)!=="/")throw new vt('String multiaddr must start with "/"');let e=[],t="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(t==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=cr.getProtocol(s);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",s="",t="protocol";continue}else if(a)throw new vt(`Component ${s} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new vt(`Component ${s} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",s="",t="protocol"}}}if(s!==""&&n!=="")throw new vt("Incomplete multiaddr");return e}function WI(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=cr.getProtocol(e.code);if(t==null)throw new vt(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function RB(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:jt(e,t)}var NB=Symbol.for("nodejs.util.inspect.custom"),Jy=Symbol.for("@multiformats/multiaddr"),BB=[53,54,55,56],Qy=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}};function UB(r){if(r==null&&(r="/"),YI(r))return r.getComponents();if(r instanceof Uint8Array)return qI(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),GI(r);if(Array.isArray(r))return r;throw new vt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var tf=class r{[Jy]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=UB(e),t.validate!==!1&&KB(this)}get bytes(){return this.#r==null&&(this.#r=VI(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=WI(this.#e)),this.#t}toJSON(){return this.toString()}toOptions(){let e,t,n,s,o="";for(let{code:a,name:c,value:l}of this.#e)a===42&&(o=`%${l??""}`),BB.includes(a)&&(t="tcp",s=443,n=`${l??""}${o}`,e=a===55?6:4),(a===6||a===273)&&(t=c==="tcp"?"tcp":"udp",s=parseInt(l??"")),(a===4||a===41)&&(t="tcp",n=`${l??""}${o}`,e=a===41?6:4);if(e==null||t==null||n==null||s==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:s}}getComponents(){return[...this.#e]}protos(){return this.#e.map(({code:e,value:t})=>{let n=cr.getProtocol(e);return{code:e,size:n.size??0,name:n.name,resolvable:!!n.resolvable,path:!!n.path}})}protoCodes(){return this.#e.map(({code:e})=>e)}protoNames(){return this.#e.map(({name:e})=>e)}tuples(){return this.#e.map(({code:e,value:t})=>{if(t==null)return[e];let n=cr.getProtocol(e),s=[e];return t!=null&&s.push(n.valueToBytes?.(t)??D(t)),s})}stringTuples(){return this.#e.map(({code:e,value:t})=>t==null?[e]:[e,t])}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new Ll(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,s),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}getPeerId(){try{let e=[];this.#e.forEach(({code:n,value:s})=>{n===421&&e.push([n,s]),n===290&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?P(Ge.decode(`z${n}`),"base58btc"):P(ot.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(let e of this.#e)if(cr.getProtocol(e.code).path)return e.value??null;return null}equals(e){return W(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(o=>o.resolvable);if(t==null)return[this];let n=jI.get(t.name);if(n==null)throw new Qy(`no available resolver for ${t.name}`);return(await n(this,e)).map(o=>Rl(o))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(){return!(this.#e.length!==2||this.#e[0].code!==4&&this.#e[0].code!==41||this.#e[1].code!==6&&this.#e[1].code!==273)}[NB](){return`Multiaddr(${this.toString()})`}};function KB(r){r.getComponents().forEach(e=>{let t=cr.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}var rf=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let p=Number.parseInt(h,e);if(!Number.isNaN(p))return p});if(u===void 0)break;if(o*=e,o+=u,o>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let s=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2],t[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];t[s]=o>>8,t[s+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,s]=e(t);if(n===16)return t;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=e(o.subarray(0,i));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var XI=45,FB=15,Xi=new rf;function QI(r){if(!(r.length>FB))return Xi.new(r).parseWith(()=>Xi.readIPv4Addr())}function JI(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>XI))return Xi.new(r).parseWith(()=>Xi.readIPv6Addr())}function Nl(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>XI)return;let t=Xi.new(r).parseWith(()=>Xi.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function ZI(r,e,t){let n=0;for(let s of r)if(!(n<e)){if(n>t)break;if(s!==255)return!1;n++}return!0}function eA(r,e,t,n){let s=0;for(let o of r)if(!(s<t)){if(s>n)break;if(o!==e[s])return!1;s++}return!0}function Zy(r){switch(r.length){case lo:return r.join(".");case uo:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function tA(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let s=t+1;s<r.length;s++)if(r[s]!=0)return-1;break}return e}function rA(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var lo=4,uo=16,khe=parseInt("0xFFFF",16),zB=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Bl(r,e){e.length===uo&&r.length===lo&&ZI(e,0,11)&&(e=e.slice(12)),e.length===lo&&r.length===uo&&eA(r,zB,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=r[s]&e[s];return n}function nA(r,e){if(typeof e=="string"&&(e=Nl(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function e3(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=lo,s=QI(e);if(s==null&&(n=uo,s=JI(e),s==null))throw new Error("Failed to parse given CIDR: "+r);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=t3(o,8*n);return{network:Bl(s,i),mask:i}}function t3(r,e){if(e!==8*lo&&e!==8*uo)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let s=0;s<t;s++){if(r>=8){n[s]=255,r-=8;continue}n[s]=255-(255>>r),r=0}return n}var Bn=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=e3(e));else{let n=Nl(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n.length*8){let o=Nl(t);if(o==null)throw new Error("Failed to parse mask");this.mask=o}else this.mask=t3(s,8*n.length);this.network=Bl(n,this.mask)}}contains(e){return nA({network:this.network,mask:this.mask},e)}toString(){let e=tA(this.mask),t=e!==-1?String(e):rA(this.mask);return Zy(this.network)+"/"+t}};function sA(r,e){return new Bn(r).contains(e)}te();ce();var jI=new Map;function YI(r){return!!r?.[Jy]}function Rl(r){return new tf(r)}function nf(r,e){let t=Math.max(r.length,e.length),n=new Uint8Array(t);for(let s=0;s<t;s++){let o=r[r.length-1-s]??0,i=e[e.length-1-s]??0;n[t-1-s]=o^i}return n}function r3(r,e){let t=Math.max(r.length,e.length);for(let n=0;n<t;n++){let s=r[n]??0,o=e[n]??0;if(s<o)return!0;if(s>o)return!1}return!1}function oA(r){for(let e=0;e<r.length;e++)if(r[e]!==0)return e;return Number.POSITIVE_INFINITY}function $B(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}function iA(r,e,t,n){return r3(e,n)?!0:r3(n,e)?!1:r<t}function sf(r,e,t,n,s,o=1){let i,a=[];for(let u of t){let h=r.getById(u);if(!h)continue;let p=nf(h.coord,e),f=n(u),d=(f?1:0)+.25*s(u);a.push({id:u,dist:p,connected:f,score:d}),(!i||iA(u,p,i.id,i.dist))&&(i={id:u,dist:p})}if(!i)return;let c=oA(i.dist),l;for(let u of a){if(!u.connected)continue;if(oA(u.dist)<=c+o){if(!l){l={id:u.id,dist:u.dist,score:u.score};continue}iA(u.id,u.dist,l.id,l.dist)?l={id:u.id,dist:u.dist,score:u.score}:$B(u.dist,l.dist)&&(u.score>l.score||u.score===l.score&&u.id<l.id)&&(l={id:u.id,dist:u.dist,score:u.score})}}return l?.id??i.id}function aA(r=12,e=.08,t=.03,n=.6,s=.7,o=1.8,i=1e-6){let a=[];for(let c=0;c<r;c++)a.push((c+.5)/r);return{centers:a,occupancy:new Float64Array(r),alpha:t,sigma:e,beta:n,sMin:s,sMax:o,eps:i}}function of(r,e){let t=nf(r,e),n=0;for(let o=0;o<t.length;o++){let i=t[o]??0;if(i===0){n+=8;continue}let a=7-Math.floor(Math.log2(i));n+=a;break}return 1-Math.min(256,n)/256}function cA(r,e){let t=r/Math.max(1e-9,e);return Math.exp(-.5*t*t)}function n3(r,e){for(let t=0;t<r.centers.length;t++){let n=cA(Math.abs(e-r.centers[t]),r.sigma);r.occupancy[t]=(1-r.alpha)*r.occupancy[t]+r.alpha*n}}function s3(r,e){let t=0,n=0;for(let i=0;i<r.centers.length;i++){let a=cA(Math.abs(e-r.centers[i]),r.sigma);t+=r.occupancy[i]*a,n+=1*a}let s=(n+r.eps)/(t+r.eps),o=Math.pow(s,r.beta);return Math.max(r.sMin,Math.min(r.sMax,o))}function HB(r,e){let t=Math.max(0,e-r.lastAccess),s=Math.log(2)/Math.max(1,6e4);return Math.exp(-s*t)}function qB(r){return Math.log1p(r.accessCount)/5}function VB(r){let e=r.successCount+r.failureCount,t=e>0?r.successCount/e:.5,n=r.avgLatencyMs>0?Math.min(1,r.avgLatencyMs/1e3):.5,s=.5*t+.5*(1-n);return Math.max(0,s)}function o3(r,e){return .4*HB(r,e)+.2*qB(r)+.4*VB(r)}function i3(r,e){return{...r,...e}}function lA(r,e,t,n=Date.now()){n3(t,e);let s=o3(r,n),o=s3(t,e),i=s*o;return i3(r,{lastAccess:n,relevance:i,accessCount:r.accessCount+1})}function uA(r,e,t,n,s=Date.now()){n3(n,t);let o=.2,i=r.avgLatencyMs>0?(1-o)*r.avgLatencyMs+o*e:e,a=o3({...r,avgLatencyMs:i,successCount:r.successCount+1},s),c=s3(n,t),l=a*c;return i3(r,{lastAccess:s,relevance:l,successCount:r.successCount+1,avgLatencyMs:i})}function hA(r,e,t,n=Date.now()){n3(t,e);let s=o3({...r,failureCount:r.failureCount+1},n)*.7,o=s3(t,e),i=s*o;return i3(r,{lastAccess:n,relevance:i,failureCount:r.failureCount+1})}var Kr=vs("service:fret"),Qi=class{mode="passive";store=new Od;cfg;node;stabilizing=!1;inflightAct=0;bucketNeighbors;bucketMaybeAct;bucketDiscovery;announcedIds=new Map;postBootstrapAnnounced=!1;sparsity=aA();cachedSelfCoord=null;preconnectRunning=!1;protocols;metadata;diag={peersDiscovered:0,snapshotsFetched:0,announcementsSent:0,pingsSent:0,pingsOk:0,pingsFail:0,maybeActForwarded:0,evictions:0};networkObservations=[];maxObservations=100;observationWindowMs=3e5;constructor(e,t){this.node=e,this.cfg={k:t?.k??15,m:t?.m??Math.ceil((t?.k??15)/2),capacity:t?.capacity??2048,profile:t?.profile??"core",bootstraps:t?.bootstraps??[],networkName:t?.networkName??"default"},this.protocols=XS(this.cfg.networkName),this.bucketDiscovery=new ji(this.cfg.profile==="core"?50:10,this.cfg.profile==="core"?25:3),this.bucketNeighbors=new ji(this.cfg.profile==="core"?20:8,this.cfg.profile==="core"?10:4),this.bucketMaybeAct=new ji(this.cfg.profile==="core"?32:8,this.cfg.profile==="core"?16:4)}getDiagnostics(){return this.diag}async selfCoord(){return this.cachedSelfCoord?this.cachedSelfCoord:(this.cachedSelfCoord=await qe(this.node.peerId),this.cachedSelfCoord)}enforceCapacity(){let e=Math.max(1,this.cfg.capacity);if(this.store.size()<=e)return;let t=this.cachedSelfCoord;if(!t)return;let n=this.store.protectedIdsAround(t,Math.max(2,this.cfg.m)),s=this.store.list();s.sort((o,i)=>o.relevance-i.relevance);for(let o of s){if(this.store.size()<=e)break;n.has(o.id)||this.store.remove(o.id)}}async applyTouch(e,t){let n=this.store.getById(e)??this.store.upsert(e,t),s=of(await this.selfCoord(),t),o=lA(n,s,this.sparsity);this.store.update(e,{lastAccess:o.lastAccess,relevance:o.relevance,accessCount:o.accessCount})}async applySuccess(e,t,n){let s=this.store.getById(e)??this.store.upsert(e,t),o=of(await this.selfCoord(),t),i=uA(s,n,o,this.sparsity);this.store.update(e,{lastAccess:i.lastAccess,relevance:i.relevance,successCount:i.successCount,avgLatencyMs:i.avgLatencyMs})}async applyFailure(e,t){let n=this.store.getById(e)??this.store.upsert(e,t),s=of(await this.selfCoord(),t),o=hA(n,s,this.sparsity);this.store.update(e,{lastAccess:o.lastAccess,relevance:o.relevance,failureCount:o.failureCount})}async start(){await this.seedFromPeerStore(),this.registerRpcHandlers(),await this.proactiveAnnounceOnStart(),this.startStabilizationLoop(),this.mode==="active"&&this.preconnectNeighbors(),this.node.addEventListener("peer:connect",async e=>{if(!this.postBootstrapAnnounced){this.postBootstrapAnnounced=!0;try{await this.announceNeighborsBounded(8)}catch(t){Kr("postBootstrap announce failed - %o",t)}}}),this.node.addEventListener("peer:connect",async e=>{try{let t=e?.detail?.id?.toString?.();if(!t)return;let n=this.store.getById(t)?.coord??await qe(Oe(t));this.store.setState(t,"connected"),await this.applyTouch(t,n)}catch(t){Kr("peer:connect handler failed - %o",t)}}),this.node.addEventListener("peer:disconnect",async e=>{try{let t=e?.detail?.id?.toString?.();if(!t)return;let n=this.store.getById(t)?.coord??await qe(Oe(t));this.store.setState(t,"disconnected"),await this.applyFailure(t,n)}catch(t){Kr("peer:disconnect handler failed - %o",t)}})}async stop(){this.stabilizing=!1;try{await this.sendLeaveToNeighbors()}catch(e){console.warn("sendLeaveToNeighbors failed",e)}}setMode(e){this.mode=e,e==="active"&&!this.preconnectRunning&&this.startActivePreconnectLoop()}async ready(){}registerRpcHandlers(){AI(this.node,async()=>this.handleNeighborsRequest(),(e,t)=>{this.mergeAnnounceSnapshot(e,t)},this.protocols),_I(this.node,async e=>this.handleMaybeAct(e),this.protocols.PROTOCOL_MAYBE_ACT),kI(this.node,async e=>this.handleLeave(e.from),this.protocols.PROTOCOL_LEAVE),MI(this.node,this.protocols.PROTOCOL_PING,()=>this.getNetworkSizeEstimate())}async handleNeighborsRequest(){return this.bucketNeighbors.tryTake()?await this.snapshot():{v:1,from:this.node.peerId.toString(),timestamp:Date.now(),successors:[],predecessors:[],sig:""}}async handleMaybeAct(e){if(e.ttl<=0)return await this.nearAnchorOnly(e);if(e.activity&&e.activity.length>128*1024)return await this.nearAnchorOnly(e);if(!this.bucketMaybeAct.tryTake())return await this.nearAnchorOnly(e);let t=this.cfg.profile==="core"?16:4;if(this.inflightAct>=t)return this.nearAnchorOnly(e);this.inflightAct++;try{return await this.routeAct(e)}catch(n){return console.error("routeAct failed:",n),await this.nearAnchorOnly(e)}finally{this.inflightAct--}}isConnected(e){try{return this.node.getConnections(Oe(e)).length>0}catch{return!1}}hasAddresses(e){try{let t=this.node.getMultiaddrsForPeer?.(Oe(e))??[];return Array.isArray(t)&&t.length>0}catch{return!1}}async proactiveAnnounceOnStart(){try{await this.announceNeighborsBounded(8)}catch(e){console.warn("proactiveAnnounceOnStart failed",e)}}async announceNeighborsBounded(e){let t=await qe(this.node.peerId),n=this.node.peerId.toString(),s=Array.from(new Set([...this.getNeighbors(t,"right",this.cfg.m),...this.getNeighbors(t,"left",this.cfg.m)])).filter(i=>i!==n).slice(0,e),o=await this.snapshot();for(let i of s)if(this.isConnected(i)||this.hasAddresses(i))try{await Py(this.node,i,o,this.protocols.PROTOCOL_NEIGHBORS_ANNOUNCE),this.diag.announcementsSent++}catch(a){console.warn("announce failed",i,a)}}async preconnectNeighbors(){try{let e=await qe(this.node.peerId),t=this.node.peerId.toString(),n=Array.from(new Set([...this.getNeighbors(e,"right",Math.min(6,this.cfg.m)),...this.getNeighbors(e,"left",Math.min(6,this.cfg.m))])).filter(s=>s!==t);for(let s of n)if(this.isConnected(s)||this.hasAddresses(s))try{await kl(this.node,s,this.protocols.PROTOCOL_PING),this.diag.pingsSent++}catch(o){Kr("preconnectNeighbors ping failed for %s - %o",s,o)}}catch(e){Kr("preconnectNeighbors outer failed - %o",e)}}startActivePreconnectLoop(){if(this.preconnectRunning)return;this.preconnectRunning=!0;let e=async()=>{if(!this.preconnectRunning||this.mode!=="active"){this.preconnectRunning=!1;return}try{let t=await this.selfCoord(),n=this.node.peerId.toString(),s=this.cfg.profile==="core"?6:3,o=Array.from(new Set([...this.getNeighbors(t,"right",Math.min(12,this.cfg.m)),...this.getNeighbors(t,"left",Math.min(12,this.cfg.m))])).filter(i=>i!==n).slice(0,s);for(let i of o)if(this.isConnected(i)||this.hasAddresses(i))try{await kl(this.node,i,this.protocols.PROTOCOL_PING),this.diag.pingsSent++}catch(a){Kr("active preconnect ping failed for %s - %o",i,a)}}catch(t){Kr("active preconnect tick failed - %o",t)}setTimeout(e,1e3)};e()}async sendLeaveToNeighbors(){try{let e=await qe(this.node.peerId),t=this.node.peerId.toString(),n=Array.from(new Set([...this.getNeighbors(e,"right",this.cfg.m),...this.getNeighbors(e,"left",this.cfg.m)])).filter(o=>o!==t).slice(0,8),s={v:1,from:this.node.peerId.toString(),timestamp:Date.now()};for(let o of n)try{await LI(this.node,o,s,this.protocols.PROTOCOL_LEAVE)}catch(i){Kr("sendLeave failed for %s - %o",o,i)}}catch(e){Kr("sendLeaveToNeighbors outer failed - %o",e)}}async handleLeave(e){try{let t=null,n=this.store.getById(e);if(n)t=n.coord;else try{t=await qe(Oe(e))}catch(l){console.warn("handleLeave: could not hash departing peer id",e,l)}if(this.store.remove(e),t)try{await this.applyFailure(e,t)}catch{}if(!t)return;let s=Array.from(new Set([...this.store.neighborsRight(t,this.cfg.m),...this.store.neighborsLeft(t,this.cfg.m)])),o=this.expandCohort(s,t,Math.max(2,Math.ceil(this.cfg.m/2))),i=new Set(s),a=o.filter(l=>!i.has(l)),c=a.slice(0,Math.min(a.length,6));for(let l of c)try{if(await kl(this.node,l,this.protocols.PROTOCOL_PING),!this.isConnected(l)){let u=await this.snapshot();await Py(this.node,l,u,this.protocols.PROTOCOL_NEIGHBORS_ANNOUNCE)}}catch(u){console.warn("warm/announce failed for",l,u)}await this.mergeNeighborSnapshots(c.slice(0,4))}catch(t){console.error("handleLeave failed for",e,t)}}async mergeAnnounceSnapshot(e,t){try{let n=Oe(e),s=await qe(n),o=[];this.store.getById(e)||o.push(e),this.store.upsert(e,s),await this.applyTouch(e,s),t.metadata&&this.store.update(e,{metadata:t.metadata});for(let i of[...t.successors??[],...t.predecessors??[]])try{let a=await qe(Oe(i));this.store.getById(i)||o.push(i),this.store.upsert(i,a),await this.applyTouch(i,a)}catch(a){console.warn("mergeAnnounceSnapshot: failed for",i,a)}for(let i of t.sample??[])try{let a=D(i.coord,"base64url");this.store.getById(i.id)||o.push(i.id),this.store.upsert(i.id,a),await this.applyTouch(i.id,a)}catch(a){Kr("mergeAnnounceSnapshot sample upsert failed for %s - %o",i.id,a)}this.enforceCapacity(),this.emitDiscovered(o)}catch(n){console.warn("mergeAnnounceSnapshot failed for",e,n)}}async seedFromPeerStore(){try{let e=this.node.peerStore?.getPeers?.()??[],t=[];for(let n of e)try{let s=await qe(n.id),o=n.id.toString();this.store.getById(o)||t.push(o),this.store.upsert(o,s)}catch(s){console.warn("failed to add peer from peerStore",n?.id?.toString?.(),s)}try{let n=await qe(this.node.peerId),s=this.node.peerId.toString();this.store.getById(s)||t.push(s),this.store.upsert(s,n)}catch(n){console.error("failed to add self to store",n)}this.enforceCapacity(),this.emitDiscovered(t)}catch(e){console.error("seedFromPeerStore failed:",e)}}startStabilizationLoop(){if(this.stabilizing)return;this.stabilizing=!0;let e=async()=>{if(this.stabilizing)try{await this.seedFromPeerStore(),await this.seedFromBootstraps(),await this.stabilizeOnce()}catch(t){console.error("stabilize tick failed:",t)}finally{let t=this.mode==="active"?300:1500;setTimeout(e,t)}};e()}async seedFromBootstraps(){if(!this.cfg.bootstraps||this.cfg.bootstraps.length===0)return;let e=[];for(let t of this.cfg.bootstraps.slice(0,8))try{let n=t;if(t.startsWith("/"))try{let a=Rl(t).getPeerId();a&&(n=a)}catch{}let s=Oe(n),o=await qe(s);this.store.getById(n)||e.push(n),this.store.upsert(n,o),await this.applyTouch(n,o)}catch(n){console.warn("seedFromBootstraps failed for",t,n)}this.enforceCapacity(),this.emitDiscovered(e)}async stabilizeOnce(){let e=await qe(this.node.peerId),t=this.node.peerId.toString(),s=this.getNeighbors(e,"both",Math.max(2,this.cfg.m)).filter(o=>o!==t&&(this.isConnected(o)||this.hasAddresses(o)));await this.probeNeighborsLatency(s.slice(0,4)),await this.mergeNeighborSnapshots(s.slice(0,4))}async probeNeighborsLatency(e){for(let t of e)try{let n=await kl(this.node,t,this.protocols.PROTOCOL_PING);if(this.diag.pingsSent++,n.ok){let s=this.store.getById(t)?.coord??await qe(Oe(t));await this.applySuccess(t,s,n.rttMs),this.diag.pingsOk++}else{let s=this.store.getById(t)?.coord??await qe(Oe(t));await this.applyFailure(t,s),this.diag.pingsFail++}}catch{try{let s=this.store.getById(t)?.coord??await qe(Oe(t));await this.applyFailure(t,s),this.diag.pingsFail++}catch{}}}async mergeNeighborSnapshots(e){let t=[];for(let n of e)try{let s=await CI(this.node,n,this.protocols.PROTOCOL_NEIGHBORS);this.diag.snapshotsFetched++;let o=this.cfg.profile==="core"?16:8,i=this.cfg.profile==="core"?16:8,a=(s.successors??[]).slice(0,o),c=(s.predecessors??[]).slice(0,i);for(let u of[...a,...c])try{let h=await qe(Oe(u));this.store.getById(u)||t.push(u),this.store.upsert(u,h),await this.applyTouch(u,h)}catch(h){console.warn("failed to merge neighbor",u,h)}let l=this.cfg.profile==="core"?8:6;for(let u of(s.sample??[]).slice(0,l))try{let h=D(u.coord,"base64url");this.store.getById(u.id)||t.push(u.id),this.store.upsert(u.id,h),await this.applyTouch(u.id,h)}catch(h){Kr("mergeNeighborSnapshots sample upsert failed for %s - %o",u.id,h)}}catch(s){console.warn("fetchNeighbors failed for",n,s)}this.enforceCapacity(),this.emitDiscovered(t)}async snapshot(){let e=await qe(this.node.peerId),{n:t,confidence:n}=Yd(this.store,this.cfg.m),s=this.cfg.profile==="core"?12:6,o=this.cfg.profile==="core"?12:6,i=this.cfg.profile==="core"?8:6,a=this.getNeighbors(e,"right",this.cfg.m),c=this.getNeighbors(e,"left",this.cfg.m),l=a.slice(0,s),u=c.slice(0,o),h=Array.from(new Set([...l.slice(0,4),...u.slice(0,4)])).slice(0,i),p=await Promise.all(h.map(async f=>{let d=this.store.getById(f);return d?{id:f,coord:YS(d.coord),relevance:d.relevance}:{id:f,coord:"",relevance:0}}));return{v:1,from:this.node.peerId.toString(),timestamp:Date.now(),successors:l,predecessors:u,sample:p,size_estimate:t,confidence:n,sig:"",metadata:this.metadata}}neighborDistance(e,t,n){let s=new Set,o=Math.max(1,n),a=this.assembleCohort(t,o,s).findIndex(c=>c===e);return a>=0?a:Number.POSITIVE_INFINITY}getNeighbors(e,t,n){let s=[];return(t==="right"||t==="both")&&s.push(...this.store.neighborsRight(e,n)),(t==="left"||t==="both")&&s.push(...this.store.neighborsLeft(e,n)),Array.from(new Set(s)).slice(0,n)}nextSuccessor(e,t){let n=t.findIndex(s=>s.id===e.id);return t[(n+1)%t.length]}nextPredecessor(e,t){let n=t.findIndex(s=>s.id===e.id);return t[(n-1+t.length)%t.length]}assembleCohort(e,t,n){let s=[],o=n??new Set,i=this.store.neighborsRight(e,t*2),a=this.store.neighborsLeft(e,t*2),c=0,l=0;for(;s.length<t&&(c<i.length||l<a.length);)if(s.length%2===0){let u=i[c++];u&&!o.has(u)&&s.push(u)}else{let u=a[l++];u&&!o.has(u)&&s.push(u)}return Array.from(new Set(s)).slice(0,t)}expandCohort(e,t,n,s){let o=new Set(e),i=this.assembleCohort(t,e.length+n,s);for(let a of i)o.add(a);return Array.from(o)}async nearAnchorOnly(e){let t=D(e.key,"base64url"),n=await ir(t),s=this.getNeighbors(n,"right",this.cfg.m),o=this.getNeighbors(n,"left",this.cfg.m);return{v:1,anchors:this.pickAnchors([...s.slice(0,3),...o.slice(0,3)]),cohort_hint:Array.from(new Set([...s.slice(0,2),...o.slice(0,2)])),estimated_cluster_size:this.cfg.k,confidence:.5}}emitDiscovered(e){if(e.length===0)return;let t=Date.now(),n=this.cfg.profile==="core"?10*6e4:30*6e4,s=this.node,o=0;for(let i of Array.from(new Set(e)))if(!((this.announcedIds.get(i)??0)>t)){if(!this.bucketDiscovery.tryTake())break;try{let c=Oe(i);s.dispatchEvent?.(new CustomEvent("peer:discovery",{detail:{id:c,multiaddrs:[]}})),this.announcedIds.set(i,t+n),o++}catch(c){console.warn("emitDiscovered failed for",i,c)}}if(o>0&&this.announcedIds.size>4096)for(let[i,a]of this.announcedIds)a<=t&&this.announcedIds.delete(i)}pickAnchors(e){let t=Array.from(new Set(e));if(t.length===0)return[];let n=c=>.5,s=new Uint8Array(32),o=sf(this.store,s,t,c=>this.isConnected(c),n),i=t.filter(c=>c!==o),a=sf(this.store,s,i,c=>this.isConnected(c),n);return[o,a].filter(c=>!!c)}async routeAct(e){let t=D(e.key,"base64url"),n=await ir(t),s=this.node.peerId.toString();if(this.neighborDistance(s,n,2)>1&&e.ttl>0){let h=new Set([...e.breadcrumbs??[],s]),p=this.assembleCohort(n,Math.max(4,this.cfg.m)).filter(m=>!h.has(m)),f=m=>.5,d=sf(this.store,n,p,m=>this.isConnected(m),f);if(d){let m={...e,ttl:e.ttl-1,breadcrumbs:[...e.breadcrumbs??[],s]};try{return await PI(this.node,d,m,this.protocols.PROTOCOL_MAYBE_ACT)}catch(g){console.warn("forward maybeAct failed to",d,g)}}}let{n:i,confidence:a}=Yd(this.store,this.cfg.m),c=this.getNeighbors(n,"right",this.cfg.m),l=this.getNeighbors(n,"left",this.cfg.m);return{v:1,anchors:this.pickAnchors([...c.slice(0,4),...l.slice(0,4)]),cohort_hint:Array.from(new Set([...c.slice(0,4),...l.slice(0,4)])),estimated_cluster_size:Math.max(this.cfg.k,i),confidence:a}}report(e){}reportNetworkSize(e,t,n="external"){let s=Date.now();this.networkObservations.push({estimate:e,confidence:t,timestamp:s,source:n});let o=s-this.observationWindowMs;this.networkObservations=this.networkObservations.filter(i=>i.timestamp>o),this.networkObservations.length>this.maxObservations&&(this.networkObservations=this.networkObservations.slice(-this.maxObservations))}getNetworkSizeEstimate(){let e=Yd(this.store,this.cfg.m),t=Date.now(),n=[{estimate:e.n,confidence:e.confidence,timestamp:t,source:"fret"},...this.networkObservations];if(n.length===0)return{size_estimate:0,confidence:0,sources:0};let s=0,o=0,i=0;for(let l of n){let u=t-l.timestamp,h=Math.exp(-u/(this.observationWindowMs/3)),p=h*l.confidence;o+=l.estimate*p,i+=l.confidence*h,s+=p}if(s===0)return{size_estimate:0,confidence:0,sources:0};let a=Math.round(o/s),c=i/n.length;return{size_estimate:a,confidence:Math.min(1,c),sources:n.length}}getNetworkChurn(){if(this.networkObservations.length<2)return 0;let e=Date.now(),t=this.observationWindowMs/2,n=e-t,s=this.networkObservations.filter(l=>l.timestamp>n),o=this.networkObservations.filter(l=>l.timestamp<=n);if(s.length===0||o.length===0)return 0;let i=s.reduce((l,u)=>l+u.estimate,0)/s.length,a=o.reduce((l,u)=>l+u.estimate,0)/o.length;return(i-a)/t*6e4}detectPartition(){if(this.networkObservations.length<10)return!1;let e=this.getNetworkSizeEstimate();if(e.confidence<.3)return!1;let t=Date.now()-3e4,n=this.networkObservations.filter(c=>c.timestamp<t);if(n.length<3)return!1;let s=n.slice(-5).reduce((c,l)=>c+l.estimate,0)/Math.min(5,n.length);if(e.size_estimate/s<.5)return!0;let i=Math.abs(this.getNetworkChurn()),a=e.size_estimate*.1;return i>a}setMetadata(e){this.metadata=e}getMetadata(e){return this.store.getById(e)?.metadata}listPeers(){return this.store.list().map(e=>({id:e.id,metadata:e.metadata}))}};var GB=vs("service:discovery");function a3(r,e){let t=r;for(let n of e.list())try{let s=Oe(n.id);t.dispatchEvent?.(new CustomEvent("peer:discovery",{detail:{id:s,multiaddrs:[]}}))}catch(s){GB("seedDiscovery failed for %s - %o",n.id,s)}}var af=class{components;cfg;inner=null;nodeRef=null;constructor(e,t){this.components=e,this.cfg=t}get[Symbol.toStringTag](){return"@optimystic/fret"}setLibp2p(e){this.nodeRef=e}ensure(){if(!this.inner){if(!this.nodeRef)throw new Error("Libp2pFretService: libp2p node not injected");this.inner=new Qi(this.nodeRef,this.cfg)}return this.inner}async start(){if(this.ensure(),!this.nodeRef)throw new Error("Libp2pFretService.start: libp2p node not injected");a3(this.nodeRef,this.inner?.store??{}),await this.ensure().start()}async stop(){await this.inner?.stop()}async routeAct(e){return await this.ensure().routeAct(e)}getNeighborsForKey(e,t,n){return this.ensure().getNeighbors(e,t,n)}assembleCohortForKey(e,t){return this.ensure().assembleCohort(e,t)}getDiagnostics(){return this.ensure().getDiagnostics?.()}neighborDistance(e,t,n){return this.ensure().neighborDistance(e,t,n)}getNeighbors(e,t,n){return this.ensure().getNeighbors(e,t,n)}assembleCohort(e,t,n){return this.ensure().assembleCohort(e,t,n)}expandCohort(e,t,n,s){return this.ensure().expandCohort(e,t,n,s)}async ready(){await this.ensure().ready()}setMode(e){this.ensure().setMode(e)}setMetadata(e){this.ensure().setMetadata(e)}report(e){this.ensure().report(e)}getMetadata(e){return this.ensure().getMetadata(e)}listPeers(){return this.ensure().listPeers()}};function c3(r){return e=>new af(e,r)}ke();var dA="/db-p2p/sync/",fA="1.0.0",Ul=(r="")=>`${r}${dA}${fA}`;var ho=class extends Cn{protocol;constructor(e,t,n=""){super(e,t),this.protocol=Ul(n)}async requestBlock(e){return await this.processMessage(e,this.protocol)}getProtocol(){return this.protocol}};var Kl=class{fretAdapter;peerNetwork;protocolPrefix;metrics={totalRequests:0,successByRing:new Map,failureByRing:new Map,averageDurationMs:0};constructor(e,t,n){this.fretAdapter=e,this.peerNetwork=t,this.protocolPrefix=n}log=Sr("storage:restoration");async restore(e,t){let n=Date.now();this.metrics.totalRequests++;let s=await this.getMyRingPeers(e),o=this.getMyRingDepth();for(let a of s){let c=await this.queryPeer(a,e,t);if(c)return this.recordSuccess(o,e,Date.now()-n),c}for(let a=o-1;a>=0;a--){let c=this.fretAdapter.findPeersAtRing(a),l=this.filterByPartition(c,e,a);for(let u of l){let h=await this.queryPeer(u,e,t);if(h)return this.recordSuccess(a,e,Date.now()-n),h}}let i=Date.now()-n;this.log("restore failed for block %s after %dms",e,i)}createRestoreCallback(){return async(e,t)=>await this.restore(e,t)}async getMyRingPeers(e){let t=new TextEncoder().encode(e),n=await ir(t);return this.fretAdapter.getFret().assembleCohort(n,10)}getMyRingDepth(){return this.fretAdapter.getMyArachnodeInfo()?.ringDepth??8}filterByPartition(e,t,n){if(n===0)return e;let s=this.extractBlockPrefix(t,n);return e.filter(o=>{let i=this.fretAdapter.getArachnodeInfo(o);return!i||!i.partition?!1:i.partition.prefixValue===s})}extractBlockPrefix(e,t){let n=new TextEncoder().encode(e),s=new Uint8Array(32);for(let i=0;i<Math.min(n.length,s.length);i++)s[i]=n[i];let o=0;for(let i=0;i<t;i++){let a=Math.floor(i/8),c=7-i%8,l=s[a]>>c&1;o=o<<1|l}return o}async queryPeer(e,t,n){try{let s=de(e),i=await new ho(s,this.peerNetwork,this.protocolPrefix).requestBlock({blockId:t,rev:n});return i.success?i.archive:void 0}catch(s){this.log("queryPeer failed for %s - %o",e,s);return}}recordSuccess(e,t,n){let s=this.metrics.successByRing.get(e)??0;this.metrics.successByRing.set(e,s+1);let o=Array.from(this.metrics.successByRing.values()).reduce((a,c)=>a+c,0),i=this.metrics.averageDurationMs*(o-1);this.metrics.averageDurationMs=(i+n)/o,console.log(`[Ring ${e}] Successfully restored block ${t} in ${n}ms`)}getMetrics(){return{...this.metrics}}};var Fl=class{fretAdapter;storageMonitor;config;constructor(e,t,n){this.fretAdapter=e,this.storageMonitor=t,this.config=n}async determineRing(){let e=await this.storageMonitor.getCapacity();if(e.available<this.config.minCapacity)return-1;let s=1e3*(100*1024),o=e.available/s,i=Math.max(0,Math.ceil(-Math.log2(Math.max(.001,o))));return Math.min(i,16)}async calculatePartition(e,t){if(e===0)return;let n=await qe({toString:()=>t}),s=e,o=this.extractPrefix(n,s);return{prefixBits:s,prefixValue:o}}async createArachnodeInfo(e){let t=await this.storageMonitor.getCapacity(),n=await this.determineRing(),s=n>=0?await this.calculatePartition(n,e):void 0;return{ringDepth:Math.max(0,n),partition:s,capacity:{total:t.total,used:t.used,available:t.available},status:"active"}}async shouldTransition(){let e=await this.storageMonitor.getCapacity(),t=e.used/e.total;if(t>this.config.thresholds.moveOut)return{shouldMove:!0,direction:"out",newRingDepth:await this.determineRing()+1};if(t<this.config.thresholds.moveIn){let n=await this.determineRing();if(n>0)return{shouldMove:!0,direction:"in",newRingDepth:n-1}}return{shouldMove:!1}}extractPrefix(e,t){let n=0;for(let s=0;s<t;s++){let o=Math.floor(s/8),i=7-s%8,a=e[o]>>i&1;n=n<<1|a}return n}};var zl=class{storage;config;constructor(e,t={}){this.storage=e,this.config=t}async getCapacity(){let t=this.config.totalBytes??10737418240,n=this.config.usedBytes,s=this.config.availableBytes;if(n!==void 0||s!==void 0||this.config.totalBytes!==void 0){let a=n??Math.max(0,t-(s??t)),c=s??Math.max(0,t-a);return{total:t,used:Math.min(t,Math.max(0,a)),available:Math.max(0,Math.min(t,c))}}let o=await this.estimateUsedSpace(),i=Math.max(0,t-o);return{total:t,used:o,available:i}}async estimateUsedSpace(){return 0}};var $l=class r{fret;static ARACHNODE_KEY="arachnode";constructor(e){this.fret=e}setArachnodeInfo(e){this.fret.setMetadata({[r.ARACHNODE_KEY]:e})}getArachnodeInfo(e){return this.fret.getMetadata(e)?.[r.ARACHNODE_KEY]}getMyArachnodeInfo(){let e=this.fret.node?.peerId?.toString();if(e)return this.getArachnodeInfo(e)}findPeersAtRing(e){return this.fret.listPeers().filter(n=>n.metadata?.[r.ARACHNODE_KEY]?.ringDepth===e).map(n=>n.id)}getKnownRings(){let e=this.fret.listPeers(),t=new Set;for(let n of e){let s=n.metadata?.[r.ARACHNODE_KEY];s?.ringDepth!==void 0&&t.add(s.ringDepth)}return Array.from(t).sort((n,s)=>n-s)}getRingStats(){let e=this.fret.listPeers(),t=new Map;for(let n of e){let s=n.metadata?.[r.ARACHNODE_KEY];if(s){let o=t.get(s.ringDepth)??{count:0,totalCapacity:0};t.set(s.ringDepth,{count:o.count+1,totalCapacity:o.totalCapacity+s.capacity.available})}}return Array.from(t.entries()).map(([n,s])=>({ringDepth:n,peerCount:s.count,avgCapacity:s.totalCapacity/s.count})).sort((n,s)=>n.ringDepth-s.ringDepth)}getFret(){return this.fret}};te();ce();var cf=class{components;running=!1;log;protocol;repo;registrar;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("db-p2p:sync-service"),this.protocol=Ul(t.protocolPrefix??""),this.repo=e.repo,this.registrar=e.registrar}async start(){this.running||(await this.registrar.handle(this.protocol,async e=>{await this.handleSyncRequest(e.stream)}),this.running=!0,this.log("Sync service started on protocol %s",this.protocol))}async stop(){this.running&&(await this.registrar.unhandle(this.protocol),this.running=!1,this.log("Sync service stopped"))}async handleSyncRequest(e){try{let t=await this.readRequest(e);this.log("[Ring Zulu] Received sync request for block %s revision %s",t.blockId,t.rev??"latest");let n=await this.buildArchive(t.blockId,t.rev,t.includePending,t.maxRevisions),s=n?{success:!0,archive:n,responderId:e.id}:{success:!1,error:"Block not found in local storage"};await this.sendResponse(e,s),this.log("[Ring Zulu] %s sync request for block %s",s.success?"Fulfilled":"Failed",t.blockId)}catch(t){this.log.error("Error handling sync request:",t);try{let n={success:!1,error:t instanceof Error?t.message:"Unknown error"};await this.sendResponse(e,n)}catch(n){this.log.error("Failed to send error response:",n)}}finally{try{await e.close()}catch{}}}async readRequest(e){let t=[];if(await ht(e,Pr,async s=>{for await(let o of s)t.push(o.subarray())}),t.length===0)throw new Error("No request received");let n=P(t[0],"utf8");return JSON.parse(n)}async sendResponse(e,t){let n=JSON.stringify(t),s=D(n,"utf8"),o=ht([s],yr);for await(let i of o)e.send(i)}async buildArchive(e,t,n,s){try{let o=t!==void 0?{rev:t,committed:[],pending:[]}:void 0,a=(await this.repo.get({blockIds:[e],context:o}))[e];if(!a||!a.state.latest)return;let c=a.state.latest;return{blockId:e,revisions:{[c.rev]:{action:{actionId:c.actionId,transform:{insert:a.block}},block:a.block}},range:[c.rev,c.rev+1]}}catch(o){this.log.error("Error building archive for block %s:",e,o);return}}},l3=(r={})=>e=>new cf(e,r);ce();ke();Ne();gr();bt();te();ce();var Et=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Un=class extends Error{static name="ValidationError";name="ValidationError"},lf=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},uf=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var ufe=new Uint8Array(0);function pA(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Tr(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function mA(r){return new TextEncoder().encode(r)}function gA(r){return new TextDecoder().decode(r)}var p3={};z(p3,{base32:()=>Ss,base32hex:()=>rU,base32hexpad:()=>sU,base32hexpadupper:()=>oU,base32hexupper:()=>nU,base32pad:()=>eU,base32padupper:()=>tU,base32upper:()=>ZB,base32z:()=>iU});function WB(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var v=d[y],S=0,E=w-1;(v!==0||S<g)&&E!==-1;E--,S++)v+=256*x[E]>>>0,x[E]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var A=c.repeat(m);I<w;++I)A+=r.charAt(x[I]);return A}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*w[S]>>>0,w[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(d[m]!==" "){for(var E=b-y;E!==b&&w[E]===0;)E++;for(var I=new Uint8Array(g+(b-E)),A=g;E!==b;)I[A++]=w[E++];return I}}}function f(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:f}}var jB=WB,YB=jB,bA=YB;var u3=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},h3=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return wA(this,e)}},d3=class{decoders;constructor(e){this.decoders=e}or(e){return wA(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function wA(r,e){return new d3({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var f3=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new u3(e,t,n),this.decoder=new h3(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ji({name:r,prefix:e,encode:t,decode:n}){return new f3(r,e,t,n)}function Es({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=bA(t,r);return Ji({prefix:e,name:r,encode:n,decode:o=>Tr(s(o))})}function XB(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function QB(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function JB(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function We({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=JB(n);return Ji({prefix:e,name:r,encode(o){return QB(o,n,t)},decode(o){return XB(o,s,t,r)}})}var Ss=We({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ZB=We({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),eU=We({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),tU=We({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),rU=We({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),nU=We({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),sU=We({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),oU=We({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),iU=We({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var m3={};z(m3,{base36:()=>Hl,base36upper:()=>aU});var Hl=Es({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),aU=Es({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var g3={};z(g3,{base58btc:()=>an,base58flickr:()=>cU});var an=Es({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),cU=Es({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var lU=EA,xA=128,uU=127,hU=~uU,dU=Math.pow(2,31);function EA(r,e,t){e=e||[],t=t||0;for(var n=t;r>=dU;)e[t++]=r&255|xA,r/=128;for(;r&hU;)e[t++]=r&255|xA,r>>>=7;return e[t]=r|0,EA.bytes=t-n+1,e}var fU=y3,pU=128,vA=127;function y3(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw y3.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&vA)<<s:(i&vA)*Math.pow(2,s),s+=7}while(i>=pU);return y3.bytes=o-n,t}var mU=Math.pow(2,7),gU=Math.pow(2,14),yU=Math.pow(2,21),bU=Math.pow(2,28),wU=Math.pow(2,35),xU=Math.pow(2,42),vU=Math.pow(2,49),EU=Math.pow(2,56),SU=Math.pow(2,63),IU=function(r){return r<mU?1:r<gU?2:r<yU?3:r<bU?4:r<wU?5:r<xU?6:r<vU?7:r<EU?8:r<SU?9:10},AU={encode:lU,decode:fU,encodingLength:IU},CU=AU,ql=CU;function Vl(r,e=0){return[ql.decode(r,e),ql.decode.bytes]}function Zi(r,e,t=0){return ql.encode(r,e,t),e}function ea(r){return ql.encodingLength(r)}function ra(r,e){let t=e.byteLength,n=ea(r),s=n+ea(t),o=new Uint8Array(s+t);return Zi(r,o,0),Zi(t,o,n),o.set(e,s),new ta(r,t,e,o)}function SA(r){let e=Tr(r),[t,n]=Vl(e),[s,o]=Vl(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new ta(t,s,i,e)}function IA(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&pA(r.bytes,t.bytes)}}var ta=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function AA(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return _U(t,b3(r),e??an.encoder);default:return PU(t,b3(r),e??Ss.encoder)}}var CA=new WeakMap;function b3(r){let e=CA.get(r);if(e==null){let t=new Map;return CA.set(r,t),t}return e}var na=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Wl)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==DU)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=ra(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&IA(e.multihash,n.multihash)}toString(e){return AA(this,e)}toJSON(){return{"/":AA(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??TA(n,s,o.bytes))}else if(t[kU]===!0){let{version:n,multihash:s,code:o}=t,i=SA(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Wl)throw new Error(`Version 0 CID must use dag-pb (code: ${Wl}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=TA(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Wl,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=Tr(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new ta(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,p]=Vl(e.subarray(t));return t+=p,h},s=n(),o=Wl;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=TU(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return b3(o).set(n,e),o}};function TU(r,e){switch(r[0]){case"Q":{let t=e??an;return[an.prefix,t.decode(`${an.prefix}${r}`)]}case an.prefix:{let t=e??an;return[an.prefix,t.decode(r)]}case Ss.prefix:{let t=e??Ss;return[Ss.prefix,t.decode(r)]}case Hl.prefix:{let t=e??Hl;return[Hl.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function _U(r,e,t){let{prefix:n}=t;if(n!==an.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function PU(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var Wl=112,DU=18;function TA(r,e,t){let n=ea(r),s=n+ea(e),o=new Uint8Array(s+t.byteLength);return Zi(r,o,0),Zi(e,o,n),o.set(t,s),o}var kU=Symbol.for("@ipld/js-cid/CID");var LU=20;function x3({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new w3(r,e,t,n,s)}var w3=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??LU,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?_A(n,this.code,t?.truncate):n.then(s=>_A(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function _A(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return ra(e,r)}var E3={};z(E3,{base64:()=>MU,base64pad:()=>OU,base64url:()=>v3,base64urlpad:()=>RU});var MU=We({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),OU=We({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),v3=We({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),RU=We({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var S3={};z(S3,{base10:()=>NU});var NU=Es({prefix:"9",name:"base10",alphabet:"0123456789"});var I3={};z(I3,{base16:()=>BU,base16upper:()=>UU});var BU=We({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),UU=We({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var A3={};z(A3,{base2:()=>KU});var KU=We({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var C3={};z(C3,{base256emoji:()=>qU});var DA=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),FU=DA.reduce((r,e,t)=>(r[t]=e,r),[]),zU=DA.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function $U(r){return r.reduce((e,t)=>(e+=FU[t],e),"")}function HU(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=zU[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var qU=Ji({prefix:"\u{1F680}",name:"base256emoji",encode:$U,decode:HU});var T3={};z(T3,{base8:()=>VU});var VU=We({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var _3={};z(_3,{identity:()=>GU});var GU=Ji({prefix:"\0",name:"identity",encode:r=>gA(r),decode:r=>mA(r)});var qfe=new TextEncoder,Vfe=new TextDecoder;var P3={};z(P3,{identity:()=>QU});var kA=0,YU="identity",LA=Tr;function XU(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return ra(kA,LA(r))}var QU={code:kA,name:YU,encode:LA,digest:XU};var k3={};z(k3,{sha256:()=>JU,sha512:()=>ZU});var D3=ie(ee("crypto"),1);var JU=x3({name:"sha2-256",code:18,encode:r=>Tr(D3.default.createHash("sha256").update(r).digest())}),ZU=x3({name:"sha2-512",code:19,encode:r=>Tr(D3.default.createHash("sha512").update(r).digest())});var MA={..._3,...A3,...T3,...S3,...I3,...p3,...m3,...g3,...E3,...C3},Qfe={...k3,...P3};bt();te();ce();function M3(r){return e=>P(e,r)}function O3(r){return e=>D(e,r)}function sa(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function fo(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function OA(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=D(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=fo(n);return Ee([t,s],t.length+s.length)}function RA(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=Ss.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=fo(n);return Ee([t,s],t.length+s.length)}function R3(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=P(e,"base32"),s=sa(t);return`${n}:${s}`}var N3=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let s=parseInt(t,10);if(isNaN(s)||s<0||s>255)throw new Et("Invalid byte value in IP address");e[n]=s}),e},NA=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=(0,fe.isIPv4)(t[n]),i;o&&(i=N3(t[n]),t[n]=P(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,P(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new Et("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},BA=function(r){if(r.byteLength!==4)throw new Et("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},UA=function(r){if(r.byteLength!==16)throw new Et("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Et(`Invalid IPv6 address "${t}"`)}};function KA(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Et(`Invalid IPv6 address "${r}"`)}}var L3=Object.values(MA).map(r=>r.decoder),eK=(function(){let r=L3[0].or(L3[1]);return L3.slice(2).forEach(e=>r=r.or(e)),r})();function FA(r){return eK.decode(r)}function zA(r){return e=>r.encoder.encode(e)}function tK(r){if(parseInt(r).toString()!==r)throw new Un("Value must be an integer")}function rK(r){if(r<0)throw new Un("Value must be a positive integer, or zero")}function nK(r){return e=>{if(e>r)throw new Un(`Value must be smaller than or equal to ${r}`)}}function sK(...r){return e=>{for(let t of r)t(e)}}var jl=sK(tK,rK,nK(65535));var mt=-1,B3=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new uf(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Kn=new B3,wK=[{code:4,name:"ip4",size:32,valueToBytes:N3,bytesToValue:BA,validate:r=>{if(!(0,fe.isIPv4)(r))throw new Un(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:fo,bytesToValue:sa,validate:jl},{code:273,name:"udp",size:16,valueToBytes:fo,bytesToValue:sa,validate:jl},{code:33,name:"dccp",size:16,valueToBytes:fo,bytesToValue:sa,validate:jl},{code:41,name:"ip6",size:128,valueToBytes:NA,bytesToValue:UA,stringToValue:KA,validate:r=>{if(!(0,fe.isIPv6)(r))throw new Un(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:mt},{code:43,name:"ipcidr",size:8,bytesToValue:M3("base10"),valueToBytes:O3("base10")},{code:53,name:"dns",size:mt},{code:54,name:"dns4",size:mt},{code:55,name:"dns6",size:mt},{code:56,name:"dnsaddr",size:mt},{code:132,name:"sctp",size:16,valueToBytes:fo,bytesToValue:sa,validate:jl},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:mt,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:mt,bytesToValue:M3("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?O3("base58btc")(r):na.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:R3,valueToBytes:OA},{code:445,name:"onion3",size:296,bytesToValue:R3,valueToBytes:RA},{code:446,name:"garlic64",size:mt},{code:447,name:"garlic32",size:mt},{code:448,name:"tls"},{code:449,name:"sni",size:mt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:mt,bytesToValue:zA(v3),valueToBytes:FA},{code:480,name:"http"},{code:481,name:"http-path",size:mt,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:mt}];wK.forEach(r=>{Kn.addProtocol(r)});function $A(r){let e=[],t=0;for(;t<r.length;){let n=jt(r,t),s=Kn.getProtocol(n),o=Ae(n),i=xK(s,r,t+o),a=0;i>0&&s.size===mt&&(a=Ae(i));let c=o+a+i,l={code:n,name:s.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+o+a,h=r.subarray(u,u+i);l.value=s.bytesToValue?.(h)??P(h)}e.push(l),t+=c}return e}function HA(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let s=Kn.getProtocol(n.code),o=Ae(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??D(n.value),a=i.byteLength,s.size===mt&&(c=Ae(a)));let l=new Uint8Array(o+c+a),u=0;In(n.code,l,u),u+=o,i!=null&&(s.size===mt&&(In(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Ee(t,e)}function qA(r){if(r.charAt(0)!=="/")throw new Et('String multiaddr must start with "/"');let e=[],t="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(t==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=Kn.getProtocol(s);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",s="",t="protocol";continue}else if(a)throw new Et(`Component ${s} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Et(`Component ${s} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",s="",t="protocol"}}}if(s!==""&&n!=="")throw new Et("Incomplete multiaddr");return e}function VA(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Kn.getProtocol(e.code);if(t==null)throw new Et(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function xK(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:jt(e,t)}var vK=Symbol.for("nodejs.util.inspect.custom"),Y3=Symbol.for("@multiformats/multiaddr");function EK(r){if(r==null&&(r="/"),As(r))return r.getComponents();if(r instanceof Uint8Array)return $A(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),qA(r);if(Array.isArray(r))return r;throw new Et("Must be a string, Uint8Array, Component[], or another Multiaddr")}var mf=class r{[Y3]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=EK(e),t.validate!==!1&&SK(this)}get bytes(){return this.#r==null&&(this.#r=HA(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=VA(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new lf(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,s),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return W(this.bytes,e.bytes)}[vK](){return`Multiaddr(${this.toString()})`}};function SK(r){r.getComponents().forEach(e=>{let t=Kn.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function As(r){return!!r?.[Y3]}function q(r){return new mf(r)}var Xl=class r{libp2p;clusterSize;selfCoordinationConfig;networkHighWaterMark=1;lastConnectedTime=Date.now();constructor(e,t=16,n){this.libp2p=e,this.clusterSize=t,this.selfCoordinationConfig={gracePeriodMs:n?.gracePeriodMs??3e4,shrinkageThreshold:n?.shrinkageThreshold??.5,allowSelfCoordination:n?.allowSelfCoordination??!0},this.setupConnectionTracking()}coordinatorCache=new Map;static MAX_CACHE_ENTRIES=1e3;log=Sr("libp2p-key-network");toCacheKey(e){return P(e,"base64url")}setupConnectionTracking(){this.libp2p.addEventListener("connection:open",()=>{this.updateNetworkObservations()})}updateNetworkObservations(){(this.libp2p.getConnections?.()??[]).length>0&&(this.lastConnectedTime=Date.now());try{let n=this.getFret().getNetworkSizeEstimate();n.size_estimate>this.networkHighWaterMark&&(this.networkHighWaterMark=n.size_estimate,this.log("network-hwm-updated mark=%d confidence=%f",this.networkHighWaterMark,n.confidence))}catch{let n=(this.libp2p.getConnections?.().length??0)+1;n>this.networkHighWaterMark&&(this.networkHighWaterMark=n,this.log("network-hwm-updated mark=%d (from connections)",this.networkHighWaterMark))}}shouldAllowSelfCoordination(){if(!this.selfCoordinationConfig.allowSelfCoordination)return{allow:!1,reason:"disabled"};if(this.networkHighWaterMark<=1)return{allow:!0,reason:"bootstrap-node"};try{let t=this.getFret();if(t.detectPartition())return this.log("self-coord-blocked: partition-detected"),{allow:!1,reason:"partition-detected"};let n=t.getNetworkSizeEstimate(),s=1-n.size_estimate/this.networkHighWaterMark;if(s>this.selfCoordinationConfig.shrinkageThreshold)return this.log("self-coord-blocked: suspicious-shrinkage current=%d hwm=%d shrinkage=%f",n.size_estimate,this.networkHighWaterMark,s),{allow:!1,reason:"suspicious-shrinkage"}}catch{let t=this.libp2p.getConnections?.()??[];if(this.networkHighWaterMark>1&&t.length===0){let n=Date.now()-this.lastConnectedTime;if(n<this.selfCoordinationConfig.gracePeriodMs)return this.log("self-coord-blocked: grace-period-not-elapsed since=%dms",n),{allow:!1,reason:"grace-period-not-elapsed"}}}let e=Date.now()-this.lastConnectedTime;return e<this.selfCoordinationConfig.gracePeriodMs&&(this.libp2p.getConnections?.()??[]).length===0?(this.log("self-coord-blocked: grace-period-not-elapsed since=%dms",e),{allow:!1,reason:"grace-period-not-elapsed"}):(this.log("self-coord-allowed: extended-isolation (warn)"),{allow:!0,reason:"extended-isolation",warn:!0})}recordCoordinator(e,t,n=1800*1e3){let s=this.toCacheKey(e),o=Date.now();for(let[i,a]of this.coordinatorCache)a.expires<=o&&this.coordinatorCache.delete(i);for(this.coordinatorCache.set(s,{id:t,expires:o+n});this.coordinatorCache.size>r.MAX_CACHE_ENTRIES;){let i=this.coordinatorCache.keys().next().value;if(i==null)break;this.coordinatorCache.delete(i)}}getCachedCoordinator(e){let t=this.toCacheKey(e),n=this.coordinatorCache.get(t);if(n&&n.expires>Date.now())return n.id;n&&this.coordinatorCache.delete(t)}connect(e,t,n){let s=this.libp2p.getConnections?.(e)??[];if(Array.isArray(s)&&s.length>0&&typeof s[0]?.newStream=="function")return s[0].newStream([t]);let o={runOnLimitedConnection:!0,negotiateFully:!1};return this.libp2p.dialProtocol(e,[t],o)}getFret(){let e=this.libp2p.services?.fret;if(e==null)throw new Error("FRET service is not registered on this libp2p node");return e}async getNeighborIdsForKey(e,t){let n=this.getFret(),s=await ir(e),o=n.getNeighbors(s,"both",t);return Array.from(new Set(o)).slice(0,t)}async findCoordinator(e,t){let n=new Set((t?.excludedPeers??[]).map(l=>l.toString())),s=this.toCacheKey(e).substring(0,12);this.log("findCoordinator:start key=%s excluded=%o",s,Array.from(n).map(l=>l.substring(0,12)));let o=this.getCachedCoordinator(e);if(o!=null&&!n.has(o.toString()))return this.log("findCoordinator:cached-hit key=%s coordinator=%s",s,o.toString().substring(0,12)),o;let i=3,a=500;for(let l=0;l<i;l++){let u=(this.libp2p.getConnections?.()??[]).map(f=>f.remotePeer),h=new Set(u.map(f=>f.toString()));this.log("findCoordinator:connected-peers key=%s count=%d peers=%o attempt=%d",s,u.length,u.map(f=>f.toString().substring(0,12)),l);try{let f=await this.getNeighborIdsForKey(e,this.clusterSize);this.log("findCoordinator:fret-neighbors key=%s candidates=%o",s,f.map(g=>g.substring(0,12)));let d=f.filter(g=>h.has(g)||g===this.libp2p.peerId.toString());this.log("findCoordinator:fret-connected key=%s count=%d peers=%o",s,d.length,d.map(g=>g.substring(0,12)));let m=d.find(g=>!n.has(g));if(m){let g=de(m);return this.recordCoordinator(e,g),this.log("findCoordinator:fret-selected key=%s coordinator=%s",s,m.substring(0,12)),g}}catch(f){this.log("findCoordinator getNeighborIdsForKey failed - %o",f)}let p=u.find(f=>!n.has(f.toString()));if(p)return this.recordCoordinator(e,p),this.log("findCoordinator:connected-fallback key=%s coordinator=%s",s,p.toString().substring(0,12)),p;if(u.length===0&&l<i-1){this.log("findCoordinator:no-connections-retry key=%s attempt=%d delay=%dms",s,l,a),await new Promise(f=>setTimeout(f,a));continue}}let c=this.libp2p.peerId;if(!n.has(c.toString())){let l=this.shouldAllowSelfCoordination();if(!l.allow)throw this.log("findCoordinator:self-coord-blocked key=%s reason=%s",s,l.reason),new Error(`Self-coordination blocked: ${l.reason}. No coordinator available for key.`);return l.warn?this.log("findCoordinator:self-selected-warn key=%s coordinator=%s reason=%s",s,c.toString().substring(0,12),l.reason):this.log("findCoordinator:self-selected key=%s coordinator=%s reason=%s",s,c.toString().substring(0,12),l.reason),c}throw this.log("findCoordinator:all-excluded key=%s self=%s",s,c.toString().substring(0,12)),new Error("No coordinator available for key (all candidates excluded)")}getConnectedAddrsByPeer(){let e=this.libp2p.getConnections(),t={};for(let n of e){let s=n.remotePeer.toString(),o=n.remoteAddr?.toString?.();o&&(t[s]??=[]).push(o)}return t}parseMultiaddrs(e){let t=[];for(let n of e)try{t.push(q(n))}catch(s){console.warn("invalid multiaddr from connection",n,s)}return t}async findCluster(e){let t=this.getFret(),n=await ir(e),s=t.assembleCohort(n,this.clusterSize),o=this.toCacheKey(e).substring(0,12),i=Array.from(new Set([...s,this.libp2p.peerId.toString()])),a=this.getConnectedAddrsByPeer(),c=Object.keys(a);this.log("findCluster key=%s fretCohort=%d connected=%d cohortPeers=%o",o,s.length,c.length,i.map(u=>u.substring(0,12)));let l={};for(let u of i){if(u===this.libp2p.peerId.toString()){l[u]={multiaddrs:this.libp2p.getMultiaddrs(),publicKey:this.libp2p.peerId.publicKey?.raw??new Uint8Array};continue}let h=a[u]??[],p=this.parseMultiaddrs(h);l[u]={multiaddrs:p,publicKey:new Uint8Array}}return this.log("findCluster:result key=%s clusterSize=%d withAddrs=%d connectedInCohort=%d",o,Object.keys(l).length,Object.values(l).filter(u=>u.multiaddrs.length>0).length,i.filter(u=>c.includes(u)||u===this.libp2p.peerId.toString()).length),l}};Bt();ke();V();async function GA(r){if(r.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new R("Private network is enforced, but no protector was provided");return r}Bt();V();var zpe=new Uint8Array(0);function WA(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function IK(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var v=d[y],S=0,E=w-1;(v!==0||S<g)&&E!==-1;E--,S++)v+=256*x[E]>>>0,x[E]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var A=c.repeat(m);I<w;++I)A+=r.charAt(x[I]);return A}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*w[S]>>>0,w[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(d[m]!==" "){for(var E=b-y;E!==b&&w[E]===0;)E++;for(var I=new Uint8Array(g+(b-E)),A=g;E!==b;)I[A++]=w[E++];return I}}}function f(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:f}}var AK=IK,CK=AK,jA=CK;var X3=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Q3=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return YA(this,e)}},J3=class{decoders;constructor(e){this.decoders=e}or(e){return YA(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function YA(r,e){return new J3({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Z3=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new X3(e,t,n),this.decoder=new Q3(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function XA({name:r,prefix:e,encode:t,decode:n}){return new Z3(r,e,t,n)}function eb({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=jA(t,r);return XA({prefix:e,name:r,encode:n,decode:o=>WA(s(o))})}function TK(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function _K(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function PK(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function zt({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=PK(n);return XA({prefix:e,name:r,encode(o){return _K(o,n,t)},decode(o){return TK(o,s,t,r)}})}var QA=zt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),jpe=zt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ype=zt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Xpe=zt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Qpe=zt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Jpe=zt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Zpe=zt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),e1e=zt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),t1e=zt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var JA=eb({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),s1e=eb({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ZA=zt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),a1e=zt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),c1e=zt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),l1e=zt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var e8=ie(ee("node:tty"),1),yf=ie(ee("node:util"),1);function DK(r,e){if(typeof r=="string")return kK(r);if(typeof r=="number")return OK(r,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}var gf=DK;function kK(r){if(typeof r!="string"||r.length===0||r.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,s=parseFloat(t),o=n.toLowerCase();switch(o){case"years":case"year":case"yrs":case"yr":case"y":return s*315576e5;case"months":case"month":case"mo":return s*26298e5;case"weeks":case"week":case"w":return s*6048e5;case"days":case"day":case"d":return s*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return s*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return s*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return s*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return s;default:throw Error(`Unknown unit "${o}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function LK(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function MK(r){let e=Math.abs(r);return e>=315576e5?bo(r,e,315576e5,"year"):e>=26298e5?bo(r,e,26298e5,"month"):e>=6048e5?bo(r,e,6048e5,"week"):e>=864e5?bo(r,e,864e5,"day"):e>=36e5?bo(r,e,36e5,"hour"):e>=6e4?bo(r,e,6e4,"minute"):e>=1e3?bo(r,e,1e3,"second"):`${r} ms`}function OK(r,e){if(typeof r!="number"||!Number.isFinite(r))throw Error("Value provided to ms.format() must be of type number.");return e?.long?MK(r):LK(r)}function bo(r,e,t,n){let s=e>=t*1.5;return`${Math.round(r/t)} ${n}${s?"s":""}`}Vg();function tb(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=s,t.enabled=i,t.humanize=gf,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let h=0;for(let p=0;p<u.length;p++)h=(h<<5)-h+u.charCodeAt(p),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(u,h){let p,f=null,d,m;function g(...y){if(!g.enabled)return;let b=g,w=Number(new Date),x=w-(p||w);b.diff=x,b.prev=p,b.curr=w,p=w,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let v=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(E,I)=>{if(E==="%%")return"%";v++;let A=t.formatters[I];if(typeof A=="function"){let X=y[v];E=A.call(b,X),y.splice(v,1),v--}return E}),t.formatArgs.call(b,y),h?.onLog!=null&&h.onLog(...y),(b.log||t.log).apply(b,y)}return g.namespace=u,g.useColors=t.useColors(),g.color=t.selectColor(u),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(d!==t.namespaces&&(d=t.namespaces,m=t.enabled(u)),m),set:y=>{f=y}}),typeof t.init=="function"&&t.init(g),g}function n(u,h){let p=t(this.namespace+(typeof h>"u"?":":h)+u);return p.log=this.log,p}function s(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let h,p=(typeof u=="string"?u:"").split(/[\s,]+/),f=p.length;for(h=0;h<f;h++)p[h]&&(u=p[h].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function o(){let u=[...t.names.map(a),...t.skips.map(a).map(h=>"-"+h)].join(",");return t.enable(""),u}function i(u){if(u[u.length-1]==="*")return!0;let h,p;for(h=0,p=t.skips.length;h<p;h++)if(t.skips[h].test(u))return!1;for(h=0,p=t.names.length;h<p;h++)if(t.names[h].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var t8=[6,2,3,4,5,1];pl.stderr!==!1&&(pl.stderr??pl).level>=2&&(t8=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]);var la=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,o)=>o.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),r[t]=n,r},{});function RK(){return"colors"in la?!!la.colors:e8.default.isatty(process.stderr.fd)}function NK(r){let{namespace:e,useColors:t}=this;if(t===!0){let n=this.color,s="\x1B[3"+(n<8?n:"8;5;"+n),o=` ${s};1m${e} \x1B[0m`;r[0]=o+r[0].split(`
|
|
7
7
|
`).join(`
|
|
8
8
|
`+o),r.push(s+"m+"+gf(this.diff)+"\x1B[0m")}else r[0]=BK()+e+" "+r[0]}function BK(){return la.hideDate!=null?"":new Date().toISOString()+" "}function UK(...r){return process.stderr.write(yf.default.format(...r)+`
|
|
9
9
|
`)}function KK(r){r!=null?process.env.DEBUG=r:delete process.env.DEBUG}function FK(){return process.env.DEBUG}function zK(r){r.inspectOpts={};let e=Object.keys(la);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=la[e[t]]}function $K(r){r.o=function(e){return this.inspectOpts.colors=this.useColors,yf.default.inspect(e,this.inspectOpts).split(`
|
|
@@ -17,7 +17,7 @@ ${e}`)}`:n!=null?`${n.split(`
|
|
|
17
17
|
${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function HK(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function o8(r,e=""){if(HK(r)){let t=n8(r,e);return r.errors.length>0?(e=`${e} `,t+=`
|
|
18
18
|
${e}${r.errors.map(n=>`${o8(n,`${e}`)}`).join(`
|
|
19
19
|
${e}`)}`):t+=`
|
|
20
|
-
${e}[Error list was empty]`,t.trim()}return n8(r,e)}Jt.formatters.e=r=>r==null?"undefined":o8(r);function qK(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function bf(r){return{forComponent(e){return i8(e,r)}}}function i8(r,e){let t=qK(`${r}:trace`);return Jt.enabled(`${r}:trace`)&&Jt.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=Jt(`${r}:trace`,e)),Object.assign(Jt(r,e),{error:Jt(`${r}:error`,e),trace:t,newScope:n=>i8(`${r}:${n}`,e)})}function s8(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}ke();var I1e=new Uint8Array(0);function wf(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function VK(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var v=d[y],S=0,E=w-1;(v!==0||S<g)&&E!==-1;E--,S++)v+=256*x[E]>>>0,x[E]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var A=c.repeat(m);I<w;++I)A+=r.charAt(x[I]);return A}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*w[S]>>>0,w[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(d[m]!==" "){for(var E=b-y;E!==b&&w[E]===0;)E++;for(var I=new Uint8Array(g+(b-E)),A=g;E!==b;)I[A++]=w[E++];return I}}}function f(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:f}}var GK=VK,WK=GK,a8=WK;var rb=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},nb=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return c8(this,e)}},sb=class{decoders;constructor(e){this.decoders=e}or(e){return c8(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function c8(r,e){return new sb({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var ob=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new rb(e,t,n),this.decoder=new nb(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function jK({name:r,prefix:e,encode:t,decode:n}){return new ob(r,e,t,n)}function ib({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=a8(t,r);return jK({prefix:e,name:r,encode:n,decode:o=>wf(s(o))})}var l8=ib({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),k1e=ib({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var YK=d8,u8=128,XK=127,QK=~XK,JK=Math.pow(2,31);function d8(r,e,t){e=e||[],t=t||0;for(var n=t;r>=JK;)e[t++]=r&255|u8,r/=128;for(;r&QK;)e[t++]=r&255|u8,r>>>=7;return e[t]=r|0,d8.bytes=t-n+1,e}var ZK=ab,eF=128,h8=127;function ab(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw ab.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&h8)<<s:(i&h8)*Math.pow(2,s),s+=7}while(i>=eF);return ab.bytes=o-n,t}var tF=Math.pow(2,7),rF=Math.pow(2,14),nF=Math.pow(2,21),sF=Math.pow(2,28),oF=Math.pow(2,35),iF=Math.pow(2,42),aF=Math.pow(2,49),cF=Math.pow(2,56),lF=Math.pow(2,63),uF=function(r){return r<tF?1:r<rF?2:r<nF?3:r<sF?4:r<oF?5:r<iF?6:r<aF?7:r<cF?8:r<lF?9:10},hF={encode:YK,decode:ZK,encodingLength:uF},dF=hF,cb=dF;function lb(r,e=0){return[cb.decode(r,e),cb.decode.bytes]}function f8(r){let e=wf(r),[t,n]=lb(e),[s,o]=lb(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new ub(t,s,i,e)}var ub=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function wo(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return t}function xf(r){let e=f8(l8.decode(`z${r}`));return Br(e)}var Zt=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return wo(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return wo(this.map.values(),e=>e.key)}values(){return wo(this.map.values(),e=>e.value)}get size(){return this.map.size}};var xo=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return wo(this.set.entries(),e=>{let t=xf(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=xf(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return wo(this.set.values(),e=>xf(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};gv();var hb={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},p8={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},m8=new globalThis.TextEncoder;function mF(r,e){let t=hb[e],n=p8[e];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(e,n*t);return n}function gF(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=hb[e],s=p8[e],o=r;for(;o.length>0;){let i=m8.encodeInto(o,t);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(t[a]),s=BigInt.asUintN(e,s*n)}return s}function db(r,{size:e=32,utf8Buffer:t}={}){if(!hb[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return gF(r,e,t);r=m8.encode(r)}return mF(r,e)}te();var Ql={hash:r=>Number(db(r,{size:32})),hashV:(r,e)=>yF(Ql.hash(r,e))};function yF(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),D(e,"base16")}te();rt();Ne();var fb=64,Fr=class{fp;h;seed;constructor(e,t,n,s=2){if(s>fb)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),i=ae(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?W(this.fp,e.fp):!1}};function vo(r,e){return Math.floor(Math.random()*(e-r))+r}var Eo=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Fr))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof Fr))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof Fr))throw new TypeError("Invalid Fingerprint");let t=vo(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof Fr))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var bF=500,Jl=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??Ql,this.seed=e.seed??vo(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=D(e));let t=new Fr(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Eo(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new Eo(this.bucketSize)),this.buckets[n].add(t)||this.buckets[s].add(t))return this.count++,!0;let o=[n,s],i=o[vo(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Eo(this.bucketSize));for(let a=0;a<bF;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Eo(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=D(e));let t=new Fr(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.has(t)??!1;if(s)return s;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=D(e));let t=new Fr(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.remove(t)??!1;if(s)return this.count--,s;let o=(n^t.hash())%this.filterSize,i=this.buckets[o]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},wF={1:.5,2:.84,4:.95,8:.98};function xF(r=.001){return r>.002?2:r>1e-5?4:8}function g8(r,e=.001){let t=xF(e),n=wF[t],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),fb);return{filterSize:s,bucketSize:t,fingerprintSize:o}}te();var vf=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??Ql,this.seed=e.seed??vo(0,Math.pow(2,10)),this.filterSeries=[new Jl({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=D(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Jl({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=D(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=D(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function ln(r,e=.001,t){return new vf({...g8(r,e),...t??{}})}V();function oe(r){let e=r.getComponents(),t={},n=0;if(e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n].name==="ip4"||e[n].name==="ip6"||e[n].name==="dns"||e[n].name==="dns4"||e[n].name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n].name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null)throw new R(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t}function y8(r){try{let e=oe(r);switch(e.type){case"ip6":return sA("2000::/3",e.host);default:return!1}}catch{return!1}}function b8(r){try{let e=oe(r);switch(e.type){case"ip4":return e.host.startsWith("169.254.");case"ip6":return e.host.toLowerCase().startsWith("fe80");default:return!1}}catch{return!1}}function w8(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function Zl(r){try{let e=oe(r);switch(e.type){case"ip4":case"ip6":return w8(e.host);default:return!1}}catch{return!1}}function St(r){try{return oe(r),!0}catch{return!1}}var v8=ie(x8(),1),vF=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],EF=vF.map(r=>new v8.Netmask(r));function pb(r){for(let e of EF)if(e.contains(r))return!0;return!1}function SF(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function IF(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),s=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return pb(s)}function AF(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function CF(r){let e=r.split(":"),t=e[e.length-1];return pb(t)}function TF(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function ua(r){if((0,fe.isIPv4)(r))return pb(r);if(SF(r))return IF(r);if(AF(r))return CF(r);if((0,fe.isIPv6)(r))return TF(r)}function Fn(r){try{let e=oe(r);switch(e.type){case"ip4":case"ip6":return ua(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}V();Ue();var mb=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},E8=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function gb(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((h,p)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){p(E8(i));return}if(i&&(c=()=>{p(E8(i))},i.addEventListener("abort",c,{once:!0})),r.then(h,p),t===Number.POSITIVE_INFINITY)return;let f=new mb;a=o.setTimeout.call(void 0,()=>{if(n){try{h(n())}catch(d){p(d)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?h():s instanceof Error?p(s):(f.message=s??`Promise timed out after ${t} milliseconds`,p(f))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},u}var _F=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function PF(r,e,t){let n,s=new Promise((o,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=_F(r),h=async(...f)=>{let d=t.multiArgs?f:f[0];if(t.filter)try{if(!await t.filter(d))return}catch(m){n(),i(m);return}c.push(d),t.count===c.length&&(n(),o(c))},p=(...f)=>{n(),i(t.rejectionMultiArgs?f:f[0])};n=()=>{for(let f of a)u(f,h);for(let f of t.rejectionEvents)a.includes(f)||u(f,p)};for(let f of a)l(f,h);for(let f of t.rejectionEvents)a.includes(f)||l(f,p);t.signal&&t.signal.addEventListener("abort",()=>{p(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(s.cancel=n,typeof t.timeout=="number"){let o=gb(s,{milliseconds:t.timeout});return o.cancel=()=>{n(),o.clear()},o}return s}function Re(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=PF(r,e,t),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}function So(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Ef=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}},Sf=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},Io=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},If=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},Af=class extends Error{static name="StreamClosedError";name="StreamClosedError"};V();Ue();function DF(r){return r.reason}async function Cs(r,e,t){if(e==null)return r;let n=t?.translateError??DF;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}V();var Cf=class{deferred;signal;constructor(e){this.signal=e,this.deferred=ut(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new rr)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function kF(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Tf=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=kF(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,j(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new rr),this.cleanup())}async join(e={}){let t=new Cf(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Cs(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var ha=class extends me{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=So(this.emitEmpty.bind(this),1),this.emitIdle=So(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Sf;let n=new Tf(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new rr)}),this.clear()}async onEmpty(e){this.size!==0&&await Re(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Re(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Re(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Ot({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new rr("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};V();Be();var LF=Math.pow(2,20)*4,Ts=class extends me{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??LF,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new U,this.writeBuffer=new U,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let n=s=>{this.onDrainPromise?.reject(s.error??new Af)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),Cs(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Ot(),t=o=>{e.push(o.data)};this.addEventListener("message",t);let n=o=>{e.end(o.error)};this.addEventListener("close",n);let s=()=>{e.end()};this.addEventListener("remoteCloseWrite",s);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",s)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new ns(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(t){this.log("failed to send reset to remote - %e",t)}this.dispatchEvent(new Th(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new ns("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new ns("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new ns(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new ns(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new wh;this.dispatchEvent(new _h(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new as))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,t=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let s=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(s===0){e=!1;break}let o=this.writeBuffer.sublist(0,s),i=new U(o);this.writeBuffer.consume(o.byteLength);let a=this.sendData(o);if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new Ch(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new dc(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new dc(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var da=class extends Ts{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",t=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),t.error!=null?t.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):t.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Re(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Re(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};V();function S8(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var _f=class extends me{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,t){super(),this.maConn=e,this.protocol=t.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(t.name),this.streamOptions=t.streamOptions,this.maxEarlyStreams=t.maxEarlyStreams??10,this.metrics=t.metrics;let n=i=>{try{this.onData(i.data)}catch(a){this.abort(a),this.maConn.abort(a)}};this.maConn.addEventListener("message",n);let s=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(i=>{i.onMuxerDrain()})};this.maConn.addEventListener("drain",s);let o=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",o)}send(e){let t=this.maConn.send(e);return t===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(n=>{n.onMuxerNeedsDrain()})),t}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await Cs(Promise.all([...this.streams].map(async t=>{await t.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(t=>{t.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(t=>{t.onTransportClosed(e)})}catch(t){this.abort(t)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new Tn;let t=this.onCreateStream({...this.streamOptions,...e});return S8(t)&&(t=await t),this.streams.push(t),this.cleanUpStream(t),t}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new If(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let t=n=>{let s=this.streams.findIndex(o=>o===e);s!==-1&&this.streams.splice(s,1),n.error!=null?n.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",t),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(t=>{this.safeDispatchEvent("stream",{detail:t})}),this.earlyStreams=[]})}};var Pf=class extends Ts{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Re(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await Re(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.log("closed readable end gracefully"))}};function $t(r){let e=new globalThis.AbortController;function t(){e.abort();for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let s=e.signal;return s.clear=n,s}Ue();var fa=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),s=e-this.movingAverage,o=n*s;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+s*o),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*s}else this.movingAverage=e;this.previousTime=t}};var MF=1.2,OF=2,RF=5e3,NF=6e4,BF=5e3,Df=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??BF;this.success=new fa(t),this.failure=new fa(t),this.next=new fa(t),this.failureMultiplier=e.failureMultiplier??OF,this.timeoutMultiplier=e.timeoutMultiplier??MF,this.minTimeout=e.minTimeout??RF,this.maxTimeout=e.maxTimeout??NF,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),s=$t([e.signal,n]);return j(1/0,s,n),s.start=Date.now(),s.timeout=t,s}cleanUp(e){let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var A8=ie(ee("node:os"),1);function I8(r){return!!(r.startsWith("169.254.")||r.toLowerCase().startsWith("fe80"))}function yb(r,e,t){let n=[r.type,t??r.host];if(r.protocol!=null){let s=e??r.port;s!=null&&n.push(r.protocol,s)}return r.type==="ip6"&&r.zone!=null&&n.unshift("ip6zone",r.zone),r.cidr!=null&&n.push("ipcidr",r.cidr),q(`/${n.join("/")}`)}var UF={4:"IPv4",6:"IPv6"};function KF(r){return["0.0.0.0","::"].includes(r)}function FF(r){let e=[],t=A8.default.networkInterfaces();for(let[,n]of Object.entries(t))if(n!=null)for(let s of n)I8(s.address)||s.family===UF[r]&&e.push(s.address);return e}function C8(r,e){if(r==null)return[];let t=oe(r);return(t.type==="ip4"||t.type==="ip6")&&KF(t.host)?FF(t.type==="ip4"?4:6).map(n=>yb(t,e,n)):[yb(t,e)]}V();function T8(r,e){if(typeof r!="string")throw new R(`invalid ip provided: ${r}`);if(typeof e=="string"&&(e=parseInt(e)),isNaN(e))throw new R(`invalid port provided: ${e}`);if((0,fe.isIPv4)(r))return q(`/ip4/${r}/tcp/${e}`);if((0,fe.isIPv6)(r))return q(`/ip6/${r}/tcp/${e}`);throw new R(`invalid ip:port for creating a multiaddr: ${r}:${e}`)}V();gr();Be();V();gr();Be();var zF=4194304,kf=class extends Error{static name="UnwrappedError";name="UnwrappedError"},tu=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},wb=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},xb=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function $F(r){return typeof r?.closeRead=="function"}function HF(r){return typeof r?.close=="function"}function bb(r){return $F(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:HF(r)?r.status!=="open":!1}function qF(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function vb(r,e){let t=e?.maxBufferSize??zF,n=new U,s,o=!1;if(!qF(r))throw new R("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>t){let h=n.byteLength;n.consume(n.byteLength),s?.reject(new Error(`Read buffer overflow - ${h} > ${t}`))}s?.resolve()};r.addEventListener("message",i);let a=u=>{u.error!=null?s?.reject(u.error):s?.resolve()};r.addEventListener("close",a);let c=()=>{s?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(u){if(o===!0)throw new kf("Stream was unwrapped");if(bb(r)){if(u?.bytes==null)return null;if(n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new Io(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let h=u?.bytes??1;for(s=Promise.withResolvers();;){if(n.byteLength>=h){s.resolve();break}if(await Cs(s.promise,u?.signal),bb(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}s=Promise.withResolvers()}let p=u?.bytes??n.byteLength;if(n.byteLength<p){if(bb(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,p),new Io(`Unexpected EOF - stream closed while reading ${n.byteLength}/${p} bytes`);return l.read(u)}let f=n.sublist(0,p);return n.consume(p),f},async write(u,h){if(o===!0)throw new kf("Stream was unwrapped");r.send(u)||await Re(r,"drain",{signal:h?.signal,rejectionEvents:["close"]})},unwrap(){return o||(o=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return l}function _s(r,e={}){let t=vb(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Ae(e.maxDataLength));let n=e?.lengthDecoder??jt,s=e?.lengthEncoder??Vr;return{async read(i){let a=-1,c=new U;for(;;){let u=await t.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(h){if(h instanceof RangeError)continue;throw h}if(a<0)throw new tu("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new xb(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new wb(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...i,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new Io(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new Io(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new U(s(i.byteLength),i),a)},async writeV(i,a){let c=new U(...i.flatMap(l=>[s(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function zr(r,e){let t=_s(r,e),n={read:async(s,o)=>{let i=await t.read(o);return s.decode(i)},write:async(s,o,i)=>{await t.write(o.encode(s),i)},writeV:async(s,o,i)=>{await t.writeV(s.map(a=>o.encode(a)),i)},pb:s=>({read:async o=>n.read(s,o),write:async(o,i)=>n.write(o,s,i),writeV:async(o,i)=>n.writeV(o,s,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}function VF(r){return r?.addEventListener!=null}function GF(r){let e=Ot(),t,n=i=>{e.push(i.data)},s=()=>{e.end(),r.removeEventListener("message",n),r.removeEventListener("close",o),r.removeEventListener("remoteCloseWrite",s)},o=i=>{e.end(i.error),i.error!=null&&t?.reject(i.error),r.removeEventListener("message",n),r.removeEventListener("close",o),r.removeEventListener("remoteCloseWrite",s)};return r.addEventListener("message",n),r.addEventListener("close",o,{once:!0}),r.addEventListener("remoteCloseWrite",s,{once:!0}),{source:e,async sink(i){async function*a(){yield*i}let c=a();for(;;){t=Promise.withResolvers();let{done:l,value:u}=await Promise.race([c.next(),t.promise]);if(r.writeStatus==="closing"||r.writeStatus==="closed"||(u!=null&&(r.send(u)||await Promise.race([Re(r,"drain",{rejectionEvents:["close"]})])),l===!0))break}await r.close()}}}function _8(...r){let e=r.map(t=>VF(t)?GF(t):t);return ht(...e)}var WF=1024*1024*4,jF=1024*1024*4,Lf=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new U,this.maxBufferSize=e.maxBufferSize??WF,this.maxDataLength=e.maxDataLength??jF,this.lengthDecoder=e.lengthDecoder??jt,this.encodingLength=e.encodingLength??Ae}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new R(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let t;try{t=this.lengthDecoder(this.buffer)}catch(o){if(o instanceof RangeError)break;throw o}if(t<0||t>this.maxDataLength)throw new tu("Invalid message length");let n=this.encodingLength(t),s=n+t;if(this.buffer.byteLength>=s){let o=this.buffer.sublist(n,s);this.buffer.consume(s),o.byteLength>0&&(yield o)}else break}}};var Ps=class extends ha{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Mf=class extends ha{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var Of=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Eb}consume(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(s,i.consumedPoints,this.blockDuration)),new Ef("Rate limit exceeded",i);return i}penalty(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,-t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,s=this.points+1;return this.memoryStorage.set(this.getKey(e),s,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:s,isFirstInDuration:!1}}set(e,t,n=0){let s=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},Eb=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let s=this.storage.get(e);if(s!=null){let o=s.expiresAt!=null?s.expiresAt.getTime()-new Date().getTime():-1;return s.expiresAt==null||o>0?(s.value+=t,{remainingPoints:0,msBeforeNext:o,consumedPoints:s.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let s=n*1e3,o=this.storage.get(e);o!=null&&clearTimeout(o.timeoutId);let i={value:t,expiresAt:s>0?new Date(Date.now()+s):void 0};return this.storage.set(e,i),s>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},s),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};Ue();function P8(r,e,t){let n,s,o=!1;function i(){let l={signal:s.signal};if(t?.timeout!=null){let u=$t([s.signal,AbortSignal.timeout(t.timeout)]);j(1/0,u),l.signal=u}o=!0,Promise.resolve().then(async()=>{await r(l)}).catch(()=>{}).finally(()=>{o=!1,!s.signal.aborted&&(n=setTimeout(i,e))})}let a=So(i,t?.debounce??100),c=!1;return{setInterval:l=>{e!==l&&(e=l,n!=null&&(clearTimeout(n),n=setTimeout(i,e)))},setTimeout:l=>{t??={},t.timeout=l},run:()=>{o||(clearTimeout(n),a())},start:()=>{c||(c=!0,s=new AbortController,j(1/0,s.signal),t?.runImmediately===!0?queueMicrotask(()=>{i()}):n=setTimeout(i,e))},stop:()=>{clearTimeout(n),s?.abort(),c=!1}}}var Sb=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Pt(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Sb({name:e,metrics:t}):n=new Map,n}var Rf=class{filter;constructor(e,t){this.filter=ln(e,t)}has(e){return this.filter.has(e.toMultihash().bytes)}add(e){this.filter.add(e.toMultihash().bytes)}remove(e){this.filter.remove?.(e.toMultihash().bytes)}};function Ib(r,e=.001){return new Rf(r,e)}var Ab=class extends Zt{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function ru(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Ab({name:e,metrics:t}):n=new Zt,n}ke();V();ke();Bt();gr();Be();Ne();te();wr();rt();var nu;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={publicKey:ae(0),payloadType:ae(0),payload:ae(0),signature:ae(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.publicKey=t.bytes();break}case 2:{o.payloadType=t.bytes();break}case 3:{o.payload=t.bytes();break}case 5:{o.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(nu||(nu={}));var Nf=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var lr=class r{static createFromProtobuf=e=>{let t=nu.decode(e),n=Ft(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let s=e.domain,o=e.codec,i=e.marshal(),a=D8(s,o,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:o,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let s=r.createFromProtobuf(e);if(!await s.validate(t,n))throw new Nf("Envelope signature is not valid for the given domain");return s};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:s,signature:o}=e;this.publicKey=t,this.payloadType=n,this.payload=s,this.signature=o}marshal(){return this.marshaled==null&&(this.marshaled=nu.encode({publicKey:dt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:W(this.marshal(),e.marshal())}async validate(e,t){let n=D8(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},D8=(r,e,t)=>{let n=D(r),s=Vr(n.byteLength),o=Vr(e.length),i=Vr(t.length);return new U(s,n,o,e,i,t)};ke();var M2e=new Uint8Array(0);function k8(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var YF=O8,L8=128,XF=127,QF=~XF,JF=Math.pow(2,31);function O8(r,e,t){e=e||[],t=t||0;for(var n=t;r>=JF;)e[t++]=r&255|L8,r/=128;for(;r&QF;)e[t++]=r&255|L8,r>>>=7;return e[t]=r|0,O8.bytes=t-n+1,e}var ZF=Cb,ez=128,M8=127;function Cb(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Cb.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&M8)<<s:(i&M8)*Math.pow(2,s),s+=7}while(i>=ez);return Cb.bytes=o-n,t}var tz=Math.pow(2,7),rz=Math.pow(2,14),nz=Math.pow(2,21),sz=Math.pow(2,28),oz=Math.pow(2,35),iz=Math.pow(2,42),az=Math.pow(2,49),cz=Math.pow(2,56),lz=Math.pow(2,63),uz=function(r){return r<tz?1:r<rz?2:r<nz?3:r<sz?4:r<oz?5:r<iz?6:r<az?7:r<cz?8:r<lz?9:10},hz={encode:YF,decode:ZF,encodingLength:uz},dz=hz,Tb=dz;function _b(r,e=0){return[Tb.decode(r,e),Tb.decode.bytes]}function R8(r){let e=k8(r),[t,n]=_b(e),[s,o]=_b(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Pb(t,s,i,e)}var Pb=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var N8="libp2p-peer-record",B8=Uint8Array.from([3,1]);wr();rt();var su;(function(r){let e;(function(n){let s;n.codec=()=>(s==null&&(s=Z((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.multiaddr!=null&&o.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(o.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={multiaddr:ae(0)},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.multiaddr=o.bytes();break}default:{o.skipType(u&7);break}}}return c})),s),n.encode=o=>J(o,n.codec()),n.decode=(o,i)=>Q(o,n.codec(),i)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Z((n,s,o={})=>{if(o.lengthDelimited!==!1&&s.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(s.uint32(10),s.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(s.uint32(16),s.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)s.uint32(26),r.AddressInfo.codec().encode(i,s);o.lengthDelimited!==!1&&s.ldelim()},(n,s,o={})=>{let i={peerId:ae(0),seq:0n,addresses:[]},a=s==null?n.len:n.pos+s;for(;n.pos<a;){let c=n.uint32();switch(c>>>3){case 1:{i.peerId=n.bytes();break}case 2:{i.seq=n.uint64();break}case 3:{if(o.limits?.addresses!=null&&i.addresses.length===o.limits.addresses)throw new _e('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:o.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),t),r.encode=n=>J(n,r.codec()),r.decode=(n,s)=>Q(n,r.codec(),s)})(su||(su={}));function U8(r,e){let t=(n,s)=>n.toString().localeCompare(s.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,s)=>e[s].equals(n)))}var ur=class r{static createFromProtobuf=e=>{let t=su.decode(e),n=Br(R8(t.peerId)),s=(t.addresses??[]).map(i=>q(i.multiaddr)),o=t.seq;return new r({peerId:n,multiaddrs:s,seqNumber:o})};static DOMAIN=N8;static CODEC=B8;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:s}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=s??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=su.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!U8(this.multiaddrs,e.multiaddrs))}};function mz(r){return r[Symbol.asyncIterator]!=null}function gz(r){if(mz(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var ou=gz;V();ke();var hr=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};Ue();async function Bf(r,e,t,n){let s=new hr(n?.errorMessage);n?.errorCode!=null&&(s.code=n.errorCode);let o=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(s):new Promise((i,a)=>{function c(){kb(t,"abort",h),kb(r,e,l),kb(r,o,u)}let l=p=>{try{if(n?.filter?.(p)===!1)return}catch(f){c(),a(f);return}c(),i(p)},u=p=>{if(c(),p instanceof Error){a(p);return}a(p.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},h=()=>{c(),a(s)};Db(t,"abort",h),Db(r,e,l),Db(r,o,u)})}function Db(r,e,t){r!=null&&(K8(r)?r.addEventListener(e,t):r.addListener(e,t))}function kb(r,e,t){r!=null&&(K8(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function K8(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var Uf=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};Ue();var Kf=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new hr)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function yz(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ff=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=yz(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,j(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new hr),this.cleanup())}async join(e={}){let t=new Kf(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await uh(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function Lb(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var iu=class extends me{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=Lb(this.emitEmpty.bind(this),1),this.emitIdle=Lb(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Uf;let n=new Ff(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(s=>(this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new hr)}),this.clear()}async onEmpty(e){this.size!==0&&await Bf(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Bf(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Bf(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Ot({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail.result)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new hr("Queue aborted"))};this.addEventListener("success",s),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var cu=ie(ee("node:cluster"),1),qf=ie(ee("node:worker_threads"),1);Ue();var Ao="lock:worker:request-read",Co="lock:worker:abort-read-request",To="lock:worker:release-read",_o="lock:master:grant-read",Po="lock:master:error-read",Do="lock:worker:request-write",ko="lock:worker:abort-write-request",Lo="lock:worker:release-write",Mo="lock:master:grant-write",Oo="lock:master:error-write",Ds="lock:worker:finalize",zf="mortice",F8={singleProcess:!1};var Mb=(r,e,t,n,s,o,i,a,c)=>l=>{if(l.data==null)return;let u={type:l.data.type,name:l.data.name,identifier:l.data.identifier};u.type===s&&r.safeDispatchEvent(t,{detail:{name:u.name,identifier:u.identifier,handler:async()=>{e.postMessage({type:c,name:u.name,identifier:u.identifier}),await new Promise(h=>{let p=f=>{if(f?.data==null)return;let d={type:f.data.type,name:f.data.name,identifier:f.data.identifier};d.type===a&&d.identifier===u.identifier&&(e.removeEventListener("message",p),h())};e.addEventListener("message",p)})},onError:h=>{e.postMessage({type:i,name:u.name,identifier:u.identifier,error:{message:h.message,name:h.name,stack:h.stack}})}}}),u.type===o&&r.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier}}),u.type===Ds&&r.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};var Ob=(r,e,t,n,s,o,i,a)=>(c,l)=>{l!=null&&(l.type===n&&r.safeDispatchEvent(e,{detail:{name:l.name,identifier:l.identifier,handler:async()=>{c.send({type:a,name:l.name,identifier:l.identifier}),await new Promise(u=>{let h=p=>{p.type===i&&p.identifier===l.identifier&&(c.removeListener("message",h),u())};c.on("message",h)})},onError:u=>{c.send({type:o,name:l.name,identifier:l.identifier,error:{message:u.message,name:u.name,stack:u.stack}})}}}),l.type===s&&r.safeDispatchEvent(t,{detail:{name:l.name,identifier:l.identifier}}),l.type===Ds&&r.safeDispatchEvent("finalizeRequest",{detail:{name:l.name}}))};var au=(r=10)=>Math.random().toString().substring(2,r+2);var $f=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(zf)}readLock(e){return this.sendRequest(Ao,Co,_o,Po,To,e)}writeLock(e){return this.sendRequest(Do,ko,Mo,Oo,Lo,e)}finalize(){this.channel.postMessage({type:Ds,name:this.name}),this.channel.close()}async sendRequest(e,t,n,s,o,i){i?.signal?.throwIfAborted();let a=au();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",u,{once:!0});let h=p=>{if(p.data?.identifier===a&&(p.data?.type===n&&(this.channel.removeEventListener("message",h),i?.signal?.removeEventListener("abort",u),c(()=>{this.channel.postMessage({type:o,identifier:a,name:this.name})})),p.data.type===s)){this.channel.removeEventListener("message",h),i?.signal?.removeEventListener("abort",u);let f=new Error;p.data.error!=null&&(f.message=p.data.error.message,f.name=p.data.error.name,f.stack=p.data.error.stack),l(f)}};this.channel.addEventListener("message",h)})}};var Hf=class{name;constructor(e){this.name=e}readLock(e){return this.sendRequest(Ao,Co,_o,Po,To,e)}writeLock(e){return this.sendRequest(Do,ko,Mo,Oo,Lo,e)}finalize(){if(process.send==null)throw new Error("No send method on process - are we a cluster worker?");process.send({type:Ds,identifier:au(),name:this.name})}async sendRequest(e,t,n,s,o,i){i?.signal?.throwIfAborted();let a=au();if(process.send==null)throw new Error("No send method on process - are we a cluster worker?");return process.send({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{process.send?.({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",u,{once:!0});let h=p=>{if(p.identifier===a&&(p.type===n&&(process.removeListener("message",h),i?.signal?.removeEventListener("abort",u),c(()=>{process.send?.({type:o,identifier:a,name:this.name})})),p.type===s)){process.removeListener("message",h),i?.signal?.removeEventListener("abort",u);let f=new Error;p.error!=null&&(f.message=p.error.message,f.name=p.error.name,f.stack=p.error.stack),l(f)}};process.on("message",h)})}};function bz(){return qf.default.isMainThread===!1||qf.default.isInternalThread===!0?!1:cu.default.isPrimary}var z8=r=>{if(r=Object.assign({},F8,r),bz()||r.singleProcess){let e=new me;cu.default.on("message",Ob(e,"requestReadLock","abortReadLockRequest",Ao,Co,Po,To,_o)),cu.default.on("message",Ob(e,"requestWriteLock","abortWriteLockRequest",Do,ko,Oo,Lo,Mo));let t=new BroadcastChannel(zf);return t.addEventListener("message",Mb(e,t,"requestReadLock","abortReadLockRequest",Ao,Co,Po,To,_o)),t.addEventListener("message",Mb(e,t,"requestWriteLock","abortWriteLockRequest",Do,ko,Oo,Lo,Mo)),t.unref?.(),e}if(cu.default.isWorker)return new Hf(r.name);if(qf.default.isMainThread===!1)return new $f(r.name);throw new Error("Not a cluster worker or worker thread")};var Ro=new Map,lu;function $8(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function wz(r){if(lu==null&&(lu=z8(r),!$8(lu))){let e=lu;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,s=t.detail.identifier,o=Ro.get(n);if(o==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==s||i.abort()};e.addEventListener("abortReadLockRequest",a),o.readLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,s=t.detail.identifier,o=Ro.get(n);if(o==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==s||i.abort()};e.addEventListener("abortWriteLockRequest",a),o.writeLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,s=Ro.get(n);s?.finalize()})}return lu}async function Rb(r,e){let t,n,s=new Promise((i,a)=>{t=i,n=a}),o=()=>{n(new hr)};return e?.signal?.addEventListener("abort",o,{once:!0}),r.add(async()=>{await new Promise(i=>{t(()=>{e?.signal?.removeEventListener("abort",o),i()})})},{signal:e?.signal}).catch(i=>{n(i)}),s}var H8=(r,e)=>{let t=Ro.get(r);if(t!=null)return t;let n=wz(e);if($8(n))return t=n,Ro.set(r,t),t;let s=new iu({concurrency:1}),o;return t={async readLock(i){if(o!=null)return Rb(o,i);o=new iu({concurrency:e.concurrency,autoStart:!1});let a=o,c=Rb(o,i);return s.add(async()=>{a.start(),await a.onIdle().then(()=>{o===a&&(o=null)})}),c},async writeLock(i){return o=null,Rb(s,i)},finalize:()=>{Ro.delete(r)},queue:s},Ro.set(r,t),e.autoFinalize===!0&&s.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var xz={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Nb(r){let e=Object.assign({},xz,r);return H8(e.name,e)}var Yge=new Uint8Array(0);function q8(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function pa(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function vz(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var v=d[y],S=0,E=w-1;(v!==0||S<g)&&E!==-1;E--,S++)v+=256*x[E]>>>0,x[E]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var A=c.repeat(m);I<w;++I)A+=r.charAt(x[I]);return A}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*w[S]>>>0,w[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(d[m]!==" "){for(var E=b-y;E!==b&&w[E]===0;)E++;for(var I=new Uint8Array(g+(b-E)),A=g;E!==b;)I[A++]=w[E++];return I}}}function f(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:f}}var Ez=vz,Sz=Ez,V8=Sz;var Bb=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Ub=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return G8(this,e)}},Kb=class{decoders;constructor(e){this.decoders=e}or(e){return G8(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function G8(r,e){return new Kb({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Fb=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new Bb(e,t,n),this.decoder=new Ub(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function W8({name:r,prefix:e,encode:t,decode:n}){return new Fb(r,e,t,n)}function ma({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=V8(t,r);return W8({prefix:e,name:r,encode:n,decode:o=>pa(s(o))})}function Iz(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function Az(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function Cz(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function un({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=Cz(n);return W8({prefix:e,name:r,encode(o){return Az(o,n,t)},decode(o){return Iz(o,s,t,r)}})}var No=un({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),rye=un({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),nye=un({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),sye=un({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),oye=un({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),iye=un({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),aye=un({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),cye=un({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),lye=un({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Vf=ma({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),dye=ma({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var zn=ma({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),mye=ma({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Tz=X8,j8=128,_z=127,Pz=~_z,Dz=Math.pow(2,31);function X8(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Dz;)e[t++]=r&255|j8,r/=128;for(;r&Pz;)e[t++]=r&255|j8,r>>>=7;return e[t]=r|0,X8.bytes=t-n+1,e}var kz=zb,Lz=128,Y8=127;function zb(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw zb.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&Y8)<<s:(i&Y8)*Math.pow(2,s),s+=7}while(i>=Lz);return zb.bytes=o-n,t}var Mz=Math.pow(2,7),Oz=Math.pow(2,14),Rz=Math.pow(2,21),Nz=Math.pow(2,28),Bz=Math.pow(2,35),Uz=Math.pow(2,42),Kz=Math.pow(2,49),Fz=Math.pow(2,56),zz=Math.pow(2,63),$z=function(r){return r<Mz?1:r<Oz?2:r<Rz?3:r<Nz?4:r<Bz?5:r<Uz?6:r<Kz?7:r<Fz?8:r<zz?9:10},Hz={encode:Tz,decode:kz,encodingLength:$z},qz=Hz,uu=qz;function hu(r,e=0){return[uu.decode(r,e),uu.decode.bytes]}function ga(r,e,t=0){return uu.encode(r,e,t),e}function ya(r){return uu.encodingLength(r)}function J8(r,e){let t=e.byteLength,n=ya(r),s=n+ya(t),o=new Uint8Array(s+t);return ga(r,o,0),ga(t,o,n),o.set(e,s),new ba(r,t,e,o)}function Z8(r){let e=pa(r),[t,n]=hu(e),[s,o]=hu(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new ba(t,s,i,e)}function eC(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&q8(r.bytes,t.bytes)}}var ba=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function tC(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Wz(t,$b(r),e??zn.encoder);default:return jz(t,$b(r),e??No.encoder)}}var rC=new WeakMap;function $b(r){let e=rC.get(r);if(e==null){let t=new Map;return rC.set(r,t),t}return e}var Gf=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==du)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Yz)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=J8(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&eC(e.multihash,n.multihash)}toString(e){return tC(this,e)}toJSON(){return{"/":tC(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??nC(n,s,o.bytes))}else if(t[Xz]===!0){let{version:n,multihash:s,code:o}=t,i=Z8(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==du)throw new Error(`Version 0 CID must use dag-pb (code: ${du}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=nC(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,du,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=pa(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new ba(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,p]=hu(e.subarray(t));return t+=p,h},s=n(),o=du;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=Gz(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return $b(o).set(n,e),o}};function Gz(r,e){switch(r[0]){case"Q":{let t=e??zn;return[zn.prefix,t.decode(`${zn.prefix}${r}`)]}case zn.prefix:{let t=e??zn;return[zn.prefix,t.decode(r)]}case No.prefix:{let t=e??No;return[No.prefix,t.decode(r)]}case Vf.prefix:{let t=e??Vf;return[Vf.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Wz(r,e,t){let{prefix:n}=t;if(n!==zn.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function jz(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var du=112,Yz=18;function nC(r,e,t){let n=ya(r),s=n+ya(e),o=new Uint8Array(s+t.byteLength);return ga(r,o,0),ga(e,o,n),o.set(t,s),o}var Xz=Symbol.for("@ipld/js-cid/CID");wr();rt();var $n;(function(r){let e;(function(s){let o;s.codec=()=>(o==null&&(o=Z((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:"",value:ae(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let h=i.uint32();switch(h>>>3){case 1:{l.key=i.string();break}case 2:{l.value=i.bytes();break}default:{i.skipType(h&7);break}}}return l})),o),s.encode=i=>J(i,s.codec()),s.decode=(i,a)=>Q(i,s.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(s){let o;s.codec=()=>(o==null&&(o=Z((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),jf.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:""},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let h=i.uint32();switch(h>>>3){case 1:{l.key=i.string();break}case 2:{l.value=jf.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(h&7);break}}}return l})),o),s.encode=i=>J(i,s.codec()),s.decode=(i,a)=>Q(i,s.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Z((s,o,i={})=>{if(i.lengthDelimited!==!1&&o.fork(),s.addresses!=null)for(let a of s.addresses)o.uint32(10),Wf.codec().encode(a,o);if(s.protocols!=null)for(let a of s.protocols)o.uint32(18),o.string(a);if(s.publicKey!=null&&(o.uint32(34),o.bytes(s.publicKey)),s.peerRecordEnvelope!=null&&(o.uint32(42),o.bytes(s.peerRecordEnvelope)),s.metadata!=null&&s.metadata.size!==0)for(let[a,c]of s.metadata.entries())o.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},o);if(s.tags!=null&&s.tags.size!==0)for(let[a,c]of s.tags.entries())o.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},o);s.updated!=null&&(o.uint32(64),o.uint64Number(s.updated)),i.lengthDelimited!==!1&&o.ldelim()},(s,o,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=o==null?s.len:s.pos+o;for(;s.pos<c;){let l=s.uint32();switch(l>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new _e('Decode error - map field "addresses" had too many elements');a.addresses.push(Wf.codec().decode(s,s.uint32(),{limits:i.limits?.addresses$}));break}case 2:{if(i.limits?.protocols!=null&&a.protocols.length===i.limits.protocols)throw new _e('Decode error - map field "protocols" had too many elements');a.protocols.push(s.string());break}case 4:{a.publicKey=s.bytes();break}case 5:{a.peerRecordEnvelope=s.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new Bc('Decode error - map field "metadata" had too many elements');let u=r.Peer$metadataEntry.codec().decode(s,s.uint32());a.metadata.set(u.key,u.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new Bc('Decode error - map field "tags" had too many elements');let u=r.Peer$tagsEntry.codec().decode(s,s.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(u.key,u.value);break}case 8:{a.updated=s.uint64Number();break}default:{s.skipType(l&7);break}}}return a})),n),r.encode=s=>J(s,r.codec()),r.decode=(s,o)=>Q(s,r.codec(),o)})($n||($n={}));var Wf;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),t.observed!=null&&(n.uint32(24),n.uint64Number(t.observed)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={multiaddr:ae(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.multiaddr=t.bytes();break}case 2:{o.isCertified=t.bool();break}case 3:{o.observed=t.uint64Number();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(Wf||(Wf={}));var jf;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={value:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.value=t.uint32();break}case 2:{o.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(jf||(jf={}));Bt();ke();function Qz(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=Ft(e.publicKey,t);return On(n)}function sC(r,e,t){let n=$n.decode(e);return wa(r,n,t)}function wa(r,e,t){let n=new Map,s=BigInt(Date.now());for(let[o,i]of e.tags.entries())i.expiry!=null&&i.expiry<s||n.set(o,i);return{...e,id:Qz(r,e),addresses:e.addresses.filter(({observed:o})=>o!=null&&o>Date.now()-t).map(({multiaddr:o,isCertified:i})=>({multiaddr:q(o),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}Ne();function oC(r,e){return Jz(r.addresses,e.addresses)&&Zz(r.protocols,e.protocols)&&e$(r.publicKey,e.publicKey)&&t$(r.peerRecordEnvelope,e.peerRecordEnvelope)&&r$(r.metadata,e.metadata)&&n$(r.tags,e.tags)}function Jz(r,e){return aC(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!W(t.multiaddr,n.multiaddr)))}function Zz(r,e){return aC(r,e,(t,n)=>t===n)}function e$(r,e){return iC(r,e)}function t$(r,e){return iC(r,e)}function r$(r,e){return cC(r,e,(t,n)=>W(t,n))}function n$(r,e){return cC(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function iC(r,e){return r==null&&e==null?!0:r!=null&&e!=null?W(r,e):!1}function aC(r,e,t){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],e[n]))return!1;return!0}function cC(r,e,t){if(r.size!==e.size)return!1;for(let[n,s]of r.entries()){let o=e.get(n);if(o==null||!t(s,o))return!1}return!0}V();te();ce();var Hn="/",lC=new TextEncoder().encode(Hn),Yf=lC[0],Bo=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=D(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Yf)throw new Error("Invalid key")}toString(e="utf8"){return P(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Hn))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=lC),this._buf[0]!==Yf){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Yf,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Yf;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let s=0;s<t.length;s++){if(n.length<s+1)return!1;let o=t[s],i=n[s];if(o<i)return!0;if(o>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Hn).slice(1)}type(){return s$(this.baseNamespace())}name(){return o$(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Hn)||(e+=Hn),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Hn):new r(e.slice(0,-1).join(Hn))}child(e){return this.toString()===Hn?e:e.toString()===Hn?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...i$(e.map(t=>t.namespaces()))])}};function s$(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function o$(r){let e=r.split(":");return e[e.length-1]}function i$(r){return[].concat(...r)}var Hb="/peers/";function fu(r){if(!cs(r)||r.type==null)throw new R("Invalid PeerId");let e=r.toCID().toString();return new Bo(`${Hb}${e}`)}Bt();V();Ne();V();async function uC(r,e,t,n,s){let o=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=q(i.multiaddr)),!As(i.multiaddr))throw new R("Multiaddr was invalid");if(!await e(r,i.multiaddr,s))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),l=o.get(c);l!=null?i.isCertified=l.isCertified||a:o.set(c,{multiaddr:i.multiaddr,isCertified:a})}return[...o.values()].sort((i,a)=>i.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:i,multiaddr:a})=>{let c=a.getComponents().find(l=>l.code===421)?.value;return r.equals(c)&&(a=a.decapsulate(q(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function Qf(r,e,t,n){if(e==null)throw new R("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new R("publicKey bytes do not match peer id publicKey bytes");let s=n.existingPeer?.peer;if(s!=null&&!r.equals(s.id))throw new R("peer id did not match existing peer id");let o=s?.addresses??[],i=new Set(s?.protocols??[]),a=s?.metadata??new Map,c=s?.tags??new Map,l=s?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(o=[],e.multiaddrs!=null&&o.push(...e.multiaddrs.map(p=>({isCertified:!1,multiaddr:p}))),e.addresses!=null&&o.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let p=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Xf(p,{validate:hC})}if(e.tags!=null){let p=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Xf(p,{validate:dC,map:fC})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&o.push(...e.multiaddrs.map(p=>({isCertified:!1,multiaddr:p}))),e.addresses!=null&&o.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let p=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[f,d]of p)d==null?a.delete(f):a.set(f,d);a=Xf([...a.entries()],{validate:hC})}if(e.tags!=null){let p=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),f=new Map(c);for(let[d,m]of p)m==null?f.delete(d):f.set(d,m);c=Xf([...f.entries()],{validate:dC,map:fC})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;s?.id.publicKey!=null?u=dt(s.id.publicKey):e.publicKey!=null?u=dt(e.publicKey):r.publicKey!=null&&(u=dt(r.publicKey));let h={addresses:await uC(r,n.addressFilter??(async()=>!0),o,n.existingPeer?.peerPB.addresses,n),protocols:[...i.values()].sort((p,f)=>p.localeCompare(f)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return h.addresses.forEach(p=>{p.observed=n.existingPeer?.peerPB.addresses?.find(f=>W(f.multiaddr,f.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete h.publicKey,h}function Xf(r,e){let t=new Map;for(let[n,s]of r)s!=null&&e.validate(n,s);for(let[n,s]of r.sort(([o],[i])=>o.localeCompare(i)))s!=null&&t.set(n,e.map?.(n,s)??s);return t}function hC(r,e){if(typeof r!="string")throw new R("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new R("Metadata value must be a Uint8Array")}function dC(r,e){if(typeof r!="string")throw new R("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new R("Tag value must be an integer");if(e.value<0||e.value>100)throw new R("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new R("Tag ttl must be an integer");if(e.ttl<0)throw new R("Tag ttl must be between greater than 0")}}function fC(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let n={value:e.value??0};return t!=null&&(n.expiry=t),n}function pC(r){let e=r.toString().split("/")[2],t=Gf.parse(e,No);return en(t)}function qb(r,e,t){let n=pC(r);return sC(n,e,t)}function a$(r,e){return{prefix:Hb,filters:(r.filters??[]).map(t=>({key:n,value:s})=>t(qb(n,s,e))),orders:(r.orders??[]).map(t=>(n,s)=>t(qb(n.key,n.value,e),qb(s.key,s.value,e)))}}var Jf=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=ru({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return t==null&&(t={refs:0,lock:Nb({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,t.refs===0&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){let n=this.getLock(e);try{let s=await n.lock.readLock(t);return()=>{s(),this.maybeRemoveLock(e,n)}}catch(s){throw this.maybeRemoveLock(e,n),s}}async getWriteLock(e,t){let n=this.getLock(e);try{let s=await n.lock.writeLock(t);return()=>{s(),this.maybeRemoveLock(e,n)}}catch(s){throw this.maybeRemoveLock(e,n),s}}async has(e,t){try{return await this.load(e,t),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(fu(e),t)}async load(e,t){let n=fu(e),s=await this.datastore.get(n,t),o=$n.decode(s);if(this.#r(e,o))throw await this.datastore.delete(n,t),new $s;return wa(e,o,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let s=await this.#e(e,n),o=await Qf(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#t(e,o,s)}async patch(e,t,n){let s=await this.#e(e,n),o=await Qf(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:s});return this.#t(e,o,s)}async merge(e,t,n){let s=await this.#e(e,n),o=await Qf(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:s});return this.#t(e,o,s)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(a$(e??{},this.maxAddressAge),e)){let s=pC(t);if(s.equals(this.peerId))continue;let o=$n.decode(n);if(this.#r(s,o)){await this.datastore.delete(t,e);continue}yield wa(s,o,this.peerId.equals(s)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=fu(e),s=await this.datastore.get(n,t),o=$n.decode(s);if(this.#r(e,o))throw await this.datastore.delete(n,t),new $s;return{peerPB:o,peer:wa(e,o,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#t(e,t,n,s){t.updated=Date.now();let o=$n.encode(t);return await this.datastore.put(fu(e),o,s),{peer:wa(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!oC(t,n.peerPB)}}#r(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,s=Date.now()-this.maxAddressAge,o=t.addresses.filter(i=>i.observed!=null&&i.observed>s);return n&&o.length===0}};var Vb=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new Jf(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let n of this.store.all(t))e(n)}async all(e){return ou(this.store.all(e))}async delete(e,t){let n=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{n()}}async has(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),n?.()}}async get(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{n?.()}}async getInfo(e,t){let n=await this.get(e,t);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:s})=>s)}}async save(e,t,n){let s=await this.store.getWriteLock(e,n);try{let o=await this.store.save(e,t,n);return this.#e(e,o),o.peer}finally{s?.()}}async patch(e,t,n){let s=await this.store.getWriteLock(e,n);try{let o=await this.store.patch(e,t,n);return this.#e(e,o),o.peer}finally{s?.()}}async merge(e,t,n){let s=await this.store.getWriteLock(e,n);try{let o=await this.store.merge(e,t,n);return this.#e(e,o),o.peer}finally{s?.()}}async consumePeerRecord(e,t,n){let s=cs(t)?t:cs(t?.expectedPeer)?t.expectedPeer:void 0,o=cs(t)||t===void 0?n:t,i=await lr.openAndCertify(e,ur.DOMAIN,o),a=en(i.publicKey.toCID());if(s?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",s,a),!1;let c=ur.createFromProtobuf(i.payload),l;try{l=await this.get(a,o)}catch(u){if(u.name!=="NotFoundError")throw u}if(l?.peerRecordEnvelope!=null){let u=lr.createFromProtobuf(l.peerRecordEnvelope),h=ur.createFromProtobuf(u.payload);if(h.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",h.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u}))},o),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function mC(r,e={}){return new Vb(r,e)}var Zf=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};function c$(r){return r[Symbol.asyncIterator]!=null}function l$(r){if(c$(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Gb=l$;function u$(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var gC=u$;function h$(r){return r[Symbol.asyncIterator]!=null}function d$(r,e){let t=0;if(h$(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=gC(r),{value:s,done:o}=n.next();if(o===!0)return(function*(){})();let i=e(s,t++);if(typeof i.then=="function")return(async function*(){await i&&(yield s);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){i===!0&&(yield s);for(let c of n)a(c,t++)&&(yield c)})()}var Uo=d$;function f$(r){return r[Symbol.asyncIterator]!=null}function p$(r,e){return f$(r)?(async function*(){yield*(await ou(r)).sort(e)})():(function*(){yield*ou(r).sort(e)})()}var Wb=p$;function m$(r){return r[Symbol.asyncIterator]!=null}function g$(r,e){return m$(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var jb=g$;var ep=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:s}of e)await this.put(n,s,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,s){e.push({key:n,value:s})},delete(n){t.push(n)},commit:async n=>{await Gb(this.putMany(e,n)),e=[],await Gb(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let s=e.prefix;n=Uo(n,o=>o.key.toString().startsWith(s))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((s,o)=>Uo(s,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((s,o)=>Wb(s,o),n)),e.offset!=null){let s=0,o=e.offset;n=Uo(n,()=>s++>=o)}return e.limit!=null&&(n=jb(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let s=e.prefix;n=Uo(n,o=>o.toString().startsWith(s))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((s,o)=>Uo(s,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((s,o)=>Wb(s,o),n)),e.offset!=null){let s=e.offset,o=0;n=Uo(n,()=>o++>=s)}return e.limit!=null&&(n=jb(n,e.limit)),n}};var tp=class extends ep{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(e.toString());if(n==null)throw new Zf;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[n,s]of this.data.entries())yield{key:new Bo(n),value:s},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new Bo(n),t?.signal?.throwIfAborted()}};Ue();bt();te();ke();var Pe=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),Y=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),yC=r=>({match:e=>r.match(e)===!1?e:!1}),he=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Dt=(...r)=>({match:e=>{let t;for(let n of r){let s=n.match(e);s!==!1&&(t==null||s.length<t.length)&&(t=s)}return t??!1}}),we=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function De(...r){function e(s){if(s==null)return!1;let o=s.getComponents();for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function t(s){return e(s)!==!1}function n(s){let o=e(s);return o===!1?!1:o.length===0}return{matchers:r,matches:t,exactMatch:n}}var y$=Y(421),bC=De(y$),np=Y(54),sp=Y(55),op=Y(56),Xb=Y(53),K3e=De(np,he(Y(421))),F3e=De(sp,he(Y(421))),z3e=De(op,he(Y(421))),$3e=De(Dt(Xb,op,np,sp),he(Y(421))),wC=we(Y(4),he(Y(43))),xC=we(he(Y(42)),Y(41),he(Y(43))),Qb=Dt(wC,xC),Ko=Dt(Qb,Xb,np,sp,op),vC=De(Dt(Qb,we(Dt(Xb,op,np,sp),he(Y(421))))),Jb=De(wC),Zb=De(xC),H3e=De(Qb),ew=we(Ko,Y(6)),pu=we(Ko,Y(273)),qn=De(we(ew,he(Y(421)))),q3e=De(pu),tw=we(pu,Pe(460),he(Y(421))),ip=we(pu,Pe(461),he(Y(421))),b$=Dt(tw,ip),V3e=De(tw),EC=De(ip),Yb=Dt(Ko,ew,pu,tw,ip),SC=Dt(we(Yb,Pe(477),he(Y(421)))),mu=De(SC),IC=Dt(we(Yb,Pe(478),he(Y(421))),we(Yb,Pe(448),he(Y(449)),Pe(477),he(Y(421)))),gu=De(IC),AC=we(pu,Pe(280),he(Y(466)),he(Y(466)),he(Y(421))),rw=De(AC),CC=we(ip,Pe(465),he(Y(466)),he(Y(466)),he(Y(421))),nw=De(CC),rp=Dt(SC,IC,we(ew,he(Y(421))),we(b$,he(Y(421))),we(Ko,he(Y(421))),AC,CC,Y(421)),ap=De(rp),w$=we(he(rp),Pe(290),yC(Pe(281)),he(Y(421))),er=De(w$),x$=Dt(we(rp,Pe(290),Pe(281),he(Y(421))),we(rp,Pe(281),he(Y(421))),we(Pe(281),he(Y(421)))),sw=De(x$),v$=Dt(we(Ko,Y(6),Pe(480),he(Y(421))),we(Ko,Pe(480),he(Y(421)))),G3e=De(v$),E$=we(Ko,Dt(we(Y(6,"443"),Pe(480)),we(Y(6),Pe(443)),we(Y(6),Pe(448),Pe(480)),we(Pe(448),Pe(480)),Pe(448),Pe(443)),he(Y(421))),W3e=De(E$),S$=Dt(we(Y(777),he(Y(421)))),j3e=De(S$),I$=Dt(we(Y(400),he(Y(421)))),cp=De(I$);var TC=864e13;var lp=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Pt({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=oe(e),n=t.host;(t.type==="ip4"||t.type==="ip6")&&t.sni!=null&&(n=t.sni);for(let s of this.mappings.values())if(s.domain===n)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let s=ua(n)===!0;this.mappings.set(n,{domain:e,verified:s,expires:s?TC-Date.now():0,lastVerified:s?TC-Date.now():void 0})})}remove(e){let t=oe(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[s,o]of this.mappings.entries())o.domain===t.sni&&(this.log("removing %s to %s DNS mapping %e",s,o.domain),this.mappings.delete(s),n=n||o.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let s=e[n].multiaddr;if(!St(s))continue;let o=oe(s);for(let[i,a]of this.mappings.entries()){if(o.host!==i)continue;let c=this.maybeAddSNIComponent(s,a.domain);c!=null&&(e.splice(n,1),n--,t.push({multiaddr:c,verified:a.verified,type:"dns-mapping",expires:a.expires,lastVerified:a.lastVerified}))}}return t}maybeAddSNIComponent(e,t){let n=e.getComponents();for(let s=0;s<n.length;s++)if(n[s].code===448&&n[s+1]?.code!==449)return n.splice(s+1,0,{name:"sni",code:449,value:t}),q(n)}confirm(e,t){let n=oe(e),s=n.host;(n.type==="ip4"||n.type==="ip6")&&n.sni!=null&&(s=n.sni);let o=!1;for(let[i,a]of this.mappings.entries())a.domain===s&&(this.log("marking %s to %s DNS mapping as verified",i,a.domain),o=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return o}unconfirm(e,t){let n=oe(e);if(n.type!=="ip4"&&n.type!=="ip6")return!1;let s=n.sni??n.host,o=!1;for(let[i,a]of this.mappings.entries())a.domain===s&&(this.log("removing verification of %s to %s DNS mapping",i,a.domain),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t);return o}};var up=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Pt({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=oe(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;for(let n of this.mappings.values())for(let s of n)if(s.externalIp===t.host)return!0;return!1}add(e,t,n,s=t,o="tcp"){let i=`${e}-${t}-${o}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:s,externalFamily:(0,fe.isIPv4)(n)?4:6,protocol:o,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=oe(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[s,o]of this.mappings.entries()){for(let i=0;i<o.length;i++){let a=o[i];a.externalIp===t.host&&a.externalPort===t.port&&a.protocol===t.protocol&&(this.log("removing %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,t.host,t.port,t.protocol),n=n||a.verified,o.splice(i,1),i--)}o.length===0&&this.mappings.delete(s)}return n}getAll(e){let t=[];for(let{multiaddr:n}of e){if(!St(n))continue;let s=oe(n);if(s.type!=="ip4"&&s.type!=="ip6")continue;let o;if(s.protocol==="tcp"?o=`${s.host}-${s.port}-tcp`:s.protocol==="udp"&&(o=`${s.host}-${s.port}-udp`),o==null)continue;let i=this.mappings.get(o);if(i!=null)for(let a of i)t.push({multiaddr:this.maybeOverrideIp(n,a.externalIp,a.externalFamily,a.protocol,a.externalPort),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}maybeOverrideIp(e,t,n,s,o){let i=e.getComponents(),a=i.findIndex(l=>l.code===4||l.code===41),c=i.findIndex(l=>l.name===s);return a>-1&&c>-1?(i[a].value=t,i[a].code=n===4?4:41,i[c].value=`${o}`,q(i)):e}confirm(e,t){if(!St(e))return!1;let n=oe(e),s=!1;for(let o of this.mappings.values())for(let i of o)i.externalIp===n.host&&(this.log("marking %s to %s IP mapping as verified",i.internalIp,i.externalIp),s=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return s}unconfirm(e,t){if(!St(e))return!1;let n=oe(e),s=!1;for(let o of this.mappings.values())for(let i=0;i<o.length;i++){let a=o[i];a.externalIp===n.host&&a.externalPort===n.port&&a.protocol===n.protocol&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,n.host,n.port,n.protocol),s=s||a.verified,a.verified=!1,a.expires=Date.now()+t)}return s}};var A$={maxObservedAddresses:10},hp=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Pt({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??A$.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(Fn(e)||b8(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:q(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),s=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},o=s.verified;return s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,s),o}};var C$={maxObservedAddresses:10},dp=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Pt({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??C$.maxObservedAddresses}get(e,t){if(Fn(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),s=this.addresses.get(n);return s==null&&(s={verified:!St(e),expires:0},this.addresses.set(n,s)),{multiaddr:e,verified:s.verified,type:"transport",expires:s.expires,lastVerified:s.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),s=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},o=s.verified;return s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now(),this.addresses.set(n,s),o}unconfirm(e,t){let n=this.toKey(e),s=this.addresses.get(n)??{verified:!1,expires:0},o=s.verified;return s.verified=!1,s.expires=Date.now()+t,this.addresses.set(n,s),o}toKey(e){if(!St(e))return e.toString();let t=oe(e);return`${t.host}-${t.port}-${t.protocol}`}};var _C=6e4,PC={maxObservedAddresses:10,addressVerificationTTL:_C*10,addressVerificationRetry:_C*5},T$=r=>r;function ow(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&de(t).equals(e)&&(r=r.decapsulate(q(`/p2p/${e.toString()}`))),r}var fp=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:s=[],appendAnnounce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(s.map(i=>i.toString())),this.appendAnnounce=new Set(o.map(i=>i.toString())),this.observed=new hp(e,t),this.dnsMappings=new lp(e,t),this.ipMappings=new up(e,t),this.transportAddresses=new dp(e,t),this.announceFilter=t.announceFilter??T$,this.observedAddressFilter=ln(1024),this.addressVerificationTTL=t.addressVerificationTTL??PC.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??PC.addressVerificationRetry,this._updatePeerStoreAddresses=So(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getComponents().findLast(n=>n.code===421)?.value===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses - %e",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>q(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>q(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>q(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=oe(e),n;switch(t.type){case"ip4":{n=`${t.host}:${t.port}`;break}case"ip6":{n=`[${t.host}]:${t.port}`;break}default:return}this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=ow(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=ow(e,this.components.peerId);let n=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=ow(e,this.components.peerId);let n=!1;this.observed.has(e)&&!this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&!this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&!this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&!this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let s=n.multiaddr.toString();return e.has(s)?!1:(e.add(s),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let s=q(n);return s.getComponents().pop()?.value===this.components.peerId.toString()?s:s.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(s=>{s.updateAnnounceAddrs(e)}),e.map(s=>({multiaddr:s,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(s=>this.transportAddresses.get(s,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(s=>{s.updateAnnounceAddrs(n)}),t=t.concat(n.map(s=>({multiaddr:s,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(q(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,s=t,o="tcp"){this.ipMappings.add(e,t,n,s,o),this.observed.removePrefixed(`/ip${(0,fe.isIPv4)(n)?4:6}/${n}/${o}/${s}`)}removePublicAddressMapping(e,t,n,s=t,o="tcp"){this.ipMappings.remove(q(`/ip${(0,fe.isIPv4)(n)?4:6}/${n}/${o}/${s}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!St(e))return!1;let t=oe(e);if(t.type!=="ip4"||ua(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),s=[o=>mu.exactMatch(o)||gu.exactMatch(o),o=>qn.exactMatch(o),o=>EC.exactMatch(o)];for(let o of s){if(!o(e))continue;let i=n.filter(l=>l.getAddrs().filter(u=>oe(u).type==="ip4"&&o(u)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>!Zl(l)).pop();if(a==null)continue;let c=oe(a);return c.port==null?!1:(this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.protocol),!0)}return!1}};V();var DC;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(DC||(DC={}));var pp=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},mp=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},xa=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},yu=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},gp=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},yp=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},bp=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},bu=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},wp=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},xp=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},vp=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},Ep=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},Sp=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},ks=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Fo=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},Ip=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},Ap=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var iw=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=bf())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Dh(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},_$=["metrics","connectionProtector","dns"],P$=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function kC(r={}){let e=new iw(r);return new Proxy(e,{get(n,s,o){if(typeof s=="string"&&!P$.includes(s)){let i=e.components[s];if(i==null&&!_$.includes(s))throw new pp(`${s} not set`);return i}return Reflect.get(n,s,o)},set(n,s,o){return typeof s=="string"?e.components[s]=o:Reflect.set(n,s,o),!0}})}function LC(r){let e={};for(let t of Object.values(r.components))for(let n of D$(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of k$(t))if(e[n]!==!0)throw new mp(`Service "${L$(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function D$(r){return Array.isArray(r?.[nt])?r[nt]:[]}function k$(r){return Array.isArray(r?.[yc])?r[yc]:[]}function L$(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function MC(r={}){return r}V();var Le=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};V();ke();function Cp(r){if(cs(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let n=e[0].getComponents().findLast(s=>s.code===421)?.value;t=n==null?void 0:de(n),e.forEach(s=>{if(!As(s))throw new ss("Invalid multiaddr");let o=s.getComponents().findLast(i=>i.code===421)?.value;if(o==null){if(t!=null)throw new R("Multiaddrs must all have the same peer id or have no peer id")}else{let i=de(o);if(t?.equals(i)!==!0)throw new R("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!bC.exactMatch(n)),{peerId:t,multiaddrs:e}}V();var M$=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function OC(r,e){let t=r?.streams?.map(s=>s.protocol)??[],n=e?.closableProtocols??M$;if(!(t.filter(s=>s!=null&&!n.includes(s)).length>0))try{await r?.close(e)}catch(s){r?.abort(s)}}function wu(r){let e=oe(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new R(`Multiaddr ${r} was not an IPv4 or IPv6 address`);if(t==null)switch(e.type){case"ip4":{t=32;break}case"ip6":{t=128;break}default:throw new R(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new Bn(e.host,t)}function aw(r){return!er.exactMatch(r)}function Tp(r,e,t){if(r==null||e==null)return;let n=e.sort((o,i)=>o.direct?-1:i.direct?1:0).find(o=>o.limits==null);if(n==null||n.direct||t==null)return n;if(!t.some(o=>aw(o)))return n}var _p=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>wu(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections - %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,n),t<=n)return;let s=new Zt;for(let c of e){let l=c.remotePeer;if(!s.has(l)){s.set(l,0);try{let u=await this.peerStore.get(l);s.set(l,[...u.tags.values()].reduce((h,p)=>h+p.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags - %e",u)}}}let o=this.sortConnections(e,s),i=Math.max(t-n,0),a=[];for(let c of o)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(u=>{if(St(c.remoteAddr)){let h=oe(c.remoteAddr);return u.contains(h.host)}return!0})||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await OC(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((n,s)=>{let o=n.timeline.open,i=s.timeline.open;return o<i?1:o>i?-1:0}).sort((n,s)=>n.direction==="outbound"&&s.direction==="inbound"?1:n.direction==="inbound"&&s.direction==="outbound"?-1:0).sort((n,s)=>n.streams.length>s.streams.length?1:n.streams.length<s.streams.length?-1:0).sort((n,s)=>{let o=t.get(n.remotePeer)??0,i=t.get(s.remotePeer)??0;return o>i?1:o<i?-1:0})}};var RC="last-dial-failure",NC="last-dial-success";var BC=300,Pp=100;V();Ue();te();function O$(r,e){let t=qn.exactMatch(r.multiaddr),n=qn.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let s=gu.exactMatch(r.multiaddr),o=gu.exactMatch(e.multiaddr);if(s&&!o)return-1;if(!s&&o)return 1;let i=mu.exactMatch(r.multiaddr),a=mu.exactMatch(e.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=sw.exactMatch(r.multiaddr),l=sw.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=rw.exactMatch(r.multiaddr),h=rw.exactMatch(e.multiaddr);if(u&&!h)return-1;if(!u&&h)return 1;let p=nw.exactMatch(r.multiaddr),f=nw.exactMatch(e.multiaddr);return p&&!f?-1:!p&&f?1:0}function R$(r,e){let t=Zl(r.multiaddr),n=Zl(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function N$(r,e){let t=Fn(r.multiaddr),n=Fn(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function B$(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function U$(r,e){let t=er.exactMatch(r.multiaddr),n=er.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function UC(r){return r.sort(O$).sort(B$).sort(U$).sort(N$).sort(R$)}var FC=ee("dns/promises");function Dp(r){let e=[kt.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}ce();var cw=60;function kp(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:kt[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:kt[e.type],TTL:e.TTL??e.ttl??cw,data:e.data instanceof Uint8Array?P(e.data):e.data}))}}var K$=async(r,e={})=>{let t=new FC.Resolver,n=()=>{t.cancel()},s=Dp(e.types);try{e.signal?.addEventListener("abort",n);let o=await Promise.all(s.map(async i=>{if(i===kt.A)return Lp(r,i,await t.resolve4(r));if(i===kt.CNAME)return Lp(r,i,await t.resolveCname(r));if(i===kt.TXT)return Lp(r,i,await t.resolveTxt(r));if(i===kt.AAAA)return Lp(r,i,await t.resolve6(r));throw new TypeError("Unsupported DNS record type")}));return kp({Question:s.map(i=>({name:r,type:i})),Answer:o.flat()})}finally{e.signal?.removeEventListener("abort",n)}};function zC(){return[K$]}function KC(r,e,t){return{name:r,type:e,data:t}}function Lp(r,e,t){return Array.isArray(t)||(t=[t]),t.map(n=>Array.isArray(n)?n.map(s=>KC(r,e,s)):KC(r,e,n)).flat()}var qC=ie(HC(),1);var lw=class{lru;constructor(e){this.lru=(0,qC.default)(e)}get(e,t){let n=!0,s=[];for(let o of t){let i=this.getAnswers(e,o);if(i.length===0){n=!1;break}s.push(...i)}if(n)return kp({answers:s})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,s=this.lru.get(n);if(s!=null){let o=s.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:kt[a.type]}));return o.length===0&&this.lru.remove(n),o}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,s=this.lru.get(n)??[];s.push({expires:Date.now()+(t.TTL??cw)*1e3,value:t}),this.lru.set(n,s)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function VC(r){return new lw(r)}var F$=1e3,Mp=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=VC(e.cacheSize??F$),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=zC())}async query(e,t={}){let n=Dp(t.types),s=t.cached!==!1?this.cache.get(e,n):void 0;if(s!=null)return t.onProgress?.(new Le("dns:cache",s)),s;let o=`${e.split(".").pop()}.`,i=(this.resolvers[o]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new Le("dns:error",l))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var kt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(kt||(kt={}));function GC(r={}){return new Mp(r)}var uw=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let n=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[e];let o=await this.getDNS(t).query(`_dnsaddr.${n}`,{signal:t?.signal,types:[kt.TXT]}),i=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of o.Answer){let l=c.data.replace(/["']/g,"").trim().split("=")[1];l!=null&&(i!=null&&!l.includes(i)||a.push(q(l)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=GC()),this.dns)}},xu=new uw;async function hw(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new Ap("Max recursive depth reached");let s=!1,o=[];for(let i of Object.values(e))if(i.canResolve(r)){s=!0;let a=await i.resolve(r,t);for(let c of a)o.push(...await hw(c,e,{...t,depth:n+1}))}return s===!1&&o.push(r),o}var vu={maxParallelDials:Pp,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:xu}},Op=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??vu.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??vu.maxDialQueueLength,this.dialTimeout=t.dialTimeout??vu.dialTimeout,this.connections=t.connections??new Zt,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??vu.resolvers,this.shutDownController=new AbortController,j(1/0,this.shutDownController.signal),this.queue=new Mf({concurrency:t.maxParallelDials??vu.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==rr.name&&this.log.error("error in dial queue - %e",n.detail.error)})}start(){this.shutDownController=new AbortController,j(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:s}=Cp(e);if(n!=null&&t.force!==!0){let i=Tp(n,this.connections.get(n),s);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new Le("dial-queue:already-connected")),i}let o=this.queue.queue.find(i=>{if(n?.equals(i.options.peerId)===!0)return!0;let a=i.options.multiaddrs;if(a==null)return!1;for(let c of s)if(a.has(c.toString()))return!0;return!1});if(o!=null){this.log("joining existing dial target for %p",n);for(let i of s)o.options.multiaddrs.add(i.toString());return t.onProgress?.(new Le("dial-queue:already-in-dial-queue")),o.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new os("Dial queue is full");return this.log("creating dial target for %p",n,s.map(i=>i.toString())),t.onProgress?.(new Le("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new Le("dial-queue:start-dial"));let a=$t([this.shutDownController.signal,i.signal]);j(1/0,a);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??mw,multiaddrs:new Set(s.map(i=>i.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,s=e.multiaddrs,o=new Set,i=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);i||s.size>0;){c++,i=!1;let u=[],h=new Set(e.multiaddrs);s.clear(),this.log("calculating addrs to dial %p from %s",n,[...h]);let p=await this.calculateMultiaddrs(n,h,{...e,signal:t});for(let f of p){if(o.has(f.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",f.multiaddr,n);continue}u.push(f)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,u.map(f=>f.multiaddr.toString())),e?.onProgress?.(new Le("dial-queue:calculated-addresses",u));for(let f of u){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new os("Peer had more than maxPeerAddrsToDial");a++;try{let d=await this.components.transportManager.dial(f.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",f.multiaddr);try{await this.components.peerStore.merge(d.remotePeer,{multiaddrs:[d.remoteAddr],metadata:{[NC]:D(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p - %e",n,m)}return d}catch(d){if(this.log.error("dial failed to %a - %e",f.multiaddr,d),o.add(f.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[RC]:D(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p - %e",n,m)}if(t.aborted)throw new Gr(d.message);l.push(d)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let s=[...t].map(h=>({multiaddr:q(h),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new os("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new bu("The dial request is blocked by gater.allowDialPeer");if(s.length===0){this.log("loading multiaddrs for %p",e);try{let h=await this.components.peerStore.get(e);s.push(...h.addresses),this.log("loaded multiaddrs for %p",e,s.map(({multiaddr:p})=>p.toString()))}catch(h){if(h.name!=="NotFoundError")throw h}}if(s.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let h=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,s.map(({multiaddr:p})=>p.toString())),s.push(...h.multiaddrs.map(p=>({multiaddr:p,isCertified:!1})))}catch(h){h.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,h)}}}let o=(await Promise.all(s.map(async h=>{let p=await hw(h.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return p.length===1&&p[0].equals(h.multiaddr)?h:p.map(f=>({multiaddr:f,isCertified:!1}))}))).flat();if(e!=null){let h=`/p2p/${e.toString()}`;o=o.map(p=>p.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:p.multiaddr.encapsulate(h),isCertified:p.isCertified}:p)}let i=o.filter(h=>{if(this.components.transportManager.dialTransportForMultiaddr(h.multiaddr)==null)return!1;let p=h.multiaddr.getComponents().findLast(f=>f.code===421)?.value;return e!=null&&p!=null?e.equals(p):!0}),a=new Map;for(let h of i){let p=h.multiaddr.toString(),f=a.get(p);if(f!=null){f.isCertified=f.isCertified||h.isCertified||!1;continue}a.set(p,h)}let c=[...a.values()];if(c.length===0)throw new vp("The dial request has no valid addresses");let l=[];for(let h of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(h.multiaddr)||l.push(h);let u=this.addressSorter==null?UC(l):l.sort(this.addressSorter);if(u.length===0)throw new bu("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",o.map(({multiaddr:h})=>h.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:h})=>h.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(s=>s.toString())),t);return t.runOnLimitedConnection===!1?n.find(s=>!er.matches(s.multiaddr))!=null:!0}catch{}return!1}};V();var z$=Object.prototype.toString,$$=r=>z$.call(r)==="[object Error]",H$=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function gw(r){if(!(r&&$$(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"?n===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")?!0:H$.has(t)}function q$(r){if(typeof r=="number"){if(r<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function Rp(r,e,{min:t=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${r}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${r}\` to be a finite number.`);if(e<t)throw new TypeError(`Expected \`${r}\` to be \u2265 ${t}.`)}}var yw=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function V$(r,e){let t=Math.max(1,r+1),n=e.randomize?Math.random()+1:1,s=Math.round(n*e.minTimeout*e.factor**(t-1));return s=Math.min(s,e.maxTimeout),s}function WC(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function G$({error:r,attemptNumber:e,retriesConsumed:t,startTime:n,options:s}){let o=r instanceof Error?r:new TypeError(`Non-error was thrown: "${r}". You should only throw errors.`);if(o instanceof yw)throw o.originalError;let i=Number.isFinite(s.retries)?Math.max(0,s.retries-t):s.retries,a=s.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:o,attemptNumber:e,retriesLeft:i,retriesConsumed:t});if(await s.onFailedAttempt(c),WC(n,a)<=0)throw o;let l=await s.shouldConsumeRetry(c),u=WC(n,a);if(u<=0||i<=0)throw o;if(o instanceof TypeError&&!gw(o)){if(l)throw o;return s.signal?.throwIfAborted(),!1}if(!await s.shouldRetry(c))throw o;if(!l)return s.signal?.throwIfAborted(),!1;let h=V$(t,s),p=Math.min(h,u);return p>0&&await new Promise((f,d)=>{let m=()=>{clearTimeout(g),s.signal?.removeEventListener("abort",m),d(s.signal.reason)},g=setTimeout(()=>{s.signal?.removeEventListener("abort",m),f()},p);s.unref&&g.unref?.(),s.signal?.addEventListener("abort",m,{once:!0})}),s.signal?.throwIfAborted(),!0}async function bw(r,e={}){if(e={...e},q$(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,Rp("factor",e.factor,{min:0,allowInfinity:!1}),Rp("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),Rp("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),Rp("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let t=0,n=0,s=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){t++;try{e.signal?.throwIfAborted();let o=await r(t);return e.signal?.throwIfAborted(),o}catch(o){await G$({error:o,attemptNumber:t,retriesConsumed:n,startTime:s,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Np=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new Ps({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(s=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,s)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);jC(t)&&(this.queue.has(e)||this.queue.add(async n=>{await bw(async s=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(o){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,s,this.retries,o),o}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let s={};[...t.tags.keys()].forEach(o=>{o.startsWith(mc)&&(s[o]=void 0)}),await this.peerStore.merge(e,{tags:s}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>jC(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error("could not open connection to keepalive peer - %e",n)})}))}).catch(e=>{this.log.error("error reconnect to peers after start - %e",e)})}stop(){this.started=!1,this.queue.abort()}};function jC(r){for(let e of r.tags.keys())if(e.startsWith(mc))return!0;return!1}var mw=50,ww={maxConnections:BC,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},Bp=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??ww.maxConnections,this.maxConnections<1)throw new R("Connection Manager maxConnections must be greater than 0");this.connections=new Zt,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map(n=>wu(q(n))),this.deny=(t.deny??[]).map(n=>wu(q(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??ww.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Of({points:t.inboundConnectionThreshold??ww.inboundConnectionThreshold,duration:1}),this.connectionPruner=new _p({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>q(n))}),this.dialQueue=new Op(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??Pp,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:xu},connections:this.connections}),this.reconnectQueue=new Np({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let s of n.streams){let o=`${s.direction} ${s.protocol??"unnegotiated"}`;e[o]=(e[o]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let s of n){let o={};for(let i of s.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;o[a]=(o[a]??0)+1}for(let[i,a]of Object.entries(o))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,s]of Object.entries(e)){s=s.sort((i,a)=>i-a);let o=Math.floor(s.length*.9);t[n]=s[o]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await kh(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await Lh(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([Re(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(s=>{n.abort(s)}));this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(this.maxConnections<1)throw new R("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(t=>{this.log.error("could not connect - %e",t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,s=!this.connections.has(n),o=this.connections.get(n)??[];o.push(t),this.connections.set(n,o),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,o=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,o),o.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:n}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new Dr("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:n,multiaddrs:s}=Cp(e);if(this.peerId.equals(n))throw new Qo("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=Tp(n,this.getConnections(n),s);if(c!=null)return this.log("had an existing connection to %p as %a",n,c.remoteAddr),t.onProgress?.(new Le("dial-queue:already-connected")),c}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??mw});if(o.status!=="open")throw new zs("Remote closed connection during opening");let i=this.connections.get(o.remotePeer);i==null&&(i=[],this.connections.set(o.remotePeer,i));let a=!1;for(let c of i)if(c.id===o.id&&(a=!0),t.force!==!0&&c.id!==o.id&&c.remoteAddr.equals(o.remoteAddr))return o.abort(new ss("Duplicate multiaddr connection")),c;return a||i.push(o),o}finally{this.outboundPendingConnections--}}async openStream(e,t,n={}){return(await this.openConnection(e,n)).newStream(t,n)}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async s=>{try{await Promise.all([Re(s,"close",t),s.close(t)])}catch(o){s.abort(o)}}))}acceptIncomingConnection(e){if(this.deny.some(s=>{if(St(e.remoteAddr)){let o=oe(e.remoteAddr);return s.contains(o.host)}return!1}))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(s=>{if(St(e.remoteAddr)){let o=oe(e.remoteAddr);return s.contains(o.host)}return!0}))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(St(e.remoteAddr)){let s=oe(e.remoteAddr);try{this.inboundConnectionRateLimiter.consume(s.host,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,s.host),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>q(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};V();Ue();var Y$=1e4,X$="1.0.0",Q$="ping",J$="ipfs",YC=32,Z$=!0,Up=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??J$}/${Q$}/${X$}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??Y$,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??Z$,this.timeout=new Df({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[nt]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,j(1/0,this.abortController.signal),this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),s=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),o=vb(s);t=Date.now(),await Promise.all([o.write(fs(YC),{signal:n}),o.read({bytes:YC,signal:n})]),e.rtt=Date.now()-t,await s.close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat - %e",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};V();ce();var Kp=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()}),getAttributesFromYieldedValue:(n,s)=>({...s,providers:[...Array.isArray(s.providers)?s.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:P(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:P(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new xa("No content routers available");let n=this,s=new xo;for await(let o of Ks(...n.routers.filter(i=>i.findProviders instanceof Function).map(i=>i.findProviders(e,t))))o!=null&&(o.multiaddrs.length>0&&await this.components.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),!s.has(o.id)&&(s.add(o.id),yield o))}async provide(e,t={}){if(this.routers.length===0)throw new xa("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new xa("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new Dr;await Promise.all(this.routers.filter(s=>s.put instanceof Function).map(async s=>{await s.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new Dr;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};V();var Fp=globalThis.CustomEvent??Event;async function*xw(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,s=new EventTarget,o=[],i=ut(),a=ut(),c=!1,l,u=!1;s.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let d of r){if(o.length===t&&(i=ut(),await i.promise),u)break;let m={done:!1};o.push(m),d().then(g=>{m.done=!0,m.ok=!0,m.value=g,s.dispatchEvent(new Fp("task-complete"))},g=>{m.done=!0,m.err=g,s.dispatchEvent(new Fp("task-complete"))})}c=!0,s.dispatchEvent(new Fp("task-complete"))}catch(d){l=d,s.dispatchEvent(new Fp("task-complete"))}});function h(){return n?o[0]?.done:!!o.find(d=>d.done)}function*p(){for(;o.length>0&&o[0].done;){let d=o[0];if(o.shift(),d.ok)yield d.value;else throw u=!0,i.resolve(),d.err;i.resolve()}}function*f(){for(;h();)for(let d=0;d<o.length;d++)if(o[d].done){let m=o[d];if(o.splice(d,1),d--,m.ok)yield m.value;else throw u=!0,i.resolve(),m.err;i.resolve()}}for(;;){if(h()||(a=ut(),await a.promise),l!=null||(n?yield*p():yield*f(),l!=null))throw l;if(c&&o.length===0)break}}ce();var zp=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,key:P(n,"base36")}),getAttributesFromYieldedValue:(n,s)=>({...s,peers:[...Array.isArray(s.peers)?s.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new yu("No peer routers available");if(e.toString()===this.peerId.toString())throw new gp("Should not try to find self");let n=this,s=Ks(...this.routers.filter(o=>o.findPeer instanceof Function).map(o=>(async function*(){try{yield await o.findPeer(e,t)}catch(i){n.log.error("router failed to find peer - %e",i)}})()));for await(let o of s)if(o!=null)return o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),o;throw new $s}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new yu("No peer routers available");let n=this,s=ln(1024);for await(let o of xw((async function*(){let i=Ks(...n.routers.filter(a=>a.getClosestPeers instanceof Function).map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs - %e",c);return}return a}})()))o!=null&&(o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),!s.has(o.id.toMultihash().bytes)&&(s.add(o.id.toMultihash().bytes),yield o))}};Ue();function eH(r){return r.reason}async function Eu(r,e,t){if(e==null)return r;let n=t?.translateError??eH;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}var $p=class extends me{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,j(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,j(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=$t([this.shutdownController.signal,e?.signal]);j(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=ut(),yield(await Re(this,"walk:peer",{signal:t,rejectionEvents:["walk:error"]})).detail}catch(n){throw n.detail!=null?n.detail:n}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,j(1/0,this.walkController.signal);let e=$t([this.walkController.signal,this.shutdownController.signal]);j(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let s=fs(32),o=Date.now();for await(let i of this.peerRouting.getClosestPeers(s,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-o,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await Eu(this.needNext.promise,e)),o=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",s,this.walkers,n)}catch(s){this.log.error("random walk errored - %e",s),this.safeDispatchEvent("walk:error",{detail:s})}this.log("no walkers left, ended walk")}).catch(s=>{this.log.error("random walk errored - %e",s)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};V();var vw=32,Ew=64,Hp=class{log;topologies;handlers;components;middleware;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.middleware=new Map,this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[n,s]of this.topologies)t[n]=s.size;return t}}),this.handlers=Pt({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new yp(`No handler registered for protocol ${e}`);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&n?.force!==!0)throw new bp(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:vw,maxOutboundStreams:Ew,...n}}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(s=>{this.handlers.delete(s)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new R("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,s=this.topologies.get(e);return s==null&&(s=new Map,this.topologies.set(e,s)),s.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}use(e,t){this.middleware.set(e,t)}unuse(e){this.middleware.delete(e)}getMiddleware(e){return this.middleware.get(e)??[]}async _onDisconnect(e){let t=e.detail,n={signal:AbortSignal.timeout(5e3)};try{let s=await this.components.peerStore.get(t,n);for(let o of s.protocols){let i=this.topologies.get(o);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter?.has(t)!==!1&&(a.filter?.remove(t),await a.onDisconnect?.(t))}))}}catch(s){if(s.name==="NotFoundError")return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,s)}}async _onPeerUpdate(e){let{peer:t,previous:n}=e.detail,s=(n?.protocols??[]).filter(o=>!t.protocols.includes(o));try{for(let o of s){let i=this.topologies.get(o);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),await a.onDisconnect?.(t.id))}))}}catch(o){this.log.error("could not inform topologies of updated peer %p - %e",t.id,o)}}async _onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,s=e.detail.peerId;try{for(let o of t){let i=this.topologies.get(o);i!=null&&await Promise.all([...i.values()].map(async a=>{n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(s)!==!0&&(a.filter?.add(s),await a.onConnect?.(s,n))}))}}catch(o){this.log.error("could not inform topologies of updated peer after identify %p - %e",s,o)}}};V();var qp=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=Pt({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Pt({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??gc.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new R("Transport must have a valid tag");if(this.transports.has(t))throw new R(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let s=n.pop();s!=null&&e.push(s.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new Ip(`No transport available for address ${String(e)}`);return t?.onProgress?.(new Le("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new Dr("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(o=>{t.errors.set(o.toString(),new wp)});let n=[];for(let[o,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",o,c);let l=i.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(o)??[];u==null&&(u=[],this.listeners.set(o,u)),u.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let h=u.findIndex(p=>p===l);u.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),Jb.matches(c)?t.ipv4.attempts++:Zb.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),Jb.matches(c)&&t.ipv4.success++,Zb.matches(c)&&t.ipv6.success++},h=>{throw this.log.error("transport %s could not listen on address %a - %e",o,c,h),t.errors.set(c.toString(),h),h}))}}let s=await Promise.allSettled(n);if(!(s.length>0&&s.every(o=>o.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===gc.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new xp(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:
|
|
20
|
+
${e}[Error list was empty]`,t.trim()}return n8(r,e)}Jt.formatters.e=r=>r==null?"undefined":o8(r);function qK(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function bf(r){return{forComponent(e){return i8(e,r)}}}function i8(r,e){let t=qK(`${r}:trace`);return Jt.enabled(`${r}:trace`)&&Jt.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=Jt(`${r}:trace`,e)),Object.assign(Jt(r,e),{error:Jt(`${r}:error`,e),trace:t,newScope:n=>i8(`${r}:${n}`,e)})}function s8(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}ke();var A1e=new Uint8Array(0);function wf(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function VK(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var v=d[y],S=0,E=w-1;(v!==0||S<g)&&E!==-1;E--,S++)v+=256*x[E]>>>0,x[E]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var A=c.repeat(m);I<w;++I)A+=r.charAt(x[I]);return A}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*w[S]>>>0,w[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(d[m]!==" "){for(var E=b-y;E!==b&&w[E]===0;)E++;for(var I=new Uint8Array(g+(b-E)),A=g;E!==b;)I[A++]=w[E++];return I}}}function f(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:f}}var GK=VK,WK=GK,a8=WK;var rb=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},nb=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return c8(this,e)}},sb=class{decoders;constructor(e){this.decoders=e}or(e){return c8(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function c8(r,e){return new sb({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var ob=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new rb(e,t,n),this.decoder=new nb(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function jK({name:r,prefix:e,encode:t,decode:n}){return new ob(r,e,t,n)}function ib({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=a8(t,r);return jK({prefix:e,name:r,encode:n,decode:o=>wf(s(o))})}var l8=ib({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),L1e=ib({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var YK=d8,u8=128,XK=127,QK=~XK,JK=Math.pow(2,31);function d8(r,e,t){e=e||[],t=t||0;for(var n=t;r>=JK;)e[t++]=r&255|u8,r/=128;for(;r&QK;)e[t++]=r&255|u8,r>>>=7;return e[t]=r|0,d8.bytes=t-n+1,e}var ZK=ab,eF=128,h8=127;function ab(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw ab.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&h8)<<s:(i&h8)*Math.pow(2,s),s+=7}while(i>=eF);return ab.bytes=o-n,t}var tF=Math.pow(2,7),rF=Math.pow(2,14),nF=Math.pow(2,21),sF=Math.pow(2,28),oF=Math.pow(2,35),iF=Math.pow(2,42),aF=Math.pow(2,49),cF=Math.pow(2,56),lF=Math.pow(2,63),uF=function(r){return r<tF?1:r<rF?2:r<nF?3:r<sF?4:r<oF?5:r<iF?6:r<aF?7:r<cF?8:r<lF?9:10},hF={encode:YK,decode:ZK,encodingLength:uF},dF=hF,cb=dF;function lb(r,e=0){return[cb.decode(r,e),cb.decode.bytes]}function f8(r){let e=wf(r),[t,n]=lb(e),[s,o]=lb(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new ub(t,s,i,e)}var ub=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function wo(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return t}function xf(r){let e=f8(l8.decode(`z${r}`));return Br(e)}var Zt=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return wo(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return wo(this.map.values(),e=>e.key)}values(){return wo(this.map.values(),e=>e.value)}get size(){return this.map.size}};var xo=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return wo(this.set.entries(),e=>{let t=xf(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=xf(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return wo(this.set.values(),e=>xf(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};gv();var hb={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},p8={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},m8=new globalThis.TextEncoder;function mF(r,e){let t=hb[e],n=p8[e];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(e,n*t);return n}function gF(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=hb[e],s=p8[e],o=r;for(;o.length>0;){let i=m8.encodeInto(o,t);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(t[a]),s=BigInt.asUintN(e,s*n)}return s}function db(r,{size:e=32,utf8Buffer:t}={}){if(!hb[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return gF(r,e,t);r=m8.encode(r)}return mF(r,e)}te();var Ql={hash:r=>Number(db(r,{size:32})),hashV:(r,e)=>yF(Ql.hash(r,e))};function yF(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),D(e,"base16")}te();rt();Ne();var fb=64,Fr=class{fp;h;seed;constructor(e,t,n,s=2){if(s>fb)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),i=ae(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?W(this.fp,e.fp):!1}};function vo(r,e){return Math.floor(Math.random()*(e-r))+r}var Eo=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Fr))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof Fr))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof Fr))throw new TypeError("Invalid Fingerprint");let t=vo(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof Fr))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var bF=500,Jl=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??Ql,this.seed=e.seed??vo(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=D(e));let t=new Fr(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Eo(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new Eo(this.bucketSize)),this.buckets[n].add(t)||this.buckets[s].add(t))return this.count++,!0;let o=[n,s],i=o[vo(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Eo(this.bucketSize));for(let a=0;a<bF;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Eo(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=D(e));let t=new Fr(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.has(t)??!1;if(s)return s;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=D(e));let t=new Fr(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.remove(t)??!1;if(s)return this.count--,s;let o=(n^t.hash())%this.filterSize,i=this.buckets[o]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},wF={1:.5,2:.84,4:.95,8:.98};function xF(r=.001){return r>.002?2:r>1e-5?4:8}function g8(r,e=.001){let t=xF(e),n=wF[t],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),fb);return{filterSize:s,bucketSize:t,fingerprintSize:o}}te();var vf=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??Ql,this.seed=e.seed??vo(0,Math.pow(2,10)),this.filterSeries=[new Jl({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=D(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Jl({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=D(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=D(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function ln(r,e=.001,t){return new vf({...g8(r,e),...t??{}})}V();function oe(r){let e=r.getComponents(),t={},n=0;if(e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n].name==="ip4"||e[n].name==="ip6"||e[n].name==="dns"||e[n].name==="dns4"||e[n].name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n].name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null)throw new R(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t}function y8(r){try{let e=oe(r);switch(e.type){case"ip6":return sA("2000::/3",e.host);default:return!1}}catch{return!1}}function b8(r){try{let e=oe(r);switch(e.type){case"ip4":return e.host.startsWith("169.254.");case"ip6":return e.host.toLowerCase().startsWith("fe80");default:return!1}}catch{return!1}}function w8(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function Zl(r){try{let e=oe(r);switch(e.type){case"ip4":case"ip6":return w8(e.host);default:return!1}}catch{return!1}}function St(r){try{return oe(r),!0}catch{return!1}}var v8=ie(x8(),1),vF=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],EF=vF.map(r=>new v8.Netmask(r));function pb(r){for(let e of EF)if(e.contains(r))return!0;return!1}function SF(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function IF(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),s=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return pb(s)}function AF(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function CF(r){let e=r.split(":"),t=e[e.length-1];return pb(t)}function TF(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function ua(r){if((0,fe.isIPv4)(r))return pb(r);if(SF(r))return IF(r);if(AF(r))return CF(r);if((0,fe.isIPv6)(r))return TF(r)}function Fn(r){try{let e=oe(r);switch(e.type){case"ip4":case"ip6":return ua(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}V();Ue();var mb=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},E8=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function gb(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((h,p)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){p(E8(i));return}if(i&&(c=()=>{p(E8(i))},i.addEventListener("abort",c,{once:!0})),r.then(h,p),t===Number.POSITIVE_INFINITY)return;let f=new mb;a=o.setTimeout.call(void 0,()=>{if(n){try{h(n())}catch(d){p(d)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?h():s instanceof Error?p(s):(f.message=s??`Promise timed out after ${t} milliseconds`,p(f))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},u}var _F=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function PF(r,e,t){let n,s=new Promise((o,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=_F(r),h=async(...f)=>{let d=t.multiArgs?f:f[0];if(t.filter)try{if(!await t.filter(d))return}catch(m){n(),i(m);return}c.push(d),t.count===c.length&&(n(),o(c))},p=(...f)=>{n(),i(t.rejectionMultiArgs?f:f[0])};n=()=>{for(let f of a)u(f,h);for(let f of t.rejectionEvents)a.includes(f)||u(f,p)};for(let f of a)l(f,h);for(let f of t.rejectionEvents)a.includes(f)||l(f,p);t.signal&&t.signal.addEventListener("abort",()=>{p(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(s.cancel=n,typeof t.timeout=="number"){let o=gb(s,{milliseconds:t.timeout});return o.cancel=()=>{n(),o.clear()},o}return s}function Re(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=PF(r,e,t),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}function So(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Ef=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}},Sf=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},Io=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},If=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},Af=class extends Error{static name="StreamClosedError";name="StreamClosedError"};V();Ue();function DF(r){return r.reason}async function Cs(r,e,t){if(e==null)return r;let n=t?.translateError??DF;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}V();var Cf=class{deferred;signal;constructor(e){this.signal=e,this.deferred=ut(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new rr)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function kF(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Tf=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=kF(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,j(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new rr),this.cleanup())}async join(e={}){let t=new Cf(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Cs(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var ha=class extends me{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=So(this.emitEmpty.bind(this),1),this.emitIdle=So(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Sf;let n=new Tf(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new rr)}),this.clear()}async onEmpty(e){this.size!==0&&await Re(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Re(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Re(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Ot({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new rr("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};V();Be();var LF=Math.pow(2,20)*4,Ts=class extends me{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??LF,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new U,this.writeBuffer=new U,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let n=s=>{this.onDrainPromise?.reject(s.error??new Af)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),Cs(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Ot(),t=o=>{e.push(o.data)};this.addEventListener("message",t);let n=o=>{e.end(o.error)};this.addEventListener("close",n);let s=()=>{e.end()};this.addEventListener("remoteCloseWrite",s);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",s)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new ns(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(t){this.log("failed to send reset to remote - %e",t)}this.dispatchEvent(new Th(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new ns("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new ns("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new ns(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new ns(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new wh;this.dispatchEvent(new _h(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new as))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,t=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let s=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(s===0){e=!1;break}let o=this.writeBuffer.sublist(0,s),i=new U(o);this.writeBuffer.consume(o.byteLength);let a=this.sendData(o);if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new Ch(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new dc(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new dc(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var da=class extends Ts{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",t=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),t.error!=null?t.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):t.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Re(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Re(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};V();function S8(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var _f=class extends me{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,t){super(),this.maConn=e,this.protocol=t.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(t.name),this.streamOptions=t.streamOptions,this.maxEarlyStreams=t.maxEarlyStreams??10,this.metrics=t.metrics;let n=i=>{try{this.onData(i.data)}catch(a){this.abort(a),this.maConn.abort(a)}};this.maConn.addEventListener("message",n);let s=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(i=>{i.onMuxerDrain()})};this.maConn.addEventListener("drain",s);let o=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",o)}send(e){let t=this.maConn.send(e);return t===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(n=>{n.onMuxerNeedsDrain()})),t}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await Cs(Promise.all([...this.streams].map(async t=>{await t.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(t=>{t.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(t=>{t.onTransportClosed(e)})}catch(t){this.abort(t)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new Tn;let t=this.onCreateStream({...this.streamOptions,...e});return S8(t)&&(t=await t),this.streams.push(t),this.cleanUpStream(t),t}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new If(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let t=n=>{let s=this.streams.findIndex(o=>o===e);s!==-1&&this.streams.splice(s,1),n.error!=null?n.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",t),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(t=>{this.safeDispatchEvent("stream",{detail:t})}),this.earlyStreams=[]})}};var Pf=class extends Ts{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Re(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await Re(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.log("closed readable end gracefully"))}};function $t(r){let e=new globalThis.AbortController;function t(){e.abort();for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let s=e.signal;return s.clear=n,s}Ue();var fa=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),s=e-this.movingAverage,o=n*s;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+s*o),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*s}else this.movingAverage=e;this.previousTime=t}};var MF=1.2,OF=2,RF=5e3,NF=6e4,BF=5e3,Df=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??BF;this.success=new fa(t),this.failure=new fa(t),this.next=new fa(t),this.failureMultiplier=e.failureMultiplier??OF,this.timeoutMultiplier=e.timeoutMultiplier??MF,this.minTimeout=e.minTimeout??RF,this.maxTimeout=e.maxTimeout??NF,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),s=$t([e.signal,n]);return j(1/0,s,n),s.start=Date.now(),s.timeout=t,s}cleanUp(e){let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var A8=ie(ee("node:os"),1);function I8(r){return!!(r.startsWith("169.254.")||r.toLowerCase().startsWith("fe80"))}function yb(r,e,t){let n=[r.type,t??r.host];if(r.protocol!=null){let s=e??r.port;s!=null&&n.push(r.protocol,s)}return r.type==="ip6"&&r.zone!=null&&n.unshift("ip6zone",r.zone),r.cidr!=null&&n.push("ipcidr",r.cidr),q(`/${n.join("/")}`)}var UF={4:"IPv4",6:"IPv6"};function KF(r){return["0.0.0.0","::"].includes(r)}function FF(r){let e=[],t=A8.default.networkInterfaces();for(let[,n]of Object.entries(t))if(n!=null)for(let s of n)I8(s.address)||s.family===UF[r]&&e.push(s.address);return e}function C8(r,e){if(r==null)return[];let t=oe(r);return(t.type==="ip4"||t.type==="ip6")&&KF(t.host)?FF(t.type==="ip4"?4:6).map(n=>yb(t,e,n)):[yb(t,e)]}V();function T8(r,e){if(typeof r!="string")throw new R(`invalid ip provided: ${r}`);if(typeof e=="string"&&(e=parseInt(e)),isNaN(e))throw new R(`invalid port provided: ${e}`);if((0,fe.isIPv4)(r))return q(`/ip4/${r}/tcp/${e}`);if((0,fe.isIPv6)(r))return q(`/ip6/${r}/tcp/${e}`);throw new R(`invalid ip:port for creating a multiaddr: ${r}:${e}`)}V();gr();Be();V();gr();Be();var zF=4194304,kf=class extends Error{static name="UnwrappedError";name="UnwrappedError"},tu=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},wb=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},xb=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function $F(r){return typeof r?.closeRead=="function"}function HF(r){return typeof r?.close=="function"}function bb(r){return $F(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:HF(r)?r.status!=="open":!1}function qF(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function vb(r,e){let t=e?.maxBufferSize??zF,n=new U,s,o=!1;if(!qF(r))throw new R("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>t){let h=n.byteLength;n.consume(n.byteLength),s?.reject(new Error(`Read buffer overflow - ${h} > ${t}`))}s?.resolve()};r.addEventListener("message",i);let a=u=>{u.error!=null?s?.reject(u.error):s?.resolve()};r.addEventListener("close",a);let c=()=>{s?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(u){if(o===!0)throw new kf("Stream was unwrapped");if(bb(r)){if(u?.bytes==null)return null;if(n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new Io(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let h=u?.bytes??1;for(s=Promise.withResolvers();;){if(n.byteLength>=h){s.resolve();break}if(await Cs(s.promise,u?.signal),bb(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}s=Promise.withResolvers()}let p=u?.bytes??n.byteLength;if(n.byteLength<p){if(bb(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,p),new Io(`Unexpected EOF - stream closed while reading ${n.byteLength}/${p} bytes`);return l.read(u)}let f=n.sublist(0,p);return n.consume(p),f},async write(u,h){if(o===!0)throw new kf("Stream was unwrapped");r.send(u)||await Re(r,"drain",{signal:h?.signal,rejectionEvents:["close"]})},unwrap(){return o||(o=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return l}function _s(r,e={}){let t=vb(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Ae(e.maxDataLength));let n=e?.lengthDecoder??jt,s=e?.lengthEncoder??Vr;return{async read(i){let a=-1,c=new U;for(;;){let u=await t.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(h){if(h instanceof RangeError)continue;throw h}if(a<0)throw new tu("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new xb(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new wb(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...i,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new Io(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new Io(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new U(s(i.byteLength),i),a)},async writeV(i,a){let c=new U(...i.flatMap(l=>[s(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function zr(r,e){let t=_s(r,e),n={read:async(s,o)=>{let i=await t.read(o);return s.decode(i)},write:async(s,o,i)=>{await t.write(o.encode(s),i)},writeV:async(s,o,i)=>{await t.writeV(s.map(a=>o.encode(a)),i)},pb:s=>({read:async o=>n.read(s,o),write:async(o,i)=>n.write(o,s,i),writeV:async(o,i)=>n.writeV(o,s,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}function VF(r){return r?.addEventListener!=null}function GF(r){let e=Ot(),t,n=i=>{e.push(i.data)},s=()=>{e.end(),r.removeEventListener("message",n),r.removeEventListener("close",o),r.removeEventListener("remoteCloseWrite",s)},o=i=>{e.end(i.error),i.error!=null&&t?.reject(i.error),r.removeEventListener("message",n),r.removeEventListener("close",o),r.removeEventListener("remoteCloseWrite",s)};return r.addEventListener("message",n),r.addEventListener("close",o,{once:!0}),r.addEventListener("remoteCloseWrite",s,{once:!0}),{source:e,async sink(i){async function*a(){yield*i}let c=a();for(;;){t=Promise.withResolvers();let{done:l,value:u}=await Promise.race([c.next(),t.promise]);if(r.writeStatus==="closing"||r.writeStatus==="closed"||(u!=null&&(r.send(u)||await Promise.race([Re(r,"drain",{rejectionEvents:["close"]})])),l===!0))break}await r.close()}}}function _8(...r){let e=r.map(t=>VF(t)?GF(t):t);return ht(...e)}var WF=1024*1024*4,jF=1024*1024*4,Lf=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new U,this.maxBufferSize=e.maxBufferSize??WF,this.maxDataLength=e.maxDataLength??jF,this.lengthDecoder=e.lengthDecoder??jt,this.encodingLength=e.encodingLength??Ae}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new R(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let t;try{t=this.lengthDecoder(this.buffer)}catch(o){if(o instanceof RangeError)break;throw o}if(t<0||t>this.maxDataLength)throw new tu("Invalid message length");let n=this.encodingLength(t),s=n+t;if(this.buffer.byteLength>=s){let o=this.buffer.sublist(n,s);this.buffer.consume(s),o.byteLength>0&&(yield o)}else break}}};var Ps=class extends ha{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Mf=class extends ha{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var Of=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Eb}consume(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(s,i.consumedPoints,this.blockDuration)),new Ef("Rate limit exceeded",i);return i}penalty(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,-t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,s=this.points+1;return this.memoryStorage.set(this.getKey(e),s,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:s,isFirstInDuration:!1}}set(e,t,n=0){let s=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},Eb=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let s=this.storage.get(e);if(s!=null){let o=s.expiresAt!=null?s.expiresAt.getTime()-new Date().getTime():-1;return s.expiresAt==null||o>0?(s.value+=t,{remainingPoints:0,msBeforeNext:o,consumedPoints:s.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let s=n*1e3,o=this.storage.get(e);o!=null&&clearTimeout(o.timeoutId);let i={value:t,expiresAt:s>0?new Date(Date.now()+s):void 0};return this.storage.set(e,i),s>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},s),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};Ue();function P8(r,e,t){let n,s,o=!1;function i(){let l={signal:s.signal};if(t?.timeout!=null){let u=$t([s.signal,AbortSignal.timeout(t.timeout)]);j(1/0,u),l.signal=u}o=!0,Promise.resolve().then(async()=>{await r(l)}).catch(()=>{}).finally(()=>{o=!1,!s.signal.aborted&&(n=setTimeout(i,e))})}let a=So(i,t?.debounce??100),c=!1;return{setInterval:l=>{e!==l&&(e=l,n!=null&&(clearTimeout(n),n=setTimeout(i,e)))},setTimeout:l=>{t??={},t.timeout=l},run:()=>{o||(clearTimeout(n),a())},start:()=>{c||(c=!0,s=new AbortController,j(1/0,s.signal),t?.runImmediately===!0?queueMicrotask(()=>{i()}):n=setTimeout(i,e))},stop:()=>{clearTimeout(n),s?.abort(),c=!1}}}var Sb=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Pt(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Sb({name:e,metrics:t}):n=new Map,n}var Rf=class{filter;constructor(e,t){this.filter=ln(e,t)}has(e){return this.filter.has(e.toMultihash().bytes)}add(e){this.filter.add(e.toMultihash().bytes)}remove(e){this.filter.remove?.(e.toMultihash().bytes)}};function Ib(r,e=.001){return new Rf(r,e)}var Ab=class extends Zt{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function ru(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Ab({name:e,metrics:t}):n=new Zt,n}ke();V();ke();Bt();gr();Be();Ne();te();wr();rt();var nu;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={publicKey:ae(0),payloadType:ae(0),payload:ae(0),signature:ae(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.publicKey=t.bytes();break}case 2:{o.payloadType=t.bytes();break}case 3:{o.payload=t.bytes();break}case 5:{o.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(nu||(nu={}));var Nf=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var lr=class r{static createFromProtobuf=e=>{let t=nu.decode(e),n=Ft(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let s=e.domain,o=e.codec,i=e.marshal(),a=D8(s,o,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:o,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let s=r.createFromProtobuf(e);if(!await s.validate(t,n))throw new Nf("Envelope signature is not valid for the given domain");return s};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:s,signature:o}=e;this.publicKey=t,this.payloadType=n,this.payload=s,this.signature=o}marshal(){return this.marshaled==null&&(this.marshaled=nu.encode({publicKey:dt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:W(this.marshal(),e.marshal())}async validate(e,t){let n=D8(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},D8=(r,e,t)=>{let n=D(r),s=Vr(n.byteLength),o=Vr(e.length),i=Vr(t.length);return new U(s,n,o,e,i,t)};ke();var O2e=new Uint8Array(0);function k8(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var YF=O8,L8=128,XF=127,QF=~XF,JF=Math.pow(2,31);function O8(r,e,t){e=e||[],t=t||0;for(var n=t;r>=JF;)e[t++]=r&255|L8,r/=128;for(;r&QF;)e[t++]=r&255|L8,r>>>=7;return e[t]=r|0,O8.bytes=t-n+1,e}var ZF=Cb,ez=128,M8=127;function Cb(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Cb.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&M8)<<s:(i&M8)*Math.pow(2,s),s+=7}while(i>=ez);return Cb.bytes=o-n,t}var tz=Math.pow(2,7),rz=Math.pow(2,14),nz=Math.pow(2,21),sz=Math.pow(2,28),oz=Math.pow(2,35),iz=Math.pow(2,42),az=Math.pow(2,49),cz=Math.pow(2,56),lz=Math.pow(2,63),uz=function(r){return r<tz?1:r<rz?2:r<nz?3:r<sz?4:r<oz?5:r<iz?6:r<az?7:r<cz?8:r<lz?9:10},hz={encode:YF,decode:ZF,encodingLength:uz},dz=hz,Tb=dz;function _b(r,e=0){return[Tb.decode(r,e),Tb.decode.bytes]}function R8(r){let e=k8(r),[t,n]=_b(e),[s,o]=_b(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Pb(t,s,i,e)}var Pb=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var N8="libp2p-peer-record",B8=Uint8Array.from([3,1]);wr();rt();var su;(function(r){let e;(function(n){let s;n.codec=()=>(s==null&&(s=Z((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.multiaddr!=null&&o.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(o.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={multiaddr:ae(0)},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.multiaddr=o.bytes();break}default:{o.skipType(u&7);break}}}return c})),s),n.encode=o=>J(o,n.codec()),n.decode=(o,i)=>Q(o,n.codec(),i)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Z((n,s,o={})=>{if(o.lengthDelimited!==!1&&s.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(s.uint32(10),s.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(s.uint32(16),s.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)s.uint32(26),r.AddressInfo.codec().encode(i,s);o.lengthDelimited!==!1&&s.ldelim()},(n,s,o={})=>{let i={peerId:ae(0),seq:0n,addresses:[]},a=s==null?n.len:n.pos+s;for(;n.pos<a;){let c=n.uint32();switch(c>>>3){case 1:{i.peerId=n.bytes();break}case 2:{i.seq=n.uint64();break}case 3:{if(o.limits?.addresses!=null&&i.addresses.length===o.limits.addresses)throw new _e('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:o.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),t),r.encode=n=>J(n,r.codec()),r.decode=(n,s)=>Q(n,r.codec(),s)})(su||(su={}));function U8(r,e){let t=(n,s)=>n.toString().localeCompare(s.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,s)=>e[s].equals(n)))}var ur=class r{static createFromProtobuf=e=>{let t=su.decode(e),n=Br(R8(t.peerId)),s=(t.addresses??[]).map(i=>q(i.multiaddr)),o=t.seq;return new r({peerId:n,multiaddrs:s,seqNumber:o})};static DOMAIN=N8;static CODEC=B8;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:s}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=s??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=su.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!U8(this.multiaddrs,e.multiaddrs))}};function mz(r){return r[Symbol.asyncIterator]!=null}function gz(r){if(mz(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var ou=gz;V();ke();var hr=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};Ue();async function Bf(r,e,t,n){let s=new hr(n?.errorMessage);n?.errorCode!=null&&(s.code=n.errorCode);let o=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(s):new Promise((i,a)=>{function c(){kb(t,"abort",h),kb(r,e,l),kb(r,o,u)}let l=p=>{try{if(n?.filter?.(p)===!1)return}catch(f){c(),a(f);return}c(),i(p)},u=p=>{if(c(),p instanceof Error){a(p);return}a(p.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},h=()=>{c(),a(s)};Db(t,"abort",h),Db(r,e,l),Db(r,o,u)})}function Db(r,e,t){r!=null&&(K8(r)?r.addEventListener(e,t):r.addListener(e,t))}function kb(r,e,t){r!=null&&(K8(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function K8(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var Uf=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};Ue();var Kf=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new hr)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function yz(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ff=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=yz(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,j(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new hr),this.cleanup())}async join(e={}){let t=new Kf(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await uh(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function Lb(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var iu=class extends me{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=Lb(this.emitEmpty.bind(this),1),this.emitIdle=Lb(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Uf;let n=new Ff(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(s=>(this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new hr)}),this.clear()}async onEmpty(e){this.size!==0&&await Bf(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Bf(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Bf(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Ot({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail.result)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new hr("Queue aborted"))};this.addEventListener("success",s),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var cu=ie(ee("node:cluster"),1),qf=ie(ee("node:worker_threads"),1);Ue();var Ao="lock:worker:request-read",Co="lock:worker:abort-read-request",To="lock:worker:release-read",_o="lock:master:grant-read",Po="lock:master:error-read",Do="lock:worker:request-write",ko="lock:worker:abort-write-request",Lo="lock:worker:release-write",Mo="lock:master:grant-write",Oo="lock:master:error-write",Ds="lock:worker:finalize",zf="mortice",F8={singleProcess:!1};var Mb=(r,e,t,n,s,o,i,a,c)=>l=>{if(l.data==null)return;let u={type:l.data.type,name:l.data.name,identifier:l.data.identifier};u.type===s&&r.safeDispatchEvent(t,{detail:{name:u.name,identifier:u.identifier,handler:async()=>{e.postMessage({type:c,name:u.name,identifier:u.identifier}),await new Promise(h=>{let p=f=>{if(f?.data==null)return;let d={type:f.data.type,name:f.data.name,identifier:f.data.identifier};d.type===a&&d.identifier===u.identifier&&(e.removeEventListener("message",p),h())};e.addEventListener("message",p)})},onError:h=>{e.postMessage({type:i,name:u.name,identifier:u.identifier,error:{message:h.message,name:h.name,stack:h.stack}})}}}),u.type===o&&r.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier}}),u.type===Ds&&r.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};var Ob=(r,e,t,n,s,o,i,a)=>(c,l)=>{l!=null&&(l.type===n&&r.safeDispatchEvent(e,{detail:{name:l.name,identifier:l.identifier,handler:async()=>{c.send({type:a,name:l.name,identifier:l.identifier}),await new Promise(u=>{let h=p=>{p.type===i&&p.identifier===l.identifier&&(c.removeListener("message",h),u())};c.on("message",h)})},onError:u=>{c.send({type:o,name:l.name,identifier:l.identifier,error:{message:u.message,name:u.name,stack:u.stack}})}}}),l.type===s&&r.safeDispatchEvent(t,{detail:{name:l.name,identifier:l.identifier}}),l.type===Ds&&r.safeDispatchEvent("finalizeRequest",{detail:{name:l.name}}))};var au=(r=10)=>Math.random().toString().substring(2,r+2);var $f=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(zf)}readLock(e){return this.sendRequest(Ao,Co,_o,Po,To,e)}writeLock(e){return this.sendRequest(Do,ko,Mo,Oo,Lo,e)}finalize(){this.channel.postMessage({type:Ds,name:this.name}),this.channel.close()}async sendRequest(e,t,n,s,o,i){i?.signal?.throwIfAborted();let a=au();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",u,{once:!0});let h=p=>{if(p.data?.identifier===a&&(p.data?.type===n&&(this.channel.removeEventListener("message",h),i?.signal?.removeEventListener("abort",u),c(()=>{this.channel.postMessage({type:o,identifier:a,name:this.name})})),p.data.type===s)){this.channel.removeEventListener("message",h),i?.signal?.removeEventListener("abort",u);let f=new Error;p.data.error!=null&&(f.message=p.data.error.message,f.name=p.data.error.name,f.stack=p.data.error.stack),l(f)}};this.channel.addEventListener("message",h)})}};var Hf=class{name;constructor(e){this.name=e}readLock(e){return this.sendRequest(Ao,Co,_o,Po,To,e)}writeLock(e){return this.sendRequest(Do,ko,Mo,Oo,Lo,e)}finalize(){if(process.send==null)throw new Error("No send method on process - are we a cluster worker?");process.send({type:Ds,identifier:au(),name:this.name})}async sendRequest(e,t,n,s,o,i){i?.signal?.throwIfAborted();let a=au();if(process.send==null)throw new Error("No send method on process - are we a cluster worker?");return process.send({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{process.send?.({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",u,{once:!0});let h=p=>{if(p.identifier===a&&(p.type===n&&(process.removeListener("message",h),i?.signal?.removeEventListener("abort",u),c(()=>{process.send?.({type:o,identifier:a,name:this.name})})),p.type===s)){process.removeListener("message",h),i?.signal?.removeEventListener("abort",u);let f=new Error;p.error!=null&&(f.message=p.error.message,f.name=p.error.name,f.stack=p.error.stack),l(f)}};process.on("message",h)})}};function bz(){return qf.default.isMainThread===!1||qf.default.isInternalThread===!0?!1:cu.default.isPrimary}var z8=r=>{if(r=Object.assign({},F8,r),bz()||r.singleProcess){let e=new me;cu.default.on("message",Ob(e,"requestReadLock","abortReadLockRequest",Ao,Co,Po,To,_o)),cu.default.on("message",Ob(e,"requestWriteLock","abortWriteLockRequest",Do,ko,Oo,Lo,Mo));let t=new BroadcastChannel(zf);return t.addEventListener("message",Mb(e,t,"requestReadLock","abortReadLockRequest",Ao,Co,Po,To,_o)),t.addEventListener("message",Mb(e,t,"requestWriteLock","abortWriteLockRequest",Do,ko,Oo,Lo,Mo)),t.unref?.(),e}if(cu.default.isWorker)return new Hf(r.name);if(qf.default.isMainThread===!1)return new $f(r.name);throw new Error("Not a cluster worker or worker thread")};var Ro=new Map,lu;function $8(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function wz(r){if(lu==null&&(lu=z8(r),!$8(lu))){let e=lu;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,s=t.detail.identifier,o=Ro.get(n);if(o==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==s||i.abort()};e.addEventListener("abortReadLockRequest",a),o.readLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,s=t.detail.identifier,o=Ro.get(n);if(o==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==s||i.abort()};e.addEventListener("abortWriteLockRequest",a),o.writeLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,s=Ro.get(n);s?.finalize()})}return lu}async function Rb(r,e){let t,n,s=new Promise((i,a)=>{t=i,n=a}),o=()=>{n(new hr)};return e?.signal?.addEventListener("abort",o,{once:!0}),r.add(async()=>{await new Promise(i=>{t(()=>{e?.signal?.removeEventListener("abort",o),i()})})},{signal:e?.signal}).catch(i=>{n(i)}),s}var H8=(r,e)=>{let t=Ro.get(r);if(t!=null)return t;let n=wz(e);if($8(n))return t=n,Ro.set(r,t),t;let s=new iu({concurrency:1}),o;return t={async readLock(i){if(o!=null)return Rb(o,i);o=new iu({concurrency:e.concurrency,autoStart:!1});let a=o,c=Rb(o,i);return s.add(async()=>{a.start(),await a.onIdle().then(()=>{o===a&&(o=null)})}),c},async writeLock(i){return o=null,Rb(s,i)},finalize:()=>{Ro.delete(r)},queue:s},Ro.set(r,t),e.autoFinalize===!0&&s.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var xz={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Nb(r){let e=Object.assign({},xz,r);return H8(e.name,e)}var Xge=new Uint8Array(0);function q8(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function pa(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function vz(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var v=d[y],S=0,E=w-1;(v!==0||S<g)&&E!==-1;E--,S++)v+=256*x[E]>>>0,x[E]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var A=c.repeat(m);I<w;++I)A+=r.charAt(x[I]);return A}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*w[S]>>>0,w[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(d[m]!==" "){for(var E=b-y;E!==b&&w[E]===0;)E++;for(var I=new Uint8Array(g+(b-E)),A=g;E!==b;)I[A++]=w[E++];return I}}}function f(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:f}}var Ez=vz,Sz=Ez,V8=Sz;var Bb=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Ub=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return G8(this,e)}},Kb=class{decoders;constructor(e){this.decoders=e}or(e){return G8(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function G8(r,e){return new Kb({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Fb=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new Bb(e,t,n),this.decoder=new Ub(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function W8({name:r,prefix:e,encode:t,decode:n}){return new Fb(r,e,t,n)}function ma({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=V8(t,r);return W8({prefix:e,name:r,encode:n,decode:o=>pa(s(o))})}function Iz(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function Az(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function Cz(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function un({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=Cz(n);return W8({prefix:e,name:r,encode(o){return Az(o,n,t)},decode(o){return Iz(o,s,t,r)}})}var No=un({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),nye=un({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),sye=un({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),oye=un({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),iye=un({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),aye=un({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),cye=un({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),lye=un({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),uye=un({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Vf=ma({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),fye=ma({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var zn=ma({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),gye=ma({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Tz=X8,j8=128,_z=127,Pz=~_z,Dz=Math.pow(2,31);function X8(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Dz;)e[t++]=r&255|j8,r/=128;for(;r&Pz;)e[t++]=r&255|j8,r>>>=7;return e[t]=r|0,X8.bytes=t-n+1,e}var kz=zb,Lz=128,Y8=127;function zb(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw zb.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&Y8)<<s:(i&Y8)*Math.pow(2,s),s+=7}while(i>=Lz);return zb.bytes=o-n,t}var Mz=Math.pow(2,7),Oz=Math.pow(2,14),Rz=Math.pow(2,21),Nz=Math.pow(2,28),Bz=Math.pow(2,35),Uz=Math.pow(2,42),Kz=Math.pow(2,49),Fz=Math.pow(2,56),zz=Math.pow(2,63),$z=function(r){return r<Mz?1:r<Oz?2:r<Rz?3:r<Nz?4:r<Bz?5:r<Uz?6:r<Kz?7:r<Fz?8:r<zz?9:10},Hz={encode:Tz,decode:kz,encodingLength:$z},qz=Hz,uu=qz;function hu(r,e=0){return[uu.decode(r,e),uu.decode.bytes]}function ga(r,e,t=0){return uu.encode(r,e,t),e}function ya(r){return uu.encodingLength(r)}function J8(r,e){let t=e.byteLength,n=ya(r),s=n+ya(t),o=new Uint8Array(s+t);return ga(r,o,0),ga(t,o,n),o.set(e,s),new ba(r,t,e,o)}function Z8(r){let e=pa(r),[t,n]=hu(e),[s,o]=hu(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new ba(t,s,i,e)}function eC(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&q8(r.bytes,t.bytes)}}var ba=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function tC(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Wz(t,$b(r),e??zn.encoder);default:return jz(t,$b(r),e??No.encoder)}}var rC=new WeakMap;function $b(r){let e=rC.get(r);if(e==null){let t=new Map;return rC.set(r,t),t}return e}var Gf=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==du)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Yz)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=J8(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&eC(e.multihash,n.multihash)}toString(e){return tC(this,e)}toJSON(){return{"/":tC(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??nC(n,s,o.bytes))}else if(t[Xz]===!0){let{version:n,multihash:s,code:o}=t,i=Z8(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==du)throw new Error(`Version 0 CID must use dag-pb (code: ${du}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=nC(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,du,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=pa(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new ba(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,p]=hu(e.subarray(t));return t+=p,h},s=n(),o=du;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=Gz(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return $b(o).set(n,e),o}};function Gz(r,e){switch(r[0]){case"Q":{let t=e??zn;return[zn.prefix,t.decode(`${zn.prefix}${r}`)]}case zn.prefix:{let t=e??zn;return[zn.prefix,t.decode(r)]}case No.prefix:{let t=e??No;return[No.prefix,t.decode(r)]}case Vf.prefix:{let t=e??Vf;return[Vf.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Wz(r,e,t){let{prefix:n}=t;if(n!==zn.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function jz(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var du=112,Yz=18;function nC(r,e,t){let n=ya(r),s=n+ya(e),o=new Uint8Array(s+t.byteLength);return ga(r,o,0),ga(e,o,n),o.set(t,s),o}var Xz=Symbol.for("@ipld/js-cid/CID");wr();rt();var $n;(function(r){let e;(function(s){let o;s.codec=()=>(o==null&&(o=Z((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:"",value:ae(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let h=i.uint32();switch(h>>>3){case 1:{l.key=i.string();break}case 2:{l.value=i.bytes();break}default:{i.skipType(h&7);break}}}return l})),o),s.encode=i=>J(i,s.codec()),s.decode=(i,a)=>Q(i,s.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(s){let o;s.codec=()=>(o==null&&(o=Z((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),jf.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:""},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let h=i.uint32();switch(h>>>3){case 1:{l.key=i.string();break}case 2:{l.value=jf.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(h&7);break}}}return l})),o),s.encode=i=>J(i,s.codec()),s.decode=(i,a)=>Q(i,s.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Z((s,o,i={})=>{if(i.lengthDelimited!==!1&&o.fork(),s.addresses!=null)for(let a of s.addresses)o.uint32(10),Wf.codec().encode(a,o);if(s.protocols!=null)for(let a of s.protocols)o.uint32(18),o.string(a);if(s.publicKey!=null&&(o.uint32(34),o.bytes(s.publicKey)),s.peerRecordEnvelope!=null&&(o.uint32(42),o.bytes(s.peerRecordEnvelope)),s.metadata!=null&&s.metadata.size!==0)for(let[a,c]of s.metadata.entries())o.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},o);if(s.tags!=null&&s.tags.size!==0)for(let[a,c]of s.tags.entries())o.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},o);s.updated!=null&&(o.uint32(64),o.uint64Number(s.updated)),i.lengthDelimited!==!1&&o.ldelim()},(s,o,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=o==null?s.len:s.pos+o;for(;s.pos<c;){let l=s.uint32();switch(l>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new _e('Decode error - map field "addresses" had too many elements');a.addresses.push(Wf.codec().decode(s,s.uint32(),{limits:i.limits?.addresses$}));break}case 2:{if(i.limits?.protocols!=null&&a.protocols.length===i.limits.protocols)throw new _e('Decode error - map field "protocols" had too many elements');a.protocols.push(s.string());break}case 4:{a.publicKey=s.bytes();break}case 5:{a.peerRecordEnvelope=s.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new Bc('Decode error - map field "metadata" had too many elements');let u=r.Peer$metadataEntry.codec().decode(s,s.uint32());a.metadata.set(u.key,u.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new Bc('Decode error - map field "tags" had too many elements');let u=r.Peer$tagsEntry.codec().decode(s,s.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(u.key,u.value);break}case 8:{a.updated=s.uint64Number();break}default:{s.skipType(l&7);break}}}return a})),n),r.encode=s=>J(s,r.codec()),r.decode=(s,o)=>Q(s,r.codec(),o)})($n||($n={}));var Wf;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),t.observed!=null&&(n.uint32(24),n.uint64Number(t.observed)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={multiaddr:ae(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.multiaddr=t.bytes();break}case 2:{o.isCertified=t.bool();break}case 3:{o.observed=t.uint64Number();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(Wf||(Wf={}));var jf;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={value:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.value=t.uint32();break}case 2:{o.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(jf||(jf={}));Bt();ke();function Qz(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=Ft(e.publicKey,t);return On(n)}function sC(r,e,t){let n=$n.decode(e);return wa(r,n,t)}function wa(r,e,t){let n=new Map,s=BigInt(Date.now());for(let[o,i]of e.tags.entries())i.expiry!=null&&i.expiry<s||n.set(o,i);return{...e,id:Qz(r,e),addresses:e.addresses.filter(({observed:o})=>o!=null&&o>Date.now()-t).map(({multiaddr:o,isCertified:i})=>({multiaddr:q(o),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}Ne();function oC(r,e){return Jz(r.addresses,e.addresses)&&Zz(r.protocols,e.protocols)&&e$(r.publicKey,e.publicKey)&&t$(r.peerRecordEnvelope,e.peerRecordEnvelope)&&r$(r.metadata,e.metadata)&&n$(r.tags,e.tags)}function Jz(r,e){return aC(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!W(t.multiaddr,n.multiaddr)))}function Zz(r,e){return aC(r,e,(t,n)=>t===n)}function e$(r,e){return iC(r,e)}function t$(r,e){return iC(r,e)}function r$(r,e){return cC(r,e,(t,n)=>W(t,n))}function n$(r,e){return cC(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function iC(r,e){return r==null&&e==null?!0:r!=null&&e!=null?W(r,e):!1}function aC(r,e,t){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],e[n]))return!1;return!0}function cC(r,e,t){if(r.size!==e.size)return!1;for(let[n,s]of r.entries()){let o=e.get(n);if(o==null||!t(s,o))return!1}return!0}V();te();ce();var Hn="/",lC=new TextEncoder().encode(Hn),Yf=lC[0],Bo=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=D(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Yf)throw new Error("Invalid key")}toString(e="utf8"){return P(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Hn))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=lC),this._buf[0]!==Yf){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Yf,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Yf;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let s=0;s<t.length;s++){if(n.length<s+1)return!1;let o=t[s],i=n[s];if(o<i)return!0;if(o>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Hn).slice(1)}type(){return s$(this.baseNamespace())}name(){return o$(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Hn)||(e+=Hn),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Hn):new r(e.slice(0,-1).join(Hn))}child(e){return this.toString()===Hn?e:e.toString()===Hn?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...i$(e.map(t=>t.namespaces()))])}};function s$(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function o$(r){let e=r.split(":");return e[e.length-1]}function i$(r){return[].concat(...r)}var Hb="/peers/";function fu(r){if(!cs(r)||r.type==null)throw new R("Invalid PeerId");let e=r.toCID().toString();return new Bo(`${Hb}${e}`)}Bt();V();Ne();V();async function uC(r,e,t,n,s){let o=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=q(i.multiaddr)),!As(i.multiaddr))throw new R("Multiaddr was invalid");if(!await e(r,i.multiaddr,s))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),l=o.get(c);l!=null?i.isCertified=l.isCertified||a:o.set(c,{multiaddr:i.multiaddr,isCertified:a})}return[...o.values()].sort((i,a)=>i.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:i,multiaddr:a})=>{let c=a.getComponents().find(l=>l.code===421)?.value;return r.equals(c)&&(a=a.decapsulate(q(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function Qf(r,e,t,n){if(e==null)throw new R("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new R("publicKey bytes do not match peer id publicKey bytes");let s=n.existingPeer?.peer;if(s!=null&&!r.equals(s.id))throw new R("peer id did not match existing peer id");let o=s?.addresses??[],i=new Set(s?.protocols??[]),a=s?.metadata??new Map,c=s?.tags??new Map,l=s?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(o=[],e.multiaddrs!=null&&o.push(...e.multiaddrs.map(p=>({isCertified:!1,multiaddr:p}))),e.addresses!=null&&o.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let p=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Xf(p,{validate:hC})}if(e.tags!=null){let p=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Xf(p,{validate:dC,map:fC})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&o.push(...e.multiaddrs.map(p=>({isCertified:!1,multiaddr:p}))),e.addresses!=null&&o.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let p=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[f,d]of p)d==null?a.delete(f):a.set(f,d);a=Xf([...a.entries()],{validate:hC})}if(e.tags!=null){let p=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),f=new Map(c);for(let[d,m]of p)m==null?f.delete(d):f.set(d,m);c=Xf([...f.entries()],{validate:dC,map:fC})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;s?.id.publicKey!=null?u=dt(s.id.publicKey):e.publicKey!=null?u=dt(e.publicKey):r.publicKey!=null&&(u=dt(r.publicKey));let h={addresses:await uC(r,n.addressFilter??(async()=>!0),o,n.existingPeer?.peerPB.addresses,n),protocols:[...i.values()].sort((p,f)=>p.localeCompare(f)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return h.addresses.forEach(p=>{p.observed=n.existingPeer?.peerPB.addresses?.find(f=>W(f.multiaddr,f.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete h.publicKey,h}function Xf(r,e){let t=new Map;for(let[n,s]of r)s!=null&&e.validate(n,s);for(let[n,s]of r.sort(([o],[i])=>o.localeCompare(i)))s!=null&&t.set(n,e.map?.(n,s)??s);return t}function hC(r,e){if(typeof r!="string")throw new R("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new R("Metadata value must be a Uint8Array")}function dC(r,e){if(typeof r!="string")throw new R("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new R("Tag value must be an integer");if(e.value<0||e.value>100)throw new R("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new R("Tag ttl must be an integer");if(e.ttl<0)throw new R("Tag ttl must be between greater than 0")}}function fC(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let n={value:e.value??0};return t!=null&&(n.expiry=t),n}function pC(r){let e=r.toString().split("/")[2],t=Gf.parse(e,No);return en(t)}function qb(r,e,t){let n=pC(r);return sC(n,e,t)}function a$(r,e){return{prefix:Hb,filters:(r.filters??[]).map(t=>({key:n,value:s})=>t(qb(n,s,e))),orders:(r.orders??[]).map(t=>(n,s)=>t(qb(n.key,n.value,e),qb(s.key,s.value,e)))}}var Jf=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=ru({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return t==null&&(t={refs:0,lock:Nb({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,t.refs===0&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){let n=this.getLock(e);try{let s=await n.lock.readLock(t);return()=>{s(),this.maybeRemoveLock(e,n)}}catch(s){throw this.maybeRemoveLock(e,n),s}}async getWriteLock(e,t){let n=this.getLock(e);try{let s=await n.lock.writeLock(t);return()=>{s(),this.maybeRemoveLock(e,n)}}catch(s){throw this.maybeRemoveLock(e,n),s}}async has(e,t){try{return await this.load(e,t),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(fu(e),t)}async load(e,t){let n=fu(e),s=await this.datastore.get(n,t),o=$n.decode(s);if(this.#r(e,o))throw await this.datastore.delete(n,t),new $s;return wa(e,o,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let s=await this.#e(e,n),o=await Qf(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#t(e,o,s)}async patch(e,t,n){let s=await this.#e(e,n),o=await Qf(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:s});return this.#t(e,o,s)}async merge(e,t,n){let s=await this.#e(e,n),o=await Qf(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:s});return this.#t(e,o,s)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(a$(e??{},this.maxAddressAge),e)){let s=pC(t);if(s.equals(this.peerId))continue;let o=$n.decode(n);if(this.#r(s,o)){await this.datastore.delete(t,e);continue}yield wa(s,o,this.peerId.equals(s)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=fu(e),s=await this.datastore.get(n,t),o=$n.decode(s);if(this.#r(e,o))throw await this.datastore.delete(n,t),new $s;return{peerPB:o,peer:wa(e,o,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#t(e,t,n,s){t.updated=Date.now();let o=$n.encode(t);return await this.datastore.put(fu(e),o,s),{peer:wa(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!oC(t,n.peerPB)}}#r(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,s=Date.now()-this.maxAddressAge,o=t.addresses.filter(i=>i.observed!=null&&i.observed>s);return n&&o.length===0}};var Vb=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new Jf(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let n of this.store.all(t))e(n)}async all(e){return ou(this.store.all(e))}async delete(e,t){let n=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{n()}}async has(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),n?.()}}async get(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{n?.()}}async getInfo(e,t){let n=await this.get(e,t);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:s})=>s)}}async save(e,t,n){let s=await this.store.getWriteLock(e,n);try{let o=await this.store.save(e,t,n);return this.#e(e,o),o.peer}finally{s?.()}}async patch(e,t,n){let s=await this.store.getWriteLock(e,n);try{let o=await this.store.patch(e,t,n);return this.#e(e,o),o.peer}finally{s?.()}}async merge(e,t,n){let s=await this.store.getWriteLock(e,n);try{let o=await this.store.merge(e,t,n);return this.#e(e,o),o.peer}finally{s?.()}}async consumePeerRecord(e,t,n){let s=cs(t)?t:cs(t?.expectedPeer)?t.expectedPeer:void 0,o=cs(t)||t===void 0?n:t,i=await lr.openAndCertify(e,ur.DOMAIN,o),a=en(i.publicKey.toCID());if(s?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",s,a),!1;let c=ur.createFromProtobuf(i.payload),l;try{l=await this.get(a,o)}catch(u){if(u.name!=="NotFoundError")throw u}if(l?.peerRecordEnvelope!=null){let u=lr.createFromProtobuf(l.peerRecordEnvelope),h=ur.createFromProtobuf(u.payload);if(h.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",h.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u}))},o),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function mC(r,e={}){return new Vb(r,e)}var Zf=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};function c$(r){return r[Symbol.asyncIterator]!=null}function l$(r){if(c$(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Gb=l$;function u$(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var gC=u$;function h$(r){return r[Symbol.asyncIterator]!=null}function d$(r,e){let t=0;if(h$(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=gC(r),{value:s,done:o}=n.next();if(o===!0)return(function*(){})();let i=e(s,t++);if(typeof i.then=="function")return(async function*(){await i&&(yield s);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){i===!0&&(yield s);for(let c of n)a(c,t++)&&(yield c)})()}var Uo=d$;function f$(r){return r[Symbol.asyncIterator]!=null}function p$(r,e){return f$(r)?(async function*(){yield*(await ou(r)).sort(e)})():(function*(){yield*ou(r).sort(e)})()}var Wb=p$;function m$(r){return r[Symbol.asyncIterator]!=null}function g$(r,e){return m$(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var jb=g$;var ep=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:s}of e)await this.put(n,s,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,s){e.push({key:n,value:s})},delete(n){t.push(n)},commit:async n=>{await Gb(this.putMany(e,n)),e=[],await Gb(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let s=e.prefix;n=Uo(n,o=>o.key.toString().startsWith(s))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((s,o)=>Uo(s,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((s,o)=>Wb(s,o),n)),e.offset!=null){let s=0,o=e.offset;n=Uo(n,()=>s++>=o)}return e.limit!=null&&(n=jb(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let s=e.prefix;n=Uo(n,o=>o.toString().startsWith(s))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((s,o)=>Uo(s,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((s,o)=>Wb(s,o),n)),e.offset!=null){let s=e.offset,o=0;n=Uo(n,()=>o++>=s)}return e.limit!=null&&(n=jb(n,e.limit)),n}};var tp=class extends ep{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(e.toString());if(n==null)throw new Zf;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[n,s]of this.data.entries())yield{key:new Bo(n),value:s},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new Bo(n),t?.signal?.throwIfAborted()}};Ue();bt();te();ke();var Pe=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),Y=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),yC=r=>({match:e=>r.match(e)===!1?e:!1}),he=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Dt=(...r)=>({match:e=>{let t;for(let n of r){let s=n.match(e);s!==!1&&(t==null||s.length<t.length)&&(t=s)}return t??!1}}),we=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function De(...r){function e(s){if(s==null)return!1;let o=s.getComponents();for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function t(s){return e(s)!==!1}function n(s){let o=e(s);return o===!1?!1:o.length===0}return{matchers:r,matches:t,exactMatch:n}}var y$=Y(421),bC=De(y$),np=Y(54),sp=Y(55),op=Y(56),Xb=Y(53),F3e=De(np,he(Y(421))),z3e=De(sp,he(Y(421))),$3e=De(op,he(Y(421))),H3e=De(Dt(Xb,op,np,sp),he(Y(421))),wC=we(Y(4),he(Y(43))),xC=we(he(Y(42)),Y(41),he(Y(43))),Qb=Dt(wC,xC),Ko=Dt(Qb,Xb,np,sp,op),vC=De(Dt(Qb,we(Dt(Xb,op,np,sp),he(Y(421))))),Jb=De(wC),Zb=De(xC),q3e=De(Qb),ew=we(Ko,Y(6)),pu=we(Ko,Y(273)),qn=De(we(ew,he(Y(421)))),V3e=De(pu),tw=we(pu,Pe(460),he(Y(421))),ip=we(pu,Pe(461),he(Y(421))),b$=Dt(tw,ip),G3e=De(tw),EC=De(ip),Yb=Dt(Ko,ew,pu,tw,ip),SC=Dt(we(Yb,Pe(477),he(Y(421)))),mu=De(SC),IC=Dt(we(Yb,Pe(478),he(Y(421))),we(Yb,Pe(448),he(Y(449)),Pe(477),he(Y(421)))),gu=De(IC),AC=we(pu,Pe(280),he(Y(466)),he(Y(466)),he(Y(421))),rw=De(AC),CC=we(ip,Pe(465),he(Y(466)),he(Y(466)),he(Y(421))),nw=De(CC),rp=Dt(SC,IC,we(ew,he(Y(421))),we(b$,he(Y(421))),we(Ko,he(Y(421))),AC,CC,Y(421)),ap=De(rp),w$=we(he(rp),Pe(290),yC(Pe(281)),he(Y(421))),er=De(w$),x$=Dt(we(rp,Pe(290),Pe(281),he(Y(421))),we(rp,Pe(281),he(Y(421))),we(Pe(281),he(Y(421)))),sw=De(x$),v$=Dt(we(Ko,Y(6),Pe(480),he(Y(421))),we(Ko,Pe(480),he(Y(421)))),W3e=De(v$),E$=we(Ko,Dt(we(Y(6,"443"),Pe(480)),we(Y(6),Pe(443)),we(Y(6),Pe(448),Pe(480)),we(Pe(448),Pe(480)),Pe(448),Pe(443)),he(Y(421))),j3e=De(E$),S$=Dt(we(Y(777),he(Y(421)))),Y3e=De(S$),I$=Dt(we(Y(400),he(Y(421)))),cp=De(I$);var TC=864e13;var lp=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Pt({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=oe(e),n=t.host;(t.type==="ip4"||t.type==="ip6")&&t.sni!=null&&(n=t.sni);for(let s of this.mappings.values())if(s.domain===n)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let s=ua(n)===!0;this.mappings.set(n,{domain:e,verified:s,expires:s?TC-Date.now():0,lastVerified:s?TC-Date.now():void 0})})}remove(e){let t=oe(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[s,o]of this.mappings.entries())o.domain===t.sni&&(this.log("removing %s to %s DNS mapping %e",s,o.domain),this.mappings.delete(s),n=n||o.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let s=e[n].multiaddr;if(!St(s))continue;let o=oe(s);for(let[i,a]of this.mappings.entries()){if(o.host!==i)continue;let c=this.maybeAddSNIComponent(s,a.domain);c!=null&&(e.splice(n,1),n--,t.push({multiaddr:c,verified:a.verified,type:"dns-mapping",expires:a.expires,lastVerified:a.lastVerified}))}}return t}maybeAddSNIComponent(e,t){let n=e.getComponents();for(let s=0;s<n.length;s++)if(n[s].code===448&&n[s+1]?.code!==449)return n.splice(s+1,0,{name:"sni",code:449,value:t}),q(n)}confirm(e,t){let n=oe(e),s=n.host;(n.type==="ip4"||n.type==="ip6")&&n.sni!=null&&(s=n.sni);let o=!1;for(let[i,a]of this.mappings.entries())a.domain===s&&(this.log("marking %s to %s DNS mapping as verified",i,a.domain),o=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return o}unconfirm(e,t){let n=oe(e);if(n.type!=="ip4"&&n.type!=="ip6")return!1;let s=n.sni??n.host,o=!1;for(let[i,a]of this.mappings.entries())a.domain===s&&(this.log("removing verification of %s to %s DNS mapping",i,a.domain),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t);return o}};var up=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Pt({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=oe(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;for(let n of this.mappings.values())for(let s of n)if(s.externalIp===t.host)return!0;return!1}add(e,t,n,s=t,o="tcp"){let i=`${e}-${t}-${o}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:s,externalFamily:(0,fe.isIPv4)(n)?4:6,protocol:o,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=oe(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[s,o]of this.mappings.entries()){for(let i=0;i<o.length;i++){let a=o[i];a.externalIp===t.host&&a.externalPort===t.port&&a.protocol===t.protocol&&(this.log("removing %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,t.host,t.port,t.protocol),n=n||a.verified,o.splice(i,1),i--)}o.length===0&&this.mappings.delete(s)}return n}getAll(e){let t=[];for(let{multiaddr:n}of e){if(!St(n))continue;let s=oe(n);if(s.type!=="ip4"&&s.type!=="ip6")continue;let o;if(s.protocol==="tcp"?o=`${s.host}-${s.port}-tcp`:s.protocol==="udp"&&(o=`${s.host}-${s.port}-udp`),o==null)continue;let i=this.mappings.get(o);if(i!=null)for(let a of i)t.push({multiaddr:this.maybeOverrideIp(n,a.externalIp,a.externalFamily,a.protocol,a.externalPort),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}maybeOverrideIp(e,t,n,s,o){let i=e.getComponents(),a=i.findIndex(l=>l.code===4||l.code===41),c=i.findIndex(l=>l.name===s);return a>-1&&c>-1?(i[a].value=t,i[a].code=n===4?4:41,i[c].value=`${o}`,q(i)):e}confirm(e,t){if(!St(e))return!1;let n=oe(e),s=!1;for(let o of this.mappings.values())for(let i of o)i.externalIp===n.host&&(this.log("marking %s to %s IP mapping as verified",i.internalIp,i.externalIp),s=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return s}unconfirm(e,t){if(!St(e))return!1;let n=oe(e),s=!1;for(let o of this.mappings.values())for(let i=0;i<o.length;i++){let a=o[i];a.externalIp===n.host&&a.externalPort===n.port&&a.protocol===n.protocol&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,n.host,n.port,n.protocol),s=s||a.verified,a.verified=!1,a.expires=Date.now()+t)}return s}};var A$={maxObservedAddresses:10},hp=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Pt({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??A$.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(Fn(e)||b8(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:q(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),s=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},o=s.verified;return s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,s),o}};var C$={maxObservedAddresses:10},dp=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Pt({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??C$.maxObservedAddresses}get(e,t){if(Fn(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),s=this.addresses.get(n);return s==null&&(s={verified:!St(e),expires:0},this.addresses.set(n,s)),{multiaddr:e,verified:s.verified,type:"transport",expires:s.expires,lastVerified:s.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),s=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},o=s.verified;return s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now(),this.addresses.set(n,s),o}unconfirm(e,t){let n=this.toKey(e),s=this.addresses.get(n)??{verified:!1,expires:0},o=s.verified;return s.verified=!1,s.expires=Date.now()+t,this.addresses.set(n,s),o}toKey(e){if(!St(e))return e.toString();let t=oe(e);return`${t.host}-${t.port}-${t.protocol}`}};var _C=6e4,PC={maxObservedAddresses:10,addressVerificationTTL:_C*10,addressVerificationRetry:_C*5},T$=r=>r;function ow(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&de(t).equals(e)&&(r=r.decapsulate(q(`/p2p/${e.toString()}`))),r}var fp=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:s=[],appendAnnounce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(s.map(i=>i.toString())),this.appendAnnounce=new Set(o.map(i=>i.toString())),this.observed=new hp(e,t),this.dnsMappings=new lp(e,t),this.ipMappings=new up(e,t),this.transportAddresses=new dp(e,t),this.announceFilter=t.announceFilter??T$,this.observedAddressFilter=ln(1024),this.addressVerificationTTL=t.addressVerificationTTL??PC.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??PC.addressVerificationRetry,this._updatePeerStoreAddresses=So(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getComponents().findLast(n=>n.code===421)?.value===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses - %e",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>q(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>q(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>q(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=oe(e),n;switch(t.type){case"ip4":{n=`${t.host}:${t.port}`;break}case"ip6":{n=`[${t.host}]:${t.port}`;break}default:return}this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=ow(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=ow(e,this.components.peerId);let n=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=ow(e,this.components.peerId);let n=!1;this.observed.has(e)&&!this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&!this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&!this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&!this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let s=n.multiaddr.toString();return e.has(s)?!1:(e.add(s),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let s=q(n);return s.getComponents().pop()?.value===this.components.peerId.toString()?s:s.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(s=>{s.updateAnnounceAddrs(e)}),e.map(s=>({multiaddr:s,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(s=>this.transportAddresses.get(s,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(s=>{s.updateAnnounceAddrs(n)}),t=t.concat(n.map(s=>({multiaddr:s,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(q(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,s=t,o="tcp"){this.ipMappings.add(e,t,n,s,o),this.observed.removePrefixed(`/ip${(0,fe.isIPv4)(n)?4:6}/${n}/${o}/${s}`)}removePublicAddressMapping(e,t,n,s=t,o="tcp"){this.ipMappings.remove(q(`/ip${(0,fe.isIPv4)(n)?4:6}/${n}/${o}/${s}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!St(e))return!1;let t=oe(e);if(t.type!=="ip4"||ua(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),s=[o=>mu.exactMatch(o)||gu.exactMatch(o),o=>qn.exactMatch(o),o=>EC.exactMatch(o)];for(let o of s){if(!o(e))continue;let i=n.filter(l=>l.getAddrs().filter(u=>oe(u).type==="ip4"&&o(u)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>!Zl(l)).pop();if(a==null)continue;let c=oe(a);return c.port==null?!1:(this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.protocol),!0)}return!1}};V();var DC;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(DC||(DC={}));var pp=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},mp=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},xa=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},yu=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},gp=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},yp=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},bp=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},bu=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},wp=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},xp=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},vp=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},Ep=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},Sp=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},ks=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Fo=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},Ip=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},Ap=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var iw=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=bf())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Dh(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},_$=["metrics","connectionProtector","dns"],P$=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function kC(r={}){let e=new iw(r);return new Proxy(e,{get(n,s,o){if(typeof s=="string"&&!P$.includes(s)){let i=e.components[s];if(i==null&&!_$.includes(s))throw new pp(`${s} not set`);return i}return Reflect.get(n,s,o)},set(n,s,o){return typeof s=="string"?e.components[s]=o:Reflect.set(n,s,o),!0}})}function LC(r){let e={};for(let t of Object.values(r.components))for(let n of D$(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of k$(t))if(e[n]!==!0)throw new mp(`Service "${L$(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function D$(r){return Array.isArray(r?.[nt])?r[nt]:[]}function k$(r){return Array.isArray(r?.[yc])?r[yc]:[]}function L$(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function MC(r={}){return r}V();var Le=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};V();ke();function Cp(r){if(cs(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let n=e[0].getComponents().findLast(s=>s.code===421)?.value;t=n==null?void 0:de(n),e.forEach(s=>{if(!As(s))throw new ss("Invalid multiaddr");let o=s.getComponents().findLast(i=>i.code===421)?.value;if(o==null){if(t!=null)throw new R("Multiaddrs must all have the same peer id or have no peer id")}else{let i=de(o);if(t?.equals(i)!==!0)throw new R("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!bC.exactMatch(n)),{peerId:t,multiaddrs:e}}V();var M$=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function OC(r,e){let t=r?.streams?.map(s=>s.protocol)??[],n=e?.closableProtocols??M$;if(!(t.filter(s=>s!=null&&!n.includes(s)).length>0))try{await r?.close(e)}catch(s){r?.abort(s)}}function wu(r){let e=oe(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new R(`Multiaddr ${r} was not an IPv4 or IPv6 address`);if(t==null)switch(e.type){case"ip4":{t=32;break}case"ip6":{t=128;break}default:throw new R(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new Bn(e.host,t)}function aw(r){return!er.exactMatch(r)}function Tp(r,e,t){if(r==null||e==null)return;let n=e.sort((o,i)=>o.direct?-1:i.direct?1:0).find(o=>o.limits==null);if(n==null||n.direct||t==null)return n;if(!t.some(o=>aw(o)))return n}var _p=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>wu(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections - %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,n),t<=n)return;let s=new Zt;for(let c of e){let l=c.remotePeer;if(!s.has(l)){s.set(l,0);try{let u=await this.peerStore.get(l);s.set(l,[...u.tags.values()].reduce((h,p)=>h+p.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags - %e",u)}}}let o=this.sortConnections(e,s),i=Math.max(t-n,0),a=[];for(let c of o)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(u=>{if(St(c.remoteAddr)){let h=oe(c.remoteAddr);return u.contains(h.host)}return!0})||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await OC(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((n,s)=>{let o=n.timeline.open,i=s.timeline.open;return o<i?1:o>i?-1:0}).sort((n,s)=>n.direction==="outbound"&&s.direction==="inbound"?1:n.direction==="inbound"&&s.direction==="outbound"?-1:0).sort((n,s)=>n.streams.length>s.streams.length?1:n.streams.length<s.streams.length?-1:0).sort((n,s)=>{let o=t.get(n.remotePeer)??0,i=t.get(s.remotePeer)??0;return o>i?1:o<i?-1:0})}};var RC="last-dial-failure",NC="last-dial-success";var BC=300,Pp=100;V();Ue();te();function O$(r,e){let t=qn.exactMatch(r.multiaddr),n=qn.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let s=gu.exactMatch(r.multiaddr),o=gu.exactMatch(e.multiaddr);if(s&&!o)return-1;if(!s&&o)return 1;let i=mu.exactMatch(r.multiaddr),a=mu.exactMatch(e.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=sw.exactMatch(r.multiaddr),l=sw.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=rw.exactMatch(r.multiaddr),h=rw.exactMatch(e.multiaddr);if(u&&!h)return-1;if(!u&&h)return 1;let p=nw.exactMatch(r.multiaddr),f=nw.exactMatch(e.multiaddr);return p&&!f?-1:!p&&f?1:0}function R$(r,e){let t=Zl(r.multiaddr),n=Zl(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function N$(r,e){let t=Fn(r.multiaddr),n=Fn(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function B$(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function U$(r,e){let t=er.exactMatch(r.multiaddr),n=er.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function UC(r){return r.sort(O$).sort(B$).sort(U$).sort(N$).sort(R$)}var FC=ee("dns/promises");function Dp(r){let e=[kt.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}ce();var cw=60;function kp(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:kt[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:kt[e.type],TTL:e.TTL??e.ttl??cw,data:e.data instanceof Uint8Array?P(e.data):e.data}))}}var K$=async(r,e={})=>{let t=new FC.Resolver,n=()=>{t.cancel()},s=Dp(e.types);try{e.signal?.addEventListener("abort",n);let o=await Promise.all(s.map(async i=>{if(i===kt.A)return Lp(r,i,await t.resolve4(r));if(i===kt.CNAME)return Lp(r,i,await t.resolveCname(r));if(i===kt.TXT)return Lp(r,i,await t.resolveTxt(r));if(i===kt.AAAA)return Lp(r,i,await t.resolve6(r));throw new TypeError("Unsupported DNS record type")}));return kp({Question:s.map(i=>({name:r,type:i})),Answer:o.flat()})}finally{e.signal?.removeEventListener("abort",n)}};function zC(){return[K$]}function KC(r,e,t){return{name:r,type:e,data:t}}function Lp(r,e,t){return Array.isArray(t)||(t=[t]),t.map(n=>Array.isArray(n)?n.map(s=>KC(r,e,s)):KC(r,e,n)).flat()}var qC=ie(HC(),1);var lw=class{lru;constructor(e){this.lru=(0,qC.default)(e)}get(e,t){let n=!0,s=[];for(let o of t){let i=this.getAnswers(e,o);if(i.length===0){n=!1;break}s.push(...i)}if(n)return kp({answers:s})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,s=this.lru.get(n);if(s!=null){let o=s.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:kt[a.type]}));return o.length===0&&this.lru.remove(n),o}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,s=this.lru.get(n)??[];s.push({expires:Date.now()+(t.TTL??cw)*1e3,value:t}),this.lru.set(n,s)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function VC(r){return new lw(r)}var F$=1e3,Mp=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=VC(e.cacheSize??F$),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=zC())}async query(e,t={}){let n=Dp(t.types),s=t.cached!==!1?this.cache.get(e,n):void 0;if(s!=null)return t.onProgress?.(new Le("dns:cache",s)),s;let o=`${e.split(".").pop()}.`,i=(this.resolvers[o]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new Le("dns:error",l))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var kt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(kt||(kt={}));function GC(r={}){return new Mp(r)}var uw=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let n=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[e];let o=await this.getDNS(t).query(`_dnsaddr.${n}`,{signal:t?.signal,types:[kt.TXT]}),i=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of o.Answer){let l=c.data.replace(/["']/g,"").trim().split("=")[1];l!=null&&(i!=null&&!l.includes(i)||a.push(q(l)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=GC()),this.dns)}},xu=new uw;async function hw(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new Ap("Max recursive depth reached");let s=!1,o=[];for(let i of Object.values(e))if(i.canResolve(r)){s=!0;let a=await i.resolve(r,t);for(let c of a)o.push(...await hw(c,e,{...t,depth:n+1}))}return s===!1&&o.push(r),o}var vu={maxParallelDials:Pp,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:xu}},Op=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??vu.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??vu.maxDialQueueLength,this.dialTimeout=t.dialTimeout??vu.dialTimeout,this.connections=t.connections??new Zt,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??vu.resolvers,this.shutDownController=new AbortController,j(1/0,this.shutDownController.signal),this.queue=new Mf({concurrency:t.maxParallelDials??vu.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==rr.name&&this.log.error("error in dial queue - %e",n.detail.error)})}start(){this.shutDownController=new AbortController,j(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:s}=Cp(e);if(n!=null&&t.force!==!0){let i=Tp(n,this.connections.get(n),s);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new Le("dial-queue:already-connected")),i}let o=this.queue.queue.find(i=>{if(n?.equals(i.options.peerId)===!0)return!0;let a=i.options.multiaddrs;if(a==null)return!1;for(let c of s)if(a.has(c.toString()))return!0;return!1});if(o!=null){this.log("joining existing dial target for %p",n);for(let i of s)o.options.multiaddrs.add(i.toString());return t.onProgress?.(new Le("dial-queue:already-in-dial-queue")),o.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new os("Dial queue is full");return this.log("creating dial target for %p",n,s.map(i=>i.toString())),t.onProgress?.(new Le("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new Le("dial-queue:start-dial"));let a=$t([this.shutDownController.signal,i.signal]);j(1/0,a);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??mw,multiaddrs:new Set(s.map(i=>i.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,s=e.multiaddrs,o=new Set,i=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);i||s.size>0;){c++,i=!1;let u=[],h=new Set(e.multiaddrs);s.clear(),this.log("calculating addrs to dial %p from %s",n,[...h]);let p=await this.calculateMultiaddrs(n,h,{...e,signal:t});for(let f of p){if(o.has(f.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",f.multiaddr,n);continue}u.push(f)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,u.map(f=>f.multiaddr.toString())),e?.onProgress?.(new Le("dial-queue:calculated-addresses",u));for(let f of u){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new os("Peer had more than maxPeerAddrsToDial");a++;try{let d=await this.components.transportManager.dial(f.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",f.multiaddr);try{await this.components.peerStore.merge(d.remotePeer,{multiaddrs:[d.remoteAddr],metadata:{[NC]:D(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p - %e",n,m)}return d}catch(d){if(this.log.error("dial failed to %a - %e",f.multiaddr,d),o.add(f.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[RC]:D(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p - %e",n,m)}if(t.aborted)throw new Gr(d.message);l.push(d)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let s=[...t].map(h=>({multiaddr:q(h),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new os("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new bu("The dial request is blocked by gater.allowDialPeer");if(s.length===0){this.log("loading multiaddrs for %p",e);try{let h=await this.components.peerStore.get(e);s.push(...h.addresses),this.log("loaded multiaddrs for %p",e,s.map(({multiaddr:p})=>p.toString()))}catch(h){if(h.name!=="NotFoundError")throw h}}if(s.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let h=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,s.map(({multiaddr:p})=>p.toString())),s.push(...h.multiaddrs.map(p=>({multiaddr:p,isCertified:!1})))}catch(h){h.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,h)}}}let o=(await Promise.all(s.map(async h=>{let p=await hw(h.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return p.length===1&&p[0].equals(h.multiaddr)?h:p.map(f=>({multiaddr:f,isCertified:!1}))}))).flat();if(e!=null){let h=`/p2p/${e.toString()}`;o=o.map(p=>p.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:p.multiaddr.encapsulate(h),isCertified:p.isCertified}:p)}let i=o.filter(h=>{if(this.components.transportManager.dialTransportForMultiaddr(h.multiaddr)==null)return!1;let p=h.multiaddr.getComponents().findLast(f=>f.code===421)?.value;return e!=null&&p!=null?e.equals(p):!0}),a=new Map;for(let h of i){let p=h.multiaddr.toString(),f=a.get(p);if(f!=null){f.isCertified=f.isCertified||h.isCertified||!1;continue}a.set(p,h)}let c=[...a.values()];if(c.length===0)throw new vp("The dial request has no valid addresses");let l=[];for(let h of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(h.multiaddr)||l.push(h);let u=this.addressSorter==null?UC(l):l.sort(this.addressSorter);if(u.length===0)throw new bu("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",o.map(({multiaddr:h})=>h.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:h})=>h.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(s=>s.toString())),t);return t.runOnLimitedConnection===!1?n.find(s=>!er.matches(s.multiaddr))!=null:!0}catch{}return!1}};V();var z$=Object.prototype.toString,$$=r=>z$.call(r)==="[object Error]",H$=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function gw(r){if(!(r&&$$(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"?n===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")?!0:H$.has(t)}function q$(r){if(typeof r=="number"){if(r<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function Rp(r,e,{min:t=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${r}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${r}\` to be a finite number.`);if(e<t)throw new TypeError(`Expected \`${r}\` to be \u2265 ${t}.`)}}var yw=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function V$(r,e){let t=Math.max(1,r+1),n=e.randomize?Math.random()+1:1,s=Math.round(n*e.minTimeout*e.factor**(t-1));return s=Math.min(s,e.maxTimeout),s}function WC(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function G$({error:r,attemptNumber:e,retriesConsumed:t,startTime:n,options:s}){let o=r instanceof Error?r:new TypeError(`Non-error was thrown: "${r}". You should only throw errors.`);if(o instanceof yw)throw o.originalError;let i=Number.isFinite(s.retries)?Math.max(0,s.retries-t):s.retries,a=s.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:o,attemptNumber:e,retriesLeft:i,retriesConsumed:t});if(await s.onFailedAttempt(c),WC(n,a)<=0)throw o;let l=await s.shouldConsumeRetry(c),u=WC(n,a);if(u<=0||i<=0)throw o;if(o instanceof TypeError&&!gw(o)){if(l)throw o;return s.signal?.throwIfAborted(),!1}if(!await s.shouldRetry(c))throw o;if(!l)return s.signal?.throwIfAborted(),!1;let h=V$(t,s),p=Math.min(h,u);return p>0&&await new Promise((f,d)=>{let m=()=>{clearTimeout(g),s.signal?.removeEventListener("abort",m),d(s.signal.reason)},g=setTimeout(()=>{s.signal?.removeEventListener("abort",m),f()},p);s.unref&&g.unref?.(),s.signal?.addEventListener("abort",m,{once:!0})}),s.signal?.throwIfAborted(),!0}async function bw(r,e={}){if(e={...e},q$(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,Rp("factor",e.factor,{min:0,allowInfinity:!1}),Rp("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),Rp("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),Rp("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let t=0,n=0,s=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){t++;try{e.signal?.throwIfAborted();let o=await r(t);return e.signal?.throwIfAborted(),o}catch(o){await G$({error:o,attemptNumber:t,retriesConsumed:n,startTime:s,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Np=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new Ps({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(s=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,s)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);jC(t)&&(this.queue.has(e)||this.queue.add(async n=>{await bw(async s=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(o){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,s,this.retries,o),o}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let s={};[...t.tags.keys()].forEach(o=>{o.startsWith(mc)&&(s[o]=void 0)}),await this.peerStore.merge(e,{tags:s}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>jC(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error("could not open connection to keepalive peer - %e",n)})}))}).catch(e=>{this.log.error("error reconnect to peers after start - %e",e)})}stop(){this.started=!1,this.queue.abort()}};function jC(r){for(let e of r.tags.keys())if(e.startsWith(mc))return!0;return!1}var mw=50,ww={maxConnections:BC,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},Bp=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??ww.maxConnections,this.maxConnections<1)throw new R("Connection Manager maxConnections must be greater than 0");this.connections=new Zt,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map(n=>wu(q(n))),this.deny=(t.deny??[]).map(n=>wu(q(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??ww.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Of({points:t.inboundConnectionThreshold??ww.inboundConnectionThreshold,duration:1}),this.connectionPruner=new _p({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>q(n))}),this.dialQueue=new Op(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??Pp,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:xu},connections:this.connections}),this.reconnectQueue=new Np({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let s of n.streams){let o=`${s.direction} ${s.protocol??"unnegotiated"}`;e[o]=(e[o]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let s of n){let o={};for(let i of s.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;o[a]=(o[a]??0)+1}for(let[i,a]of Object.entries(o))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,s]of Object.entries(e)){s=s.sort((i,a)=>i-a);let o=Math.floor(s.length*.9);t[n]=s[o]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await kh(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await Lh(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([Re(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(s=>{n.abort(s)}));this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(this.maxConnections<1)throw new R("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(t=>{this.log.error("could not connect - %e",t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,s=!this.connections.has(n),o=this.connections.get(n)??[];o.push(t),this.connections.set(n,o),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,o=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,o),o.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:n}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new Dr("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:n,multiaddrs:s}=Cp(e);if(this.peerId.equals(n))throw new Qo("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=Tp(n,this.getConnections(n),s);if(c!=null)return this.log("had an existing connection to %p as %a",n,c.remoteAddr),t.onProgress?.(new Le("dial-queue:already-connected")),c}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??mw});if(o.status!=="open")throw new zs("Remote closed connection during opening");let i=this.connections.get(o.remotePeer);i==null&&(i=[],this.connections.set(o.remotePeer,i));let a=!1;for(let c of i)if(c.id===o.id&&(a=!0),t.force!==!0&&c.id!==o.id&&c.remoteAddr.equals(o.remoteAddr))return o.abort(new ss("Duplicate multiaddr connection")),c;return a||i.push(o),o}finally{this.outboundPendingConnections--}}async openStream(e,t,n={}){return(await this.openConnection(e,n)).newStream(t,n)}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async s=>{try{await Promise.all([Re(s,"close",t),s.close(t)])}catch(o){s.abort(o)}}))}acceptIncomingConnection(e){if(this.deny.some(s=>{if(St(e.remoteAddr)){let o=oe(e.remoteAddr);return s.contains(o.host)}return!1}))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(s=>{if(St(e.remoteAddr)){let o=oe(e.remoteAddr);return s.contains(o.host)}return!0}))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(St(e.remoteAddr)){let s=oe(e.remoteAddr);try{this.inboundConnectionRateLimiter.consume(s.host,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,s.host),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>q(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};V();Ue();var Y$=1e4,X$="1.0.0",Q$="ping",J$="ipfs",YC=32,Z$=!0,Up=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??J$}/${Q$}/${X$}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??Y$,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??Z$,this.timeout=new Df({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[nt]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,j(1/0,this.abortController.signal),this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),s=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),o=vb(s);t=Date.now(),await Promise.all([o.write(fs(YC),{signal:n}),o.read({bytes:YC,signal:n})]),e.rtt=Date.now()-t,await s.close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat - %e",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};V();ce();var Kp=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()}),getAttributesFromYieldedValue:(n,s)=>({...s,providers:[...Array.isArray(s.providers)?s.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:P(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:P(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new xa("No content routers available");let n=this,s=new xo;for await(let o of Ks(...n.routers.filter(i=>i.findProviders instanceof Function).map(i=>i.findProviders(e,t))))o!=null&&(o.multiaddrs.length>0&&await this.components.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),!s.has(o.id)&&(s.add(o.id),yield o))}async provide(e,t={}){if(this.routers.length===0)throw new xa("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new xa("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new Dr;await Promise.all(this.routers.filter(s=>s.put instanceof Function).map(async s=>{await s.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new Dr;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};V();var Fp=globalThis.CustomEvent??Event;async function*xw(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,s=new EventTarget,o=[],i=ut(),a=ut(),c=!1,l,u=!1;s.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let d of r){if(o.length===t&&(i=ut(),await i.promise),u)break;let m={done:!1};o.push(m),d().then(g=>{m.done=!0,m.ok=!0,m.value=g,s.dispatchEvent(new Fp("task-complete"))},g=>{m.done=!0,m.err=g,s.dispatchEvent(new Fp("task-complete"))})}c=!0,s.dispatchEvent(new Fp("task-complete"))}catch(d){l=d,s.dispatchEvent(new Fp("task-complete"))}});function h(){return n?o[0]?.done:!!o.find(d=>d.done)}function*p(){for(;o.length>0&&o[0].done;){let d=o[0];if(o.shift(),d.ok)yield d.value;else throw u=!0,i.resolve(),d.err;i.resolve()}}function*f(){for(;h();)for(let d=0;d<o.length;d++)if(o[d].done){let m=o[d];if(o.splice(d,1),d--,m.ok)yield m.value;else throw u=!0,i.resolve(),m.err;i.resolve()}}for(;;){if(h()||(a=ut(),await a.promise),l!=null||(n?yield*p():yield*f(),l!=null))throw l;if(c&&o.length===0)break}}ce();var zp=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,key:P(n,"base36")}),getAttributesFromYieldedValue:(n,s)=>({...s,peers:[...Array.isArray(s.peers)?s.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new yu("No peer routers available");if(e.toString()===this.peerId.toString())throw new gp("Should not try to find self");let n=this,s=Ks(...this.routers.filter(o=>o.findPeer instanceof Function).map(o=>(async function*(){try{yield await o.findPeer(e,t)}catch(i){n.log.error("router failed to find peer - %e",i)}})()));for await(let o of s)if(o!=null)return o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),o;throw new $s}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new yu("No peer routers available");let n=this,s=ln(1024);for await(let o of xw((async function*(){let i=Ks(...n.routers.filter(a=>a.getClosestPeers instanceof Function).map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs - %e",c);return}return a}})()))o!=null&&(o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),!s.has(o.id.toMultihash().bytes)&&(s.add(o.id.toMultihash().bytes),yield o))}};Ue();function eH(r){return r.reason}async function Eu(r,e,t){if(e==null)return r;let n=t?.translateError??eH;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}var $p=class extends me{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,j(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,j(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=$t([this.shutdownController.signal,e?.signal]);j(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=ut(),yield(await Re(this,"walk:peer",{signal:t,rejectionEvents:["walk:error"]})).detail}catch(n){throw n.detail!=null?n.detail:n}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,j(1/0,this.walkController.signal);let e=$t([this.walkController.signal,this.shutdownController.signal]);j(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let s=fs(32),o=Date.now();for await(let i of this.peerRouting.getClosestPeers(s,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-o,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await Eu(this.needNext.promise,e)),o=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",s,this.walkers,n)}catch(s){this.log.error("random walk errored - %e",s),this.safeDispatchEvent("walk:error",{detail:s})}this.log("no walkers left, ended walk")}).catch(s=>{this.log.error("random walk errored - %e",s)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};V();var vw=32,Ew=64,Hp=class{log;topologies;handlers;components;middleware;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.middleware=new Map,this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[n,s]of this.topologies)t[n]=s.size;return t}}),this.handlers=Pt({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new yp(`No handler registered for protocol ${e}`);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&n?.force!==!0)throw new bp(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:vw,maxOutboundStreams:Ew,...n}}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(s=>{this.handlers.delete(s)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new R("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,s=this.topologies.get(e);return s==null&&(s=new Map,this.topologies.set(e,s)),s.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}use(e,t){this.middleware.set(e,t)}unuse(e){this.middleware.delete(e)}getMiddleware(e){return this.middleware.get(e)??[]}async _onDisconnect(e){let t=e.detail,n={signal:AbortSignal.timeout(5e3)};try{let s=await this.components.peerStore.get(t,n);for(let o of s.protocols){let i=this.topologies.get(o);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter?.has(t)!==!1&&(a.filter?.remove(t),await a.onDisconnect?.(t))}))}}catch(s){if(s.name==="NotFoundError")return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,s)}}async _onPeerUpdate(e){let{peer:t,previous:n}=e.detail,s=(n?.protocols??[]).filter(o=>!t.protocols.includes(o));try{for(let o of s){let i=this.topologies.get(o);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),await a.onDisconnect?.(t.id))}))}}catch(o){this.log.error("could not inform topologies of updated peer %p - %e",t.id,o)}}async _onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,s=e.detail.peerId;try{for(let o of t){let i=this.topologies.get(o);i!=null&&await Promise.all([...i.values()].map(async a=>{n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(s)!==!0&&(a.filter?.add(s),await a.onConnect?.(s,n))}))}}catch(o){this.log.error("could not inform topologies of updated peer after identify %p - %e",s,o)}}};V();var qp=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=Pt({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Pt({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??gc.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new R("Transport must have a valid tag");if(this.transports.has(t))throw new R(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let s=n.pop();s!=null&&e.push(s.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new Ip(`No transport available for address ${String(e)}`);return t?.onProgress?.(new Le("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new Dr("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(o=>{t.errors.set(o.toString(),new wp)});let n=[];for(let[o,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",o,c);let l=i.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(o)??[];u==null&&(u=[],this.listeners.set(o,u)),u.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let h=u.findIndex(p=>p===l);u.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),Jb.matches(c)?t.ipv4.attempts++:Zb.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),Jb.matches(c)&&t.ipv4.success++,Zb.matches(c)&&t.ipv6.success++},h=>{throw this.log.error("transport %s could not listen on address %a - %e",o,c,h),t.errors.set(c.toString(),h),h}))}}let s=await Promise.allSettled(n);if(!(s.length>0&&s.every(o=>o.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===gc.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new xp(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:
|
|
21
21
|
${[...t.errors.entries()].map(([o,i])=>`
|
|
22
22
|
${o}: ${`${tH(i)}`.split(`
|
|
23
23
|
`).join(`
|
|
@@ -31,7 +31,7 @@ ${[...t.errors.entries()].map(([o,i])=>`
|
|
|
31
31
|
`),t),n.trace('responded with "%s" for "%s"',o,o),s.unwrap(),o;if(o==="ls"){let i=new U(...e.map(a=>yr.single(D(`${a}
|
|
32
32
|
`))),D(`
|
|
33
33
|
`));n.trace('respond with "%s" for %s',e,o),await s.write(i,t),n.trace('responded with "%s" for %s',e,o);continue}n.trace('respond with "na" for "%s"',o),await s.write(D(`na
|
|
34
|
-
`),t),n('responded with "na" for "%s"',o)}}ke();Ue();V();Ue();var Iw=class extends me{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.closeTimeout=t.closeTimeout??1e3,this.direct=aw(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new as(n.local,n.error))})}[Symbol.toStringTag]="Connection";[X5]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new ks("Connection is not multiplexed");if(this.muxer.status!=="open")throw new zs(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new zs(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new fc("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let a=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);j(1/0,a),t={...t,signal:a}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await va(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let s=oH(n.protocol,this.components.registrar,t),o=JC(n.protocol,"outbound",this);if(o>s){let a=new Jo(`Too many outbound protocol streams for protocol "${n.protocol}" - ${o}/${s}`);throw n.abort(a),a}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol);return await this.runMiddlewareChain(n,this,i)}catch(s){throw n.status==="open"?n.abort(s):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,s),s}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);j(1/0,n),t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let l=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",l),t.protocol=await Ea(t,l,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let s=sH(t.protocol,this.components.registrar);if(JC(t.protocol,"inbound",this)>s)throw new Ah(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${s}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);let{handler:i,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new fc("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(l,u,h)=>{await i(l,u),h(l,u)}),await this.runMiddlewareChain(t,this,c)}catch(s){t.abort(s)}}async runMiddlewareChain(e,t,n){for(let s=0;s<n.length;s++){let o=n[s];e.log.trace("running middleware",s,o),await new Promise((i,a)=>{try{let c=o(e,t,(l,u)=>{e=l,t=u,i()});c instanceof Promise&&c.catch(a)}catch(c){a(c)}}),e.log.trace("ran middleware",s,o)}return e}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),e.signal==null){let t=AbortSignal.timeout(this.closeTimeout);j(1/0,t),e={...e,signal:t}}await this.muxer?.close(e),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}};function ZC(r,e){return new Iw(r,e)}function sH(r,e){try{let{options:t}=e.getHandler(r);if(t.maxInboundStreams!=null)return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return vw}function oH(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??Ew}function JC(r,e,t){let n=0;return t.streams.forEach(s=>{s.direction===e&&s.protocol===r&&n++}),n}var Vp=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=Pt({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=Pt({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new Ep(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=$t([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return j(1/0,t),t}async upgradeInbound(e,t){let n=!1,s=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new Sp("Connection denied");await Eu(this.shouldBlockConnection("denyInboundConnection",e),s),await this._performUpgrade(e,"inbound",{...t,signal:s})}catch(o){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[o.name??"Error"]:!0}),o}finally{s.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getComponents().findLast(i=>i.code===421)?.value,s;n!=null&&(s=de(n),await Eu(this.shouldBlockConnection("denyOutboundConnection",s,e),t.signal));let o="outbound";return t.initiator===!1&&(o="inbound"),await this._performUpgrade(e,o,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let s=e,o,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${l}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let h=this.components.connectionProtector;h!=null&&(e.log("protecting the %s connection",t),s=await h.protect(s,n))}try{if(iH(n)){if(n.remotePeer==null)throw new ss(`${t} connection that skipped encryption must have a peer id`);c="native",o=n.remotePeer}else{let h=e.remoteAddr.getComponents().findLast(f=>f.code===421)?.value,p;h!=null&&(p=de(h)),n?.onProgress?.(new Le(`upgrader:encrypt-${t}-connection`)),{connection:s,remotePeer:o,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(s,{...n,remotePeer:p}):this._encryptOutbound(s,{...n,remotePeer:p}))}if(o.equals(this.components.peerId)){let h=new Qo("Can not dial self");throw e.abort(h),h}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",o,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new Le(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(s,this.streamMuxers,n):this._multiplexOutbound(s,this.streamMuxers,n)))}catch(h){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,h),h}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(s)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",o,e);let u=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,stream:s,muxer:a,remotePeer:o,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return u.log("successfully upgraded connection"),u}_createConnection(e){let t=ZC(this.components,{...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout});return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let s=await Ea(e,n,t),o=this.connectionEncrypters.get(s);if(o==null)throw new Fo(`no crypto module found for ${s}`);return e.log("encrypting inbound connection using %s",s),{...await o.secureInbound(e,t),protocol:s}}catch(s){throw new Fo(s.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let s=await va(e,n,t),o=this.connectionEncrypters.get(s);if(o==null)throw new Fo(`no crypto module found for ${s}`);return e.log("encrypting outbound connection using %s",s),{...await o.secureOutbound(e,t),protocol:s}}catch(s){throw new Fo(s.message)}}async _multiplexOutbound(e,t,n){let s=Array.from(t.keys());e.log("outbound selecting muxer %s",s);try{e.log.trace("selecting stream muxer from %s",s);let o=await va(e,s,n),i=t.get(o);if(i==null)throw new ks(`No muxer configured for protocol "${o}"`);return e.log("selected %s as muxer protocol",o),i}catch(o){throw e.log.error("error multiplexing outbound connection - %e",o),new ks(String(o))}}async _multiplexInbound(e,t,n){let s=Array.from(t.keys());e.log("inbound handling muxers %s",s);try{e.log.trace("selecting stream muxer from %s",s);let o=await Ea(e,s,n),i=t.get(o);if(i==null)throw new ks(`No muxer configured for protocol "${o}"`);return e.log("selected %s as muxer protocol",o),i}catch(o){throw e.log.error("error multiplexing inbound connection - %e",o),o}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function iH(r){return r.skipEncryption===!0}var Ls=ie(ee("node:process"),1);var Gp="3.1.3",Wp="js-libp2p";function tT(r,e){let t="node",n=Ls.default.versions.node;return Ls.default.versions.deno!=null&&(t="deno",n=Ls.default.versions.deno),Ls.default.versions.bun!=null&&(t="bun",n=Ls.default.versions.bun),Ls.default.versions.electron!=null&&(t="electron",n=Ls.default.versions.electron),`${r??Wp}/${e??Gp} ${t}/${n.replaceAll("v","")}`}var jp=class extends me{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new me,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=n(l),h=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||h},j(1/0,t),this.peerId=e.peerId,this.logger=e.logger??bf(),this.log=this.logger.forComponent("libp2p"),this.services={};let s=e.nodeInfo?.name??Wp,o=e.nodeInfo?.version??Gp,i=this.components=kC({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:s,version:o,userAgent:e.nodeInfo?.userAgent??tT(s,o)},logger:this.logger,events:t,datastore:e.datastore??new tp,connectionGater:MC(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",mC(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(h=>h.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Vp(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new qp(this.components,e.transportManager)),this.configureComponent("connectionManager",new Bp(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Up(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Hp(this.components)),this.configureComponent("addressManager",new fp(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new zp(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Kp(this.components,{routers:c})),this.configureComponent("randomWalk",new $p(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",p=>{this.#e(p)})}),e.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let u=e.services[l],h=u(this.components);if(h==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=h,this.configureComponent(l,h),h[Mm]!=null&&(this.log("registering service %s for content routing",l),c.push(h[Mm])),h[Om]!=null&&(this.log("registering service %s for peer routing",l),a.push(h[Om])),h[pc]!=null&&(this.log("registering service %s for peer discovery",l),h[pc].addEventListener?.("peer",p=>{this.#e(p)}))}LC(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started with peer id %p",this.peerId)}catch(e){throw this.log.error("an error occurred starting libp2p - %e",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new xo;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new R("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new R("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){As(e)&&(e=de(e.getComponents().findLast(n=>n.code===421)?.value??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Ee([D("/pk/"),e.toMultihash().bytes]),s=await this.contentRouting.get(n,t),o=Ft(s);return await this.peerStore.patch(e,{publicKey:o},t),o}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async s=>{await this.components.registrar.handle(s,t,n)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.unhandle(n,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}use(e,t){this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){this.components.registrar.unuse(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error("could not update multiaddrs of discovered peer - %e",n)})}};async function rT(r={}){r.privateKey??=await dE("Ed25519");let e=new jp({...await GA(r),peerId:q2(r.privateKey)});return r.start!==!1&&await e.start(),e}var iT=ie(ee("net"),1);V();var oT=ie(ee("node:net"),1);V();Ue();V();var Aw=class extends da{socket;constructor(e){let t=e.remoteAddr;if(e.localAddr!=null&&cp.matches(e.localAddr))t=e.localAddr;else if(t==null){if(e.socket.remoteAddress==null||e.socket.remotePort==null)throw new R("Could not determine remote address or port");t=T8(e.socket.remoteAddress,e.socket.remotePort)}super({...e,remoteAddr:t}),this.socket=e.socket,this.socket.on("data",n=>{this.onData(n)}),this.socket.on("error",n=>{this.log("tcp error",t,n),this.abort(n)}),this.socket.setTimeout(e.inactivityTimeout??120*1e3),this.socket.once("timeout",()=>{this.log("tcp timeout",t),this.abort(new Gr)}),this.socket.once("end",()=>{this.log("tcp end",t),this.onTransportClosed()}),this.socket.once("close",n=>{if(this.log("tcp close",t),n){this.abort(new Error("TCP transmission error"));return}this.onTransportClosed()}),this.socket.on("drain",()=>{this.log("tcp drain"),this.safeDispatchEvent("drain")})}sendData(e){let t=0,n=!0;for(let s of e)if(t+=s.byteLength,n=this.socket.write(s),!n)break;return{sentBytes:t,canSendMore:n}}async sendClose(e){this.socket.destroyed||(this.socket.destroySoon(),await Re(this.socket,"close",e))}sendReset(){this.socket.resetAndDestroy()}sendPause(){this.socket.pause()}sendResume(){this.socket.resume()}},Yp=r=>new Aw(r);var nT=ie(ee("os"),1),sT=ie(ee("path"),1);V();function Xp(r,e={}){if(cp.exactMatch(r)){let o=r.getComponents().find(i=>i.code===400)?.value;if(o==null)throw new R(`Multiaddr ${r} was not a Unix address`);return nT.default.platform()==="win32"?{path:sT.default.join("\\\\.\\pipe\\",o)}:{path:o}}let t=oe(r),n=t.host,s=t.port;return{host:n,port:s,ipv6Only:t.type==="ip6",...e}}var gt;(function(r){r[r.INACTIVE=0]="INACTIVE",r[r.ACTIVE=1]="ACTIVE",r[r.PAUSED=2]="PAUSED"})(gt||(gt={}));var Qp=class extends me{context;server;sockets=new Set;status={code:gt.INACTIVE};metrics;addr;log;shutdownController;constructor(e){if(super(),this.context=e,e.keepAlive=e.keepAlive??!0,e.noDelay=e.noDelay??!0,e.allowHalfOpen=e.allowHalfOpen??!1,this.shutdownController=new AbortController,j(1/0,this.shutdownController.signal),this.log=e.logger.forComponent("libp2p:tcp:listener"),this.addr="unknown",this.server=oT.default.createServer(e,this.onSocket.bind(this)),e.maxConnections!==void 0&&(this.server.maxConnections=e.maxConnections),e.closeServerOnMaxConnections!=null&&e.closeServerOnMaxConnections.closeAbove<e.closeServerOnMaxConnections.listenBelow)throw new R("closeAbove must be >= listenBelow");e.metrics?.registerMetricGroup("libp2p_tcp_inbound_connections_total",{label:"address",help:"Current active connections in TCP listener",calculate:()=>({[this.addr]:this.sockets.size})}),this.metrics={status:e.metrics?.registerMetricGroup("libp2p_tcp_listener_status_info",{label:"address",help:"Current status of the TCP listener socket"}),errors:e.metrics?.registerMetricGroup("libp2p_tcp_listener_errors_total",{label:"address",help:"Total count of TCP listener errors by type"}),events:e.metrics?.registerMetricGroup("libp2p_tcp_listener_events_total",{label:"address",help:"Total count of TCP listener events by type"})},this.server.on("listening",()=>{let t=this.server.address();t==null?this.addr="unknown":typeof t=="string"?this.addr=t:this.addr=`${t.address}:${t.port}`,this.metrics.status?.update({[this.addr]:gt.ACTIVE}),this.safeDispatchEvent("listening")}).on("error",t=>{this.metrics.errors?.increment({[`${this.addr} listen_error`]:!0}),this.safeDispatchEvent("error",{detail:t})}).on("close",()=>{this.metrics.status?.update({[this.addr]:this.status.code}),this.status.code!==gt.PAUSED&&this.safeDispatchEvent("close")}).on("drop",()=>{this.metrics.events?.increment({[`${this.addr} drop`]:!0})})}onSocket(e){if(this.metrics.events?.increment({[`${this.addr} connection`]:!0}),this.status.code!==gt.ACTIVE)throw e.destroy(),new Dr("Server is not listening yet");let t;try{t=Yp({socket:e,inactivityTimeout:this.context.inactivityTimeout,metrics:this.metrics?.events,metricPrefix:`${this.addr} `,direction:"inbound",localAddr:this.status.listeningAddr,log:this.context.logger.forComponent("libp2p:tcp:connection")})}catch(n){this.log.error("inbound connection failed - %e",n),this.metrics.errors?.increment({[`${this.addr} inbound_to_connection`]:!0}),e.destroy();return}this.log("new inbound connection %s",t.remoteAddr),this.sockets.add(e),this.context.upgrader.upgradeInbound(t,{signal:this.shutdownController.signal}).then(()=>{this.log("inbound connection upgraded %s",t.remoteAddr),e.once("close",()=>{this.sockets.delete(e),this.context.closeServerOnMaxConnections!=null&&this.sockets.size<this.context.closeServerOnMaxConnections.listenBelow&&this.resume().catch(n=>{this.log.error("error attempting to listen server once connection count under limit - %e",n),this.context.closeServerOnMaxConnections?.onListenError?.(n)})}),this.context.closeServerOnMaxConnections!=null&&this.sockets.size>=this.context.closeServerOnMaxConnections.closeAbove&&(this.log("pausing incoming connections as limit is exceeded - %d/%d",this.sockets.size,this.context.closeServerOnMaxConnections.closeAbove),this.pause())}).catch(async n=>{this.log.error("inbound connection upgrade failed - %e",n),this.metrics.errors?.increment({[`${this.addr} inbound_upgrade`]:!0}),this.sockets.delete(e),t.abort(n)})}getAddrs(){if(this.status.code===gt.INACTIVE)return[];let e=this.server.address();return e==null?[]:typeof e=="string"?[q(`/unix/${encodeURIComponent(e)}`)]:C8(this.status.listeningAddr,e.port)}updateAnnounceAddrs(){}async listen(e){if(this.status.code===gt.ACTIVE||this.status.code===gt.PAUSED)throw new Ih("server is already listening");try{this.status={code:gt.ACTIVE,listeningAddr:e,netConfig:Xp(e,this.context)},await this.resume()}catch(t){throw this.status={code:gt.INACTIVE},t}}async close(e){let t=[];this.server.listening&&t.push(Re(this.server,"close",e)),this.pause(!0),this.shutdownController.abort(),this.sockets.forEach(n=>{n.readable&&(t.push(Re(n,"close",e)),n.destroy())}),await Promise.all(t)}async resume(){if(this.server.listening||this.status.code===gt.INACTIVE)return;let e=this.status.netConfig;await new Promise((t,n)=>{this.server.once("error",n),this.server.listen(e,t)}),this.status={...this.status,code:gt.ACTIVE},this.log("listening on %s",this.server.address())}pause(e=!1){if(!this.server.listening&&this.status.code===gt.PAUSED&&e){this.status={code:gt.INACTIVE};return}!this.server.listening||this.status.code!==gt.ACTIVE||(this.log("%s server on %s",e?"closing":"pausing",this.server.address()),this.status=e?{code:gt.INACTIVE}:{...this.status,code:gt.PAUSED},this.server.close())}};var Jp=class{opts;metrics;components;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:tcp"),this.opts=t,this.components=e,e.metrics!=null&&(this.metrics={events:e.metrics.registerCounterGroup("libp2p_tcp_dialer_events_total",{label:"event",help:"Total count of TCP dialer events by type"}),errors:e.metrics.registerCounterGroup("libp2p_tcp_dialer_errors_total",{label:"event",help:"Total count of TCP dialer events by type"})})}[Mh]=!0;[Symbol.toStringTag]="@libp2p/tcp";[nt]=["@libp2p/transport"];async dial(e,t){t.keepAlive=t.keepAlive??!0,t.noDelay=t.noDelay??!0,t.allowHalfOpen=t.allowHalfOpen??!1;let n=await this._connect(e,t),s;try{s=Yp({socket:n,inactivityTimeout:this.opts.outboundSocketInactivityTimeout,metrics:this.metrics?.events,direction:"outbound",remoteAddr:e,log:this.log.newScope("connection")})}catch(o){throw this.metrics?.errors.increment({outbound_to_connection:!0}),n.destroy(o),o}try{return this.log("new outbound connection %s",s.remoteAddr),await t.upgrader.upgradeOutbound(s,t)}catch(o){throw this.metrics?.errors.increment({outbound_upgrade:!0}),this.log.error("error upgrading outbound connection - %e",o),s.abort(o),o}}async _connect(e,t){t.signal.throwIfAborted(),t.onProgress?.(new Le("tcp:open-connection"));let n;return new Promise((s,o)=>{let i=Date.now(),a=Xp(e,{...this.opts.dialOpts??{},...t});this.log("dialing %a with opts %o",e,a),n=iT.default.connect(a);let c=f=>{this.log.error("dial to %a errored - %e",e,f);let d=a.path??`${a.host??""}:${a.port}`;f.message=`connection error ${d}: ${f.message}`,this.metrics?.events.increment({error:!0}),p(f)},l=()=>{this.log("connection timeout %a",e),this.metrics?.events.increment({timeout:!0});let f=new Gr(`Connection timeout after ${Date.now()-i}ms`);n.emit("error",f)},u=()=>{this.log("connection opened %a",e),this.metrics?.events.increment({connect:!0}),p()},h=()=>{this.log("connection aborted %a",e),this.metrics?.events.increment({abort:!0}),p(new rr)},p=f=>{if(n.removeListener("error",c),n.removeListener("timeout",l),n.removeListener("connect",u),t.signal!=null&&t.signal.removeEventListener("abort",h),f!=null){o(f);return}s(n)};n.on("error",c),n.on("timeout",l),n.on("connect",u),t.signal.addEventListener("abort",h)}).catch(s=>{throw n?.destroy(),s})}createListener(e){return new Qp({...this.opts.listenOpts??{},...e,maxConnections:this.opts.maxConnections,backlog:this.opts.backlog,closeServerOnMaxConnections:this.opts.closeServerOnMaxConnections,inactivityTimeout:this.opts.inboundSocketInactivityTimeout,metrics:this.components.metrics,logger:this.components.logger})}listenFilter(e){return e.filter(t=>qn.exactMatch(t)||t.toString().startsWith("/unix/"))}dialFilter(e){return this.listenFilter(e)}};function aT(r={}){return e=>new Jp(e,r)}Bt();V();ke();rt();var Sa=!!globalThis.process?.env?.DUMP_SESSION_KEYS,Cw=16;var mn=ie(ee("node:crypto"),1),u1=ie(pT(),1);var IH=typeof process<"u"&&process.versions!=null&&process.versions.node!=null,mT=IH?CH:AH;function AH(r=0){return new Uint8Array(r)}function CH(r=0){let e=Buffer.allocUnsafe(r);return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var gT=Uint8Array.from([0,97,115,109,1,0,0,0,1,43,8,96,2,127,127,0,96,1,127,0,96,1,127,1,127,96,2,127,127,1,127,96,0,0,96,3,127,127,127,0,96,4,127,127,127,127,0,96,3,127,127,126,0,2,13,1,3,101,110,118,5,97,98,111,114,116,0,6,3,23,22,0,0,0,0,0,7,2,3,3,2,4,5,1,2,5,0,1,1,0,1,1,4,5,3,1,0,1,6,187,1,37,127,0,65,4,11,127,0,65,128,4,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,0,65,0,11,7,169,1,13,8,72,65,83,95,83,73,77,68,3,36,22,98,97,116,99,104,72,97,115,104,52,85,105,110,116,65,114,114,97,121,54,52,115,0,17,26,98,97,116,99,104,72,97,115,104,52,72,97,115,104,79,98,106,101,99,116,73,110,112,117,116,115,0,18,12,73,78,80,85,84,95,76,69,78,71,84,72,3,1,15,80,65,82,65,76,76,69,76,95,70,65,67,84,79,82,3,0,5,105,110,112,117,116,3,30,6,111,117,116,112,117,116,3,32,4,105,110,105,116,0,11,6,117,112,100,97,116,101,0,19,5,102,105,110,97,108,0,20,6,100,105,103,101,115,116,0,21,8,100,105,103,101,115,116,54,52,0,16,6,109,101,109,111,114,121,2,0,8,1,22,12,1,18,10,153,23,22,9,0,32,0,32,1,54,2,0,11,9,0,32,0,32,1,54,2,4,11,9,0,32,0,32,1,54,2,8,11,192,1,1,4,127,32,1,40,2,0,65,124,113,34,3,65,128,2,73,4,127,32,3,65,4,118,5,65,31,65,252,255,255,255,3,32,3,32,3,65,252,255,255,255,3,79,27,34,3,103,107,34,4,65,7,107,33,2,32,3,32,4,65,4,107,118,65,16,115,11,33,3,32,1,40,2,8,33,5,32,1,40,2,4,34,4,4,64,32,4,32,5,16,3,11,32,5,4,64,32,5,32,4,16,2,11,32,1,32,0,32,2,65,4,116,32,3,106,65,2,116,106,34,1,40,2,96,70,4,64,32,1,32,5,54,2,96,32,5,69,4,64,32,0,32,2,65,2,116,106,34,1,40,2,4,65,126,32,3,119,113,33,3,32,1,32,3,54,2,4,32,3,69,4,64,32,0,32,0,40,2,0,65,126,32,2,119,113,16,1,11,11,11,11,181,2,1,5,127,32,1,40,2,0,33,3,32,1,65,4,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,34,2,65,1,113,4,64,32,0,32,4,16,4,32,1,32,3,65,4,106,32,2,65,124,113,106,34,3,16,1,32,1,65,4,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,33,2,11,32,3,65,2,113,4,64,32,1,65,4,107,40,2,0,34,1,40,2,0,33,6,32,0,32,1,16,4,32,1,32,6,65,4,106,32,3,65,124,113,106,34,3,16,1,11,32,4,32,2,65,2,114,16,1,32,4,65,4,107,32,1,54,2,0,32,0,32,3,65,124,113,34,2,65,128,2,73,4,127,32,2,65,4,118,5,65,31,65,252,255,255,255,3,32,2,32,2,65,252,255,255,255,3,79,27,34,2,103,107,34,3,65,7,107,33,5,32,2,32,3,65,4,107,118,65,16,115,11,34,2,32,5,65,4,116,106,65,2,116,106,40,2,96,33,3,32,1,65,0,16,2,32,1,32,3,16,3,32,3,4,64,32,3,32,1,16,2,11,32,0,32,5,65,4,116,32,2,106,65,2,116,106,32,1,54,2,96,32,0,32,0,40,2,0,65,1,32,5,116,114,16,1,32,0,32,5,65,2,116,106,34,0,32,0,40,2,4,65,1,32,2,116,114,54,2,4,11,130,1,1,3,127,32,1,65,19,106,65,112,113,65,4,107,33,1,32,0,40,2,160,12,34,3,4,64,32,3,32,1,65,16,107,34,5,70,4,64,32,3,40,2,0,33,4,32,5,33,1,11,11,32,2,167,65,112,113,32,1,107,34,3,65,20,73,4,64,15,11,32,1,32,4,65,2,113,32,3,65,8,107,34,3,65,1,114,114,16,1,32,1,65,0,16,2,32,1,65,0,16,3,32,1,65,4,106,32,3,106,34,3,65,2,16,1,32,0,32,3,54,2,160,12,32,0,32,1,16,5,11,29,0,32,0,65,1,65,27,32,0,103,107,116,106,65,1,107,32,0,32,0,65,254,255,255,255,1,73,27,11,142,1,1,2,127,32,1,65,128,2,73,4,127,32,1,65,4,118,5,65,31,32,1,16,7,34,1,103,107,34,3,65,7,107,33,2,32,1,32,3,65,4,107,118,65,16,115,11,33,1,32,0,32,2,65,2,116,106,40,2,4,65,127,32,1,116,113,34,1,4,127,32,0,32,1,104,32,2,65,4,116,106,65,2,116,106,40,2,96,5,32,0,40,2,0,65,127,32,2,65,1,106,116,113,34,1,4,127,32,0,32,0,32,1,104,34,0,65,2,116,106,40,2,4,104,32,0,65,4,116,106,65,2,116,106,40,2,96,5,65,0,11,11,11,148,2,1,3,127,32,1,65,252,255,255,255,3,75,4,64,65,176,14,65,176,15,65,205,3,65,29,16,0,0,11,32,0,65,12,32,1,65,19,106,65,112,113,65,4,107,32,1,65,12,77,27,34,1,16,8,34,2,69,4,64,32,1,65,128,2,79,4,127,32,1,16,7,5,32,1,11,33,2,63,0,34,3,32,2,65,4,32,0,40,2,160,12,32,3,65,16,116,65,4,107,71,116,106,65,255,255,3,106,65,128,128,124,113,65,16,118,34,2,32,2,32,3,72,27,64,0,65,0,72,4,64,32,2,64,0,65,0,72,4,64,0,11,11,32,0,32,3,65,16,116,63,0,172,66,16,134,16,6,32,0,32,1,16,8,33,2,11,32,2,40,2,0,26,32,0,32,2,16,4,32,2,40,2,0,34,3,65,124,113,32,1,107,34,4,65,16,79,4,64,32,2,32,1,32,3,65,2,113,114,16,1,32,2,65,4,106,32,1,106,34,1,32,4,65,4,107,65,1,114,16,1,32,0,32,1,16,5,5,32,2,32,3,65,126,113,16,1,32,2,65,4,106,32,2,40,2,0,65,124,113,106,34,0,32,0,40,2,0,65,125,113,16,1,11,32,2,11,169,2,1,3,127,32,0,65,252,255,255,255,3,75,4,64,65,192,13,65,240,13,65,52,65,43,16,0,0,11,32,0,65,236,255,255,255,3,75,4,64,65,176,14,65,240,14,65,253,0,65,30,16,0,0,11,35,23,69,4,64,63,0,34,2,65,0,76,4,127,65,1,32,2,107,64,0,65,0,72,5,65,0,11,4,64,0,11,65,128,16,65,0,16,1,65,160,28,65,0,54,2,0,3,64,32,1,65,23,73,4,64,32,1,65,2,116,65,128,16,106,65,0,54,2,4,65,0,33,2,3,64,32,2,65,16,73,4,64,32,1,65,4,116,32,2,106,65,2,116,65,128,16,106,65,0,54,2,96,32,2,65,1,106,33,2,12,1,11,11,32,1,65,1,106,33,1,12,1,11,11,65,128,16,65,164,28,63,0,172,66,16,134,16,6,65,128,16,36,23,11,35,23,32,0,65,16,106,16,9,34,2,65,1,54,2,12,32,2,32,0,54,2,16,35,24,34,3,40,2,8,33,1,32,2,32,3,16,2,32,2,32,1,16,3,32,1,32,2,32,1,40,2,4,65,3,113,114,16,2,32,3,32,2,16,3,35,25,32,2,40,2,0,65,124,113,65,4,106,106,36,25,32,2,65,20,106,34,1,65,0,32,0,252,11,0,32,1,11,74,0,65,231,204,167,208,6,36,4,65,133,221,158,219,123,36,5,65,242,230,187,227,3,36,6,65,186,234,191,170,122,36,7,65,255,164,185,136,5,36,8,65,140,209,149,216,121,36,9,65,171,179,143,252,1,36,10,65,153,154,131,223,5,36,11,65,0,36,34,65,0,36,35,11,233,3,1,1,127,35,4,36,12,35,5,36,13,35,6,36,14,35,7,36,15,35,8,36,16,35,9,36,17,35,10,36,18,35,11,36,19,65,0,36,20,3,64,35,20,65,16,73,4,64,32,0,35,20,65,2,116,106,32,1,35,20,32,2,108,65,2,116,34,3,65,3,106,106,45,0,0,32,1,32,3,106,45,0,0,65,24,116,32,1,32,3,65,1,106,106,45,0,0,65,16,116,114,32,1,32,3,65,2,106,106,45,0,0,65,8,116,114,114,54,2,0,35,20,65,1,106,36,20,12,1,11,11,65,16,36,20,3,64,35,20,65,192,0,73,4,64,32,0,35,20,65,2,116,106,32,0,35,20,65,16,107,65,2,116,106,40,2,0,32,0,35,20,65,7,107,65,2,116,106,40,2,0,32,0,35,20,65,2,107,65,2,116,106,40,2,0,34,1,65,17,120,32,1,65,19,120,115,32,1,65,10,118,115,106,32,0,35,20,65,15,107,65,2,116,106,40,2,0,34,1,65,7,120,32,1,65,18,120,115,32,1,65,3,118,115,106,106,54,2,0,35,20,65,1,106,36,20,12,1,11,11,65,0,36,20,3,64,35,20,65,192,0,73,4,64,32,0,35,20,65,2,116,34,1,106,40,2,0,32,1,35,2,106,40,2,0,35,19,35,16,34,1,65,6,120,32,1,65,11,120,115,32,1,65,25,120,115,106,35,16,34,1,35,17,113,35,18,32,1,65,127,115,113,115,106,106,106,36,21,35,12,34,1,65,2,120,32,1,65,13,120,115,32,1,65,22,120,115,35,13,34,1,35,14,34,2,113,32,1,35,12,34,1,113,32,1,32,2,113,115,115,106,36,22,35,18,36,19,35,17,36,18,35,16,36,17,35,15,35,21,106,36,16,35,14,36,15,35,13,36,14,35,12,36,13,35,21,35,22,106,36,12,35,20,65,1,106,36,20,12,1,11,11,35,4,35,12,106,36,4,35,5,35,13,106,36,5,35,6,35,14,106,36,6,35,7,35,15,106,36,7,35,8,35,16,106,36,8,35,9,35,17,106,36,9,35,10,35,18,106,36,10,35,11,35,19,106,36,11,11,253,1,1,2,127,35,4,36,12,35,5,36,13,35,6,36,14,35,7,36,15,35,8,36,16,35,9,36,17,35,10,36,18,35,11,36,19,65,0,36,20,3,64,35,20,65,192,0,73,4,64,32,0,35,20,65,2,116,106,40,2,0,35,19,35,16,34,1,65,6,120,32,1,65,11,120,115,32,1,65,25,120,115,106,35,16,34,1,35,17,113,35,18,32,1,65,127,115,113,115,106,106,36,21,35,12,34,1,65,2,120,32,1,65,13,120,115,32,1,65,22,120,115,35,13,34,2,35,14,34,1,113,32,2,35,12,34,2,113,32,1,32,2,113,115,115,106,36,22,35,18,36,19,35,17,36,18,35,16,36,17,35,15,35,21,106,36,16,35,14,36,15,35,13,36,14,35,12,36,13,35,21,35,22,106,36,12,35,20,65,1,106,36,20,12,1,11,11,35,4,35,12,106,36,4,35,5,35,13,106,36,5,35,6,35,14,106,36,6,35,7,35,15,106,36,7,35,8,35,16,106,36,8,35,9,35,17,106,36,9,35,10,35,18,106,36,10,35,11,35,19,106,36,11,11,25,0,32,0,65,128,254,131,120,113,65,8,119,32,0,65,255,129,252,7,113,65,8,120,114,11,88,0,16,11,35,29,32,0,32,2,16,12,35,3,16,13,32,1,35,4,16,14,54,2,0,32,1,35,5,16,14,54,2,4,32,1,35,6,16,14,54,2,8,32,1,35,7,16,14,54,2,12,32,1,35,8,16,14,54,2,16,32,1,35,9,16,14,54,2,20,32,1,35,10,16,14,54,2,24,32,1,35,11,16,14,54,2,28,11,10,0,32,0,32,1,65,1,16,15,11,42,1,1,127,3,64,32,1,65,4,72,4,64,35,31,32,1,65,6,116,106,32,0,32,1,65,5,116,106,16,16,32,1,65,1,106,33,1,12,1,11,11,11,44,1,1,127,3,64,32,1,65,4,72,4,64,35,31,32,1,65,2,116,106,32,0,32,1,65,5,116,106,65,4,16,15,32,1,65,1,106,33,1,12,1,11,11,11,178,1,1,2,127,35,35,32,1,106,36,35,35,34,4,64,65,192,0,35,34,107,34,2,32,1,76,4,64,35,27,35,34,106,32,0,32,2,252,10,0,0,35,34,32,2,106,36,34,65,192,0,35,34,107,33,2,32,1,65,192,0,35,34,107,107,33,1,35,29,35,27,65,1,16,12,65,0,36,34,5,35,27,35,34,106,32,0,32,1,252,10,0,0,35,34,32,1,106,36,34,15,11,11,3,64,32,3,32,1,65,192,0,109,72,4,64,35,29,32,0,32,2,106,65,1,16,12,32,3,65,1,106,33,3,32,2,65,64,107,33,2,12,1,11,11,32,1,65,63,113,34,1,4,64,35,27,35,34,106,32,0,32,2,106,32,1,252,10,0,0,35,34,32,1,106,36,34,11,11,235,1,1,2,127,35,27,35,34,106,65,128,1,58,0,0,35,34,65,1,106,36,34,35,34,65,56,74,4,64,35,27,35,34,106,34,1,65,192,0,35,34,107,106,33,2,3,64,32,1,32,2,73,4,64,32,1,65,0,58,0,0,32,1,65,1,106,33,1,12,1,11,11,35,29,35,27,65,1,16,12,65,0,36,34,11,35,27,35,34,106,34,1,65,56,35,34,107,106,33,2,3,64,32,1,32,2,73,4,64,32,1,65,0,58,0,0,32,1,65,1,106,33,1,12,1,11,11,35,27,35,35,65,128,128,128,128,2,109,16,14,54,2,56,35,27,35,35,65,3,116,16,14,54,2,60,35,29,35,27,65,1,16,12,32,0,35,4,16,14,54,2,0,32,0,35,5,16,14,54,2,4,32,0,35,6,16,14,54,2,8,32,0,35,7,16,14,54,2,12,32,0,35,8,16,14,54,2,16,32,0,35,9,16,14,54,2,20,32,0,35,10,16,14,54,2,24,32,0,35,11,16,14,54,2,28,11,14,0,16,11,35,31,32,0,16,19,35,33,16,20,11,82,0,65,196,10,40,2,0,36,2,65,148,13,40,2,0,36,3,65,224,15,65,224,15,16,2,65,224,15,65,224,15,16,3,65,224,15,36,24,65,192,0,16,10,36,26,35,26,36,27,65,128,8,16,10,36,28,35,28,36,29,65,128,4,16,10,36,30,35,30,36,31,65,32,16,10,36,32,35,32,36,33,11,11,253,6,18,0,65,140,8,11,2,28,1,0,65,152,8,11,136,2,1,0,0,0,0,1,0,0,152,47,138,66,145,68,55,113,207,251,192,181,165,219,181,233,91,194,86,57,241,17,241,89,164,130,63,146,213,94,28,171,152,170,7,216,1,91,131,18,190,133,49,36,195,125,12,85,116,93,190,114,254,177,222,128,167,6,220,155,116,241,155,193,193,105,155,228,134,71,190,239,198,157,193,15,204,161,12,36,111,44,233,45,170,132,116,74,220,169,176,92,218,136,249,118,82,81,62,152,109,198,49,168,200,39,3,176,199,127,89,191,243,11,224,198,71,145,167,213,81,99,202,6,103,41,41,20,133,10,183,39,56,33,27,46,252,109,44,77,19,13,56,83,84,115,10,101,187,10,106,118,46,201,194,129,133,44,114,146,161,232,191,162,75,102,26,168,112,139,75,194,163,81,108,199,25,232,146,209,36,6,153,214,133,53,14,244,112,160,106,16,22,193,164,25,8,108,55,30,76,119,72,39,181,188,176,52,179,12,28,57,74,170,216,78,79,202,156,91,243,111,46,104,238,130,143,116,111,99,165,120,20,120,200,132,8,2,199,140,250,255,190,144,235,108,80,164,247,163,249,190,242,120,113,198,0,65,172,10,11,1,44,0,65,184,10,11,21,4,0,0,0,16,0,0,0,32,4,0,0,32,4,0,0,0,1,0,0,64,0,65,220,10,11,2,28,1,0,65,232,10,11,136,2,1,0,0,0,0,1,0,0,152,47,138,194,145,68,55,113,207,251,192,181,165,219,181,233,91,194,86,57,241,17,241,89,164,130,63,146,213,94,28,171,152,170,7,216,1,91,131,18,190,133,49,36,195,125,12,85,116,93,190,114,254,177,222,128,167,6,220,155,116,243,155,193,193,105,155,100,134,71,254,240,198,237,225,15,84,242,12,36,111,52,233,79,190,132,201,108,30,65,185,97,250,136,249,22,82,81,198,242,109,90,142,168,101,252,25,176,199,158,217,185,195,49,18,154,160,234,14,231,43,35,177,253,176,62,53,199,213,186,105,48,95,109,151,203,143,17,15,90,253,238,30,220,137,182,53,10,4,122,11,222,157,202,244,88,22,91,93,225,134,62,127,0,128,137,8,55,50,234,7,165,55,149,171,111,16,97,64,23,241,214,140,13,109,59,170,205,55,190,187,192,218,59,97,131,99,163,72,219,49,233,2,11,167,92,209,111,202,250,26,82,49,132,51,49,149,26,212,110,144,120,67,109,242,145,156,195,189,171,204,158,230,160,201,181,60,182,47,83,198,65,199,210,163,126,35,7,104,75,149,164,118,29,25,76,0,65,252,12,11,1,44,0,65,136,13,11,21,4,0,0,0,16,0,0,0,112,5,0,0,112,5,0,0,0,1,0,0,64,0,65,172,13,11,1,44,0,65,184,13,11,35,2,0,0,0,28,0,0,0,73,0,110,0,118,0,97,0,108,0,105,0,100,0,32,0,108,0,101,0,110,0,103,0,116,0,104,0,65,220,13,11,1,60,0,65,232,13,11,45,2,0,0,0,38,0,0,0,126,0,108,0,105,0,98,0,47,0,97,0,114,0,114,0,97,0,121,0,98,0,117,0,102,0,102,0,101,0,114,0,46,0,116,0,115,0,65,156,14,11,1,60,0,65,168,14,11,47,2,0,0,0,40,0,0,0,65,0,108,0,108,0,111,0,99,0,97,0,116,0,105,0,111,0,110,0,32,0,116,0,111,0,111,0,32,0,108,0,97,0,114,0,103,0,101,0,65,220,14,11,1,60,0,65,232,14,11,37,2,0,0,0,30,0,0,0,126,0,108,0,105,0,98,0,47,0,114,0,116,0,47,0,116,0,99,0,109,0,115,0,46,0,116,0,115,0,65,156,15,11,1,60,0,65,168,15,11,37,2,0,0,0,30,0,0,0,126,0,108,0,105,0,98,0,47,0,114,0,116,0,47,0,116,0,108,0,115,0,102,0,46,0,116,0,115]);var Lw=Uint8Array.from([0,97,115,109,1,0,0,0,1,37,7,96,2,127,127,0,96,1,127,1,127,96,2,127,127,1,127,96,1,127,0,96,0,0,96,4,127,127,127,127,0,96,3,127,127,126,0,2,13,1,3,101,110,118,5,97,98,111,114,116,0,5,3,30,29,0,0,0,0,0,6,1,2,2,2,1,2,1,1,2,4,4,1,0,3,3,4,0,0,3,3,3,0,4,5,3,1,0,1,6,227,4,61,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,127,1,65,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,0,65,4,11,127,0,65,128,4,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,0,65,1,11,7,169,1,13,8,72,65,83,95,83,73,77,68,3,60,22,98,97,116,99,104,72,97,115,104,52,85,105,110,116,65,114,114,97,121,54,52,115,0,20,26,98,97,116,99,104,72,97,115,104,52,72,97,115,104,79,98,106,101,99,116,73,110,112,117,116,115,0,21,12,73,78,80,85,84,95,76,69,78,71,84,72,3,28,15,80,65,82,65,76,76,69,76,95,70,65,67,84,79,82,3,27,5,105,110,112,117,116,3,54,6,111,117,116,112,117,116,3,56,4,105,110,105,116,0,22,6,117,112,100,97,116,101,0,24,5,102,105,110,97,108,0,25,6,100,105,103,101,115,116,0,26,8,100,105,103,101,115,116,54,52,0,28,6,109,101,109,111,114,121,2,0,8,1,29,12,1,38,10,243,111,29,9,0,32,0,32,1,54,2,0,11,9,0,32,0,32,1,54,2,4,11,9,0,32,0,32,1,54,2,8,11,192,1,1,4,127,32,1,40,2,0,65,124,113,34,3,65,128,2,73,4,127,32,3,65,4,118,5,65,31,65,252,255,255,255,3,32,3,32,3,65,252,255,255,255,3,79,27,34,3,103,107,34,4,65,7,107,33,2,32,3,32,4,65,4,107,118,65,16,115,11,33,3,32,1,40,2,8,33,5,32,1,40,2,4,34,4,4,64,32,4,32,5,16,3,11,32,5,4,64,32,5,32,4,16,2,11,32,1,32,0,32,2,65,4,116,32,3,106,65,2,116,106,34,1,40,2,96,70,4,64,32,1,32,5,54,2,96,32,5,69,4,64,32,0,32,2,65,2,116,106,34,1,40,2,4,65,126,32,3,119,113,33,3,32,1,32,3,54,2,4,32,3,69,4,64,32,0,32,0,40,2,0,65,126,32,2,119,113,16,1,11,11,11,11,181,2,1,5,127,32,1,40,2,0,33,3,32,1,65,4,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,34,2,65,1,113,4,64,32,0,32,4,16,4,32,1,32,3,65,4,106,32,2,65,124,113,106,34,3,16,1,32,1,65,4,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,33,2,11,32,3,65,2,113,4,64,32,1,65,4,107,40,2,0,34,1,40,2,0,33,6,32,0,32,1,16,4,32,1,32,6,65,4,106,32,3,65,124,113,106,34,3,16,1,11,32,4,32,2,65,2,114,16,1,32,4,65,4,107,32,1,54,2,0,32,0,32,3,65,124,113,34,2,65,128,2,73,4,127,32,2,65,4,118,5,65,31,65,252,255,255,255,3,32,2,32,2,65,252,255,255,255,3,79,27,34,2,103,107,34,3,65,7,107,33,5,32,2,32,3,65,4,107,118,65,16,115,11,34,2,32,5,65,4,116,106,65,2,116,106,40,2,96,33,3,32,1,65,0,16,2,32,1,32,3,16,3,32,3,4,64,32,3,32,1,16,2,11,32,0,32,5,65,4,116,32,2,106,65,2,116,106,32,1,54,2,96,32,0,32,0,40,2,0,65,1,32,5,116,114,16,1,32,0,32,5,65,2,116,106,34,0,32,0,40,2,4,65,1,32,2,116,114,54,2,4,11,130,1,1,3,127,32,1,65,19,106,65,112,113,65,4,107,33,1,32,0,40,2,160,12,34,3,4,64,32,3,32,1,65,16,107,34,5,70,4,64,32,3,40,2,0,33,4,32,5,33,1,11,11,32,2,167,65,112,113,32,1,107,34,3,65,20,73,4,64,15,11,32,1,32,4,65,2,113,32,3,65,8,107,34,3,65,1,114,114,16,1,32,1,65,0,16,2,32,1,65,0,16,3,32,1,65,4,106,32,3,106,34,3,65,2,16,1,32,0,32,3,54,2,160,12,32,0,32,1,16,5,11,29,0,32,0,65,1,65,27,32,0,103,107,116,106,65,1,107,32,0,32,0,65,254,255,255,255,1,73,27,11,142,1,1,2,127,32,1,65,128,2,73,4,127,32,1,65,4,118,5,65,31,32,1,16,7,34,1,103,107,34,3,65,7,107,33,2,32,1,32,3,65,4,107,118,65,16,115,11,33,1,32,0,32,2,65,2,116,106,40,2,4,65,127,32,1,116,113,34,1,4,127,32,0,32,1,104,32,2,65,4,116,106,65,2,116,106,40,2,96,5,32,0,40,2,0,65,127,32,2,65,1,106,116,113,34,1,4,127,32,0,32,0,32,1,104,34,0,65,2,116,106,40,2,4,104,32,0,65,4,116,106,65,2,116,106,40,2,96,5,65,0,11,11,11,148,2,1,3,127,32,1,65,252,255,255,255,3,75,4,64,65,176,14,65,176,15,65,205,3,65,29,16,0,0,11,32,0,65,12,32,1,65,19,106,65,112,113,65,4,107,32,1,65,12,77,27,34,1,16,8,34,2,69,4,64,32,1,65,128,2,79,4,127,32,1,16,7,5,32,1,11,33,2,63,0,34,3,32,2,65,4,32,0,40,2,160,12,32,3,65,16,116,65,4,107,71,116,106,65,255,255,3,106,65,128,128,124,113,65,16,118,34,2,32,2,32,3,72,27,64,0,65,0,72,4,64,32,2,64,0,65,0,72,4,64,0,11,11,32,0,32,3,65,16,116,63,0,172,66,16,134,16,6,32,0,32,1,16,8,33,2,11,32,2,40,2,0,26,32,0,32,2,16,4,32,2,40,2,0,34,3,65,124,113,32,1,107,34,4,65,16,79,4,64,32,2,32,1,32,3,65,2,113,114,16,1,32,2,65,4,106,32,1,106,34,1,32,4,65,4,107,65,1,114,16,1,32,0,32,1,16,5,5,32,2,32,3,65,126,113,16,1,32,2,65,4,106,32,2,40,2,0,65,124,113,106,34,0,32,0,40,2,0,65,125,113,16,1,11,32,2,11,133,2,1,2,127,32,0,65,236,255,255,255,3,75,4,64,65,176,14,65,240,14,65,253,0,65,30,16,0,0,11,35,20,69,4,64,63,0,34,3,65,0,76,4,127,65,1,32,3,107,64,0,65,0,72,5,65,0,11,4,64,0,11,65,208,21,65,0,16,1,65,240,33,65,0,54,2,0,3,64,32,2,65,23,73,4,64,32,2,65,2,116,65,208,21,106,65,0,54,2,4,65,0,33,3,3,64,32,3,65,16,73,4,64,32,2,65,4,116,32,3,106,65,2,116,65,208,21,106,65,0,54,2,96,32,3,65,1,106,33,3,12,1,11,11,32,2,65,1,106,33,2,12,1,11,11,65,208,21,65,244,33,63,0,172,66,16,134,16,6,65,208,21,36,20,11,35,20,32,0,65,16,106,16,9,34,2,32,1,54,2,12,32,2,32,0,54,2,16,35,21,34,0,40,2,8,33,1,32,2,32,0,16,2,32,2,32,1,16,3,32,1,32,2,32,1,40,2,4,65,3,113,114,16,2,32,0,32,2,16,3,35,22,32,2,40,2,0,65,124,113,65,4,106,106,36,22,32,2,65,20,106,11,46,1,1,127,32,0,65,252,255,255,255,3,75,4,64,65,192,13,65,240,13,65,52,65,43,16,0,0,11,32,0,65,1,16,10,34,1,65,0,32,0,252,11,0,32,1,11,41,0,32,1,32,0,40,2,12,79,4,64,65,144,16,65,208,16,65,242,0,65,42,16,0,0,11,32,0,40,2,4,32,1,65,2,116,106,40,2,0,11,181,1,1,4,127,32,0,69,4,64,65,192,18,15,11,65,0,32,0,107,32,0,32,0,65,31,118,65,1,116,34,1,27,34,0,65,10,79,65,1,106,32,0,65,144,206,0,79,65,3,106,32,0,65,232,7,79,106,32,0,65,228,0,73,27,32,0,65,192,132,61,79,65,6,106,32,0,65,128,148,235,220,3,79,65,8,106,32,0,65,128,194,215,47,79,106,32,0,65,128,173,226,4,73,27,32,0,65,160,141,6,73,27,34,2,65,1,116,32,1,106,65,2,16,10,34,3,32,1,106,33,4,3,64,32,4,32,2,65,1,107,34,2,65,1,116,106,32,0,65,10,112,65,48,106,59,1,0,32,0,65,10,110,34,0,13,0,11,32,1,4,64,32,3,65,45,59,1,0,11,32,3,11,13,0,32,0,65,20,107,40,2,16,65,1,118,11,64,1,3,127,32,0,16,14,65,1,116,34,2,32,1,16,14,65,1,116,34,3,106,34,4,69,4,64,65,160,20,15,11,32,4,65,2,16,10,34,4,32,0,32,2,252,10,0,0,32,2,32,4,106,32,1,32,3,252,10,0,0,32,4,11,145,16,2,2,127,1,123,65,224,15,65,224,15,16,2,65,224,15,65,224,15,16,3,65,224,15,36,21,65,128,8,16,11,36,23,35,23,36,24,2,64,3,64,32,0,65,192,0,72,4,64,35,24,33,1,65,192,10,32,0,16,12,253,17,33,2,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,32,0,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,67,11,32,1,32,2,253,11,4,0,12,63,11,32,1,32,2,253,11,4,16,12,62,11,32,1,32,2,253,11,4,32,12,61,11,32,1,32,2,253,11,4,48,12,60,11,32,1,32,2,253,11,4,64,12,59,11,32,1,32,2,253,11,4,80,12,58,11,32,1,32,2,253,11,4,96,12,57,11,32,1,32,2,253,11,4,112,12,56,11,32,1,32,2,253,11,4,128,1,12,55,11,32,1,32,2,253,11,4,144,1,12,54,11,32,1,32,2,253,11,4,160,1,12,53,11,32,1,32,2,253,11,4,176,1,12,52,11,32,1,32,2,253,11,4,192,1,12,51,11,32,1,32,2,253,11,4,208,1,12,50,11,32,1,32,2,253,11,4,224,1,12,49,11,32,1,32,2,253,11,4,240,1,12,48,11,32,1,32,2,253,11,4,128,2,12,47,11,32,1,32,2,253,11,4,144,2,12,46,11,32,1,32,2,253,11,4,160,2,12,45,11,32,1,32,2,253,11,4,176,2,12,44,11,32,1,32,2,253,11,4,192,2,12,43,11,32,1,32,2,253,11,4,208,2,12,42,11,32,1,32,2,253,11,4,224,2,12,41,11,32,1,32,2,253,11,4,240,2,12,40,11,32,1,32,2,253,11,4,128,3,12,39,11,32,1,32,2,253,11,4,144,3,12,38,11,32,1,32,2,253,11,4,160,3,12,37,11,32,1,32,2,253,11,4,176,3,12,36,11,32,1,32,2,253,11,4,192,3,12,35,11,32,1,32,2,253,11,4,208,3,12,34,11,32,1,32,2,253,11,4,224,3,12,33,11,32,1,32,2,253,11,4,240,3,12,32,11,32,1,32,2,253,11,4,128,4,12,31,11,32,1,32,2,253,11,4,144,4,12,30,11,32,1,32,2,253,11,4,160,4,12,29,11,32,1,32,2,253,11,4,176,4,12,28,11,32,1,32,2,253,11,4,192,4,12,27,11,32,1,32,2,253,11,4,208,4,12,26,11,32,1,32,2,253,11,4,224,4,12,25,11,32,1,32,2,253,11,4,240,4,12,24,11,32,1,32,2,253,11,4,128,5,12,23,11,32,1,32,2,253,11,4,144,5,12,22,11,32,1,32,2,253,11,4,160,5,12,21,11,32,1,32,2,253,11,4,176,5,12,20,11,32,1,32,2,253,11,4,192,5,12,19,11,32,1,32,2,253,11,4,208,5,12,18,11,32,1,32,2,253,11,4,224,5,12,17,11,32,1,32,2,253,11,4,240,5,12,16,11,32,1,32,2,253,11,4,128,6,12,15,11,32,1,32,2,253,11,4,144,6,12,14,11,32,1,32,2,253,11,4,160,6,12,13,11,32,1,32,2,253,11,4,176,6,12,12,11,32,1,32,2,253,11,4,192,6,12,11,11,32,1,32,2,253,11,4,208,6,12,10,11,32,1,32,2,253,11,4,224,6,12,9,11,32,1,32,2,253,11,4,240,6,12,8,11,32,1,32,2,253,11,4,128,7,12,7,11,32,1,32,2,253,11,4,144,7,12,6,11,32,1,32,2,253,11,4,160,7,12,5,11,32,1,32,2,253,11,4,176,7,12,4,11,32,1,32,2,253,11,4,192,7,12,3,11,32,1,32,2,253,11,4,208,7,12,2,11,32,1,32,2,253,11,4,224,7,12,1,11,32,1,32,2,253,11,4,240,7,11,32,0,65,1,106,33,0,12,1,11,11,65,128,8,16,11,36,25,35,25,36,26,65,0,33,0,3,64,32,0,65,192,0,72,4,64,35,26,33,1,65,144,13,32,0,16,12,253,17,33,2,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,32,0,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,67,11,32,1,32,2,253,11,4,0,12,63,11,32,1,32,2,253,11,4,16,12,62,11,32,1,32,2,253,11,4,32,12,61,11,32,1,32,2,253,11,4,48,12,60,11,32,1,32,2,253,11,4,64,12,59,11,32,1,32,2,253,11,4,80,12,58,11,32,1,32,2,253,11,4,96,12,57,11,32,1,32,2,253,11,4,112,12,56,11,32,1,32,2,253,11,4,128,1,12,55,11,32,1,32,2,253,11,4,144,1,12,54,11,32,1,32,2,253,11,4,160,1,12,53,11,32,1,32,2,253,11,4,176,1,12,52,11,32,1,32,2,253,11,4,192,1,12,51,11,32,1,32,2,253,11,4,208,1,12,50,11,32,1,32,2,253,11,4,224,1,12,49,11,32,1,32,2,253,11,4,240,1,12,48,11,32,1,32,2,253,11,4,128,2,12,47,11,32,1,32,2,253,11,4,144,2,12,46,11,32,1,32,2,253,11,4,160,2,12,45,11,32,1,32,2,253,11,4,176,2,12,44,11,32,1,32,2,253,11,4,192,2,12,43,11,32,1,32,2,253,11,4,208,2,12,42,11,32,1,32,2,253,11,4,224,2,12,41,11,32,1,32,2,253,11,4,240,2,12,40,11,32,1,32,2,253,11,4,128,3,12,39,11,32,1,32,2,253,11,4,144,3,12,38,11,32,1,32,2,253,11,4,160,3,12,37,11,32,1,32,2,253,11,4,176,3,12,36,11,32,1,32,2,253,11,4,192,3,12,35,11,32,1,32,2,253,11,4,208,3,12,34,11,32,1,32,2,253,11,4,224,3,12,33,11,32,1,32,2,253,11,4,240,3,12,32,11,32,1,32,2,253,11,4,128,4,12,31,11,32,1,32,2,253,11,4,144,4,12,30,11,32,1,32,2,253,11,4,160,4,12,29,11,32,1,32,2,253,11,4,176,4,12,28,11,32,1,32,2,253,11,4,192,4,12,27,11,32,1,32,2,253,11,4,208,4,12,26,11,32,1,32,2,253,11,4,224,4,12,25,11,32,1,32,2,253,11,4,240,4,12,24,11,32,1,32,2,253,11,4,128,5,12,23,11,32,1,32,2,253,11,4,144,5,12,22,11,32,1,32,2,253,11,4,160,5,12,21,11,32,1,32,2,253,11,4,176,5,12,20,11,32,1,32,2,253,11,4,192,5,12,19,11,32,1,32,2,253,11,4,208,5,12,18,11,32,1,32,2,253,11,4,224,5,12,17,11,32,1,32,2,253,11,4,240,5,12,16,11,32,1,32,2,253,11,4,128,6,12,15,11,32,1,32,2,253,11,4,144,6,12,14,11,32,1,32,2,253,11,4,160,6,12,13,11,32,1,32,2,253,11,4,176,6,12,12,11,32,1,32,2,253,11,4,192,6,12,11,11,32,1,32,2,253,11,4,208,6,12,10,11,32,1,32,2,253,11,4,224,6,12,9,11,32,1,32,2,253,11,4,240,6,12,8,11,32,1,32,2,253,11,4,128,7,12,7,11,32,1,32,2,253,11,4,144,7,12,6,11,32,1,32,2,253,11,4,160,7,12,5,11,32,1,32,2,253,11,4,176,7,12,4,11,32,1,32,2,253,11,4,192,7,12,3,11,32,1,32,2,253,11,4,208,7,12,2,11,32,1,32,2,253,11,4,224,7,12,1,11,32,1,32,2,253,11,4,240,7,11,32,0,65,1,106,33,0,12,1,11,11,15,11,65,192,19,32,0,16,13,16,15,65,192,20,65,201,1,65,7,16,0,0,11,192,10,2,2,123,2,127,35,0,36,8,35,1,36,9,35,2,36,10,35,3,36,11,35,4,36,12,35,5,36,13,35,6,36,14,35,7,36,15,65,0,36,18,3,64,35,18,65,192,0,72,4,64,35,15,35,12,34,0,65,6,253,173,1,32,0,65,26,253,171,1,253,80,32,0,65,11,253,173,1,32,0,65,21,253,171,1,253,80,253,81,32,0,65,25,253,173,1,32,0,65,7,253,171,1,253,80,253,81,253,174,1,35,12,34,0,35,13,253,78,32,0,253,77,35,14,253,78,253,81,253,174,1,33,1,35,26,33,2,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,34,3,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,11,32,2,253,0,4,0,33,0,12,64,11,32,2,253,0,4,16,33,0,12,63,11,32,2,253,0,4,32,33,0,12,62,11,32,2,253,0,4,48,33,0,12,61,11,32,2,253,0,4,64,33,0,12,60,11,32,2,253,0,4,80,33,0,12,59,11,32,2,253,0,4,96,33,0,12,58,11,32,2,253,0,4,112,33,0,12,57,11,32,2,253,0,4,128,1,33,0,12,56,11,32,2,253,0,4,144,1,33,0,12,55,11,32,2,253,0,4,160,1,33,0,12,54,11,32,2,253,0,4,176,1,33,0,12,53,11,32,2,253,0,4,192,1,33,0,12,52,11,32,2,253,0,4,208,1,33,0,12,51,11,32,2,253,0,4,224,1,33,0,12,50,11,32,2,253,0,4,240,1,33,0,12,49,11,32,2,253,0,4,128,2,33,0,12,48,11,32,2,253,0,4,144,2,33,0,12,47,11,32,2,253,0,4,160,2,33,0,12,46,11,32,2,253,0,4,176,2,33,0,12,45,11,32,2,253,0,4,192,2,33,0,12,44,11,32,2,253,0,4,208,2,33,0,12,43,11,32,2,253,0,4,224,2,33,0,12,42,11,32,2,253,0,4,240,2,33,0,12,41,11,32,2,253,0,4,128,3,33,0,12,40,11,32,2,253,0,4,144,3,33,0,12,39,11,32,2,253,0,4,160,3,33,0,12,38,11,32,2,253,0,4,176,3,33,0,12,37,11,32,2,253,0,4,192,3,33,0,12,36,11,32,2,253,0,4,208,3,33,0,12,35,11,32,2,253,0,4,224,3,33,0,12,34,11,32,2,253,0,4,240,3,33,0,12,33,11,32,2,253,0,4,128,4,33,0,12,32,11,32,2,253,0,4,144,4,33,0,12,31,11,32,2,253,0,4,160,4,33,0,12,30,11,32,2,253,0,4,176,4,33,0,12,29,11,32,2,253,0,4,192,4,33,0,12,28,11,32,2,253,0,4,208,4,33,0,12,27,11,32,2,253,0,4,224,4,33,0,12,26,11,32,2,253,0,4,240,4,33,0,12,25,11,32,2,253,0,4,128,5,33,0,12,24,11,32,2,253,0,4,144,5,33,0,12,23,11,32,2,253,0,4,160,5,33,0,12,22,11,32,2,253,0,4,176,5,33,0,12,21,11,32,2,253,0,4,192,5,33,0,12,20,11,32,2,253,0,4,208,5,33,0,12,19,11,32,2,253,0,4,224,5,33,0,12,18,11,32,2,253,0,4,240,5,33,0,12,17,11,32,2,253,0,4,128,6,33,0,12,16,11,32,2,253,0,4,144,6,33,0,12,15,11,32,2,253,0,4,160,6,33,0,12,14,11,32,2,253,0,4,176,6,33,0,12,13,11,32,2,253,0,4,192,6,33,0,12,12,11,32,2,253,0,4,208,6,33,0,12,11,11,32,2,253,0,4,224,6,33,0,12,10,11,32,2,253,0,4,240,6,33,0,12,9,11,32,2,253,0,4,128,7,33,0,12,8,11,32,2,253,0,4,144,7,33,0,12,7,11,32,2,253,0,4,160,7,33,0,12,6,11,32,2,253,0,4,176,7,33,0,12,5,11,32,2,253,0,4,192,7,33,0,12,4,11,32,2,253,0,4,208,7,33,0,12,3,11,32,2,253,0,4,224,7,33,0,12,2,11,32,2,253,0,4,240,7,33,0,12,1,11,65,128,21,32,3,16,13,16,15,65,192,20,65,213,2,65,7,16,0,0,11,32,1,32,0,253,174,1,36,16,35,8,34,0,65,2,253,173,1,32,0,65,30,253,171,1,253,80,32,0,65,13,253,173,1,32,0,65,19,253,171,1,253,80,253,81,32,0,65,22,253,173,1,32,0,65,10,253,171,1,253,80,253,81,35,8,34,0,35,9,34,1,253,78,32,0,35,10,34,0,253,78,253,81,32,1,32,0,253,78,253,81,253,174,1,36,17,35,14,36,15,35,13,36,14,35,12,36,13,35,11,35,16,253,174,1,36,12,35,10,36,11,35,9,36,10,35,8,36,9,35,16,35,17,253,174,1,36,8,35,18,65,1,106,36,18,12,1,11,11,35,0,35,8,253,174,1,36,0,35,1,35,9,253,174,1,36,1,35,2,35,10,253,174,1,36,2,35,3,35,11,253,174,1,36,3,35,4,35,12,253,174,1,36,4,35,5,35,13,253,174,1,36,5,35,6,35,14,253,174,1,36,6,35,7,35,15,253,174,1,36,7,11,25,0,32,0,65,128,254,131,120,113,65,8,119,32,0,65,255,129,252,7,113,65,8,120,114,11,157,57,2,2,123,2,127,253,12,103,230,9,106,103,230,9,106,103,230,9,106,103,230,9,106,36,0,253,12,133,174,103,187,133,174,103,187,133,174,103,187,133,174,103,187,36,1,253,12,114,243,110,60,114,243,110,60,114,243,110,60,114,243,110,60,36,2,253,12,58,245,79,165,58,245,79,165,58,245,79,165,58,245,79,165,36,3,253,12,127,82,14,81,127,82,14,81,127,82,14,81,127,82,14,81,36,4,253,12,140,104,5,155,140,104,5,155,140,104,5,155,140,104,5,155,36,5,253,12,171,217,131,31,171,217,131,31,171,217,131,31,171,217,131,31,36,6,253,12,25,205,224,91,25,205,224,91,25,205,224,91,25,205,224,91,36,7,253,12,103,230,9,106,103,230,9,106,103,230,9,106,103,230,9,106,36,8,253,12,133,174,103,187,133,174,103,187,133,174,103,187,133,174,103,187,36,9,253,12,114,243,110,60,114,243,110,60,114,243,110,60,114,243,110,60,36,10,253,12,58,245,79,165,58,245,79,165,58,245,79,165,58,245,79,165,36,11,253,12,127,82,14,81,127,82,14,81,127,82,14,81,127,82,14,81,36,12,253,12,140,104,5,155,140,104,5,155,140,104,5,155,140,104,5,155,36,13,253,12,171,217,131,31,171,217,131,31,171,217,131,31,171,217,131,31,36,14,253,12,25,205,224,91,25,205,224,91,25,205,224,91,25,205,224,91,36,15,65,0,36,18,2,64,3,64,35,18,65,192,0,72,4,64,35,18,65,16,72,4,123,2,123,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,34,4,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,68,11,32,0,253,0,4,0,12,63,11,32,0,253,0,4,16,12,62,11,32,0,253,0,4,32,12,61,11,32,0,253,0,4,48,12,60,11,32,0,253,0,4,64,12,59,11,32,0,253,0,4,80,12,58,11,32,0,253,0,4,96,12,57,11,32,0,253,0,4,112,12,56,11,32,0,253,0,4,128,1,12,55,11,32,0,253,0,4,144,1,12,54,11,32,0,253,0,4,160,1,12,53,11,32,0,253,0,4,176,1,12,52,11,32,0,253,0,4,192,1,12,51,11,32,0,253,0,4,208,1,12,50,11,32,0,253,0,4,224,1,12,49,11,32,0,253,0,4,240,1,12,48,11,32,0,253,0,4,128,2,12,47,11,32,0,253,0,4,144,2,12,46,11,32,0,253,0,4,160,2,12,45,11,32,0,253,0,4,176,2,12,44,11,32,0,253,0,4,192,2,12,43,11,32,0,253,0,4,208,2,12,42,11,32,0,253,0,4,224,2,12,41,11,32,0,253,0,4,240,2,12,40,11,32,0,253,0,4,128,3,12,39,11,32,0,253,0,4,144,3,12,38,11,32,0,253,0,4,160,3,12,37,11,32,0,253,0,4,176,3,12,36,11,32,0,253,0,4,192,3,12,35,11,32,0,253,0,4,208,3,12,34,11,32,0,253,0,4,224,3,12,33,11,32,0,253,0,4,240,3,12,32,11,32,0,253,0,4,128,4,12,31,11,32,0,253,0,4,144,4,12,30,11,32,0,253,0,4,160,4,12,29,11,32,0,253,0,4,176,4,12,28,11,32,0,253,0,4,192,4,12,27,11,32,0,253,0,4,208,4,12,26,11,32,0,253,0,4,224,4,12,25,11,32,0,253,0,4,240,4,12,24,11,32,0,253,0,4,128,5,12,23,11,32,0,253,0,4,144,5,12,22,11,32,0,253,0,4,160,5,12,21,11,32,0,253,0,4,176,5,12,20,11,32,0,253,0,4,192,5,12,19,11,32,0,253,0,4,208,5,12,18,11,32,0,253,0,4,224,5,12,17,11,32,0,253,0,4,240,5,12,16,11,32,0,253,0,4,128,6,12,15,11,32,0,253,0,4,144,6,12,14,11,32,0,253,0,4,160,6,12,13,11,32,0,253,0,4,176,6,12,12,11,32,0,253,0,4,192,6,12,11,11,32,0,253,0,4,208,6,12,10,11,32,0,253,0,4,224,6,12,9,11,32,0,253,0,4,240,6,12,8,11,32,0,253,0,4,128,7,12,7,11,32,0,253,0,4,144,7,12,6,11,32,0,253,0,4,160,7,12,5,11,32,0,253,0,4,176,7,12,4,11,32,0,253,0,4,192,7,12,3,11,32,0,253,0,4,208,7,12,2,11,32,0,253,0,4,224,7,12,1,11,32,0,253,0,4,240,7,11,5,2,123,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,65,2,107,34,4,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,68,11,32,0,253,0,4,0,12,63,11,32,0,253,0,4,16,12,62,11,32,0,253,0,4,32,12,61,11,32,0,253,0,4,48,12,60,11,32,0,253,0,4,64,12,59,11,32,0,253,0,4,80,12,58,11,32,0,253,0,4,96,12,57,11,32,0,253,0,4,112,12,56,11,32,0,253,0,4,128,1,12,55,11,32,0,253,0,4,144,1,12,54,11,32,0,253,0,4,160,1,12,53,11,32,0,253,0,4,176,1,12,52,11,32,0,253,0,4,192,1,12,51,11,32,0,253,0,4,208,1,12,50,11,32,0,253,0,4,224,1,12,49,11,32,0,253,0,4,240,1,12,48,11,32,0,253,0,4,128,2,12,47,11,32,0,253,0,4,144,2,12,46,11,32,0,253,0,4,160,2,12,45,11,32,0,253,0,4,176,2,12,44,11,32,0,253,0,4,192,2,12,43,11,32,0,253,0,4,208,2,12,42,11,32,0,253,0,4,224,2,12,41,11,32,0,253,0,4,240,2,12,40,11,32,0,253,0,4,128,3,12,39,11,32,0,253,0,4,144,3,12,38,11,32,0,253,0,4,160,3,12,37,11,32,0,253,0,4,176,3,12,36,11,32,0,253,0,4,192,3,12,35,11,32,0,253,0,4,208,3,12,34,11,32,0,253,0,4,224,3,12,33,11,32,0,253,0,4,240,3,12,32,11,32,0,253,0,4,128,4,12,31,11,32,0,253,0,4,144,4,12,30,11,32,0,253,0,4,160,4,12,29,11,32,0,253,0,4,176,4,12,28,11,32,0,253,0,4,192,4,12,27,11,32,0,253,0,4,208,4,12,26,11,32,0,253,0,4,224,4,12,25,11,32,0,253,0,4,240,4,12,24,11,32,0,253,0,4,128,5,12,23,11,32,0,253,0,4,144,5,12,22,11,32,0,253,0,4,160,5,12,21,11,32,0,253,0,4,176,5,12,20,11,32,0,253,0,4,192,5,12,19,11,32,0,253,0,4,208,5,12,18,11,32,0,253,0,4,224,5,12,17,11,32,0,253,0,4,240,5,12,16,11,32,0,253,0,4,128,6,12,15,11,32,0,253,0,4,144,6,12,14,11,32,0,253,0,4,160,6,12,13,11,32,0,253,0,4,176,6,12,12,11,32,0,253,0,4,192,6,12,11,11,32,0,253,0,4,208,6,12,10,11,32,0,253,0,4,224,6,12,9,11,32,0,253,0,4,240,6,12,8,11,32,0,253,0,4,128,7,12,7,11,32,0,253,0,4,144,7,12,6,11,32,0,253,0,4,160,7,12,5,11,32,0,253,0,4,176,7,12,4,11,32,0,253,0,4,192,7,12,3,11,32,0,253,0,4,208,7,12,2,11,32,0,253,0,4,224,7,12,1,11,32,0,253,0,4,240,7,11,34,2,65,17,253,173,1,32,2,65,15,253,171,1,253,80,32,2,65,19,253,173,1,32,2,65,13,253,171,1,253,80,253,81,32,2,65,10,253,173,1,253,81,2,123,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,65,7,107,34,4,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,68,11,32,0,253,0,4,0,12,63,11,32,0,253,0,4,16,12,62,11,32,0,253,0,4,32,12,61,11,32,0,253,0,4,48,12,60,11,32,0,253,0,4,64,12,59,11,32,0,253,0,4,80,12,58,11,32,0,253,0,4,96,12,57,11,32,0,253,0,4,112,12,56,11,32,0,253,0,4,128,1,12,55,11,32,0,253,0,4,144,1,12,54,11,32,0,253,0,4,160,1,12,53,11,32,0,253,0,4,176,1,12,52,11,32,0,253,0,4,192,1,12,51,11,32,0,253,0,4,208,1,12,50,11,32,0,253,0,4,224,1,12,49,11,32,0,253,0,4,240,1,12,48,11,32,0,253,0,4,128,2,12,47,11,32,0,253,0,4,144,2,12,46,11,32,0,253,0,4,160,2,12,45,11,32,0,253,0,4,176,2,12,44,11,32,0,253,0,4,192,2,12,43,11,32,0,253,0,4,208,2,12,42,11,32,0,253,0,4,224,2,12,41,11,32,0,253,0,4,240,2,12,40,11,32,0,253,0,4,128,3,12,39,11,32,0,253,0,4,144,3,12,38,11,32,0,253,0,4,160,3,12,37,11,32,0,253,0,4,176,3,12,36,11,32,0,253,0,4,192,3,12,35,11,32,0,253,0,4,208,3,12,34,11,32,0,253,0,4,224,3,12,33,11,32,0,253,0,4,240,3,12,32,11,32,0,253,0,4,128,4,12,31,11,32,0,253,0,4,144,4,12,30,11,32,0,253,0,4,160,4,12,29,11,32,0,253,0,4,176,4,12,28,11,32,0,253,0,4,192,4,12,27,11,32,0,253,0,4,208,4,12,26,11,32,0,253,0,4,224,4,12,25,11,32,0,253,0,4,240,4,12,24,11,32,0,253,0,4,128,5,12,23,11,32,0,253,0,4,144,5,12,22,11,32,0,253,0,4,160,5,12,21,11,32,0,253,0,4,176,5,12,20,11,32,0,253,0,4,192,5,12,19,11,32,0,253,0,4,208,5,12,18,11,32,0,253,0,4,224,5,12,17,11,32,0,253,0,4,240,5,12,16,11,32,0,253,0,4,128,6,12,15,11,32,0,253,0,4,144,6,12,14,11,32,0,253,0,4,160,6,12,13,11,32,0,253,0,4,176,6,12,12,11,32,0,253,0,4,192,6,12,11,11,32,0,253,0,4,208,6,12,10,11,32,0,253,0,4,224,6,12,9,11,32,0,253,0,4,240,6,12,8,11,32,0,253,0,4,128,7,12,7,11,32,0,253,0,4,144,7,12,6,11,32,0,253,0,4,160,7,12,5,11,32,0,253,0,4,176,7,12,4,11,32,0,253,0,4,192,7,12,3,11,32,0,253,0,4,208,7,12,2,11,32,0,253,0,4,224,7,12,1,11,32,0,253,0,4,240,7,11,253,174,1,2,123,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,65,15,107,34,4,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,68,11,32,0,253,0,4,0,12,63,11,32,0,253,0,4,16,12,62,11,32,0,253,0,4,32,12,61,11,32,0,253,0,4,48,12,60,11,32,0,253,0,4,64,12,59,11,32,0,253,0,4,80,12,58,11,32,0,253,0,4,96,12,57,11,32,0,253,0,4,112,12,56,11,32,0,253,0,4,128,1,12,55,11,32,0,253,0,4,144,1,12,54,11,32,0,253,0,4,160,1,12,53,11,32,0,253,0,4,176,1,12,52,11,32,0,253,0,4,192,1,12,51,11,32,0,253,0,4,208,1,12,50,11,32,0,253,0,4,224,1,12,49,11,32,0,253,0,4,240,1,12,48,11,32,0,253,0,4,128,2,12,47,11,32,0,253,0,4,144,2,12,46,11,32,0,253,0,4,160,2,12,45,11,32,0,253,0,4,176,2,12,44,11,32,0,253,0,4,192,2,12,43,11,32,0,253,0,4,208,2,12,42,11,32,0,253,0,4,224,2,12,41,11,32,0,253,0,4,240,2,12,40,11,32,0,253,0,4,128,3,12,39,11,32,0,253,0,4,144,3,12,38,11,32,0,253,0,4,160,3,12,37,11,32,0,253,0,4,176,3,12,36,11,32,0,253,0,4,192,3,12,35,11,32,0,253,0,4,208,3,12,34,11,32,0,253,0,4,224,3,12,33,11,32,0,253,0,4,240,3,12,32,11,32,0,253,0,4,128,4,12,31,11,32,0,253,0,4,144,4,12,30,11,32,0,253,0,4,160,4,12,29,11,32,0,253,0,4,176,4,12,28,11,32,0,253,0,4,192,4,12,27,11,32,0,253,0,4,208,4,12,26,11,32,0,253,0,4,224,4,12,25,11,32,0,253,0,4,240,4,12,24,11,32,0,253,0,4,128,5,12,23,11,32,0,253,0,4,144,5,12,22,11,32,0,253,0,4,160,5,12,21,11,32,0,253,0,4,176,5,12,20,11,32,0,253,0,4,192,5,12,19,11,32,0,253,0,4,208,5,12,18,11,32,0,253,0,4,224,5,12,17,11,32,0,253,0,4,240,5,12,16,11,32,0,253,0,4,128,6,12,15,11,32,0,253,0,4,144,6,12,14,11,32,0,253,0,4,160,6,12,13,11,32,0,253,0,4,176,6,12,12,11,32,0,253,0,4,192,6,12,11,11,32,0,253,0,4,208,6,12,10,11,32,0,253,0,4,224,6,12,9,11,32,0,253,0,4,240,6,12,8,11,32,0,253,0,4,128,7,12,7,11,32,0,253,0,4,144,7,12,6,11,32,0,253,0,4,160,7,12,5,11,32,0,253,0,4,176,7,12,4,11,32,0,253,0,4,192,7,12,3,11,32,0,253,0,4,208,7,12,2,11,32,0,253,0,4,224,7,12,1,11,32,0,253,0,4,240,7,11,34,2,65,7,253,173,1,32,2,65,25,253,171,1,253,80,32,2,65,18,253,173,1,32,2,65,14,253,171,1,253,80,253,81,32,2,65,3,253,173,1,253,81,253,174,1,2,123,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,65,16,107,34,4,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,68,11,32,0,253,0,4,0,12,63,11,32,0,253,0,4,16,12,62,11,32,0,253,0,4,32,12,61,11,32,0,253,0,4,48,12,60,11,32,0,253,0,4,64,12,59,11,32,0,253,0,4,80,12,58,11,32,0,253,0,4,96,12,57,11,32,0,253,0,4,112,12,56,11,32,0,253,0,4,128,1,12,55,11,32,0,253,0,4,144,1,12,54,11,32,0,253,0,4,160,1,12,53,11,32,0,253,0,4,176,1,12,52,11,32,0,253,0,4,192,1,12,51,11,32,0,253,0,4,208,1,12,50,11,32,0,253,0,4,224,1,12,49,11,32,0,253,0,4,240,1,12,48,11,32,0,253,0,4,128,2,12,47,11,32,0,253,0,4,144,2,12,46,11,32,0,253,0,4,160,2,12,45,11,32,0,253,0,4,176,2,12,44,11,32,0,253,0,4,192,2,12,43,11,32,0,253,0,4,208,2,12,42,11,32,0,253,0,4,224,2,12,41,11,32,0,253,0,4,240,2,12,40,11,32,0,253,0,4,128,3,12,39,11,32,0,253,0,4,144,3,12,38,11,32,0,253,0,4,160,3,12,37,11,32,0,253,0,4,176,3,12,36,11,32,0,253,0,4,192,3,12,35,11,32,0,253,0,4,208,3,12,34,11,32,0,253,0,4,224,3,12,33,11,32,0,253,0,4,240,3,12,32,11,32,0,253,0,4,128,4,12,31,11,32,0,253,0,4,144,4,12,30,11,32,0,253,0,4,160,4,12,29,11,32,0,253,0,4,176,4,12,28,11,32,0,253,0,4,192,4,12,27,11,32,0,253,0,4,208,4,12,26,11,32,0,253,0,4,224,4,12,25,11,32,0,253,0,4,240,4,12,24,11,32,0,253,0,4,128,5,12,23,11,32,0,253,0,4,144,5,12,22,11,32,0,253,0,4,160,5,12,21,11,32,0,253,0,4,176,5,12,20,11,32,0,253,0,4,192,5,12,19,11,32,0,253,0,4,208,5,12,18,11,32,0,253,0,4,224,5,12,17,11,32,0,253,0,4,240,5,12,16,11,32,0,253,0,4,128,6,12,15,11,32,0,253,0,4,144,6,12,14,11,32,0,253,0,4,160,6,12,13,11,32,0,253,0,4,176,6,12,12,11,32,0,253,0,4,192,6,12,11,11,32,0,253,0,4,208,6,12,10,11,32,0,253,0,4,224,6,12,9,11,32,0,253,0,4,240,6,12,8,11,32,0,253,0,4,128,7,12,7,11,32,0,253,0,4,144,7,12,6,11,32,0,253,0,4,160,7,12,5,11,32,0,253,0,4,176,7,12,4,11,32,0,253,0,4,192,7,12,3,11,32,0,253,0,4,208,7,12,2,11,32,0,253,0,4,224,7,12,1,11,32,0,253,0,4,240,7,11,253,174,1,11,36,19,35,18,65,16,78,4,64,35,19,33,2,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,34,4,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,11,32,0,32,2,253,11,4,0,12,64,11,32,0,32,2,253,11,4,16,12,63,11,32,0,32,2,253,11,4,32,12,62,11,32,0,32,2,253,11,4,48,12,61,11,32,0,32,2,253,11,4,64,12,60,11,32,0,32,2,253,11,4,80,12,59,11,32,0,32,2,253,11,4,96,12,58,11,32,0,32,2,253,11,4,112,12,57,11,32,0,32,2,253,11,4,128,1,12,56,11,32,0,32,2,253,11,4,144,1,12,55,11,32,0,32,2,253,11,4,160,1,12,54,11,32,0,32,2,253,11,4,176,1,12,53,11,32,0,32,2,253,11,4,192,1,12,52,11,32,0,32,2,253,11,4,208,1,12,51,11,32,0,32,2,253,11,4,224,1,12,50,11,32,0,32,2,253,11,4,240,1,12,49,11,32,0,32,2,253,11,4,128,2,12,48,11,32,0,32,2,253,11,4,144,2,12,47,11,32,0,32,2,253,11,4,160,2,12,46,11,32,0,32,2,253,11,4,176,2,12,45,11,32,0,32,2,253,11,4,192,2,12,44,11,32,0,32,2,253,11,4,208,2,12,43,11,32,0,32,2,253,11,4,224,2,12,42,11,32,0,32,2,253,11,4,240,2,12,41,11,32,0,32,2,253,11,4,128,3,12,40,11,32,0,32,2,253,11,4,144,3,12,39,11,32,0,32,2,253,11,4,160,3,12,38,11,32,0,32,2,253,11,4,176,3,12,37,11,32,0,32,2,253,11,4,192,3,12,36,11,32,0,32,2,253,11,4,208,3,12,35,11,32,0,32,2,253,11,4,224,3,12,34,11,32,0,32,2,253,11,4,240,3,12,33,11,32,0,32,2,253,11,4,128,4,12,32,11,32,0,32,2,253,11,4,144,4,12,31,11,32,0,32,2,253,11,4,160,4,12,30,11,32,0,32,2,253,11,4,176,4,12,29,11,32,0,32,2,253,11,4,192,4,12,28,11,32,0,32,2,253,11,4,208,4,12,27,11,32,0,32,2,253,11,4,224,4,12,26,11,32,0,32,2,253,11,4,240,4,12,25,11,32,0,32,2,253,11,4,128,5,12,24,11,32,0,32,2,253,11,4,144,5,12,23,11,32,0,32,2,253,11,4,160,5,12,22,11,32,0,32,2,253,11,4,176,5,12,21,11,32,0,32,2,253,11,4,192,5,12,20,11,32,0,32,2,253,11,4,208,5,12,19,11,32,0,32,2,253,11,4,224,5,12,18,11,32,0,32,2,253,11,4,240,5,12,17,11,32,0,32,2,253,11,4,128,6,12,16,11,32,0,32,2,253,11,4,144,6,12,15,11,32,0,32,2,253,11,4,160,6,12,14,11,32,0,32,2,253,11,4,176,6,12,13,11,32,0,32,2,253,11,4,192,6,12,12,11,32,0,32,2,253,11,4,208,6,12,11,11,32,0,32,2,253,11,4,224,6,12,10,11,32,0,32,2,253,11,4,240,6,12,9,11,32,0,32,2,253,11,4,128,7,12,8,11,32,0,32,2,253,11,4,144,7,12,7,11,32,0,32,2,253,11,4,160,7,12,6,11,32,0,32,2,253,11,4,176,7,12,5,11,32,0,32,2,253,11,4,192,7,12,4,11,32,0,32,2,253,11,4,208,7,12,3,11,32,0,32,2,253,11,4,224,7,12,2,11,32,0,32,2,253,11,4,240,7,12,1,11,65,192,19,32,4,16,13,16,15,65,192,20,65,201,1,65,7,16,0,0,11,11,35,15,35,12,34,2,65,6,253,173,1,32,2,65,26,253,171,1,253,80,32,2,65,11,253,173,1,32,2,65,21,253,171,1,253,80,253,81,32,2,65,25,253,173,1,32,2,65,7,253,171,1,253,80,253,81,253,174,1,35,12,34,2,35,13,253,78,32,2,253,77,35,14,253,78,253,81,253,174,1,33,3,35,24,33,4,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,34,5,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,11,32,4,253,0,4,0,33,2,12,64,11,32,4,253,0,4,16,33,2,12,63,11,32,4,253,0,4,32,33,2,12,62,11,32,4,253,0,4,48,33,2,12,61,11,32,4,253,0,4,64,33,2,12,60,11,32,4,253,0,4,80,33,2,12,59,11,32,4,253,0,4,96,33,2,12,58,11,32,4,253,0,4,112,33,2,12,57,11,32,4,253,0,4,128,1,33,2,12,56,11,32,4,253,0,4,144,1,33,2,12,55,11,32,4,253,0,4,160,1,33,2,12,54,11,32,4,253,0,4,176,1,33,2,12,53,11,32,4,253,0,4,192,1,33,2,12,52,11,32,4,253,0,4,208,1,33,2,12,51,11,32,4,253,0,4,224,1,33,2,12,50,11,32,4,253,0,4,240,1,33,2,12,49,11,32,4,253,0,4,128,2,33,2,12,48,11,32,4,253,0,4,144,2,33,2,12,47,11,32,4,253,0,4,160,2,33,2,12,46,11,32,4,253,0,4,176,2,33,2,12,45,11,32,4,253,0,4,192,2,33,2,12,44,11,32,4,253,0,4,208,2,33,2,12,43,11,32,4,253,0,4,224,2,33,2,12,42,11,32,4,253,0,4,240,2,33,2,12,41,11,32,4,253,0,4,128,3,33,2,12,40,11,32,4,253,0,4,144,3,33,2,12,39,11,32,4,253,0,4,160,3,33,2,12,38,11,32,4,253,0,4,176,3,33,2,12,37,11,32,4,253,0,4,192,3,33,2,12,36,11,32,4,253,0,4,208,3,33,2,12,35,11,32,4,253,0,4,224,3,33,2,12,34,11,32,4,253,0,4,240,3,33,2,12,33,11,32,4,253,0,4,128,4,33,2,12,32,11,32,4,253,0,4,144,4,33,2,12,31,11,32,4,253,0,4,160,4,33,2,12,30,11,32,4,253,0,4,176,4,33,2,12,29,11,32,4,253,0,4,192,4,33,2,12,28,11,32,4,253,0,4,208,4,33,2,12,27,11,32,4,253,0,4,224,4,33,2,12,26,11,32,4,253,0,4,240,4,33,2,12,25,11,32,4,253,0,4,128,5,33,2,12,24,11,32,4,253,0,4,144,5,33,2,12,23,11,32,4,253,0,4,160,5,33,2,12,22,11,32,4,253,0,4,176,5,33,2,12,21,11,32,4,253,0,4,192,5,33,2,12,20,11,32,4,253,0,4,208,5,33,2,12,19,11,32,4,253,0,4,224,5,33,2,12,18,11,32,4,253,0,4,240,5,33,2,12,17,11,32,4,253,0,4,128,6,33,2,12,16,11,32,4,253,0,4,144,6,33,2,12,15,11,32,4,253,0,4,160,6,33,2,12,14,11,32,4,253,0,4,176,6,33,2,12,13,11,32,4,253,0,4,192,6,33,2,12,12,11,32,4,253,0,4,208,6,33,2,12,11,11,32,4,253,0,4,224,6,33,2,12,10,11,32,4,253,0,4,240,6,33,2,12,9,11,32,4,253,0,4,128,7,33,2,12,8,11,32,4,253,0,4,144,7,33,2,12,7,11,32,4,253,0,4,160,7,33,2,12,6,11,32,4,253,0,4,176,7,33,2,12,5,11,32,4,253,0,4,192,7,33,2,12,4,11,32,4,253,0,4,208,7,33,2,12,3,11,32,4,253,0,4,224,7,33,2,12,2,11,32,4,253,0,4,240,7,33,2,12,1,11,65,128,21,32,5,16,13,16,15,65,192,20,65,213,2,65,7,16,0,0,11,32,3,32,2,253,174,1,35,19,253,174,1,36,16,35,8,34,2,65,2,253,173,1,32,2,65,30,253,171,1,253,80,32,2,65,13,253,173,1,32,2,65,19,253,171,1,253,80,253,81,32,2,65,22,253,173,1,32,2,65,10,253,171,1,253,80,253,81,35,8,34,2,35,9,34,3,253,78,32,2,35,10,34,2,253,78,253,81,32,3,32,2,253,78,253,81,253,174,1,36,17,35,14,36,15,35,13,36,14,35,12,36,13,35,11,35,16,253,174,1,36,12,35,10,36,11,35,9,36,10,35,8,36,9,35,16,35,17,253,174,1,36,8,35,18,65,1,106,36,18,12,1,11,11,35,0,35,8,253,174,1,36,0,35,1,35,9,253,174,1,36,1,35,2,35,10,253,174,1,36,2,35,3,35,11,253,174,1,36,3,35,4,35,12,253,174,1,36,4,35,5,35,13,253,174,1,36,5,35,6,35,14,253,174,1,36,6,35,7,35,15,253,174,1,36,7,16,17,32,1,35,0,253,27,0,16,18,54,2,0,32,1,35,1,253,27,0,16,18,54,2,4,32,1,35,2,253,27,0,16,18,54,2,8,32,1,35,3,253,27,0,16,18,54,2,12,32,1,35,4,253,27,0,16,18,54,2,16,32,1,35,5,253,27,0,16,18,54,2,20,32,1,35,6,253,27,0,16,18,54,2,24,32,1,35,7,253,27,0,16,18,54,2,28,32,1,35,0,253,27,1,16,18,54,2,32,32,1,35,1,253,27,1,16,18,54,2,36,32,1,35,2,253,27,1,16,18,54,2,40,32,1,35,3,253,27,1,16,18,54,2,44,32,1,35,4,253,27,1,16,18,54,2,48,32,1,35,5,253,27,1,16,18,54,2,52,32,1,35,6,253,27,1,16,18,54,2,56,32,1,35,7,253,27,1,16,18,54,2,60,32,1,65,64,107,35,0,253,27,2,16,18,54,2,0,32,1,35,1,253,27,2,16,18,54,2,68,32,1,35,2,253,27,2,16,18,54,2,72,32,1,35,3,253,27,2,16,18,54,2,76,32,1,35,4,253,27,2,16,18,54,2,80,32,1,35,5,253,27,2,16,18,54,2,84,32,1,35,6,253,27,2,16,18,54,2,88,32,1,35,7,253,27,2,16,18,54,2,92,32,1,35,0,253,27,3,16,18,54,2,96,32,1,35,1,253,27,3,16,18,54,2,100,32,1,35,2,253,27,3,16,18,54,2,104,32,1,35,3,253,27,3,16,18,54,2,108,32,1,35,4,253,27,3,16,18,54,2,112,32,1,35,5,253,27,3,16,18,54,2,116,32,1,35,6,253,27,3,16,18,54,2,120,32,1,35,7,253,27,3,16,18,54,2,124,15,11,65,128,21,32,4,16,13,16,15,65,192,20,65,213,2,65,7,16,0,0,11,203,2,1,5,127,3,64,32,1,65,16,72,4,64,32,1,65,2,116,34,2,65,1,106,33,3,35,53,32,2,65,2,116,106,32,2,65,3,106,34,4,35,55,34,5,106,45,0,0,32,2,32,5,106,45,0,0,65,24,116,32,3,32,5,106,45,0,0,65,16,116,114,32,2,65,2,106,34,2,32,5,106,45,0,0,65,8,116,114,114,54,2,0,35,53,32,3,65,2,116,106,35,55,34,3,32,1,65,16,106,65,2,116,34,5,65,3,106,106,45,0,0,32,3,32,5,106,45,0,0,65,24,116,32,5,65,1,106,32,3,106,45,0,0,65,16,116,114,32,5,65,2,106,32,3,106,45,0,0,65,8,116,114,114,54,2,0,35,53,32,2,65,2,116,106,35,55,34,2,32,1,65,32,106,65,2,116,34,3,65,3,106,106,45,0,0,32,2,32,3,106,45,0,0,65,24,116,32,3,65,1,106,32,2,106,45,0,0,65,16,116,114,32,3,65,2,106,32,2,106,45,0,0,65,8,116,114,114,54,2,0,35,53,32,4,65,2,116,106,35,55,34,2,32,1,65,48,106,65,2,116,34,3,65,3,106,106,45,0,0,32,2,32,3,106,45,0,0,65,24,116,32,3,65,1,106,32,2,106,45,0,0,65,16,116,114,32,3,65,2,106,32,2,106,45,0,0,65,8,116,114,114,54,2,0,32,1,65,1,106,33,1,12,1,11,11,35,53,32,0,16,19,11,99,1,3,127,3,64,32,2,65,192,0,72,4,64,32,2,65,2,116,34,1,35,53,106,35,55,34,3,32,1,65,3,106,106,45,0,0,32,1,32,3,106,45,0,0,65,24,116,32,1,65,1,106,32,3,106,45,0,0,65,16,116,114,32,1,65,2,106,32,3,106,45,0,0,65,8,116,114,114,54,2,0,32,2,65,1,106,33,2,12,1,11,11,35,53,32,0,16,19,11,74,0,65,231,204,167,208,6,36,31,65,133,221,158,219,123,36,32,65,242,230,187,227,3,36,33,65,186,234,191,170,122,36,34,65,255,164,185,136,5,36,35,65,140,209,149,216,121,36,36,65,171,179,143,252,1,36,37,65,153,154,131,223,5,36,38,65,0,36,58,65,0,36,59,11,227,3,1,2,127,35,31,36,39,35,32,36,40,35,33,36,41,35,34,36,42,35,35,36,43,35,36,36,44,35,37,36,45,35,38,36,46,65,0,36,47,3,64,35,47,65,16,73,4,64,35,47,65,2,116,34,2,32,0,106,32,1,32,2,65,3,106,106,45,0,0,32,1,32,2,106,45,0,0,65,24,116,32,1,32,2,65,1,106,106,45,0,0,65,16,116,114,32,1,32,2,65,2,106,106,45,0,0,65,8,116,114,114,54,2,0,35,47,65,1,106,36,47,12,1,11,11,65,16,36,47,3,64,35,47,65,192,0,73,4,64,32,0,35,47,65,2,116,106,32,0,35,47,65,16,107,65,2,116,106,40,2,0,32,0,35,47,65,7,107,65,2,116,106,40,2,0,32,0,35,47,65,2,107,65,2,116,106,40,2,0,34,1,65,17,120,32,1,65,19,120,115,32,1,65,10,118,115,106,32,0,35,47,65,15,107,65,2,116,106,40,2,0,34,1,65,7,120,32,1,65,18,120,115,32,1,65,3,118,115,106,106,54,2,0,35,47,65,1,106,36,47,12,1,11,11,65,0,36,47,3,64,35,47,65,192,0,73,4,64,35,47,65,2,116,34,1,32,0,106,40,2,0,32,1,35,29,106,40,2,0,35,46,35,43,34,1,65,6,120,32,1,65,11,120,115,32,1,65,25,120,115,106,35,43,34,1,35,44,113,35,45,32,1,65,127,115,113,115,106,106,106,36,48,35,39,34,1,65,2,120,32,1,65,13,120,115,32,1,65,22,120,115,35,40,34,2,35,41,34,3,113,35,39,34,1,32,2,113,32,1,32,3,113,115,115,106,36,49,35,45,36,46,35,44,36,45,35,43,36,44,35,42,35,48,106,36,43,35,41,36,42,35,40,36,41,35,39,36,40,35,48,35,49,106,36,39,35,47,65,1,106,36,47,12,1,11,11,35,31,35,39,106,36,31,35,32,35,40,106,36,32,35,33,35,41,106,36,33,35,34,35,42,106,36,34,35,35,35,43,106,36,35,35,36,35,44,106,36,36,35,37,35,45,106,36,37,35,38,35,46,106,36,38,11,174,1,1,2,127,35,59,32,1,106,36,59,35,58,4,64,65,192,0,35,58,107,34,2,32,1,76,4,64,35,51,35,58,106,32,0,32,2,252,10,0,0,35,58,32,2,106,36,58,65,192,0,35,58,107,33,2,32,1,65,192,0,35,58,107,107,33,1,35,53,35,51,16,23,65,0,36,58,5,35,51,35,58,106,32,0,32,1,252,10,0,0,35,58,32,1,106,36,58,15,11,11,3,64,32,3,32,1,65,192,0,109,72,4,64,35,53,32,0,32,2,106,16,23,32,3,65,1,106,33,3,32,2,65,64,107,33,2,12,1,11,11,32,1,65,63,113,34,1,4,64,35,51,35,58,106,32,0,32,2,106,32,1,252,10,0,0,35,58,32,1,106,36,58,11,11,231,1,1,2,127,35,51,35,58,106,65,128,1,58,0,0,35,58,65,1,106,36,58,35,58,65,56,74,4,64,35,51,35,58,106,34,1,65,192,0,35,58,107,106,33,2,3,64,32,1,32,2,73,4,64,32,1,65,0,58,0,0,32,1,65,1,106,33,1,12,1,11,11,35,53,35,51,16,23,65,0,36,58,11,35,51,35,58,106,34,1,65,56,35,58,107,106,33,2,3,64,32,1,32,2,73,4,64,32,1,65,0,58,0,0,32,1,65,1,106,33,1,12,1,11,11,35,51,35,59,65,128,128,128,128,2,109,16,18,54,2,56,35,51,35,59,65,3,116,16,18,54,2,60,35,53,35,51,16,23,32,0,35,31,16,18,54,2,0,32,0,35,32,16,18,54,2,4,32,0,35,33,16,18,54,2,8,32,0,35,34,16,18,54,2,12,32,0,35,35,16,18,54,2,16,32,0,35,36,16,18,54,2,20,32,0,35,37,16,18,54,2,24,32,0,35,38,16,18,54,2,28,11,14,0,16,22,35,55,32,0,16,24,35,57,16,25,11,253,1,1,2,127,35,31,36,39,35,32,36,40,35,33,36,41,35,34,36,42,35,35,36,43,35,36,36,44,35,37,36,45,35,38,36,46,65,0,36,47,3,64,35,47,65,192,0,73,4,64,32,0,35,47,65,2,116,106,40,2,0,35,46,35,43,34,1,65,6,120,32,1,65,11,120,115,32,1,65,25,120,115,106,35,43,34,1,35,44,113,35,45,32,1,65,127,115,113,115,106,106,36,48,35,39,34,1,65,2,120,32,1,65,13,120,115,32,1,65,22,120,115,35,40,34,2,35,41,34,1,113,32,2,35,39,34,2,113,32,1,32,2,113,115,115,106,36,49,35,45,36,46,35,44,36,45,35,43,36,44,35,42,35,48,106,36,43,35,41,36,42,35,40,36,41,35,39,36,40,35,48,35,49,106,36,39,35,47,65,1,106,36,47,12,1,11,11,35,31,35,39,106,36,31,35,32,35,40,106,36,32,35,33,35,41,106,36,33,35,34,35,42,106,36,34,35,35,35,43,106,36,35,35,36,35,44,106,36,36,35,37,35,45,106,36,37,35,38,35,46,106,36,38,11,86,0,16,22,35,53,32,0,16,23,35,30,16,27,32,1,35,31,16,18,54,2,0,32,1,35,32,16,18,54,2,4,32,1,35,33,16,18,54,2,8,32,1,35,34,16,18,54,2,12,32,1,35,35,16,18,54,2,16,32,1,35,36,16,18,54,2,20,32,1,35,37,16,18,54,2,24,32,1,35,38,16,18,54,2,28,11,63,0,16,16,65,196,10,40,2,0,36,29,65,148,13,40,2,0,36,30,65,192,0,16,11,36,50,35,50,36,51,65,128,8,16,11,36,52,35,52,36,53,65,128,4,16,11,36,54,35,54,36,55,65,32,16,11,36,56,35,56,36,57,11,11,141,12,38,0,65,140,8,11,2,28,1,0,65,152,8,11,136,2,1,0,0,0,0,1,0,0,152,47,138,66,145,68,55,113,207,251,192,181,165,219,181,233,91,194,86,57,241,17,241,89,164,130,63,146,213,94,28,171,152,170,7,216,1,91,131,18,190,133,49,36,195,125,12,85,116,93,190,114,254,177,222,128,167,6,220,155,116,241,155,193,193,105,155,228,134,71,190,239,198,157,193,15,204,161,12,36,111,44,233,45,170,132,116,74,220,169,176,92,218,136,249,118,82,81,62,152,109,198,49,168,200,39,3,176,199,127,89,191,243,11,224,198,71,145,167,213,81,99,202,6,103,41,41,20,133,10,183,39,56,33,27,46,252,109,44,77,19,13,56,83,84,115,10,101,187,10,106,118,46,201,194,129,133,44,114,146,161,232,191,162,75,102,26,168,112,139,75,194,163,81,108,199,25,232,146,209,36,6,153,214,133,53,14,244,112,160,106,16,22,193,164,25,8,108,55,30,76,119,72,39,181,188,176,52,179,12,28,57,74,170,216,78,79,202,156,91,243,111,46,104,238,130,143,116,111,99,165,120,20,120,200,132,8,2,199,140,250,255,190,144,235,108,80,164,247,163,249,190,242,120,113,198,0,65,172,10,11,1,44,0,65,184,10,11,21,4,0,0,0,16,0,0,0,32,4,0,0,32,4,0,0,0,1,0,0,64,0,65,220,10,11,2,28,1,0,65,232,10,11,136,2,1,0,0,0,0,1,0,0,152,47,138,194,145,68,55,113,207,251,192,181,165,219,181,233,91,194,86,57,241,17,241,89,164,130,63,146,213,94,28,171,152,170,7,216,1,91,131,18,190,133,49,36,195,125,12,85,116,93,190,114,254,177,222,128,167,6,220,155,116,243,155,193,193,105,155,100,134,71,254,240,198,237,225,15,84,242,12,36,111,52,233,79,190,132,201,108,30,65,185,97,250,136,249,22,82,81,198,242,109,90,142,168,101,252,25,176,199,158,217,185,195,49,18,154,160,234,14,231,43,35,177,253,176,62,53,199,213,186,105,48,95,109,151,203,143,17,15,90,253,238,30,220,137,182,53,10,4,122,11,222,157,202,244,88,22,91,93,225,134,62,127,0,128,137,8,55,50,234,7,165,55,149,171,111,16,97,64,23,241,214,140,13,109,59,170,205,55,190,187,192,218,59,97,131,99,163,72,219,49,233,2,11,167,92,209,111,202,250,26,82,49,132,51,49,149,26,212,110,144,120,67,109,242,145,156,195,189,171,204,158,230,160,201,181,60,182,47,83,198,65,199,210,163,126,35,7,104,75,149,164,118,29,25,76,0,65,252,12,11,1,44,0,65,136,13,11,21,4,0,0,0,16,0,0,0,112,5,0,0,112,5,0,0,0,1,0,0,64,0,65,172,13,11,1,44,0,65,184,13,11,35,2,0,0,0,28,0,0,0,73,0,110,0,118,0,97,0,108,0,105,0,100,0,32,0,108,0,101,0,110,0,103,0,116,0,104,0,65,220,13,11,1,60,0,65,232,13,11,45,2,0,0,0,38,0,0,0,126,0,108,0,105,0,98,0,47,0,97,0,114,0,114,0,97,0,121,0,98,0,117,0,102,0,102,0,101,0,114,0,46,0,116,0,115,0,65,156,14,11,1,60,0,65,168,14,11,47,2,0,0,0,40,0,0,0,65,0,108,0,108,0,111,0,99,0,97,0,116,0,105,0,111,0,110,0,32,0,116,0,111,0,111,0,32,0,108,0,97,0,114,0,103,0,101,0,65,220,14,11,1,60,0,65,232,14,11,37,2,0,0,0,30,0,0,0,126,0,108,0,105,0,98,0,47,0,114,0,116,0,47,0,116,0,99,0,109,0,115,0,46,0,116,0,115,0,65,156,15,11,1,60,0,65,168,15,11,37,2,0,0,0,30,0,0,0,126,0,108,0,105,0,98,0,47,0,114,0,116,0,47,0,116,0,108,0,115,0,102,0,46,0,116,0,115,0,65,252,15,11,1,60,0,65,136,16,11,43,2,0,0,0,36,0,0,0,73,0,110,0,100,0,101,0,120,0,32,0,111,0,117,0,116,0,32,0,111,0,102,0,32,0,114,0,97,0,110,0,103,0,101,0,65,188,16,11,1,44,0,65,200,16,11,33,2,0,0,0,26,0,0,0,126,0,108,0,105,0,98,0,47,0,97,0,114,0,114,0,97,0,121,0,46,0,116,0,115,0,65,236,16,11,1,124,0,65,248,16,11,107,2,0,0,0,100,0,0,0,116,0,111,0,83,0,116,0,114,0,105,0,110,0,103,0,40,0,41,0,32,0,114,0,97,0,100,0,105,0,120,0,32,0,97,0,114,0,103,0,117,0,109,0,101,0,110,0,116,0,32,0,109,0,117,0,115,0,116,0,32,0,98,0,101,0,32,0,98,0,101,0,116,0,119,0,101,0,101,0,110,0,32,0,50,0,32,0,97,0,110,0,100,0,32,0,51,0,54,0,65,236,17,11,1,60,0,65,248,17,11,45,2,0,0,0,38,0,0,0,126,0,108,0,105,0,98,0,47,0,117,0,116,0,105,0,108,0,47,0,110,0,117,0,109,0,98,0,101,0,114,0,46,0,116,0,115,0,65,172,18,11,1,28,0,65,184,18,11,9,2,0,0,0,2,0,0,0,48,0,65,204,18,11,1,92,0,65,216,18,11,79,2,0,0,0,72,0,0,0,48,0,49,0,50,0,51,0,52,0,53,0,54,0,55,0,56,0,57,0,97,0,98,0,99,0,100,0,101,0,102,0,103,0,104,0,105,0,106,0,107,0,108,0,109,0,110,0,111,0,112,0,113,0,114,0,115,0,116,0,117,0,118,0,119,0,120,0,121,0,122,0,65,172,19,11,1,92,0,65,184,19,11,79,2,0,0,0,72,0,0,0,115,0,101,0,116,0,86,0,49,0,50,0,56,0,58,0,32,0,101,0,120,0,112,0,101,0,99,0,116,0,32,0,105,0,32,0,102,0,114,0,111,0,109,0,32,0,48,0,32,0,116,0,111,0,32,0,54,0,51,0,44,0,32,0,103,0,111,0,116,0,32,0,65,140,20,11,1,28,0,65,152,20,11,1,2,0,65,172,20,11,1,60,0,65,184,20,11,51,2,0,0,0,44,0,0,0,97,0,115,0,115,0,101,0,109,0,98,0,108,0,121,0,47,0,117,0,116,0,105,0,108,0,115,0,47,0,118,0,49,0,50,0,56,0,46,0,116,0,115,0,65,236,20,11,1,92,0,65,248,20,11,79,2,0,0,0,72,0,0,0,103,0,101,0,116,0,86,0,49,0,50,0,56,0,58,0,32,0,101,0,120,0,112,0,101,0,99,0,116,0,32,0,105,0,32,0,102,0,114,0,111,0,109,0,32,0,48,0,32,0,116,0,111,0,32,0,54,0,51,0,44,0,32,0,103,0,111,0,116,0,32]);var yT={env:{abort:(r,e,t,n)=>{throw Error(`abort: ${r}:${e}:${t}:${n}`)}}};function Mw(r){return(r!==void 0?r:WebAssembly.validate(Lw))?new WebAssembly.Instance(new WebAssembly.Module(Lw),yT).exports:new WebAssembly.Instance(new WebAssembly.Module(gT),yT).exports}var it,TH,Aa,Iu,Au,_H,bT,PH;function DH(r){it=Mw(r),TH=!!it.HAS_SIMD.valueOf(),Aa=it.input.value,Iu=it.output.value,Au=new Uint8Array(it.memory.buffer,Aa,it.INPUT_LENGTH),_H=new Uint8Array(it.memory.buffer,Iu,it.PARALLEL_FACTOR*32),bT=new Uint8Array(it.memory.buffer,Iu,32),PH=new Uint32Array(it.memory.buffer,Aa,it.INPUT_LENGTH)}DH();function wT(r){return r.length===64?kH(r):r.length<=it.INPUT_LENGTH?(Au.set(r),it.digest(r.length),Ow()):(it.init(),LH(r),MH())}function kH(r){if(r.length===64)return Au.set(r),it.digest64(Aa,Iu),Ow();throw new Error("InvalidLengthForDigest64")}function LH(r){let e=it.INPUT_LENGTH;if(r.length>e)for(let t=0;t<r.length;t+=e){let n=r.subarray(t,t+e);Au.set(n),it.update(Aa,n.length)}else Au.set(r),it.update(Aa,r.length)}function MH(){return it.final(Iu),Ow()}function Ow(){let r=mT(32);return r.set(bT),r}Be();var ET=ie(vT(),1),RH=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,ST=(0,ET.default)();var IT=ST&&!RH;var n4e=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&globalThis.process.release.name==="node"&&!ST,s4e=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,o4e=typeof globalThis.process<"u"&&typeof globalThis.process.env<"u"&&globalThis.process.env["NODE"+"_"+"ENV"]==="test",i4e=typeof navigator<"u"&&navigator.product==="ReactNative";function NH(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function s1(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}function o1(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function yt(r,e,t=""){let n=NH(r),s=r?.length,o=e!==void 0;if(!n||o&&s!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function Rw(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function AT(r,e){yt(r,void 0,"output");let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Gn(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Wn(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function BH(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}var UH=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function CT(r,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(r,e)}function TT(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}var Nw=(r,e)=>{function t(n,...s){if(yt(n,void 0,"key"),!UH)throw new Error("Non little-endian hardware is not yet supported");if(r.nonceLength!==void 0){let u=s[0];yt(u,r.varSizeNonce?void 0:r.nonceLength,"nonce")}let o=r.tagLength;o&&s[1]!==void 0&&yt(s[1],void 0,"AAD");let i=e(n,...s),a=(u,h)=>{if(h!==void 0){if(u!==2)throw new Error("cipher output not supported");yt(h,void 0,"output")}},c=!1;return{encrypt(u,h){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,yt(u),a(i.encrypt.length,h),i.encrypt(u,h)},decrypt(u,h){if(yt(u),o&&u.length<o)throw new Error('"ciphertext" expected length bigger than tagLength='+o);return a(i.decrypt.length,h),i.decrypt(u,h)}}}return Object.assign(t,r),t};function Bw(r,e,t=!0){if(e===void 0)return new Uint8Array(r);if(e.length!==r)throw new Error('"output" expected Uint8Array of length '+r+", got: "+e.length);if(t&&!KH(e))throw new Error("invalid output, must be aligned");return e}function _T(r,e,t){s1(t);let n=new Uint8Array(16),s=BH(n);return s.setBigUint64(0,BigInt(e),t),s.setBigUint64(8,BigInt(r),t),n}function KH(r){return r.byteOffset%4===0}function Ca(r){return Uint8Array.from(r)}var DT=r=>Uint8Array.from(r.split(""),e=>e.charCodeAt(0)),FH=DT("expand 16-byte k"),zH=DT("expand 32-byte k"),$H=Gn(FH),HH=Gn(zH);function $(r,e){return r<<e|r>>>32-e}function Uw(r){return r.byteOffset%4===0}var i1=64,qH=16,kT=2**32-1,PT=Uint32Array.of();function VH(r,e,t,n,s,o,i,a){let c=s.length,l=new Uint8Array(i1),u=Gn(l),h=Uw(s)&&Uw(o),p=h?Gn(s):PT,f=h?Gn(o):PT;for(let d=0;d<c;i++){if(r(e,t,n,u,i,a),i>=kT)throw new Error("arx: counter overflow");let m=Math.min(i1,c-d);if(h&&m===i1){let g=d/4;if(d%4!==0)throw new Error("arx: invalid block position");for(let y=0,b;y<qH;y++)b=g+y,f[b]=p[b]^u[y];d+=i1;continue}for(let g=0,y;g<m;g++)y=d+g,o[y]=s[y]^l[g];d+=m}}function Kw(r,e){let{allowShortKeys:t,extendNonceFn:n,counterLength:s,counterRight:o,rounds:i}=CT({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof r!="function")throw new Error("core must be a function");return o1(s),o1(i),s1(o),s1(t),(a,c,l,u,h=0)=>{yt(a,void 0,"key"),yt(c,void 0,"nonce"),yt(l,void 0,"data");let p=l.length;if(u===void 0&&(u=new Uint8Array(p)),yt(u,void 0,"output"),o1(h),h<0||h>=kT)throw new Error("arx: counter overflow");if(u.length<p)throw new Error(`arx: output (${u.length}) is shorter than data (${p})`);let f=[],d=a.length,m,g;if(d===32)f.push(m=Ca(a)),g=HH;else if(d===16&&t)m=new Uint8Array(32),m.set(a),m.set(a,16),g=$H,f.push(m);else throw yt(a,32,"arx key"),new Error("invalid key size");Uw(c)||f.push(c=Ca(c));let y=Gn(m);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(g,y,Gn(c.subarray(0,16)),y),c=c.subarray(16)}let b=16-s;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let x=new Uint8Array(12);x.set(c,o?0:12-c.length),c=x,f.push(c)}let w=Gn(c);return VH(r,g,y,w,l,u,h,i),Wn(...f),u}}function It(r,e){return r[e++]&255|(r[e++]&255)<<8}var Fw=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;constructor(e){e=Ca(yt(e,32,"key"));let t=It(e,0),n=It(e,2),s=It(e,4),o=It(e,6),i=It(e,8),a=It(e,10),c=It(e,12),l=It(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|s<<6)&7939,this.r[3]=(s>>>7|o<<9)&8191,this.r[4]=(o>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=It(e,16+2*u)}process(e,t,n=!1){let s=n?0:2048,{h:o,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],h=i[4],p=i[5],f=i[6],d=i[7],m=i[8],g=i[9],y=It(e,t+0),b=It(e,t+2),w=It(e,t+4),x=It(e,t+6),v=It(e,t+8),S=It(e,t+10),E=It(e,t+12),I=It(e,t+14),A=o[0]+(y&8191),X=o[1]+((y>>>13|b<<3)&8191),ne=o[2]+((b>>>10|w<<6)&8191),H=o[3]+((w>>>7|x<<9)&8191),L=o[4]+((x>>>4|v<<12)&8191),C=o[5]+(v>>>1&8191),T=o[6]+((v>>>14|S<<2)&8191),M=o[7]+((S>>>11|E<<5)&8191),B=o[8]+((E>>>8|I<<8)&8191),N=o[9]+(I>>>5|s),k=0,O=k+A*a+X*(5*g)+ne*(5*m)+H*(5*d)+L*(5*f);k=O>>>13,O&=8191,O+=C*(5*p)+T*(5*h)+M*(5*u)+B*(5*l)+N*(5*c),k+=O>>>13,O&=8191;let K=k+A*c+X*a+ne*(5*g)+H*(5*m)+L*(5*d);k=K>>>13,K&=8191,K+=C*(5*f)+T*(5*p)+M*(5*h)+B*(5*u)+N*(5*l),k+=K>>>13,K&=8191;let F=k+A*l+X*c+ne*a+H*(5*g)+L*(5*m);k=F>>>13,F&=8191,F+=C*(5*d)+T*(5*f)+M*(5*p)+B*(5*h)+N*(5*u),k+=F>>>13,F&=8191;let ve=k+A*u+X*l+ne*c+H*a+L*(5*g);k=ve>>>13,ve&=8191,ve+=C*(5*m)+T*(5*d)+M*(5*f)+B*(5*p)+N*(5*h),k+=ve>>>13,ve&=8191;let ue=k+A*h+X*u+ne*l+H*c+L*a;k=ue>>>13,ue&=8191,ue+=C*(5*g)+T*(5*m)+M*(5*d)+B*(5*f)+N*(5*p),k+=ue>>>13,ue&=8191;let se=k+A*p+X*h+ne*u+H*l+L*c;k=se>>>13,se&=8191,se+=C*a+T*(5*g)+M*(5*m)+B*(5*d)+N*(5*f),k+=se>>>13,se&=8191;let pe=k+A*f+X*p+ne*h+H*u+L*l;k=pe>>>13,pe&=8191,pe+=C*c+T*a+M*(5*g)+B*(5*m)+N*(5*d),k+=pe>>>13,pe&=8191;let Te=k+A*d+X*f+ne*p+H*h+L*u;k=Te>>>13,Te&=8191,Te+=C*l+T*c+M*a+B*(5*g)+N*(5*m),k+=Te>>>13,Te&=8191;let Qe=k+A*m+X*d+ne*f+H*p+L*h;k=Qe>>>13,Qe&=8191,Qe+=C*u+T*l+M*c+B*a+N*(5*g),k+=Qe>>>13,Qe&=8191;let ye=k+A*g+X*m+ne*d+H*f+L*p;k=ye>>>13,ye&=8191,ye+=C*h+T*u+M*l+B*c+N*a,k+=ye>>>13,ye&=8191,k=(k<<2)+k|0,k=k+O|0,O=k&8191,k=k>>>13,K+=k,o[0]=O,o[1]=K,o[2]=F,o[3]=ve,o[4]=ue,o[5]=se,o[6]=pe,o[7]=Te,o[8]=Qe,o[9]=ye}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),s=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=s,s=e[a]>>>13,e[a]&=8191;e[0]+=s*5,s=e[0]>>>13,e[0]&=8191,e[1]+=s,s=e[1]>>>13,e[1]&=8191,e[2]+=s,n[0]=e[0]+5,s=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+s,s=n[a]>>>13,n[a]&=8191;n[9]-=8192;let o=(s^1)-1;for(let a=0;a<10;a++)n[a]&=o;o=~o;for(let a=0;a<10;a++)e[a]=e[a]&o|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+t[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+t[a]|0)+(i>>>16)|0,e[a]=i&65535;Wn(n)}update(e){Rw(this),yt(e),e=Ca(e);let{buffer:t,blockLen:n}=this,s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);if(i===n){for(;n<=s-o;o+=n)this.process(e,o);continue}t.set(e.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){Wn(this.h,this.r,this.buffer,this.pad)}digestInto(e){Rw(this),AT(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:s}=this;if(s){for(t[s++]=1;s<16;s++)t[s]=0;this.process(t,0,!0)}this.finalize();let o=0;for(let i=0;i<8;i++)e[o++]=n[i]>>>0,e[o++]=n[i]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}};function GH(r){let e=(n,s)=>r(s).update(n).digest(),t=r(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=n=>r(n),e}var LT=GH(r=>new Fw(r));function RT(r,e,t,n,s,o=20){let i=r[0],a=r[1],c=r[2],l=r[3],u=e[0],h=e[1],p=e[2],f=e[3],d=e[4],m=e[5],g=e[6],y=e[7],b=s,w=t[0],x=t[1],v=t[2],S=i,E=a,I=c,A=l,X=u,ne=h,H=p,L=f,C=d,T=m,M=g,B=y,N=b,k=w,O=x,K=v;for(let ve=0;ve<o;ve+=2)S=S+X|0,N=$(N^S,16),C=C+N|0,X=$(X^C,12),S=S+X|0,N=$(N^S,8),C=C+N|0,X=$(X^C,7),E=E+ne|0,k=$(k^E,16),T=T+k|0,ne=$(ne^T,12),E=E+ne|0,k=$(k^E,8),T=T+k|0,ne=$(ne^T,7),I=I+H|0,O=$(O^I,16),M=M+O|0,H=$(H^M,12),I=I+H|0,O=$(O^I,8),M=M+O|0,H=$(H^M,7),A=A+L|0,K=$(K^A,16),B=B+K|0,L=$(L^B,12),A=A+L|0,K=$(K^A,8),B=B+K|0,L=$(L^B,7),S=S+ne|0,K=$(K^S,16),M=M+K|0,ne=$(ne^M,12),S=S+ne|0,K=$(K^S,8),M=M+K|0,ne=$(ne^M,7),E=E+H|0,N=$(N^E,16),B=B+N|0,H=$(H^B,12),E=E+H|0,N=$(N^E,8),B=B+N|0,H=$(H^B,7),I=I+L|0,k=$(k^I,16),C=C+k|0,L=$(L^C,12),I=I+L|0,k=$(k^I,8),C=C+k|0,L=$(L^C,7),A=A+X|0,O=$(O^A,16),T=T+O|0,X=$(X^T,12),A=A+X|0,O=$(O^A,8),T=T+O|0,X=$(X^T,7);let F=0;n[F++]=i+S|0,n[F++]=a+E|0,n[F++]=c+I|0,n[F++]=l+A|0,n[F++]=u+X|0,n[F++]=h+ne|0,n[F++]=p+H|0,n[F++]=f+L|0,n[F++]=d+C|0,n[F++]=m+T|0,n[F++]=g+M|0,n[F++]=y+B|0,n[F++]=b+N|0,n[F++]=w+k|0,n[F++]=x+O|0,n[F++]=v+K|0}function WH(r,e,t,n){let s=r[0],o=r[1],i=r[2],a=r[3],c=e[0],l=e[1],u=e[2],h=e[3],p=e[4],f=e[5],d=e[6],m=e[7],g=t[0],y=t[1],b=t[2],w=t[3];for(let v=0;v<20;v+=2)s=s+c|0,g=$(g^s,16),p=p+g|0,c=$(c^p,12),s=s+c|0,g=$(g^s,8),p=p+g|0,c=$(c^p,7),o=o+l|0,y=$(y^o,16),f=f+y|0,l=$(l^f,12),o=o+l|0,y=$(y^o,8),f=f+y|0,l=$(l^f,7),i=i+u|0,b=$(b^i,16),d=d+b|0,u=$(u^d,12),i=i+u|0,b=$(b^i,8),d=d+b|0,u=$(u^d,7),a=a+h|0,w=$(w^a,16),m=m+w|0,h=$(h^m,12),a=a+h|0,w=$(w^a,8),m=m+w|0,h=$(h^m,7),s=s+l|0,w=$(w^s,16),d=d+w|0,l=$(l^d,12),s=s+l|0,w=$(w^s,8),d=d+w|0,l=$(l^d,7),o=o+u|0,g=$(g^o,16),m=m+g|0,u=$(u^m,12),o=o+u|0,g=$(g^o,8),m=m+g|0,u=$(u^m,7),i=i+h|0,y=$(y^i,16),p=p+y|0,h=$(h^p,12),i=i+h|0,y=$(y^i,8),p=p+y|0,h=$(h^p,7),a=a+c|0,b=$(b^a,16),f=f+b|0,c=$(c^f,12),a=a+c|0,b=$(b^a,8),f=f+b|0,c=$(c^f,7);let x=0;n[x++]=s,n[x++]=o,n[x++]=i,n[x++]=a,n[x++]=g,n[x++]=y,n[x++]=b,n[x++]=w}var jH=Kw(RT,{counterRight:!1,counterLength:4,allowShortKeys:!1}),YH=Kw(RT,{counterRight:!1,counterLength:8,extendNonceFn:WH,allowShortKeys:!1});var XH=new Uint8Array(16),MT=(r,e)=>{r.update(e);let t=e.length%16;t&&r.update(XH.subarray(t))},QH=new Uint8Array(32);function OT(r,e,t,n,s){s!==void 0&&yt(s,void 0,"AAD");let o=r(e,t,QH),i=_T(n.length,s?s.length:0,!0),a=LT.create(o);s&&MT(a,s),MT(a,n),a.update(i);let c=a.digest();return Wn(o,i),c}var NT=r=>(e,t,n)=>({encrypt(o,i){let a=o.length;i=Bw(a+16,i,!1),i.set(o);let c=i.subarray(0,-16);r(e,t,c,c,1);let l=OT(r,e,t,c,n);return i.set(l,a),Wn(l),i},decrypt(o,i){i=Bw(o.length-16,i,!1);let a=o.subarray(0,-16),c=o.subarray(-16),l=OT(r,e,t,a,n);if(!TT(c,l))throw new Error("invalid tag");return i.set(o.subarray(0,-16)),r(e,t,i,i,1),Wn(l),i}}),zw=Nw({blockSize:64,nonceLength:12,tagLength:16},NT(jH)),E4e=Nw({blockSize:64,nonceLength:24,tagLength:16},NT(YH));yi();Wc();E2();yi();var Cu=BigInt(0),Ta=BigInt(1),a1=BigInt(2);function JH(r){return Qs(r,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...r})}function BT(r){let e=JH(r),{P:t,type:n,adjustScalarBytes:s,powPminus2:o,randomBytes:i}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i||Qr,l=a?255:448,u=a?32:56,h=BigInt(a?9:5),p=BigInt(a?121665:39081),f=a?a1**BigInt(254):a1**BigInt(447),d=a?BigInt(8)*a1**BigInt(251)-Ta:BigInt(4)*a1**BigInt(445)-Ta,m=f+d+Ta,g=C=>Ut(C,t),y=b(h);function b(C){return qc(g(C),u)}function w(C){let T=td(ge(C,u,"uCoordinate"));return a&&(T[31]&=127),g(mi(T))}function x(C){return mi(s(td(ge(C,u,"scalar"))))}function v(C,T){let M=X(w(T),x(C));if(M===Cu)throw new Error("invalid private or public key received");return b(M)}function S(C){return v(C,y)}let E=S,I=v;function A(C,T,M){let B=g(C*(T-M));return T=g(T-B),M=g(M+B),{x_2:T,x_3:M}}function X(C,T){Vc("u",C,Cu,t),Vc("scalar",T,f,m);let M=T,B=C,N=Ta,k=Cu,O=C,K=Ta,F=Cu;for(let ue=BigInt(l-1);ue>=Cu;ue--){let se=M>>ue&Ta;F^=se,{x_2:N,x_3:O}=A(F,N,O),{x_2:k,x_3:K}=A(F,k,K),F=se;let pe=N+k,Te=g(pe*pe),Qe=N-k,ye=g(Qe*Qe),et=Te-ye,Wo=O+K,ih=O-K,ac=g(ih*pe),U5=g(Wo*Qe),K5=ac+U5,F5=ac-U5;O=g(K5*K5),K=g(B*g(F5*F5)),N=g(Te*ye),k=g(et*(Te+g(p*et)))}({x_2:N,x_3:O}=A(F,N,O)),{x_2:k,x_3:K}=A(F,k,K);let ve=o(k);return g(N*ve)}let ne={secretKey:u,publicKey:u,seed:u},H=(C=c(u))=>(ge(C,ne.seed,"seed"),C),L={randomSecretKey:H};return Object.freeze({keygen:nd(H,E),getSharedSecret:I,getPublicKey:E,scalarMult:v,scalarMultBase:S,utils:L,GuBytes:y.slice(),lengths:ne})}var ZH=BigInt(1),UT=BigInt(2),eq=BigInt(3),tq=BigInt(5),L4e=BigInt(8),KT=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");function rq(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),s=BigInt(80),o=KT,a=r*r%o*r%o,c=Me(a,UT,o)*a%o,l=Me(c,ZH,o)*r%o,u=Me(l,tq,o)*l%o,h=Me(u,e,o)*u%o,p=Me(h,t,o)*h%o,f=Me(p,n,o)*p%o,d=Me(f,s,o)*f%o,m=Me(d,s,o)*f%o,g=Me(m,e,o)*u%o;return{pow_p_5_8:Me(g,UT,o)*r%o,b2:a}}function nq(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Tu=(()=>{let r=KT;return BT({P:r,type:"x25519",powPminus2:e=>{let{pow_p_5_8:t,b2:n}=rq(e);return Ut(Me(t,eq,r)*n,r)},adjustScalarBytes:nq})})();S2();Jr();function zT(r,e,t){return js(r),t===void 0&&(t=new Uint8Array(r.outputLen)),wi(r,t,e)}var $w=Uint8Array.of(0),FT=Uint8Array.of();function $T(r,e,t,n=32){js(r),xr(n,"length");let s=r.outputLen;if(n>255*s)throw new Error("Length must be <= 255*HashLen");let o=Math.ceil(n/s);t===void 0?t=FT:ge(t,void 0,"info");let i=new Uint8Array(o*s),a=wi.create(r,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<o;u++)$w[0]=u+1,c.update(u===0?FT:l).update(t).update($w).digestInto(l),i.set(l,s*u),a._cloneInto(c);return a.destroy(),c.destroy(),kn(l,$w),i.slice(0,n)}Kc();var Hw={hashSHA256(r){return Yt(r.subarray())},getHKDF(r,e){let t=zT(Yt,e,r),s=$T(Yt,t,void 0,96),o=s.subarray(0,32),i=s.subarray(32,64),a=s.subarray(64,96);return[o,i,a]},generateX25519KeyPair(){let r=Tu.utils.randomSecretKey();return{publicKey:Tu.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:Tu.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,e){return Tu.getSharedSecret(r.subarray(),e.subarray())},chaCha20Poly1305Encrypt(r,e,t,n){return zw(n,e,t).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,e,t,n,s){return zw(n,e,t).decrypt(r.subarray(),s)}};var sq=(0,u1.newInstance)(),HT=new u1.ChaCha20Poly1305(sq),qT="chacha20-poly1305",_a=Buffer.from([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),_u=Buffer.from([48,42,48,5,6,3,43,101,110,3,33,0]);var qw={hashSHA256(r){let e=mn.default.createHash("sha256");if(r instanceof Uint8Array)return e.update(r).digest();for(let t of r)e.update(t);return e.digest()},chaCha20Poly1305Encrypt(r,e,t,n){let s=mn.default.createCipheriv(qT,n,e,{authTagLength:16});if(s.setAAD(t,{plaintextLength:r.byteLength}),r instanceof Uint8Array){let a=s.update(r),c=s.final(),l=s.getAuthTag();return Buffer.concat([a,c,l],a.byteLength+c.byteLength+l.byteLength)}let o=new U;for(let a of r)o.append(s.update(a));let i=s.final();return i.byteLength>0&&o.append(i),o.append(s.getAuthTag()),o},chaCha20Poly1305Decrypt(r,e,t,n,s){let o=r.subarray(r.length-16),i=mn.default.createDecipheriv(qT,n,e,{authTagLength:16}),a;if(r instanceof Uint8Array?a=r.subarray(0,r.length-16):a=r.sublist(0,r.length-16),i.setAAD(t,{plaintextLength:a.byteLength}),i.setAuthTag(o),a instanceof Uint8Array){let u=i.update(a),h=i.final();return h.byteLength>0?Buffer.concat([u,h],u.byteLength+h.byteLength):u}let c=new U;for(let u of a)c.append(i.update(u));let l=i.final();return l.byteLength>0&&c.append(l),c}},c1={hashSHA256(r){return wT(r.subarray())},chaCha20Poly1305Encrypt(r,e,t,n){return HT.seal(n,e,r.subarray(),t)},chaCha20Poly1305Decrypt(r,e,t,n,s){let o=HT.open(n,e,r.subarray(),t,s);if(!o)throw new Error("Invalid chacha20poly1305 decryption");return o}},l1={...Hw,hashSHA256(r){return qw.hashSHA256(r)},chaCha20Poly1305Encrypt(r,e,t,n){return r.byteLength<1200?c1.chaCha20Poly1305Encrypt(r,e,t,n):qw.chaCha20Poly1305Encrypt(r,e,t,n)},chaCha20Poly1305Decrypt(r,e,t,n,s){return r.byteLength<1200?c1.chaCha20Poly1305Decrypt(r,e,t,n,s):qw.chaCha20Poly1305Decrypt(r,e,t,n,s)},generateX25519KeyPair(){let{publicKey:r,privateKey:e}=mn.default.generateKeyPairSync("x25519",{publicKeyEncoding:{type:"spki",format:"der"},privateKeyEncoding:{type:"pkcs8",format:"der"}});return{publicKey:r.subarray(_u.length),privateKey:e.subarray(_a.length)}},generateX25519KeyPairFromSeed(r){let e=mn.default.createPrivateKey({key:Buffer.concat([_a,r],_a.byteLength+r.byteLength),type:"pkcs8",format:"der"});return{publicKey:mn.default.createPublicKey(e).export({type:"spki",format:"der"}).subarray(_u.length),privateKey:r}},generateX25519SharedKey(r,e){return e instanceof Uint8Array?e=Buffer.concat([_u,e],_u.byteLength+e.byteLength):e=new U(_u,e).subarray(),r instanceof Uint8Array?r=Buffer.concat([_a,r],_a.byteLength+r.byteLength):r=new U(_a,r).subarray(),mn.default.diffieHellman({publicKey:mn.default.createPublicKey({key:Buffer.from(e.buffer,e.byteOffset,e.byteLength),type:"spki",format:"der"}),privateKey:mn.default.createPrivateKey({key:Buffer.from(r.buffer,r.byteOffset,r.byteLength),type:"pkcs8",format:"der"})})}};IT&&(l1.chaCha20Poly1305Encrypt=c1.chaCha20Poly1305Encrypt,l1.chaCha20Poly1305Decrypt=c1.chaCha20Poly1305Decrypt);function VT(r){return{generateKeypair:r.generateX25519KeyPair,dh:(e,t)=>r.generateX25519SharedKey(e.privateKey,t).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}rt();var Pa=r=>{let e=tt(2);return e[0]=r>>8,e[1]=r,e};Pa.bytes=2;var Da=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let e=0;return e+=r[0]<<8,e+=r[1],e}return r.getUint16(0)};Da.bytes=2;function GT(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}ce();function Vw(r,e){!e.enabled||!Sa||(r?(e(`LOCAL_STATIC_PUBLIC_KEY ${P(r.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${P(r.privateKey,"hex")}`)):e("Missing local static keys."))}function Gw(r,e){!e.enabled||!Sa||(r?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${P(r.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${P(r.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function WT(r,e){!e.enabled||!Sa||e(r?`REMOTE_STATIC_PUBLIC_KEY ${P(r.subarray(),"hex")}`:"Missing remote static public key.")}function Ww(r,e){!e.enabled||!Sa||e(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${P(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function jw(r,e,t){!t.enabled||!Sa||(t(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&P(r.k,"hex")}`),t(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&P(e.k,"hex")}`))}Be();Ne();rt();cc();bt();te();ce();rt();var ka=class r extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};rt();var oq=0,iq=4294967295,aq="Cipherstate has reached maximum n, a new handshake must be performed",h1=class{n;bytes;view;constructor(e=oq){this.n=e,this.bytes=ae(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>iq)throw new Error(aq)}};var zo=ae(0),La=class{k;n;crypto;constructor(e,t=void 0,n=0){this.crypto=e,this.k=t,this.n=new h1(n)}hasKey(){return!!this.k}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();let n=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,t,n){if(!this.hasKey())return t;this.n.assertValue();let s=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,n);return this.n.increment(),s}},Yw=class{cs;ck;h;crypto;constructor(e,t){this.crypto=e;let n=D(t,"utf-8");this.h=cq(e,n),this.ck=this.h,this.cs=new La(e)}mixKey(e){let[t,n]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new La(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new U(this.h,e))}encryptAndHash(e){let t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){let t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){let[e,t]=this.crypto.hkdf(this.ck,zo);return[new La(this.crypto,e),new La(this.crypto,t)]}},Xw=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:t,protocolName:n,prologue:s,initiator:o,s:i,e:a,rs:c,re:l}=e;this.crypto=t,this.ss=new Yw(t,n),this.ss.mixHash(s),this.initiator=o,this.s=i,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,t=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw new Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+n)throw new Error("message is not long enough");let s=e.sublist(t,t+n);return this.rs=this.ss.decryptAndHash(s),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},Pu=class extends Xw{writeMessageA(e){return new U(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let t=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new U(t,n,this.ss.encryptAndHash(e))}writeMessageC(e){let t=this.writeS();return this.writeSE(),new U(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(t){throw new ka(`handshake stage 0 validation fail: ${t.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();let t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(t){throw new ka(`handshake stage 1 validation fail: ${t.message}`)}}readMessageC(e){try{let t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(t){throw new ka(`handshake stage 2 validation fail: ${t.message}`)}}};function cq(r,e){if(e.length<=32){let t=ae(32);return t.set(e),t}else return r.hash(e)}Bt();V();Be();bt();te();wr();rt();var d1;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.webtransportCerthashes!=null)for(let o of t.webtransportCerthashes)n.uint32(10),n.bytes(o);if(t.streamMuxers!=null)for(let o of t.streamMuxers)n.uint32(18),n.string(o);s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={webtransportCerthashes:[],streamMuxers:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{if(s.limits?.webtransportCerthashes!=null&&o.webtransportCerthashes.length===s.limits.webtransportCerthashes)throw new _e('Decode error - map field "webtransportCerthashes" had too many elements');o.webtransportCerthashes.push(t.bytes());break}case 2:{if(s.limits?.streamMuxers!=null&&o.streamMuxers.length===s.limits.streamMuxers)throw new _e('Decode error - map field "streamMuxers" had too many elements');o.streamMuxers.push(t.string());break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(d1||(d1={}));var Du;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.identityKey!=null&&t.identityKey.byteLength>0&&(n.uint32(10),n.bytes(t.identityKey)),t.identitySig!=null&&t.identitySig.byteLength>0&&(n.uint32(18),n.bytes(t.identitySig)),t.extensions!=null&&(n.uint32(34),d1.codec().encode(t.extensions,n)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={identityKey:ae(0),identitySig:ae(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.identityKey=t.bytes();break}case 2:{o.identitySig=t.bytes();break}case 4:{o.extensions=d1.codec().decode(t,t.uint32(),{limits:s.limits?.extensions});break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(Du||(Du={}));async function Jw(r,e,t){let n=await r.sign(YT(e));return Du.encode({identityKey:dt(r.publicKey),identitySig:n,extensions:t})}async function Zw(r,e,t){try{let n=Du.decode(r),s=Ft(n.identityKey);if(t?.equals(s)===!1)throw new Error(`Payload identity key ${s} does not match expected remote identity key ${t}`);if(!e)throw new Error("Remote static does not exist");let o=YT(e);if(!await s.verify(o,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new yh(n.message)}}function YT(r){let e=D("noise-libp2p-static-key:");return r instanceof Uint8Array?Ee([e,r],e.length+r.length):(r.prepend(e),r)}var Qw=class extends Ts{stream;handshake;metrics;decoder;constructor(e,t,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=t,this.metrics=n,this.decoder=new Lf({lengthDecoder:Da,maxBufferSize:16*1024*1024,encodingLength:()=>2});let s=c=>{try{for(let l of this.decoder.decode(c.data))this.onData(this.decrypt(l))}catch(l){this.abort(l)}};this.stream.addEventListener("message",s);let o=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",o);let i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);let a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){let t=new U;for(let n=0;n<e.byteLength;n+=65519){let s=n+65519;s>e.byteLength&&(s=e.byteLength);let o;e instanceof Uint8Array?o=this.handshake.encrypt(e.subarray(n,s)):o=this.handshake.encrypt(e.sublist(n,s)),this.metrics?.encryptedPackets.increment(),t.append(Pa(o.byteLength)),t.append(o)}return t}decrypt(e){let t=new U;for(let n=0;n<e.byteLength;n+=65535){let s=n+65535;if(s>e.byteLength&&(s=e.byteLength),s-Cw<n)throw new Error("Invalid chunk");let o;e instanceof Uint8Array?o=e.subarray(n,s):o=e.sublist(n,s);let i=e.subarray(n,s-Cw);try{let a=this.handshake.decrypt(o,i);this.metrics?.decryptedPackets.increment(),t.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return t}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}};function e6(r,e,t){return new Qw(r,e,t)}async function XT(r,e){let{log:t,connection:n,crypto:s,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Jw(o,a.publicKey,l),h=new Pu({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Vw(h.s,t),t.trace("Stage 0 - Initiator starting to send first message."),await n.write(h.writeMessageA(zo),e),t.trace("Stage 0 - Initiator finished sending first message."),Gw(h.e,t),t.trace("Stage 1 - Initiator waiting to receive first message from responder...");let p=h.readMessageB(await n.read(e));t.trace("Stage 1 - Initiator received the message."),Ww(h.re,t),WT(h.rs,t),t.trace("Initiator going to check remote's signature...");let f=await Zw(p,h.rs,c);t.trace("All good with the signature!"),t.trace("Stage 2 - Initiator sending third handshake message."),await n.write(h.writeMessageC(u),e),t.trace("Stage 2 - Initiator sent message with signed payload.");let[d,m]=h.ss.split();return jw(d,m,t),{payload:f,encrypt:g=>d.encryptWithAd(zo,g),decrypt:(g,y)=>m.decryptWithAd(zo,g,y)}}async function QT(r,e){let{log:t,connection:n,crypto:s,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Jw(o,a.publicKey,l),h=new Pu({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Vw(h.s,t),t.trace("Stage 0 - Responder waiting to receive first message."),h.readMessageA(await n.read(e)),t.trace("Stage 0 - Responder received first message."),Ww(h.re,t),t.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(h.writeMessageB(u),e),t.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Gw(h.e,t),t.trace("Stage 2 - Responder waiting for third handshake message...");let p=h.readMessageC(await n.read(e));t.trace("Stage 2 - Responder received the message, finished handshake.");let f=await Zw(p,h.rs,c),[d,m]=h.ss.split();return jw(d,m,t),{payload:f,encrypt:g=>m.encryptWithAd(zo,g),decrypt:(g,y)=>d.decryptWithAd(zo,g,y)}}var f1=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,t={}){let{staticNoiseKey:n,extensions:s,crypto:o,prologueBytes:i}=t,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");let c=o??l1;this.crypto=VT(c),this.extensions={webtransportCerthashes:[],...s},this.metrics=a?GT(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??ae(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[nt]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){let n=e.log?.newScope("noise")??this.log,s=_s(e,{lengthEncoder:Pa,lengthDecoder:Da,maxDataLength:65535}),o=await this.performHandshakeInitiator(s,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=Ft(o.payload.identityKey);return{connection:e6(s.unwrap(),o,this.metrics),remoteExtensions:o.payload.extensions,remotePeer:On(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(o.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;let t=this.components.upgrader.getStreamMuxers();if(t!=null)for(let n of e){let s=t.get(n);if(s!=null)return s}if(e.length)throw new bh("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,t){let n=e.log?.newScope("noise")??this.log,s=_s(e,{lengthEncoder:Pa,lengthDecoder:Da,maxDataLength:65535}),o=await this.performHandshakeResponder(s,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=Ft(o.payload.identityKey);return{connection:e6(s.unwrap(),o,this.metrics),remoteExtensions:o.payload.extensions,remotePeer:On(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(o.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,n,s,o){let i,a=o?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await XT({connection:e,privateKey:t,remoteIdentityKey:s,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(e,t,n,s,o){let i,a=o?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await QT({connection:e,privateKey:t,remoteIdentityKey:s,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}};function JT(r={}){return e=>new f1(e,r)}V();function lq(r){return r.reason}async function t6(r,e,t){if(e==null)return r;let n=t?.translateError??lq;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}Be();V();var Fe;(function(r){r[r.Data=0]="Data",r[r.WindowUpdate=1]="WindowUpdate",r[r.Ping=2]="Ping",r[r.GoAway=3]="GoAway"})(Fe||(Fe={}));var xe;(function(r){r[r.SYN=1]="SYN",r[r.ACK=2]="ACK",r[r.FIN=4]="FIN",r[r.RST=8]="RST"})(xe||(xe={}));var nEe=Object.values(xe).filter(r=>typeof r!="string"),ZT=0,at;(function(r){r[r.NormalTermination=0]="NormalTermination",r[r.ProtocolError=1]="ProtocolError",r[r.InternalError=2]="InternalError"})(at||(at={}));var gn=12;var jn=class extends Error{static name="ProtocolError";reason;constructor(e,t){super(e),this.name="ProtocolError",this.reason=t}};function e_(r){return r?.reason!==null}var dr=class extends jn{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e,at.ProtocolError),this.name="InvalidFrameError"}},Ma=class extends jn{static name="UnRequestedPingError";constructor(e="Un-requested ping error"){super(e,at.ProtocolError),this.name="UnRequestedPingError"}},Oa=class extends jn{static name="NotMatchingPingError";constructor(e="Not matching ping error"){super(e,at.ProtocolError),this.name="NotMatchingPingError"}};var p1=class extends jn{static name="StreamAlreadyExistsError";constructor(e="Stream already exists"){super(e,at.ProtocolError),this.name="StreamAlreadyExistsError"}},m1=class extends jn{static name="DecodeInvalidVersionError";constructor(e="Decode invalid version"){super(e,at.ProtocolError),this.name="DecodeInvalidVersionError"}},g1=class extends jn{static name="BothClientsError";constructor(e="Both clients"){super(e,at.ProtocolError),this.name="BothClientsError"}},Ra=class extends jn{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e,at.ProtocolError),this.name="ReceiveWindowExceededError"}};var cEe=new Set([dr.name,Ma.name,Oa.name,p1.name,m1.name,g1.name,Ra.name]),Lu=256*1024,y1=16*1024*1024;var Mu={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,maxMessageSize:64*1024,maxEarlyStreams:10,streamOptions:{initialStreamWindowSize:Lu,maxStreamWindowSize:y1,inactivityTimeout:12e4,maxReadBufferLength:4194304,maxWriteBufferLength:1/0}};function t_(r){if(r.keepAliveInterval!=null&&r.keepAliveInterval<=0)throw new R("keep-alive interval must be positive");if(r.maxInboundStreams!=null&&r.maxInboundStreams<0)throw new R("max inbound streams must be larger or equal 0");if(r.maxOutboundStreams!=null&&r.maxOutboundStreams<0)throw new R("max outbound streams must be larger or equal 0");if(r.maxMessageSize!=null&&r.maxMessageSize<1024)throw new R("MaxMessageSize must be greater than a kilobyte");if(r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize<Lu)throw new R("InitialStreamWindowSize must be larger or equal 256 kB");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize<r.streamOptions?.initialStreamWindowSize)throw new R("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize>2**32-1)throw new R("MaxStreamWindowSize must be less than equal MAX_UINT32")}Be();function n_(r){return r.header.type===Fe.Data&&r.data!==null}var r_=2**24;function uq(r){if(r[0]!==ZT)throw new dr("Invalid frame version");return{type:r[1],flag:(r[2]<<8)+r[3],streamID:r[4]*r_+(r[5]<<16)+(r[6]<<8)+r[7],length:r[8]*r_+(r[9]<<16)+(r[10]<<8)+r[11]}}var b1=class{buffer;constructor(){this.buffer=new U}*emitFrames(e){for(this.buffer.append(e);;){let t=this.readFrame();if(t===void 0)break;yield t}}readFrame(){let e=gn;if(this.buffer.byteLength<gn)return;let t=uq(this.buffer.subarray(0,gn));if(t.type===Fe.Data){if(e+=t.length,this.buffer.byteLength<e)return;let n=this.buffer.sublist(gn,e);return this.buffer.consume(e),{header:t,data:n}}return this.buffer.consume(e),{header:t}}};function r6(r){let e=new Uint8Array(gn);return e[1]=r.type,e[2]=r.flag>>>8,e[3]=r.flag,e[4]=r.streamID>>>24,e[5]=r.streamID>>>16,e[6]=r.streamID>>>8,e[7]=r.streamID,e[8]=r.length>>>24,e[9]=r.length>>>16,e[10]=r.length>>>8,e[11]=r.length,e}Be();var Ht;(function(r){r[r.Init=0]="Init",r[r.SYNSent=1]="SYNSent",r[r.SYNReceived=2]="SYNReceived",r[r.Established=3]="Established",r[r.Finished=4]="Finished",r[r.Paused=5]="Paused"})(Ht||(Ht={}));var w1=class extends Pf{streamId;state;sendWindowCapacity;recvWindow;recvWindowCapacity;maxStreamWindowSize;epochStart;getRTT;sendFrame;constructor(e){let t=e.initialStreamWindowSize??Lu;super({...e,maxMessageSize:t-gn}),this.streamId=e.streamId,this.state=e.state,this.sendWindowCapacity=t,this.recvWindow=t,this.recvWindowCapacity=this.recvWindow,this.maxStreamWindowSize=e.maxStreamWindowSize??y1,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.sendFrame=e.sendFrame;let n=()=>{this.state=Ht.Finished};this.addEventListener("close",n)}sendData(e){let t=e.byteLength,n=0,s=!0;for(this.log?.trace("send window capacity is %d bytes",this.sendWindowCapacity);e.byteLength>0;){if(this.sendWindowCapacity===0){s=!1,this.log?.trace("sent %d/%d bytes, exhausted send window, waiting for window update",n,t);break}let o=Math.min(this.sendWindowCapacity,e.byteLength),i=this.getSendFlags(),a=e.sublist(0,o);e.consume(o);let c=this.sendFrame({type:Fe.Data,flag:i,streamID:this.streamId,length:o},a);if(this.sendWindowCapacity-=o,n+=o,!c){s=c,this.log.trace("sent %d/%d bytes, wait for muxer to have more send capacity",n,t);break}}return{sentBytes:n,canSendMore:s}}sendReset(){this.sendFrame({type:Fe.WindowUpdate,flag:xe.RST,streamID:this.streamId,length:0})}async sendCloseWrite(){let e=this.getSendFlags()|xe.FIN;this.sendFrame({type:Fe.WindowUpdate,flag:e,streamID:this.streamId,length:0})}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){this.state=Ht.Paused}sendResume(){this.state=Ht.Established,this.sendWindowUpdate()}handleWindowUpdate(e){this.processFlags(e.header.flag),this.sendWindowCapacity+=e.header.length,this.maxMessageSize=this.sendWindowCapacity-gn,this.maxMessageSize<0&&(this.maxMessageSize=0),this.maxMessageSize!==0&&this.writeBuffer.byteLength>0&&(this.log?.trace("window update of %d bytes allows more data to be sent, have %d bytes queued, sending data %s",e.header.length,this.writeBuffer.byteLength,this.sendingData),this.safeDispatchEvent("drain"))}handleData(e){if(!n_(e))throw new dr("Frame was not data frame");if(this.processFlags(e.header.flag),this.recvWindowCapacity<e.header.length)throw new Ra("Receive window exceeded");this.recvWindowCapacity-=e.header.length,this.onData(e.data),this.sendWindowUpdate()}processFlags(e){(e&xe.ACK)===xe.ACK&&this.state===Ht.SYNSent&&(this.state=Ht.Established),(e&xe.FIN)===xe.FIN&&this.onRemoteCloseWrite(),(e&xe.RST)===xe.RST&&this.onRemoteReset()}getSendFlags(){switch(this.state){case Ht.Init:return this.state=Ht.SYNSent,xe.SYN;case Ht.SYNReceived:return this.state=Ht.Established,xe.ACK;default:return 0}}sendWindowUpdate(){if(this.state===Ht.Paused){this.epochStart=Date.now();return}let e=this.getSendFlags(),t=Date.now(),n=this.getRTT();if(e===0&&n>-1&&t-this.epochStart<=n*4&&(this.recvWindow=Math.min(this.recvWindow*2,this.maxStreamWindowSize)),this.recvWindowCapacity>=this.recvWindow&&e===0)return;let s=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:Fe.WindowUpdate,flag:e,streamID:this.streamId,length:s})}};function s_(r){return{type:Fe[r.type],flags:[(r.flag&xe.SYN)===xe.SYN?"SYN":void 0,(r.flag&xe.ACK)===xe.ACK?"ACK":void 0,(r.flag&xe.FIN)===xe.FIN?"FIN":void 0,(r.flag&xe.RST)===xe.RST?"RST":void 0].filter(Boolean),streamID:r.streamID,length:r.length}}var o_="/yamux/1.0.0",x1=class{protocol=o_;_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@chainsafe/libp2p-yamux";[nt]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new n6(e,{...this._init})}},n6=class extends _f{nextStreamID;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;decoder;keepAlive;enableKeepAlive;keepAliveInterval;maxInboundStreams;maxOutboundStreams;constructor(e,t={}){super(e,{...t,protocol:o_,name:"yamux"}),this.client=e.direction==="outbound",t_(t),this.enableKeepAlive=t.enableKeepAlive??Mu.enableKeepAlive,this.keepAliveInterval=t.keepAliveInterval??Mu.keepAliveInterval,this.maxInboundStreams=t.maxInboundStreams??Mu.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??Mu.maxOutboundStreams,this.decoder=new b1,this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,this.log.trace("muxer created"),this.enableKeepAlive&&(this.log.trace("muxer keepalive enabled interval=%s",this.keepAliveInterval),this.keepAlive=P8(async n=>{try{await this.ping(n)}catch(s){this.log.error("ping error: %s",s)}},this.keepAliveInterval,{runImmediately:!0}),this.keepAlive.start())}onData(e){for(let t of this.decoder.emitFrames(e))this.handleFrame(t)}onCreateStream(){if(this.remoteGoAway!==void 0)throw new Tn("Muxer closed remotely");if(this.localGoAway!==void 0)throw new Tn("Muxer closed locally");let e=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.maxOutboundStreams)throw new Jo("max outbound streams exceeded");this.log.trace("new outgoing stream id=%s",e);let t=this._newStream(e,Ht.Init,"outbound");return this.numOutboundStreams++,queueMicrotask(()=>{t.sendWindowUpdate()}),t}async ping(e){if(this.remoteGoAway!==void 0)throw new Tn("Muxer closed remotely");if(this.localGoAway!==void 0)throw new Tn("Muxer closed locally");if(this.activePing!=null)return t6(this.activePing.promise,e?.signal);this.activePing=Object.assign(Promise.withResolvers(),{id:this.nextPingID++,start:Date.now()}),this.sendPing(this.activePing.id);try{this.rtt=await t6(this.activePing.promise,e?.signal)}finally{this.activePing=void 0}return this.rtt}getRTT(){return this.rtt}async close(e={}){if(this.status==="open")try{let t=e?.reason??at.NormalTermination;this.log.trace("muxer close reason=%s",at[t]),await super.close(e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}abort(e){if(this.status==="open")try{super.abort(e);let t=at.InternalError;e_(e)&&(t=e.reason),this.log.error("muxer abort reason=%s error=%s",t,e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}onTransportClosed(){try{super.onTransportClosed()}finally{this.keepAlive?.stop()}}_newStream(e,t,n){if(this.streams.find(o=>o.streamId===e)!=null)throw new R("Stream already exists with that id");let s=new w1({...this.streamOptions,id:`${e}`,streamId:e,state:t,direction:n,sendFrame:this.sendFrame.bind(this),log:this.log.newScope(`${n}:${e}`),getRTT:this.getRTT.bind(this)});return s.addEventListener("close",()=>{this.closeStream(e)},{once:!0}),s}closeStream(e){this.client===(e%2===0)?this.numInboundStreams--:this.numOutboundStreams--}handleFrame(e){let{streamID:t,type:n,length:s}=e.header;if(this.log.trace("received frame %o",s_(e.header)),t===0)switch(n){case Fe.Ping:{this.handlePing(e.header);return}case Fe.GoAway:{this.handleGoAway(s);return}default:throw new dr("Invalid frame type")}else switch(e.header.type){case Fe.Data:case Fe.WindowUpdate:{this.handleStreamMessage(e);return}default:throw new dr("Invalid frame type")}}handlePing(e){if(e.flag===xe.SYN)this.log.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,xe.ACK);else if(e.flag===xe.ACK)this.log.trace("received ping response pingId=%s",e.length),this.handlePingResponse(e.length);else throw new dr("Invalid frame flag")}handlePingResponse(e){if(this.activePing===void 0)throw new Ma("ping not requested");if(this.activePing.id!==e)throw new Oa("ping doesn't match our id");this.activePing.resolve(Date.now()-this.activePing.start)}handleGoAway(e){this.log.trace("received GoAway reason=%s",at[e]??"unknown"),this.remoteGoAway=e,e===at.NormalTermination?this.onTransportClosed():this.abort(new Error("Remote sent GoAway"))}handleStreamMessage(e){let{streamID:t,flag:n,type:s}=e.header;(n&xe.SYN)===xe.SYN&&this.incomingStream(t);let o=this.streams.find(i=>i.streamId===t);if(o===void 0){this.log.trace("frame for missing stream id=%s",t);return}switch(s){case Fe.WindowUpdate:{o.handleWindowUpdate(e);return}case Fe.Data:{o.handleData(e);return}default:throw new Error("unreachable")}}incomingStream(e){if(this.client!==(e%2===0))throw new R("Both endpoints are clients");if(this.streams.find(n=>n.streamId===e))return;if(this.log.trace("new incoming stream id=%s",e),this.localGoAway!==void 0){this.sendFrame({type:Fe.WindowUpdate,flag:xe.RST,streamID:e,length:0});return}if(this.numInboundStreams>=this.maxInboundStreams){this.log("maxIncomingStreams exceeded, forcing stream reset"),this.sendFrame({type:Fe.WindowUpdate,flag:xe.RST,streamID:e,length:0});return}let t=this._newStream(e,Ht.SYNReceived,"inbound");this.numInboundStreams++,this.onRemoteStream(t)}sendFrame(e,t){let n;if(e.type===Fe.Data){if(t==null)throw new dr("Invalid frame");n=new U(r6(e),t)}else n=r6(e);return this.log.trace("sending frame %o",s_(e)),this.send(n)}sendPing(e,t=xe.SYN){t===xe.SYN?this.log.trace("sending ping request pingId=%s",e):this.log.trace("sending ping response pingId=%s",e),this.sendFrame({type:Fe.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=at.NormalTermination){this.log("sending GoAway reason=%s",at[e]),this.localGoAway=e,this.sendFrame({type:Fe.GoAway,flag:0,streamID:0,length:e})}};function i_(r={}){return()=>new x1(r)}var a_="0.1.0";var c_="1.0.0";wr();var Ou;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.protocolVersion!=null&&(n.uint32(42),n.string(t.protocolVersion)),t.agentVersion!=null&&(n.uint32(50),n.string(t.agentVersion)),t.publicKey!=null&&(n.uint32(10),n.bytes(t.publicKey)),t.listenAddrs!=null)for(let o of t.listenAddrs)n.uint32(18),n.bytes(o);if(t.observedAddr!=null&&(n.uint32(34),n.bytes(t.observedAddr)),t.protocols!=null)for(let o of t.protocols)n.uint32(26),n.string(o);t.signedPeerRecord!=null&&(n.uint32(66),n.bytes(t.signedPeerRecord)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={listenAddrs:[],protocols:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 5:{o.protocolVersion=t.string();break}case 6:{o.agentVersion=t.string();break}case 1:{o.publicKey=t.bytes();break}case 2:{if(s.limits?.listenAddrs!=null&&o.listenAddrs.length===s.limits.listenAddrs)throw new _e('Decode error - map field "listenAddrs" had too many elements');o.listenAddrs.push(t.bytes());break}case 4:{o.observedAddr=t.bytes();break}case 3:{if(s.limits?.protocols!=null&&o.protocols.length===s.limits.protocols)throw new _e('Decode error - map field "protocols" had too many elements');o.protocols.push(t.string());break}case 8:{o.signedPeerRecord=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(Ou||(Ou={}));Bt();V();ke();te();var yn={protocolPrefix:"ipfs",timeout:5e3,maxInboundStreams:1,maxOutboundStreams:1,maxObservedAddresses:10,maxMessageSize:8192,runOnConnectionOpen:!0,runOnSelfUpdate:!0,runOnLimitedConnection:!0,concurrency:32};function l_(r){if(r!=null&&r.length>0)try{return q(r)}catch{}}async function u_(r,e,t,n,s){if(t("received identify from %p",n.remotePeer),s==null)throw new Rt("message was null or undefined");let o={};if(s.listenAddrs.length>0&&(o.addresses=s.listenAddrs.map(c=>({isCertified:!1,multiaddr:q(c)}))),s.protocols.length>0&&(o.protocols=s.protocols),s.publicKey!=null){let c=Ft(s.publicKey);if(!On(c).equals(n.remotePeer))throw new Rt("public key did not match remote PeerId");o.publicKey=c}let i;if(s.signedPeerRecord!=null){t.trace("received signedPeerRecord from %p",n.remotePeer);let c=s.signedPeerRecord,l=await lr.openAndCertify(c,ur.DOMAIN),u=ur.createFromProtobuf(l.payload),h=en(l.publicKey.toCID());if(!u.peerId.equals(h))throw new Rt("signing key does not match PeerId in the PeerRecord");if(!n.remotePeer.equals(u.peerId))throw new Rt("signing key does not match remote PeerId");let p;try{p=await r.get(u.peerId)}catch(f){if(f.name!=="NotFoundError")throw f}if(p!=null&&(o.metadata=p.metadata,p.peerRecordEnvelope!=null)){let f=lr.createFromProtobuf(p.peerRecordEnvelope),d=ur.createFromProtobuf(f.payload);d.seqNumber>=u.seqNumber&&(t("sequence number was lower or equal to existing sequence number - stored: %d received: %d",d.seqNumber,u.seqNumber),u=d,c=p.peerRecordEnvelope)}o.peerRecordEnvelope=c,o.addresses=u.multiaddrs.map(f=>({isCertified:!0,multiaddr:f})),i={seq:u.seqNumber,addresses:u.multiaddrs}}else t("%p did not send a signed peer record",n.remotePeer);if(t.trace("patching %p with",n.remotePeer,o),await r.patch(n.remotePeer,o),s.agentVersion!=null||s.protocolVersion!=null){let c={};s.agentVersion!=null&&(c.AgentVersion=D(s.agentVersion)),s.protocolVersion!=null&&(c.ProtocolVersion=D(s.protocolVersion)),t.trace("merging %p metadata",n.remotePeer,c),await r.merge(n.remotePeer,{metadata:c})}let a={peerId:n.remotePeer,protocolVersion:s.protocolVersion,agentVersion:s.agentVersion,publicKey:s.publicKey,listenAddrs:s.listenAddrs.map(c=>q(c)),observedAddr:s.observedAddr==null?void 0:q(s.observedAddr),protocols:s.protocols,signedPeerRecord:i,connection:n};return e.safeDispatchEvent("peer:identify",{detail:a}),a}var v1=class{host;components;protocol;started;timeout;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxObservedAddresses;runOnLimitedConnection;log;constructor(e,t){this.protocol=t.protocol,this.started=!1,this.components=e,this.log=t.log,this.timeout=t.timeout??yn.timeout,this.maxInboundStreams=t.maxInboundStreams??yn.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??yn.maxOutboundStreams,this.maxMessageSize=t.maxMessageSize??yn.maxMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??yn.maxObservedAddresses,this.runOnLimitedConnection=t.runOnLimitedConnection??yn.runOnLimitedConnection,this.host={protocolVersion:`${t.protocolPrefix??yn.protocolPrefix}/${a_}`,agentVersion:e.nodeInfo.userAgent},this.handleProtocol=this.handleProtocol.bind(this)}isStarted(){return this.started}async start(){this.started||(await this.components.peerStore.merge(this.components.peerId,{metadata:{AgentVersion:D(this.host.agentVersion),ProtocolVersion:D(this.host.protocolVersion)}}),await this.components.registrar.handle(this.protocol,this.handleProtocol,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}};Bt();V();ke();Ue();var E1=class extends v1{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??yn.protocolPrefix}/${"id"}/${c_}`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??yn.runOnConnectionOpen)&&e.events.addEventListener("connection:open",n=>{let s=n.detail;this.identify(s).catch(()=>{})})}[nt]=["@libp2p/identify"];async _identify(e,t={}){let n,s;if(t.signal==null){let o=AbortSignal.timeout(this.timeout);j(1/0,o),t={...t,signal:o}}this.log("run identify on new connection %a",e.remoteAddr);try{n=await e.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection}),s=n.log.newScope("identify");let o=zr(n,{maxDataLength:this.maxMessageSize}).pb(Ou),i=await o.read(t);return await o.unwrap().unwrap().close(t),i}catch(o){throw s?.error("identify failed - %e",o),n?.abort(o),o}}async identify(e,t={}){let n=await this._identify(e,t),{publicKey:s,protocols:o,observedAddr:i}=n;if(s==null)throw new Rt("Public key was missing from identify message");let a=Ft(s),c=en(a.toCID());if(!e.remotePeer.equals(c))throw new Rt("Identified peer does not match the expected peer");if(this.components.peerId.equals(c))throw new Rt("Identified peer is our own peer id?");return this.maybeAddObservedAddress(i),this.log("completed for peer %p and protocols %o",c,o),u_(this.components.peerStore,this.components.events,this.log,e,n)}maybeAddObservedAddress(e){let t=l_(e);if(t==null||(this.log.trace("our observed address was %a",t),Fn(t)))return;let n=t.getComponents();if((n[0].code===41||n[0].code===42&&n[1].code===41)&&!y8(t)){this.log.trace("our observed address was IPv6 but not a global unicast address");return}qn.exactMatch(t)||(this.log.trace("storing the observed address"),this.components.addressManager.addObservedAddr(t))}async handleProtocol(e,t){let n=e.log.newScope("identify");n("responding to identify");let s=AbortSignal.timeout(this.timeout);j(1/0,s);let o=await this.components.peerStore.get(this.components.peerId,{signal:s}),i=this.components.addressManager.getAddresses().map(u=>u.decapsulateCode(421)),a=o.peerRecordEnvelope;if(i.length>0&&a==null){let u=new ur({peerId:this.components.peerId,multiaddrs:i});a=(await lr.seal(u,this.components.privateKey,{signal:s})).marshal().subarray()}let c=t.remoteAddr.bytes;vC.matches(t.remoteAddr)||(c=void 0);let l=zr(e).pb(Ou);n("send response"),await l.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:dt(this.components.privateKey.publicKey),listenAddrs:i.map(u=>u.bytes),signedPeerRecord:a,observedAddr:c,protocols:o.protocols},{signal:s}),n("close write"),await l.unwrap().unwrap().close({signal:s})}};function h_(r={}){return e=>new E1(e,r)}V();function pq(r){return r.reason}async function d_(r,e,t){if(e==null)return r;let n=t?.translateError??pq;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}Be();Ne();var f_="1.0.0",p_="ping",m_="ipfs";var S1=class{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;constructor(e,t={}){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix??m_}/${p_}/${f_}`,this.timeout=t.timeout??1e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??1,this.runOnLimitedConnection=t.runOnLimitedConnection??!0,this.handlePing=this.handlePing.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[nt]=["@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(e,t){let n=e.log.newScope("ping");n.trace("ping from %p",t.remotePeer);let s=AbortSignal.timeout(this.timeout);j(1/0,s),s.addEventListener("abort",()=>{e.abort(new Gr("Ping timed out"))});let o=Date.now();for await(let i of e){if(e.status!=="open"){n("stream status changed to %s",e.status);break}e.send(i)||(n("waiting for stream to drain"),await Re(e,"drain",{rejectionEvents:["close"],signal:s}),n("stream drained"))}n("ping from %p complete in %dms",t.remotePeer,Date.now()-o),await e.close({signal:s})}async ping(e,t={}){let n=fs(32),s=await this.components.connectionManager.openStream(e,this.protocol,{runOnLimitedConnection:this.runOnLimitedConnection,...t}),o=s.log.newScope("ping");try{let i=Date.now(),a=Promise.withResolvers(),c=new U,l=u=>{if(c.append(u.data),c.byteLength===32){s.removeEventListener("message",l);let h=Date.now()-i;Promise.all([s.closeRead(t)]).then(()=>{if(W(n,c.subarray()))a.resolve(h);else throw new Sh(`Received wrong ping ack after ${h}ms`)}).catch(p=>{s.abort(p),a.reject(p)})}};return s.addEventListener("message",l),s.send(n),await s.close(t),await d_(a.promise,t.signal)}catch(i){throw o.error("error while pinging %o - %e",e,i),s?.abort(i),i}finally{s?.close()}}};function y_(r={}){return e=>new S1(e,r)}var s6=Symbol.for("@libp2p/peer-id");var $o="StrictSign",Na="StrictNoSign",qt;(function(r){r.Accept="accept",r.Ignore="ignore",r.Reject="reject"})(qt||(qt={}));var ASe=Symbol.for("@libp2p/pubsub");var I1=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var A1=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},C1=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};Ue();var b_=Symbol.for("@libp2p/service-capabilities"),w_=Symbol.for("@libp2p/service-dependencies");var ct=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Ba=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Ru=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var l6={};z(l6,{base58btc:()=>Xe,base58flickr:()=>Iq});var XSe=new Uint8Array(0);function x_(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function _r(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function v_(r){return new TextEncoder().encode(r)}function E_(r){return new TextDecoder().decode(r)}function bq(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var v=d[y],S=0,E=w-1;(v!==0||S<g)&&E!==-1;E--,S++)v+=256*x[E]>>>0,x[E]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var A=c.repeat(m);I<w;++I)A+=r.charAt(x[I]);return A}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*w[S]>>>0,w[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(d[m]!==" "){for(var E=b-y;E!==b&&w[E]===0;)E++;for(var I=new Uint8Array(g+(b-E)),A=g;E!==b;)I[A++]=w[E++];return I}}}function f(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:f}}var wq=bq,xq=wq,I_=xq;var o6=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},i6=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return A_(this,e)}},a6=class{decoders;constructor(e){this.decoders=e}or(e){return A_(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function A_(r,e){return new a6({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var c6=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new o6(e,t,n),this.decoder=new i6(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ua({name:r,prefix:e,encode:t,decode:n}){return new c6(r,e,t,n)}function Ms({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=I_(t,r);return Ua({prefix:e,name:r,encode:n,decode:o=>_r(s(o))})}function vq(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function Eq(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function Sq(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Ye({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=Sq(n);return Ua({prefix:e,name:r,encode(o){return Eq(o,n,t)},decode(o){return vq(o,s,t,r)}})}var Xe=Ms({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Iq=Ms({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var u6={};z(u6,{base32:()=>Os,base32hex:()=>_q,base32hexpad:()=>Dq,base32hexpadupper:()=>kq,base32hexupper:()=>Pq,base32pad:()=>Cq,base32padupper:()=>Tq,base32upper:()=>Aq,base32z:()=>Lq});var Os=Ye({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Aq=Ye({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Cq=Ye({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Tq=Ye({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),_q=Ye({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Pq=Ye({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Dq=Ye({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),kq=Ye({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Lq=Ye({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var h6={};z(h6,{base36:()=>Nu,base36upper:()=>Mq});var Nu=Ms({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Mq=Ms({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Oq=__,C_=128,Rq=127,Nq=~Rq,Bq=Math.pow(2,31);function __(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Bq;)e[t++]=r&255|C_,r/=128;for(;r&Nq;)e[t++]=r&255|C_,r>>>=7;return e[t]=r|0,__.bytes=t-n+1,e}var Uq=d6,Kq=128,T_=127;function d6(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw d6.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&T_)<<s:(i&T_)*Math.pow(2,s),s+=7}while(i>=Kq);return d6.bytes=o-n,t}var Fq=Math.pow(2,7),zq=Math.pow(2,14),$q=Math.pow(2,21),Hq=Math.pow(2,28),qq=Math.pow(2,35),Vq=Math.pow(2,42),Gq=Math.pow(2,49),Wq=Math.pow(2,56),jq=Math.pow(2,63),Yq=function(r){return r<Fq?1:r<zq?2:r<$q?3:r<Hq?4:r<qq?5:r<Vq?6:r<Gq?7:r<Wq?8:r<jq?9:10},Xq={encode:Oq,decode:Uq,encodingLength:Yq},Qq=Xq,Bu=Qq;function Uu(r,e=0){return[Bu.decode(r,e),Bu.decode.bytes]}function Ka(r,e,t=0){return Bu.encode(r,e,t),e}function Fa(r){return Bu.encodingLength(r)}function bn(r,e){let t=e.byteLength,n=Fa(r),s=n+Fa(t),o=new Uint8Array(s+t);return Ka(r,o,0),Ka(t,o,n),o.set(e,s),new za(r,t,e,o)}function Yn(r){let e=_r(r),[t,n]=Uu(e),[s,o]=Uu(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new za(t,s,i,e)}function P_(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&x_(r.bytes,t.bytes)}}var za=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function D_(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Zq(t,f6(r),e??Xe.encoder);default:return eV(t,f6(r),e??Os.encoder)}}var k_=new WeakMap;function f6(r){let e=k_.get(r);if(e==null){let t=new Map;return k_.set(r,t),t}return e}var lt=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Ku)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==tV)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=bn(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&P_(e.multihash,n.multihash)}toString(e){return D_(this,e)}toJSON(){return{"/":D_(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??L_(n,s,o.bytes))}else if(t[rV]===!0){let{version:n,multihash:s,code:o}=t,i=Yn(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Ku)throw new Error(`Version 0 CID must use dag-pb (code: ${Ku}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=L_(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ku,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=_r(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new za(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,p]=Uu(e.subarray(t));return t+=p,h},s=n(),o=Ku;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=Jq(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return f6(o).set(n,e),o}};function Jq(r,e){switch(r[0]){case"Q":{let t=e??Xe;return[Xe.prefix,t.decode(`${Xe.prefix}${r}`)]}case Xe.prefix:{let t=e??Xe;return[Xe.prefix,t.decode(r)]}case Os.prefix:{let t=e??Os;return[Os.prefix,t.decode(r)]}case Nu.prefix:{let t=e??Nu;return[Nu.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Zq(r,e,t){let{prefix:n}=t;if(n!==Xe.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function eV(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var Ku=112,tV=18;function L_(r,e,t){let n=Fa(r),s=n+Fa(e),o=new Uint8Array(s+t.byteLength);return Ka(r,o,0),Ka(e,o,n),o.set(t,s),o}var rV=Symbol.for("@ipld/js-cid/CID");var p6={};z(p6,{identity:()=>$r});var M_=0,nV="identity",O_=_r;function sV(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return bn(M_,O_(r))}var $r={code:M_,name:nV,encode:O_,digest:sV};Ne();Be();te();ce();Be();var oV=parseInt("11111",2),m6=parseInt("10000000",2),iV=parseInt("01111111",2),R_={0:Fu,1:Fu,2:aV,3:uV,4:hV,5:lV,6:cV,16:Fu,22:Fu,48:Fu};function Xn(r,e={offset:0}){let t=r[e.offset]&oV;if(e.offset++,R_[t]!=null)return R_[t](r,e);throw new Error("No decoder for tag "+t)}function zu(r,e){let t=0;if((r[e.offset]&m6)===m6){let n=r[e.offset]&iV,s="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)s+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(s,16)}else t=r[e.offset],e.offset++;return t}function Fu(r,e){zu(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=Xn(r,e);if(n===null)break;t.push(n)}return t}function aV(r,e){let t=zu(r,e),n=e.offset,s=e.offset+t,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function cV(r,e){let t=zu(r,e),n=e.offset+t,s=r[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let h=0;h<c.length;h++)u+=c[h]<<h*7;a+=`.${u}`,c=[]}}return a}function lV(r,e){return e.offset++,null}function uV(r,e){let t=zu(r,e),n=r[e.offset];e.offset++;let s=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function hV(r,e){let t=zu(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function dV(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new U;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function g6(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=dV(r.byteLength);return new U(Uint8Array.from([e.byteLength|m6]),e)}function tr(r){let e=new U,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new U(Uint8Array.from([2]),g6(e),e)}function _1(r){let e=Uint8Array.from([0]),t=new U(e,r);return new U(Uint8Array.from([3]),g6(t),t)}function Ns(r,e=48){let t=new U;for(let n of r)t.append(n);return new U(Uint8Array.from([e]),g6(t),t)}async function N_(r,e,t,n){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,e,t.subarray());return n?.signal?.throwIfAborted(),o}var fV=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),pV=Uint8Array.from([6,5,43,129,4,0,34]),mV=Uint8Array.from([6,5,43,129,4,0,35]),gV={ext:!0,kty:"EC",crv:"P-256"},yV={ext:!0,kty:"EC",crv:"P-384"},bV={ext:!0,kty:"EC",crv:"P-521"},y6=32,b6=48,w6=66;function x6(r){let e=Xn(r);return B_(e)}function B_(r){let e=r[1][1][0],t=1,n,s;if(e.byteLength===y6*2+1)return n=P(e.subarray(t,t+y6),"base64url"),s=P(e.subarray(t+y6),"base64url"),new $a({...gV,key_ops:["verify"],x:n,y:s});if(e.byteLength===b6*2+1)return n=P(e.subarray(t,t+b6),"base64url"),s=P(e.subarray(t+b6),"base64url"),new $a({...yV,key_ops:["verify"],x:n,y:s});if(e.byteLength===w6*2+1)return n=P(e.subarray(t,t+w6),"base64url"),s=P(e.subarray(t+w6),"base64url"),new $a({...bV,key_ops:["verify"],x:n,y:s});throw new ct(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function U_(r){return Ns([tr(Uint8Array.from([1])),Ns([wV(r.crv)],160),Ns([_1(new U(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function wV(r){if(r==="P-256")return fV;if(r==="P-384")return pV;if(r==="P-521")return mV;throw new ct(`Invalid curve ${r}`)}var $a=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=U_(this.jwk)),this._raw}toMultihash(){return $r.digest(Bs(this))}toCID(){return lt.createV1(114,this.toMultihash())}toString(){return Xe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}async verify(e,t,n){return N_(this.jwk,t,e,n)}};var P1=ie(ee("crypto"),1);bt();te();ce();var KIe=P1.default.generateKeyPairSync,$u=32;var xV=64;function K_(r,e,t){if(r.byteLength!==$u)throw new TypeError('"key" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');if(e.byteLength!==xV)throw new TypeError('"sig" must be 64 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"sig" must be a node.js Buffer, or Uint8Array.');let n=P1.default.createPublicKey({format:"jwk",key:{crv:"Ed25519",x:P(r,"base64url"),kty:"OKP"}});return P1.default.verify(null,t instanceof Uint8Array?t:t.subarray(),n,e)}Ne();bt();te();function z_(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var D1=class{type="Ed25519";raw;constructor(e){this.raw=v6(e,$u)}toMultihash(){return $r.digest(Bs(this))}toCID(){return lt.createV1(114,this.toMultihash())}toString(){return Xe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let s=K_(this.raw,t,e);return z_(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}};function E6(r){return r=v6(r,$u),new D1(r)}function v6(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new ct(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}wr();var Ze;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Ze||(Ze={}));var S6;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(S6||(S6={}));(function(r){r.codec=()=>sr(S6)})(Ze||(Ze={}));var wn;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Ze.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=Ze.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(wn||(wn={}));var I6;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Ze.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=Ze.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(I6||(I6={}));var L1=ie(ee("node:crypto"),1),X_=ee("node:util");te();Jr();function k1(r){if(isNaN(r)||r<=0)throw new ct("random bytes length must be a Number bigger than 0");return Qr(r)}var qu={};z(qu,{MAX_RSA_KEY_SIZE:()=>A6,generateRSAKeyPair:()=>G_,jwkToJWKKeyPair:()=>W_,jwkToPkcs1:()=>AV,jwkToPkix:()=>P6,jwkToRSAPrivateKey:()=>M6,pkcs1MessageToJwk:()=>T6,pkcs1MessageToRSAPrivateKey:()=>D6,pkcs1ToJwk:()=>IV,pkcs1ToRSAPrivateKey:()=>V_,pkixMessageToJwk:()=>_6,pkixMessageToRSAPublicKey:()=>L6,pkixToJwk:()=>CV,pkixToRSAPublicKey:()=>k6});Kc();te();ce();Ne();var Ha=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=qu.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return lt.createV1(114,this._multihash)}toString(){return Xe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){return q_(this.jwk,t,e,n)}},Hu=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=qu.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}sign(e,t){return H_(this.jwk,e,t)}};var A6=8192,C6=18,EV=1062,SV=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function IV(r){let e=Xn(r);return T6(e)}function T6(r){return{n:P(r[1],"base64url"),e:P(r[2],"base64url"),d:P(r[3],"base64url"),p:P(r[4],"base64url"),q:P(r[5],"base64url"),dp:P(r[6],"base64url"),dq:P(r[7],"base64url"),qi:P(r[8],"base64url"),kty:"RSA"}}function AV(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new ct("JWK was missing components");return Ns([tr(Uint8Array.from([0])),tr(D(r.n,"base64url")),tr(D(r.e,"base64url")),tr(D(r.d,"base64url")),tr(D(r.p,"base64url")),tr(D(r.q,"base64url")),tr(D(r.dp,"base64url")),tr(D(r.dq,"base64url")),tr(D(r.qi,"base64url"))]).subarray()}function CV(r){let e=Xn(r,{offset:0});return _6(e)}function _6(r){let e=Xn(r[1],{offset:0});return{kty:"RSA",n:P(e[0],"base64url"),e:P(e[1],"base64url")}}function P6(r){if(r.n==null||r.e==null)throw new ct("JWK was missing components");return Ns([SV,_1(Ns([tr(D(r.n,"base64url")),tr(D(r.e,"base64url"))]))]).subarray()}function V_(r){let e=Xn(r);return D6(e)}function D6(r){let e=T6(r);return M6(e)}function k6(r,e){if(r.byteLength>=EV)throw new Ba("Key size is too large");let t=Xn(r,{offset:0});return L6(t,r,e)}function L6(r,e,t){let n=_6(r);if(t==null){let s=Yt(wn.encode({Type:Ze.RSA,Data:e}));t=bn(C6,s)}return new Ha(n,t)}function M6(r){if(Y_(r)>A6)throw new ct("Key size is too large");let e=W_(r),t=Yt(wn.encode({Type:Ze.RSA,Data:P6(e.publicKey)})),n=bn(C6,t);return new Hu(e.privateKey,new Ha(e.publicKey,n))}async function G_(r){if(r>A6)throw new ct("Key size is too large");let e=await j_(r),t=Yt(wn.encode({Type:Ze.RSA,Data:P6(e.publicKey)})),n=bn(C6,t);return new Hu(e.privateKey,new Ha(e.publicKey,n))}function W_(r){if(r==null)throw new ct("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var TV=(0,X_.promisify)(L1.default.generateKeyPair);async function j_(r,e){let t=await TV("rsa",{modulusLength:r,publicKeyEncoding:{type:"pkcs1",format:"jwk"},privateKeyEncoding:{type:"pkcs1",format:"jwk"}});return e?.signal?.throwIfAborted(),{privateKey:t.privateKey,publicKey:t.publicKey}}function H_(r,e,t){t?.signal?.throwIfAborted();let n=L1.default.createSign("RSA-SHA256");if(e instanceof Uint8Array)n.update(e);else for(let s of e)n.update(s);return n.sign({format:"jwk",key:r})}function q_(r,e,t,n){n?.signal?.throwIfAborted();let s=L1.default.createVerify("RSA-SHA256");if(t instanceof Uint8Array)s.update(t);else for(let o of t)s.update(o);return s.verify({format:"jwk",key:r},e)}function Y_(r){if(r.kty!=="RSA")throw new ct("Invalid key type");if(r.n==null)throw new ct("Invalid key modulus");return D(r.n,"base64url").length*8}var Q_=ie(ee("node:crypto"),1);eo();var M1=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}};function J_(r,e,t,n){n?.signal?.throwIfAborted();let s=Q_.default.createHash("sha256");if(t instanceof Uint8Array)s.update(t);else for(let i of t)s.update(i);let o=s.digest();try{return st.verify(e,o,r,{prehash:!1,format:"der"})}catch(i){throw new M1(String(i))}}eo();Ne();var O1=class{type="secp256k1";raw;_key;constructor(e){this._key=eP(e),this.raw=Z_(this._key)}toMultihash(){return $r.digest(Bs(this))}toCID(){return lt.createV1(114,this.toMultihash())}toString(){return Xe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){return J_(this._key,t,e,n)}};function O6(r){return new O1(r)}function Z_(r){return st.Point.fromBytes(r).toBytes()}function eP(r){try{return st.Point.fromBytes(r),r}catch(e){throw new Ba(String(e))}}function R6(r,e){let{Type:t,Data:n}=wn.decode(r),s=n??new Uint8Array;switch(t){case Ze.RSA:return k6(s,e);case Ze.Ed25519:return E6(s);case Ze.secp256k1:return O6(s);case Ze.ECDSA:return x6(s);default:throw new Ru}}function tP(r){let{Type:e,Data:t}=wn.decode(r.digest),n=t??new Uint8Array;switch(e){case Ze.Ed25519:return E6(n);case Ze.secp256k1:return O6(n);case Ze.ECDSA:return x6(n);default:throw new Ru}}function Bs(r){return wn.encode({Type:Ze[r.type],Data:r.raw})}var K6={};z(K6,{sha256:()=>Vu,sha512:()=>PV});var U6=ie(ee("crypto"),1);var _V=20;function B6({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new N6(r,e,t,n,s)}var N6=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??_V,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?rP(n,this.code,t?.truncate):n.then(s=>rP(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function rP(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return bn(e,r)}var Vu=B6({name:"sha2-256",code:18,encode:r=>_r(U6.default.createHash("sha256").update(r).digest())}),PV=B6({name:"sha2-512",code:19,encode:r=>_r(U6.default.createHash("sha512").update(r).digest())});ce();Ne();te();ce();var sP=Symbol.for("nodejs.util.inspect.custom"),DV=114,Gu=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[s6]=!0;toString(){return this.string==null&&(this.string=Xe.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return lt.createV1(DV,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return W(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return W(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[sP](){return`PeerId(${this.toString()})`}},R1=class extends Gu{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},N1=class extends Gu{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},B1=class extends Gu{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},kV=2336,Wu=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=$r.digest(D(this.url))}[sP](){return`PeerId(${this.url})`}[s6]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return lt.createV1(kV,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=P(e)),e.toString()===this.toString())}};var LV=114,oP=2336;function Ho(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Yn(Xe.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return MV(lt.parse(r));if(e==null)throw new I1('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Yn(e.decode(r))}return qa(t)}function qa(r){if(RV(r))return new R1({multihash:r});if(OV(r))try{let e=tP(r);if(e.type==="Ed25519")return new N1({multihash:r,publicKey:e});if(e.type==="secp256k1")return new B1({multihash:r,publicKey:e})}catch{let t=P(r.digest);return new Wu(new URL(t))}throw new C1("Supplied PeerID Multihash is invalid")}function MV(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==LV&&r.code!==oP)throw new A1("Supplied PeerID CID is invalid");if(r.code===oP){let e=P(r.multihash.digest);return new Wu(new URL(e))}return qa(r.multihash)}function OV(r){return r.code===$r.code}function RV(r){return r.code===Vu.code}gr();Be();rt();function U1(r){return r[Symbol.asyncIterator]!=null}var K1=r=>{let e=Ae(r),t=tt(e);return Vr(r,t),K1.bytes=e,t};K1.bytes=0;function Va(r,e){e=e??{};let t=e.lengthEncoder??K1;function*n(s){let o=t(s.byteLength);o instanceof Uint8Array?yield o:yield*o,s instanceof Uint8Array?yield s:yield*s}return U1(r)?(async function*(){for await(let s of r)yield*n(s)})():(function*(){for(let s of r)yield*n(s)})()}Va.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??K1;return new U(t(r.byteLength),r)};gr();Be();var F1=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},z1=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},$1=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},ju=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var NV=8,BV=1024*1024*4,qo;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(qo||(qo={}));var F6=r=>{let e=jt(r);return F6.bytes=Ae(e),e};F6.bytes=0;function Yu(r,e){let t=new U,n=qo.LENGTH,s=-1,o=e?.lengthDecoder??F6,i=e?.maxLengthLength??NV,a=e?.maxDataLength??BV;function*c(){for(;t.byteLength>0;){if(n===qo.LENGTH)try{if(s=o(t),s<0)throw new F1("Invalid message length");if(s>a)throw new z1("Message length too long");let l=o.bytes;t.consume(l),e?.onLength!=null&&e.onLength(s),n=qo.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new $1("Message length length too long");break}throw l}if(n===qo.DATA){if(t.byteLength<s)break;let l=t.sublist(0,s);t.consume(s),e?.onData!=null&&e.onData(l),yield l,n=qo.LENGTH}}}return U1(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new ju("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new ju("Unexpected end of input")})()}Yu.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:o,value:i}=await r.next(t);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}})();return Yu(n,{...e??{},onLength:o=>{t=o}})};var z6="/floodsub/1.0.0",$6="/meshsub/1.0.0",iP="/meshsub/1.1.0",H1="/meshsub/1.2.0";var aP="ERR_TOPIC_VALIDATOR_REJECT",cP="ERR_TOPIC_VALIDATOR_IGNORE";var lP={maxSubscriptions:1/0,maxMessages:1/0,maxIhaveMessageIDs:1/0,maxIwantMessageIDs:1/0,maxIdontwantMessageIDs:1/0,maxControlMessages:1/0,maxPeerInfos:1/0};wr();var Qn;(function(r){let e;(function(h){let p;h.codec=()=>(p==null&&(p=Z((f,d,m={})=>{m.lengthDelimited!==!1&&d.fork(),f.subscribe!=null&&(d.uint32(8),d.bool(f.subscribe)),f.topic!=null&&(d.uint32(18),d.string(f.topic)),m.lengthDelimited!==!1&&d.ldelim()},(f,d,m={})=>{let g={},y=d==null?f.len:f.pos+d;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{g.subscribe=f.bool();break}case 2:{g.topic=f.string();break}default:{f.skipType(b&7);break}}}return g})),p),h.encode=f=>J(f,h.codec()),h.decode=(f,d)=>Q(f,h.codec(),d)})(e=r.SubOpts||(r.SubOpts={}));let t;(function(h){let p;h.codec=()=>(p==null&&(p=Z((f,d,m={})=>{m.lengthDelimited!==!1&&d.fork(),f.from!=null&&(d.uint32(10),d.bytes(f.from)),f.data!=null&&(d.uint32(18),d.bytes(f.data)),f.seqno!=null&&(d.uint32(26),d.bytes(f.seqno)),f.topic!=null&&f.topic!==""&&(d.uint32(34),d.string(f.topic)),f.signature!=null&&(d.uint32(42),d.bytes(f.signature)),f.key!=null&&(d.uint32(50),d.bytes(f.key)),m.lengthDelimited!==!1&&d.ldelim()},(f,d,m={})=>{let g={topic:""},y=d==null?f.len:f.pos+d;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{g.from=f.bytes();break}case 2:{g.data=f.bytes();break}case 3:{g.seqno=f.bytes();break}case 4:{g.topic=f.string();break}case 5:{g.signature=f.bytes();break}case 6:{g.key=f.bytes();break}default:{f.skipType(b&7);break}}}return g})),p),h.encode=f=>J(f,h.codec()),h.decode=(f,d)=>Q(f,h.codec(),d)})(t=r.Message||(r.Message={}));let n;(function(h){let p;h.codec=()=>(p==null&&(p=Z((f,d,m={})=>{if(m.lengthDelimited!==!1&&d.fork(),f.ihave!=null)for(let g of f.ihave)d.uint32(10),r.ControlIHave.codec().encode(g,d);if(f.iwant!=null)for(let g of f.iwant)d.uint32(18),r.ControlIWant.codec().encode(g,d);if(f.graft!=null)for(let g of f.graft)d.uint32(26),r.ControlGraft.codec().encode(g,d);if(f.prune!=null)for(let g of f.prune)d.uint32(34),r.ControlPrune.codec().encode(g,d);if(f.idontwant!=null)for(let g of f.idontwant)d.uint32(42),r.ControlIDontWant.codec().encode(g,d);m.lengthDelimited!==!1&&d.ldelim()},(f,d,m={})=>{let g={ihave:[],iwant:[],graft:[],prune:[],idontwant:[]},y=d==null?f.len:f.pos+d;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{if(m.limits?.ihave!=null&&g.ihave.length===m.limits.ihave)throw new _e('Decode error - map field "ihave" had too many elements');g.ihave.push(r.ControlIHave.codec().decode(f,f.uint32(),{limits:m.limits?.ihave$}));break}case 2:{if(m.limits?.iwant!=null&&g.iwant.length===m.limits.iwant)throw new _e('Decode error - map field "iwant" had too many elements');g.iwant.push(r.ControlIWant.codec().decode(f,f.uint32(),{limits:m.limits?.iwant$}));break}case 3:{if(m.limits?.graft!=null&&g.graft.length===m.limits.graft)throw new _e('Decode error - map field "graft" had too many elements');g.graft.push(r.ControlGraft.codec().decode(f,f.uint32(),{limits:m.limits?.graft$}));break}case 4:{if(m.limits?.prune!=null&&g.prune.length===m.limits.prune)throw new _e('Decode error - map field "prune" had too many elements');g.prune.push(r.ControlPrune.codec().decode(f,f.uint32(),{limits:m.limits?.prune$}));break}case 5:{if(m.limits?.idontwant!=null&&g.idontwant.length===m.limits.idontwant)throw new _e('Decode error - map field "idontwant" had too many elements');g.idontwant.push(r.ControlIDontWant.codec().decode(f,f.uint32(),{limits:m.limits?.idontwant$}));break}default:{f.skipType(b&7);break}}}return g})),p),h.encode=f=>J(f,h.codec()),h.decode=(f,d)=>Q(f,h.codec(),d)})(n=r.ControlMessage||(r.ControlMessage={}));let s;(function(h){let p;h.codec=()=>(p==null&&(p=Z((f,d,m={})=>{if(m.lengthDelimited!==!1&&d.fork(),f.topicID!=null&&(d.uint32(10),d.string(f.topicID)),f.messageIDs!=null)for(let g of f.messageIDs)d.uint32(18),d.bytes(g);m.lengthDelimited!==!1&&d.ldelim()},(f,d,m={})=>{let g={messageIDs:[]},y=d==null?f.len:f.pos+d;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{g.topicID=f.string();break}case 2:{if(m.limits?.messageIDs!=null&&g.messageIDs.length===m.limits.messageIDs)throw new _e('Decode error - map field "messageIDs" had too many elements');g.messageIDs.push(f.bytes());break}default:{f.skipType(b&7);break}}}return g})),p),h.encode=f=>J(f,h.codec()),h.decode=(f,d)=>Q(f,h.codec(),d)})(s=r.ControlIHave||(r.ControlIHave={}));let o;(function(h){let p;h.codec=()=>(p==null&&(p=Z((f,d,m={})=>{if(m.lengthDelimited!==!1&&d.fork(),f.messageIDs!=null)for(let g of f.messageIDs)d.uint32(10),d.bytes(g);m.lengthDelimited!==!1&&d.ldelim()},(f,d,m={})=>{let g={messageIDs:[]},y=d==null?f.len:f.pos+d;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{if(m.limits?.messageIDs!=null&&g.messageIDs.length===m.limits.messageIDs)throw new _e('Decode error - map field "messageIDs" had too many elements');g.messageIDs.push(f.bytes());break}default:{f.skipType(b&7);break}}}return g})),p),h.encode=f=>J(f,h.codec()),h.decode=(f,d)=>Q(f,h.codec(),d)})(o=r.ControlIWant||(r.ControlIWant={}));let i;(function(h){let p;h.codec=()=>(p==null&&(p=Z((f,d,m={})=>{m.lengthDelimited!==!1&&d.fork(),f.topicID!=null&&(d.uint32(10),d.string(f.topicID)),m.lengthDelimited!==!1&&d.ldelim()},(f,d,m={})=>{let g={},y=d==null?f.len:f.pos+d;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{g.topicID=f.string();break}default:{f.skipType(b&7);break}}}return g})),p),h.encode=f=>J(f,h.codec()),h.decode=(f,d)=>Q(f,h.codec(),d)})(i=r.ControlGraft||(r.ControlGraft={}));let a;(function(h){let p;h.codec=()=>(p==null&&(p=Z((f,d,m={})=>{if(m.lengthDelimited!==!1&&d.fork(),f.topicID!=null&&(d.uint32(10),d.string(f.topicID)),f.peers!=null)for(let g of f.peers)d.uint32(18),r.PeerInfo.codec().encode(g,d);f.backoff!=null&&(d.uint32(24),d.uint64Number(f.backoff)),m.lengthDelimited!==!1&&d.ldelim()},(f,d,m={})=>{let g={peers:[]},y=d==null?f.len:f.pos+d;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{g.topicID=f.string();break}case 2:{if(m.limits?.peers!=null&&g.peers.length===m.limits.peers)throw new _e('Decode error - map field "peers" had too many elements');g.peers.push(r.PeerInfo.codec().decode(f,f.uint32(),{limits:m.limits?.peers$}));break}case 3:{g.backoff=f.uint64Number();break}default:{f.skipType(b&7);break}}}return g})),p),h.encode=f=>J(f,h.codec()),h.decode=(f,d)=>Q(f,h.codec(),d)})(a=r.ControlPrune||(r.ControlPrune={}));let c;(function(h){let p;h.codec=()=>(p==null&&(p=Z((f,d,m={})=>{m.lengthDelimited!==!1&&d.fork(),f.peerID!=null&&(d.uint32(10),d.bytes(f.peerID)),f.signedPeerRecord!=null&&(d.uint32(18),d.bytes(f.signedPeerRecord)),m.lengthDelimited!==!1&&d.ldelim()},(f,d,m={})=>{let g={},y=d==null?f.len:f.pos+d;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{g.peerID=f.bytes();break}case 2:{g.signedPeerRecord=f.bytes();break}default:{f.skipType(b&7);break}}}return g})),p),h.encode=f=>J(f,h.codec()),h.decode=(f,d)=>Q(f,h.codec(),d)})(c=r.PeerInfo||(r.PeerInfo={}));let l;(function(h){let p;h.codec=()=>(p==null&&(p=Z((f,d,m={})=>{if(m.lengthDelimited!==!1&&d.fork(),f.messageIDs!=null)for(let g of f.messageIDs)d.uint32(10),d.bytes(g);m.lengthDelimited!==!1&&d.ldelim()},(f,d,m={})=>{let g={messageIDs:[]},y=d==null?f.len:f.pos+d;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{if(m.limits?.messageIDs!=null&&g.messageIDs.length===m.limits.messageIDs)throw new _e('Decode error - map field "messageIDs" had too many elements');g.messageIDs.push(f.bytes());break}default:{f.skipType(b&7);break}}}return g})),p),h.encode=f=>J(f,h.codec()),h.decode=(f,d)=>Q(f,h.codec(),d)})(l=r.ControlIDontWant||(r.ControlIDontWant={}));let u;r.codec=()=>(u==null&&(u=Z((h,p,f={})=>{if(f.lengthDelimited!==!1&&p.fork(),h.subscriptions!=null)for(let d of h.subscriptions)p.uint32(10),r.SubOpts.codec().encode(d,p);if(h.messages!=null)for(let d of h.messages)p.uint32(18),r.Message.codec().encode(d,p);h.control!=null&&(p.uint32(26),r.ControlMessage.codec().encode(h.control,p)),f.lengthDelimited!==!1&&p.ldelim()},(h,p,f={})=>{let d={subscriptions:[],messages:[]},m=p==null?h.len:h.pos+p;for(;h.pos<m;){let g=h.uint32();switch(g>>>3){case 1:{if(f.limits?.subscriptions!=null&&d.subscriptions.length===f.limits.subscriptions)throw new _e('Decode error - map field "subscriptions" had too many elements');d.subscriptions.push(r.SubOpts.codec().decode(h,h.uint32(),{limits:f.limits?.subscriptions$}));break}case 2:{if(f.limits?.messages!=null&&d.messages.length===f.limits.messages)throw new _e('Decode error - map field "messages" had too many elements');d.messages.push(r.Message.codec().decode(h,h.uint32(),{limits:f.limits?.messages$}));break}case 3:{d.control=r.ControlMessage.codec().decode(h,h.uint32(),{limits:f.limits?.control});break}default:{h.skipType(g&7);break}}}return d})),u),r.encode=h=>J(h,r.codec()),r.decode=(h,p)=>Q(h,r.codec(),p)})(Qn||(Qn={}));var q1=class{gossip;msgs=new Map;msgIdToStrFn;history=[];notValidatedCount=0;constructor(e,t,n){this.gossip=e,this.msgIdToStrFn=n;for(let s=0;s<t;s++)this.history[s]=[]}get size(){return this.msgs.size}put(e,t,n=!1){let{msgIdStr:s}=e;return this.msgs.has(s)?!1:(this.msgs.set(s,{message:t,validated:n,originatingPeers:new Set,iwantCounts:new Map}),this.history[0].push({...e,topic:t.topic}),n||this.notValidatedCount++,!0)}observeDuplicate(e,t){let n=this.msgs.get(e);n!=null&&!n.validated&&n.originatingPeers.add(t)}get(e){return this.msgs.get(this.msgIdToStrFn(e))?.message}getWithIWantCount(e,t){let n=this.msgs.get(e);if(n==null)return null;let s=(n.iwantCounts.get(t)??0)+1;return n.iwantCounts.set(t,s),{msg:n.message,count:s}}getGossipIDs(e){let t=new Map;for(let n=0;n<this.gossip;n++)this.history[n].forEach(s=>{if((this.msgs.get(s.msgIdStr)?.validated??!1)&&e.has(s.topic)){let i=t.get(s.topic);i==null&&(i=[],t.set(s.topic,i)),i.push(s.msgId)}});return t}validate(e){let t=this.msgs.get(e);if(t==null)return null;t.validated||this.notValidatedCount--;let{message:n,originatingPeers:s}=t;return t.validated=!0,t.originatingPeers=new Set,{message:n,originatingPeers:s}}shift(){this.history[this.history.length-1].forEach(t=>{let n=this.msgs.get(t.msgIdStr);n!=null&&(this.msgs.delete(t.msgIdStr),n.validated||this.notValidatedCount--)}),this.history.pop(),this.history.unshift([])}remove(e){let t=this.msgs.get(e);return t==null?null:(this.msgs.delete(e),t)}};var uP;(function(r){r.StrictSign="StrictSign",r.StrictNoSign="StrictNoSign"})(uP||(uP={}));var Us;(function(r){r[r.Signing=0]="Signing",r[r.Anonymous=1]="Anonymous"})(Us||(Us={}));var Vt;(function(r){r.Error="error",r.Ignore="ignore",r.Reject="reject",r.Blacklisted="blacklisted"})(Vt||(Vt={}));var Lt;(function(r){r.InvalidSignature="invalid_signature",r.InvalidSeqno="invalid_seqno",r.InvalidPeerId="invalid_peerid",r.SignaturePresent="signature_present",r.SeqnoPresent="seqno_present",r.FromPresent="from_present",r.TransformFailed="transform_failed"})(Lt||(Lt={}));var Mt;(function(r){r.duplicate="duplicate",r.invalid="invalid",r.valid="valid"})(Mt||(Mt={}));function H6(r){switch(r){case qt.Ignore:return Vt.Ignore;case qt.Reject:return Vt.Reject;default:throw new Error("Unreachable")}}var hP;(function(r){r.forward="forward",r.publish="publish"})(hP||(hP={}));var Gt;(function(r){r.Fanout="fanout",r.Random="random",r.Subscribed="subscribed",r.Outbound="outbound",r.NotEnough="not_enough",r.Opportunistic="opportunistic"})(Gt||(Gt={}));var Hr;(function(r){r.Dc="disconnected",r.BadScore="bad_score",r.Prune="prune",r.Excess="excess"})(Hr||(Hr={}));var Wa;(function(r){r.GraftBackoff="graft_backoff",r.BrokenPromise="broken_promise",r.MessageDeficit="message_deficit",r.IPColocation="IP_colocation"})(Wa||(Wa={}));var ja;(function(r){r.LowScore="low_score",r.MaxIhave="max_ihave",r.MaxIasked="max_iasked"})(ja||(ja={}));var Ga;(function(r){r.graylist="graylist",r.publish="publish",r.gossip="gossip",r.mesh="mesh"})(Ga||(Ga={}));function dP(r,e,t){return{protocolsEnabled:r.gauge({name:"gossipsub_protocol",help:"Status of enabled protocols",labelNames:["protocol"]}),topicSubscriptionStatus:r.gauge({name:"gossipsub_topic_subscription_status",help:"Status of our subscription to this topic",labelNames:["topicStr"]}),topicPeersCount:r.gauge({name:"gossipsub_topic_peer_count",help:"Number of peers subscribed to each topic",labelNames:["topicStr"]}),meshPeerCounts:r.gauge({name:"gossipsub_mesh_peer_count",help:"Number of peers in our mesh",labelNames:["topicStr"]}),meshPeerInclusionEventsFanout:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_fanout_total",help:"Number of times we include peers in a topic mesh for fanout reasons",labelNames:["topic"]}),meshPeerInclusionEventsRandom:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_random_total",help:"Number of times we include peers in a topic mesh for random reasons",labelNames:["topic"]}),meshPeerInclusionEventsSubscribed:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_subscribed_total",help:"Number of times we include peers in a topic mesh for subscribed reasons",labelNames:["topic"]}),meshPeerInclusionEventsOutbound:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_outbound_total",help:"Number of times we include peers in a topic mesh for outbound reasons",labelNames:["topic"]}),meshPeerInclusionEventsNotEnough:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_not_enough_total",help:"Number of times we include peers in a topic mesh for not_enough reasons",labelNames:["topic"]}),meshPeerInclusionEventsOpportunistic:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_opportunistic_total",help:"Number of times we include peers in a topic mesh for opportunistic reasons",labelNames:["topic"]}),meshPeerInclusionEventsUnknown:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_unknown_total",help:"Number of times we include peers in a topic mesh for unknown reasons",labelNames:["topic"]}),meshPeerChurnEventsDisconnected:r.gauge({name:"gossipsub_peer_churn_events_disconnected_total",help:"Number of times we remove peers in a topic mesh for disconnected reasons",labelNames:["topic"]}),meshPeerChurnEventsBadScore:r.gauge({name:"gossipsub_peer_churn_events_bad_score_total",help:"Number of times we remove peers in a topic mesh for bad_score reasons",labelNames:["topic"]}),meshPeerChurnEventsPrune:r.gauge({name:"gossipsub_peer_churn_events_prune_total",help:"Number of times we remove peers in a topic mesh for prune reasons",labelNames:["topic"]}),meshPeerChurnEventsExcess:r.gauge({name:"gossipsub_peer_churn_events_excess_total",help:"Number of times we remove peers in a topic mesh for excess reasons",labelNames:["topic"]}),meshPeerChurnEventsUnknown:r.gauge({name:"gossipsub_peer_churn_events_unknown_total",help:"Number of times we remove peers in a topic mesh for unknown reasons",labelNames:["topic"]}),peersPerProtocol:r.gauge({name:"gossipsub_peers_per_protocol_count",help:"Peers connected for each topic",labelNames:["protocol"]}),heartbeatDuration:r.histogram({name:"gossipsub_heartbeat_duration_seconds",help:"The time it takes to complete one iteration of the heartbeat",buckets:[.01,.1,1]}),heartbeatSkipped:r.gauge({name:"gossipsub_heartbeat_skipped",help:"Heartbeat run took longer than heartbeat interval so next is skipped"}),acceptedMessagesTotal:r.gauge({name:"gossipsub_accepted_messages_total",help:"Total accepted messages for each topic",labelNames:["topic"]}),ignoredMessagesTotal:r.gauge({name:"gossipsub_ignored_messages_total",help:"Total ignored messages for each topic",labelNames:["topic"]}),rejectedMessagesTotal:r.gauge({name:"gossipsub_rejected_messages_total",help:"Total rejected messages for each topic",labelNames:["topic"]}),unknownValidationResultsTotal:r.gauge({name:"gossipsub_unknown_validation_results_total",help:"Total unknown validation results for each topic",labelNames:["topic"]}),asyncValidationMcacheHit:r.gauge({name:"gossipsub_async_validation_mcache_hit_total",help:"Async validation result reported by the user layer",labelNames:["hit"]}),asyncValidationDelayFromFirstSeenSec:r.histogram({name:"gossipsub_async_validation_delay_from_first_seen",help:"Async validation report delay from first seen in second",buckets:[.01,.03,.1,.3,1,3,10]}),asyncValidationUnknownFirstSeen:r.gauge({name:"gossipsub_async_validation_unknown_first_seen_count_total",help:"Async validation report unknown first seen value for message"}),peerReadStreamError:r.gauge({name:"gossipsub_peer_read_stream_err_count_total",help:"Peer read stream error"}),rpcRecvBytes:r.gauge({name:"gossipsub_rpc_recv_bytes_total",help:"RPC recv"}),rpcRecvCount:r.gauge({name:"gossipsub_rpc_recv_count_total",help:"RPC recv"}),rpcRecvSubscription:r.gauge({name:"gossipsub_rpc_recv_subscription_total",help:"RPC recv"}),rpcRecvMessage:r.gauge({name:"gossipsub_rpc_recv_message_total",help:"RPC recv"}),rpcRecvControl:r.gauge({name:"gossipsub_rpc_recv_control_total",help:"RPC recv"}),rpcRecvIHave:r.gauge({name:"gossipsub_rpc_recv_ihave_total",help:"RPC recv"}),rpcRecvIWant:r.gauge({name:"gossipsub_rpc_recv_iwant_total",help:"RPC recv"}),rpcRecvGraft:r.gauge({name:"gossipsub_rpc_recv_graft_total",help:"RPC recv"}),rpcRecvPrune:r.gauge({name:"gossipsub_rpc_recv_prune_total",help:"RPC recv"}),rpcDataError:r.gauge({name:"gossipsub_rpc_data_err_count_total",help:"RPC data error"}),rpcRecvError:r.gauge({name:"gossipsub_rpc_recv_err_count_total",help:"RPC recv error"}),rpcRecvNotAccepted:r.gauge({name:"gossipsub_rpc_rcv_not_accepted_total",help:"Total count of RPC dropped because acceptFrom() == false"}),rpcSentBytes:r.gauge({name:"gossipsub_rpc_sent_bytes_total",help:"RPC sent"}),rpcSentCount:r.gauge({name:"gossipsub_rpc_sent_count_total",help:"RPC sent"}),rpcSentSubscription:r.gauge({name:"gossipsub_rpc_sent_subscription_total",help:"RPC sent"}),rpcSentMessage:r.gauge({name:"gossipsub_rpc_sent_message_total",help:"RPC sent"}),rpcSentControl:r.gauge({name:"gossipsub_rpc_sent_control_total",help:"RPC sent"}),rpcSentIHave:r.gauge({name:"gossipsub_rpc_sent_ihave_total",help:"RPC sent"}),rpcSentIWant:r.gauge({name:"gossipsub_rpc_sent_iwant_total",help:"RPC sent"}),rpcSentGraft:r.gauge({name:"gossipsub_rpc_sent_graft_total",help:"RPC sent"}),rpcSentPrune:r.gauge({name:"gossipsub_rpc_sent_prune_total",help:"RPC sent"}),rpcSentIDontWant:r.gauge({name:"gossipsub_rpc_sent_idontwant_total",help:"RPC sent"}),msgPublishCount:r.gauge({name:"gossipsub_msg_publish_count_total",help:"Total count of msg published by topic",labelNames:["topic"]}),msgPublishPeersByTopic:r.gauge({name:"gossipsub_msg_publish_peers_total",help:"Total count of peers that we publish a msg to",labelNames:["topic"]}),directPeersPublishedTotal:r.gauge({name:"gossipsub_direct_peers_published_total",help:"Total direct peers that we publish a msg to",labelNames:["topic"]}),floodsubPeersPublishedTotal:r.gauge({name:"gossipsub_floodsub_peers_published_total",help:"Total floodsub peers that we publish a msg to",labelNames:["topic"]}),meshPeersPublishedTotal:r.gauge({name:"gossipsub_mesh_peers_published_total",help:"Total mesh peers that we publish a msg to",labelNames:["topic"]}),fanoutPeersPublishedTotal:r.gauge({name:"gossipsub_fanout_peers_published_total",help:"Total fanout peers that we publish a msg to",labelNames:["topic"]}),msgPublishBytes:r.gauge({name:"gossipsub_msg_publish_bytes_total",help:"Total count of msg publish data.length bytes",labelNames:["topic"]}),msgPublishTime:r.histogram({name:"gossipsub_msg_publish_seconds",help:"Total time in seconds to publish a message",buckets:[.001,.002,.005,.01,.1,.5,1],labelNames:["topic"]}),msgForwardCount:r.gauge({name:"gossipsub_msg_forward_count_total",help:"Total count of msg forwarded by topic",labelNames:["topic"]}),msgForwardPeers:r.gauge({name:"gossipsub_msg_forward_peers_total",help:"Total count of peers that we forward a msg to",labelNames:["topic"]}),msgReceivedPreValidation:r.gauge({name:"gossipsub_msg_received_prevalidation_total",help:"Total count of recv msgs before any validation",labelNames:["topic"]}),msgReceivedError:r.gauge({name:"gossipsub_msg_received_error_total",help:"Total count of recv msgs error",labelNames:["topic"]}),prevalidationInvalidTotal:r.gauge({name:"gossipsub_pre_validation_invalid_total",help:"Total count of invalid messages received",labelNames:["topic"]}),prevalidationValidTotal:r.gauge({name:"gossipsub_pre_validation_valid_total",help:"Total count of valid messages received",labelNames:["topic"]}),prevalidationDuplicateTotal:r.gauge({name:"gossipsub_pre_validation_duplicate_total",help:"Total count of duplicate messages received",labelNames:["topic"]}),prevalidationUnknownTotal:r.gauge({name:"gossipsub_pre_validation_unknown_status_total",help:"Total count of unknown_status messages received",labelNames:["topic"]}),msgReceivedInvalid:r.gauge({name:"gossipsub_msg_received_invalid_total",help:"Tracks specific reason of invalid",labelNames:["error"]}),msgReceivedInvalidByTopic:r.gauge({name:"gossipsub_msg_received_invalid_by_topic_total",help:"Tracks specific invalid message by topic",labelNames:["topic"]}),duplicateMsgDeliveryDelay:r.histogram({name:"gossisub_duplicate_msg_delivery_delay_seconds",help:"Time since the 1st duplicated message validated",labelNames:["topic"],buckets:[.25*t.maxMeshMessageDeliveriesWindowSec,.5*t.maxMeshMessageDeliveriesWindowSec,Number(t.maxMeshMessageDeliveriesWindowSec),2*t.maxMeshMessageDeliveriesWindowSec,4*t.maxMeshMessageDeliveriesWindowSec]}),duplicateMsgLateDelivery:r.gauge({name:"gossisub_duplicate_msg_late_delivery_total",help:"Total count of late duplicate message delivery by topic, which triggers P3 penalty",labelNames:["topic"]}),duplicateMsgIgnored:r.gauge({name:"gossisub_ignored_published_duplicate_msgs_total",help:"Total count of published duplicate message ignored by topic",labelNames:["topic"]}),scoreFnCalls:r.gauge({name:"gossipsub_score_fn_calls_total",help:"Total times score() is called"}),scoreFnRuns:r.gauge({name:"gossipsub_score_fn_runs_total",help:"Total times score() call actually computed computeScore(), no cache"}),scoreCachedDelta:r.histogram({name:"gossipsub_score_cache_delta",help:"Delta of score between cached values that expired",buckets:[10,100,1e3]}),peersByScoreThreshold:r.gauge({name:"gossipsub_peers_by_score_threshold_count",help:"Current count of peers by score threshold",labelNames:["threshold"]}),score:r.avgMinMax({name:"gossipsub_score",help:"Avg min max of gossip scores"}),scoreWeights:r.avgMinMax({name:"gossipsub_score_weights",help:"Separate score weights",labelNames:["topic","p"]}),scorePerMesh:r.avgMinMax({name:"gossipsub_score_per_mesh",help:"Histogram of the scores for each mesh topic",labelNames:["topic"]}),scoringPenalties:r.gauge({name:"gossipsub_scoring_penalties_total",help:"A counter of the kind of penalties being applied to peers",labelNames:["penalty"]}),behaviourPenalty:r.histogram({name:"gossipsub_peer_stat_behaviour_penalty",help:"Current peer stat behaviour_penalty at each scrape",buckets:[.25*t.behaviourPenaltyThreshold,.5*t.behaviourPenaltyThreshold,Number(t.behaviourPenaltyThreshold),2*t.behaviourPenaltyThreshold,4*t.behaviourPenaltyThreshold]}),ihaveRcvIgnored:r.gauge({name:"gossipsub_ihave_rcv_ignored_total",help:"Total received IHAVE messages that we ignore for some reason",labelNames:["reason"]}),ihaveRcvMsgids:r.gauge({name:"gossipsub_ihave_rcv_msgids_total",help:"Total received IHAVE messages by topic",labelNames:["topic"]}),ihaveRcvNotSeenMsgids:r.gauge({name:"gossipsub_ihave_rcv_not_seen_msgids_total",help:"Total messages per topic we do not have, not actual requests",labelNames:["topic"]}),iwantRcvMsgids:r.gauge({name:"gossipsub_iwant_rcv_msgids_total",help:"Total received IWANT messages by topic",labelNames:["topic"]}),iwantRcvDonthaveMsgids:r.gauge({name:"gossipsub_iwant_rcv_dont_have_msgids_total",help:"Total requested messageIDs that we do not have"}),idontwantRcvMsgids:r.gauge({name:"gossipsub_idontwant_rcv_msgids_total",help:"Total received IDONTWANT messages"}),idontwantRcvDonthaveMsgids:r.gauge({name:"gossipsub_idontwant_rcv_dont_have_msgids_total",help:"Total received IDONTWANT messageIDs that we do not have in mcache"}),iwantPromiseStarted:r.gauge({name:"gossipsub_iwant_promise_sent_total",help:"Total count of started IWANT promises"}),iwantPromiseResolved:r.gauge({name:"gossipsub_iwant_promise_resolved_total",help:"Total count of resolved IWANT promises"}),iwantPromiseResolvedFromDuplicate:r.gauge({name:"gossipsub_iwant_promise_resolved_from_duplicate_total",help:"Total count of resolved IWANT promises from duplicate messages"}),iwantPromiseResolvedPeers:r.gauge({name:"gossipsub_iwant_promise_resolved_peers",help:"Total count of peers we have asked IWANT promises that are resolved"}),iwantPromiseBroken:r.gauge({name:"gossipsub_iwant_promise_broken",help:"Total count of broken IWANT promises"}),iwantMessagePruned:r.gauge({name:"gossipsub_iwant_message_pruned",help:"Total count of pruned IWANT messages"}),iwantPromiseDeliveryTime:r.histogram({name:"gossipsub_iwant_promise_delivery_seconds",help:"Histogram of delivery time of resolved IWANT promises",buckets:[.5*t.gossipPromiseExpireSec,Number(t.gossipPromiseExpireSec),2*t.gossipPromiseExpireSec,4*t.gossipPromiseExpireSec]}),iwantPromiseUntracked:r.gauge({name:"gossip_iwant_promise_untracked",help:"Total count of untracked IWANT promise"}),connectedPeersBackoffSec:r.histogram({name:"gossipsub_connected_peers_backoff_seconds",help:"Backoff time in seconds",buckets:[1,2,4,10,20,60,120]}),cacheSize:r.gauge({name:"gossipsub_cache_size",help:"Unbounded cache sizes",labelNames:["cache"]}),mcacheSize:r.gauge({name:"gossipsub_mcache_size",help:"Current mcache msg count"}),mcacheNotValidatedCount:r.gauge({name:"gossipsub_mcache_not_validated_count",help:"Current mcache msg count not validated"}),fastMsgIdCacheCollision:r.gauge({name:"gossipsub_fastmsgid_cache_collision_total",help:"Total count of key collisions on fastmsgid cache put"}),newConnectionCount:r.gauge({name:"gossipsub_new_connection_total",help:"Total new connection by status",labelNames:["status"]}),topicStrToLabel:e,toTopic(n){return this.topicStrToLabel.get(n)??n},onJoin(n){this.topicSubscriptionStatus.set({topicStr:n},1),this.meshPeerCounts.set({topicStr:n},0)},onLeave(n){this.topicSubscriptionStatus.set({topicStr:n},0),this.meshPeerCounts.set({topicStr:n},0)},onAddToMesh(n,s,o){let i=this.toTopic(n);switch(s){case Gt.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:i},o);break;case Gt.Random:this.meshPeerInclusionEventsRandom.inc({topic:i},o);break;case Gt.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:i},o);break;case Gt.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:i},o);break;case Gt.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:i},o);break;case Gt.Opportunistic:this.meshPeerInclusionEventsOpportunistic.inc({topic:i},o);break;default:this.meshPeerInclusionEventsUnknown.inc({topic:i},o);break}},onRemoveFromMesh(n,s,o){let i=this.toTopic(n);switch(s){case Hr.Dc:this.meshPeerChurnEventsDisconnected.inc({topic:i},o);break;case Hr.BadScore:this.meshPeerChurnEventsBadScore.inc({topic:i},o);break;case Hr.Prune:this.meshPeerChurnEventsPrune.inc({topic:i},o);break;case Hr.Excess:this.meshPeerChurnEventsExcess.inc({topic:i},o);break;default:this.meshPeerChurnEventsUnknown.inc({topic:i},o);break}},onReportValidation(n,s,o){if(this.asyncValidationMcacheHit.inc({hit:n!=null?"hit":"miss"}),n!=null){let i=this.toTopic(n.message.topic);switch(s){case qt.Accept:this.acceptedMessagesTotal.inc({topic:i});break;case qt.Ignore:this.ignoredMessagesTotal.inc({topic:i});break;case qt.Reject:this.rejectedMessagesTotal.inc({topic:i});break;default:this.unknownValidationResultsTotal.inc({topic:i});break}}o!=null?this.asyncValidationDelayFromFirstSeenSec.observe((Date.now()-o)/1e3):this.asyncValidationUnknownFirstSeen.inc()},onScorePenalty(n){this.scoringPenalties.inc({penalty:n},1)},onIhaveRcv(n,s,o){let i=this.toTopic(n);this.ihaveRcvMsgids.inc({topic:i},s),this.ihaveRcvNotSeenMsgids.inc({topic:i},o)},onIwantRcv(n,s){for(let[o,i]of n){let a=this.toTopic(o);this.iwantRcvMsgids.inc({topic:a},i)}this.iwantRcvDonthaveMsgids.inc(s)},onIdontwantRcv(n,s){this.idontwantRcvMsgids.inc(n),this.idontwantRcvDonthaveMsgids.inc(s)},onForwardMsg(n,s){let o=this.toTopic(n);this.msgForwardCount.inc({topic:o},1),this.msgForwardPeers.inc({topic:o},s)},onPublishMsg(n,s,o,i,a){let c=this.toTopic(n);this.msgPublishCount.inc({topic:c},1),this.msgPublishBytes.inc({topic:c},o*i),this.msgPublishPeersByTopic.inc({topic:c},o),this.directPeersPublishedTotal.inc({topic:c},s.direct),this.floodsubPeersPublishedTotal.inc({topic:c},s.floodsub),this.meshPeersPublishedTotal.inc({topic:c},s.mesh),this.fanoutPeersPublishedTotal.inc({topic:c},s.fanout),this.msgPublishTime.observe({topic:c},a/1e3)},onMsgRecvPreValidation(n){let s=this.toTopic(n);this.msgReceivedPreValidation.inc({topic:s},1)},onMsgRecvError(n){let s=this.toTopic(n);this.msgReceivedError.inc({topic:s},1)},onPrevalidationResult(n,s){let o=this.toTopic(n);switch(s){case Mt.duplicate:this.prevalidationDuplicateTotal.inc({topic:o});break;case Mt.invalid:this.prevalidationInvalidTotal.inc({topic:o});break;case Mt.valid:this.prevalidationValidTotal.inc({topic:o});break;default:this.prevalidationUnknownTotal.inc({topic:o});break}},onMsgRecvInvalid(n,s){let o=this.toTopic(n),i=s.reason===Vt.Error?s.error:s.reason;this.msgReceivedInvalid.inc({error:i},1),this.msgReceivedInvalidByTopic.inc({topic:o},1)},onDuplicateMsgDelivery(n,s,o){let i=this.toTopic(n);this.duplicateMsgDeliveryDelay.observe({topic:i},s/1e3),o&&this.duplicateMsgLateDelivery.inc({topic:i},1)},onPublishDuplicateMsg(n){let s=this.toTopic(n);this.duplicateMsgIgnored.inc({topic:s},1)},onPeerReadStreamError(){this.peerReadStreamError.inc(1)},onRpcRecvError(){this.rpcRecvError.inc(1)},onRpcDataError(){this.rpcDataError.inc(1)},onRpcRecv(n,s){this.rpcRecvBytes.inc(s),this.rpcRecvCount.inc(1),n.subscriptions!=null&&this.rpcRecvSubscription.inc(n.subscriptions.length),n.messages!=null&&this.rpcRecvMessage.inc(n.messages.length),n.control!=null&&(this.rpcRecvControl.inc(1),n.control.ihave!=null&&this.rpcRecvIHave.inc(n.control.ihave.length),n.control.iwant!=null&&this.rpcRecvIWant.inc(n.control.iwant.length),n.control.graft!=null&&this.rpcRecvGraft.inc(n.control.graft.length),n.control.prune!=null&&this.rpcRecvPrune.inc(n.control.prune.length))},onRpcSent(n,s){if(this.rpcSentBytes.inc(s),this.rpcSentCount.inc(1),n.subscriptions!=null&&this.rpcSentSubscription.inc(n.subscriptions.length),n.messages!=null&&this.rpcSentMessage.inc(n.messages.length),n.control!=null){let o=n.control.ihave?.length??0,i=n.control.iwant?.length??0,a=n.control.graft?.length??0,c=n.control.prune?.length??0,l=n.control.idontwant?.length??0;o>0&&this.rpcSentIHave.inc(o),i>0&&this.rpcSentIWant.inc(i),a>0&&this.rpcSentGraft.inc(a),c>0&&this.rpcSentPrune.inc(c),l>0&&this.rpcSentIDontWant.inc(l),(o>0||i>0||a>0||c>0||l>0)&&this.rpcSentControl.inc(1)}},registerScores(n,s){let o=0,i=0,a=0,c=0;for(let l of n)l>=s.graylistThreshold&&o++,l>=s.publishThreshold&&i++,l>=s.gossipThreshold&&a++,l>=0&&c++;this.peersByScoreThreshold.set({threshold:Ga.graylist},o),this.peersByScoreThreshold.set({threshold:Ga.publish},i),this.peersByScoreThreshold.set({threshold:Ga.gossip},a),this.peersByScoreThreshold.set({threshold:Ga.mesh},c),this.score.set(n)},registerScoreWeights(n){for(let[s,o]of n.byTopic)this.scoreWeights.set({topic:s,p:"p1"},o.p1w),this.scoreWeights.set({topic:s,p:"p2"},o.p2w),this.scoreWeights.set({topic:s,p:"p3"},o.p3w),this.scoreWeights.set({topic:s,p:"p3b"},o.p3bw),this.scoreWeights.set({topic:s,p:"p4"},o.p4w);this.scoreWeights.set({p:"p5"},n.p5w),this.scoreWeights.set({p:"p6"},n.p6w),this.scoreWeights.set({p:"p7"},n.p7w)},registerScorePerMesh(n,s){let o=new Map;n.forEach((i,a)=>{let c=this.topicStrToLabel.get(a)??"unknown",l=o.get(c);l==null&&(l=new Set,o.set(c,l)),i.forEach(u=>l?.add(u))});for(let[i,a]of o){let c=[];a.forEach(l=>{c.push(s.get(l)??0)}),this.scorePerMesh.set({topic:i},c)}}}}var Ie=class extends Error{static name="InvalidPeerScoreParamsError";constructor(e="Invalid peer score params"){super(e),this.name="InvalidPeerScoreParamsError"}};var KV={topics:{},topicScoreCap:10,appSpecificScore:()=>0,appSpecificWeight:10,IPColocationFactorWeight:-5,IPColocationFactorThreshold:10,IPColocationFactorWhitelist:new Set,behaviourPenaltyWeight:-10,behaviourPenaltyThreshold:0,behaviourPenaltyDecay:.2,decayInterval:1e3,decayToZero:.1,retainScore:3600*1e3},FV={topicWeight:.5,timeInMeshWeight:1,timeInMeshQuantum:1,timeInMeshCap:3600,firstMessageDeliveriesWeight:1,firstMessageDeliveriesDecay:.5,firstMessageDeliveriesCap:2e3,meshMessageDeliveriesWeight:-1,meshMessageDeliveriesDecay:.5,meshMessageDeliveriesCap:100,meshMessageDeliveriesThreshold:20,meshMessageDeliveriesWindow:10,meshMessageDeliveriesActivation:5e3,meshFailurePenaltyWeight:-1,meshFailurePenaltyDecay:.5,invalidMessageDeliveriesWeight:-1,invalidMessageDeliveriesDecay:.3};function fP(r={}){return{...KV,...r,topics:r.topics!=null?Object.entries(r.topics).reduce((e,[t,n])=>(e[t]=zV(n),e),{}):{}}}function zV(r={}){return{...FV,...r}}function pP(r){for(let[e,t]of Object.entries(r.topics))try{$V(t)}catch(n){throw new Ie(`invalid score parameters for topic ${e}: ${n.message}`)}if(r.topicScoreCap<0)throw new Ie("invalid topic score cap; must be positive (or 0 for no cap)");if(r.appSpecificScore===null||r.appSpecificScore===void 0)throw new Ie("missing application specific score function");if(r.IPColocationFactorWeight>0)throw new Ie("invalid IPColocationFactorWeight; must be negative (or 0 to disable)");if(r.IPColocationFactorWeight!==0&&r.IPColocationFactorThreshold<1)throw new Ie("invalid IPColocationFactorThreshold; must be at least 1");if(r.behaviourPenaltyWeight>0)throw new Ie("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)");if(r.behaviourPenaltyWeight!==0&&(r.behaviourPenaltyDecay<=0||r.behaviourPenaltyDecay>=1))throw new Ie("invalid BehaviourPenaltyDecay; must be between 0 and 1");if(r.decayInterval<1e3)throw new Ie("invalid DecayInterval; must be at least 1s");if(r.decayToZero<=0||r.decayToZero>=1)throw new Ie("invalid DecayToZero; must be between 0 and 1")}function $V(r){if(r.topicWeight<0)throw new Ie("invalid topic weight; must be >= 0");if(r.timeInMeshQuantum===0)throw new Ie("invalid TimeInMeshQuantum; must be non zero");if(r.timeInMeshWeight<0)throw new Ie("invalid TimeInMeshWeight; must be positive (or 0 to disable)");if(r.timeInMeshWeight!==0&&r.timeInMeshQuantum<=0)throw new Ie("invalid TimeInMeshQuantum; must be positive");if(r.timeInMeshWeight!==0&&r.timeInMeshCap<=0)throw new Ie("invalid TimeInMeshCap; must be positive");if(r.firstMessageDeliveriesWeight<0)throw new Ie("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)");if(r.firstMessageDeliveriesWeight!==0&&(r.firstMessageDeliveriesDecay<=0||r.firstMessageDeliveriesDecay>=1))throw new Ie("invalid FirstMessageDeliveriesDecay; must be between 0 and 1");if(r.firstMessageDeliveriesWeight!==0&&r.firstMessageDeliveriesCap<=0)throw new Ie("invalid FirstMessageDeliveriesCap; must be positive");if(r.meshMessageDeliveriesWeight>0)throw new Ie("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)");if(r.meshMessageDeliveriesWeight!==0&&(r.meshMessageDeliveriesDecay<=0||r.meshMessageDeliveriesDecay>=1))throw new Ie("invalid MeshMessageDeliveriesDecay; must be between 0 and 1");if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesCap<=0)throw new Ie("invalid MeshMessageDeliveriesCap; must be positive");if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesThreshold<=0)throw new Ie("invalid MeshMessageDeliveriesThreshold; must be positive");if(r.meshMessageDeliveriesWindow<0)throw new Ie("invalid MeshMessageDeliveriesWindow; must be non-negative");if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesActivation<1e3)throw new Ie("invalid MeshMessageDeliveriesActivation; must be at least 1s");if(r.meshFailurePenaltyWeight>0)throw new Ie("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)");if(r.meshFailurePenaltyWeight!==0&&(r.meshFailurePenaltyDecay<=0||r.meshFailurePenaltyDecay>=1))throw new Ie("invalid MeshFailurePenaltyDecay; must be between 0 and 1");if(r.invalidMessageDeliveriesWeight>0)throw new Ie("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)");if(r.invalidMessageDeliveriesDecay<=0||r.invalidMessageDeliveriesDecay>=1)throw new Ie("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1")}var HV={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function mP(r={}){return{...HV,...r}}function G1(r,e,t=()=>!0){let n=new Set;if(e<=0)return n;for(let s of r){if(n.size>=e)break;t(s)&&(n.add(s),r.delete(s))}return n}function gP(r,e){return G1(r,e,()=>!0)}var V1=class extends Map{getDefault;constructor(e){super(),this.getDefault=e}getOrDefault(e){let t=super.get(e);return t===void 0&&(t=this.getDefault(),this.set(e,t)),t}};function yP(r,e,t,n){let s=0;Object.entries(e.topics).forEach(([i,a])=>{let c=t.topics[i];if(c===void 0)return;let l=0;if(a.inMesh){let f=a.meshTime/c.timeInMeshQuantum;f>c.timeInMeshCap&&(f=c.timeInMeshCap),l+=f*c.timeInMeshWeight}let u=a.firstMessageDeliveries;if(u>c.firstMessageDeliveriesCap&&(u=c.firstMessageDeliveriesCap),l+=u*c.firstMessageDeliveriesWeight,a.meshMessageDeliveriesActive&&a.meshMessageDeliveries<c.meshMessageDeliveriesThreshold){let f=c.meshMessageDeliveriesThreshold-a.meshMessageDeliveries,d=f*f;l+=d*c.meshMessageDeliveriesWeight}let h=a.meshFailurePenalty;l+=h*c.meshFailurePenaltyWeight;let p=a.invalidMessageDeliveries*a.invalidMessageDeliveries;l+=p*c.invalidMessageDeliveriesWeight,s+=l*c.topicWeight}),t.topicScoreCap>0&&s>t.topicScoreCap&&(s=t.topicScoreCap);let o=t.appSpecificScore(r);if(s+=o*t.appSpecificWeight,e.knownIPs.forEach(i=>{if(t.IPColocationFactorWhitelist.has(i))return;let a=n.get(i),c=a!=null?a.size:0;if(c>t.IPColocationFactorThreshold){let l=c-t.IPColocationFactorThreshold,u=l*l;s+=u*t.IPColocationFactorWeight}}),e.behaviourPenalty>t.behaviourPenaltyThreshold){let i=e.behaviourPenalty-t.behaviourPenaltyThreshold,a=i*i;s+=a*t.behaviourPenaltyWeight}return s}var xP=ie(wP(),1);var Wt;(function(r){r[r.unknown=0]="unknown",r[r.valid=1]="valid",r[r.invalid=2]="invalid",r[r.ignored=3]="ignored"})(Wt||(Wt={}));var W1=class{records;queue;constructor(){this.records=new Map,this.queue=new xP.default}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(t!=null)return t;t={status:Wt.unknown,firstSeenTsMs:Date.now(),validated:0,peers:new Set},this.records.set(e,t);let n={msgId:e,expire:Date.now()+12e4};return this.queue.push(n),t}gc(){let e=Date.now(),t=this.queue.peekFront();for(;t!=null&&t.expire<e;)this.records.delete(t.msgId),this.queue.shift(),t=this.queue.peekFront()}clear(){this.records.clear(),this.queue.clear()}};var j1=class{params;metrics;peerStats=new Map;peerIPs=new V1(()=>new Set);scoreCache=new Map;deliveryRecords=new W1;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,n,s){this.params=e,this.metrics=t,pP(e),this.scoreCacheValidityMs=s.scoreCacheValidityMs,this.computeScore=s.computeScore??yP,this.log=n.forComponent("libp2p:gossipsub:score")}get size(){return this.peerStats.size}start(){if(this._backgroundInterval!=null){this.log("Peer score already running");return}this._backgroundInterval=setInterval(()=>{this.background()},this.params.decayInterval),this.log("started")}stop(){if(this._backgroundInterval==null){this.log("Peer score already stopped");return}clearInterval(this._backgroundInterval),delete this._backgroundInterval,this.peerIPs.clear(),this.peerStats.clear(),this.deliveryRecords.clear(),this.log("stopped")}background(){this.refreshScores(),this.deliveryRecords.gc()}dumpPeerScoreStats(){return Object.fromEntries(Array.from(this.peerStats.entries()).map(([e,t])=>[e,t]))}messageFirstSeenTimestampMs(e){let t=this.deliveryRecords.getRecord(e);return t!=null?t.firstSeenTsMs:null}refreshScores(){let e=Date.now(),t=this.params.decayToZero;this.peerStats.forEach((n,s)=>{if(!n.connected){e>n.expire&&(this.removeIPsForPeer(s,n.knownIPs),this.peerStats.delete(s),this.scoreCache.delete(s));return}Object.entries(n.topics).forEach(([o,i])=>{let a=this.params.topics[o];a!==void 0&&(i.firstMessageDeliveries*=a.firstMessageDeliveriesDecay,i.firstMessageDeliveries<t&&(i.firstMessageDeliveries=0),i.meshMessageDeliveries*=a.meshMessageDeliveriesDecay,i.meshMessageDeliveries<t&&(i.meshMessageDeliveries=0),i.meshFailurePenalty*=a.meshFailurePenaltyDecay,i.meshFailurePenalty<t&&(i.meshFailurePenalty=0),i.invalidMessageDeliveries*=a.invalidMessageDeliveriesDecay,i.invalidMessageDeliveries<t&&(i.invalidMessageDeliveries=0),i.inMesh&&(i.meshTime=e-i.graftTime,i.meshTime>a.meshMessageDeliveriesActivation&&(i.meshMessageDeliveriesActive=!0)))}),n.behaviourPenalty*=this.params.behaviourPenaltyDecay,n.behaviourPenalty<t&&(n.behaviourPenalty=0)})}score(e){this.metrics?.scoreFnCalls.inc();let t=this.peerStats.get(e);if(t==null)return 0;let n=Date.now(),s=this.scoreCache.get(e);if(s!=null&&s.cacheUntil>n)return s.score;this.metrics?.scoreFnRuns.inc();let o=this.computeScore(e,t,this.params,this.peerIPs),i=n+this.scoreCacheValidityMs;return s!=null?(this.metrics?.scoreCachedDelta.observe(Math.abs(o-s.score)),s.score=o,s.cacheUntil=i):this.scoreCache.set(e,{score:o,cacheUntil:i}),o}addPenalty(e,t,n){let s=this.peerStats.get(e);s!=null&&(s.behaviourPenalty+=t,this.metrics?.onScorePenalty(n))}addPeer(e){let t={connected:!0,expire:0,topics:{},knownIPs:new Set,behaviourPenalty:0};this.peerStats.set(e,t)}addIP(e,t){let n=this.peerStats.get(e);n?.knownIPs.add(t),this.peerIPs.getOrDefault(t).add(e)}removeIP(e,t){let n=this.peerStats.get(e);n?.knownIPs.delete(t);let s=this.peerIPs.get(t);s!=null&&(s.delete(e),s.size===0&&this.peerIPs.delete(t))}removePeer(e){let t=this.peerStats.get(e);if(t!=null){if(this.score(e)>0){this.removeIPsForPeer(e,t.knownIPs),this.peerStats.delete(e);return}Object.entries(t.topics).forEach(([n,s])=>{s.firstMessageDeliveries=0;let o=this.params.topics[n].meshMessageDeliveriesThreshold;if(s.inMesh&&s.meshMessageDeliveriesActive&&s.meshMessageDeliveries<o){let i=o-s.meshMessageDeliveries;s.meshFailurePenalty+=i*i}s.inMesh=!1,s.meshMessageDeliveriesActive=!1}),t.connected=!1,t.expire=Date.now()+this.params.retainScore}}graft(e,t){let n=this.peerStats.get(e);if(n!=null){let s=this.getPtopicStats(n,t);s!=null&&(s.inMesh=!0,s.graftTime=Date.now(),s.meshTime=0,s.meshMessageDeliveriesActive=!1)}}prune(e,t){let n=this.peerStats.get(e);if(n!=null){let s=this.getPtopicStats(n,t);if(s!=null){let o=this.params.topics[t].meshMessageDeliveriesThreshold;if(s.meshMessageDeliveriesActive&&s.meshMessageDeliveries<o){let i=o-s.meshMessageDeliveries;s.meshFailurePenalty+=i*i}s.meshMessageDeliveriesActive=!1,s.inMesh=!1}}}validateMessage(e){this.deliveryRecords.ensureRecord(e)}deliverMessage(e,t,n){this.markFirstMessageDelivery(e,n);let s=this.deliveryRecords.ensureRecord(t),o=Date.now();if(s.status!==Wt.unknown){this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,o-s.firstSeenTsMs,Wt[s.status]);return}s.status=Wt.valid,s.validated=o,s.peers.forEach(i=>{i!==e.toString()&&this.markDuplicateMessageDelivery(i,n)})}rejectInvalidMessage(e,t){this.markInvalidMessageDelivery(e,t)}rejectMessage(e,t,n,s){switch(s){case Vt.Error:this.markInvalidMessageDelivery(e,n);return;case Vt.Blacklisted:return}let o=this.deliveryRecords.ensureRecord(t);if(o.status!==Wt.unknown){this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-o.firstSeenTsMs,Wt[o.status]);return}if(s===Vt.Ignore){o.status=Wt.ignored,o.peers.clear();return}o.status=Wt.invalid,this.markInvalidMessageDelivery(e,n),o.peers.forEach(i=>{this.markInvalidMessageDelivery(i,n)}),o.peers.clear()}duplicateMessage(e,t,n){let s=this.deliveryRecords.ensureRecord(t);if(!s.peers.has(e))switch(s.status){case Wt.unknown:s.peers.add(e);break;case Wt.valid:s.peers.add(e),this.markDuplicateMessageDelivery(e,n,s.validated);break;case Wt.invalid:this.markInvalidMessageDelivery(e,n);break;case Wt.ignored:break}}markInvalidMessageDelivery(e,t){let n=this.peerStats.get(e);if(n!=null){let s=this.getPtopicStats(n,t);s!=null&&(s.invalidMessageDeliveries+=1)}}markFirstMessageDelivery(e,t){let n=this.peerStats.get(e);if(n!=null){let s=this.getPtopicStats(n,t);if(s!=null){let o=this.params.topics[t].firstMessageDeliveriesCap;s.firstMessageDeliveries=Math.min(o,s.firstMessageDeliveries+1),s.inMesh&&(o=this.params.topics[t].meshMessageDeliveriesCap,s.meshMessageDeliveries=Math.min(o,s.meshMessageDeliveries+1))}}}markDuplicateMessageDelivery(e,t,n){let s=this.peerStats.get(e);if(s!=null){let o=n!==void 0?Date.now():0,i=this.getPtopicStats(s,t);if(i!=null&&i.inMesh){let a=this.params.topics[t];if(n!==void 0){let l=o-n,u=l>a.meshMessageDeliveriesWindow;if(this.metrics?.onDuplicateMsgDelivery(t,l,u),u)return}let c=a.meshMessageDeliveriesCap;i.meshMessageDeliveries=Math.min(c,i.meshMessageDeliveries+1)}}}removeIPsForPeer(e,t){for(let n of t){let s=this.peerIPs.get(n);s!=null&&(s.delete(e),s.size===0&&this.peerIPs.delete(n))}}getPtopicStats(e,t){let n=e.topics[t];return n!==void 0?n:this.params.topics[t]!==void 0?(n={inMesh:!1,graftTime:0,meshTime:0,firstMessageDeliveries:0,meshMessageDeliveries:0,meshMessageDeliveriesActive:!1,meshFailurePenalty:0,invalidMessageDeliveries:0},e.topics[t]=n,n):null}};function qV(r,e,t,n,s){let o=0,i=new Map;if(Object.entries(e.topics).forEach(([p,f])=>{let d=s.get(p)??"unknown",m=t.topics[p];if(m===void 0)return;let g=i.get(d);g==null&&(g={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},i.set(d,g));let y=0,b=0,w=0,x=0,v=0;if(f.inMesh){let A=Math.max(f.meshTime/m.timeInMeshQuantum,m.timeInMeshCap);y+=A*m.timeInMeshWeight}let S=f.firstMessageDeliveries;if(S>m.firstMessageDeliveriesCap&&(S=m.firstMessageDeliveriesCap),b+=S*m.firstMessageDeliveriesWeight,f.meshMessageDeliveriesActive&&f.meshMessageDeliveries<m.meshMessageDeliveriesThreshold){let A=m.meshMessageDeliveriesThreshold-f.meshMessageDeliveries,X=A*A;w+=X*m.meshMessageDeliveriesWeight}let E=f.meshFailurePenalty;x+=E*m.meshFailurePenaltyWeight;let I=f.invalidMessageDeliveries*f.invalidMessageDeliveries;v+=I*m.invalidMessageDeliveriesWeight,o+=(y+b+w+x+v)*m.topicWeight,g.p1w+=y,g.p2w+=b,g.p3w+=w,g.p3bw+=x,g.p4w+=v}),t.topicScoreCap>0&&o>t.topicScoreCap){o=t.topicScoreCap;let p=t.topicScoreCap/o;for(let f of i.values())f.p1w*=p,f.p2w*=p,f.p3w*=p,f.p3bw*=p,f.p4w*=p}let a=0,c=0,l=0,u=t.appSpecificScore(r);a+=u*t.appSpecificWeight,e.knownIPs.forEach(p=>{if(t.IPColocationFactorWhitelist.has(p))return;let f=n.get(p),d=f!=null?f.size:0;if(d>t.IPColocationFactorThreshold){let m=d-t.IPColocationFactorThreshold,g=m*m;c+=g*t.IPColocationFactorWeight}});let h=e.behaviourPenalty*e.behaviourPenalty;return l+=h*t.behaviourPenaltyWeight,o+=a+c+l,{byTopic:i,p5w:a,p6w:c,p7w:l,score:o}}function vP(r,e,t,n,s){let o={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(let i of r){let a=e.get(i);if(a!=null){let c=qV(i,a,t,n,s);for(let[l,u]of c.byTopic){let h=o.byTopic.get(l);h==null&&(h={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},o.byTopic.set(l,h)),h.p1w.push(u.p1w),h.p2w.push(u.p2w),h.p3w.push(u.p3w),h.p3bw.push(u.p3bw),h.p4w.push(u.p4w)}o.p5w.push(c.p5w),o.p6w.push(c.p6w),o.p7w.push(c.p7w),o.score.push(c.score)}else o.p5w.push(0),o.p6w.push(0),o.p7w.push(0),o.score.push(0)}return o}var Y1=class{rawStream;pushable;closeController;maxBufferSize;constructor(e,t,n){this.rawStream=e,this.pushable=Ot(),this.closeController=new AbortController,this.maxBufferSize=n.maxBufferSize??1/0,this.closeController.signal.addEventListener("abort",()=>{e.close().catch(s=>{e.abort(s)})}),ht(this.pushable,this.rawStream).catch(t)}get protocol(){return this.rawStream.protocol}push(e){if(this.pushable.readableLength>this.maxBufferSize)throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`);this.pushable.push(Va.single(e))}pushPrefixed(e){if(this.pushable.readableLength>this.maxBufferSize)throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`);this.pushable.push(e)}async close(){this.closeController.abort(),await this.pushable.return()}},X1=class{source;rawStream;closeController;constructor(e,t={}){this.rawStream=e,this.closeController=new AbortController,this.closeController.signal.addEventListener("abort",()=>{e.close().catch(n=>{e.abort(n)})}),this.source=ht(this.rawStream,n=>Yu(n,t))}async close(){this.closeController.abort()}};var Q1=class{gossipsubIWantFollowupMs;msgIdToStrFn;metrics;promises=new Map;requestMsByMsg=new Map;requestMsByMsgExpire;constructor(e,t,n){this.gossipsubIWantFollowupMs=e,this.msgIdToStrFn=t,this.metrics=n,this.requestMsByMsgExpire=10*e}get size(){return this.promises.size}get requestMsByMsgSize(){return this.requestMsByMsg.size}addPromise(e,t){let n=Math.floor(Math.random()*t.length),s=t[n],o=this.msgIdToStrFn(s),i=this.promises.get(o);i==null&&(i=new Map,this.promises.set(o,i));let a=Date.now();i.has(e)||(i.set(e,a+this.gossipsubIWantFollowupMs),this.metrics!=null&&(this.metrics.iwantPromiseStarted.inc(1),this.requestMsByMsg.has(o)||this.requestMsByMsg.set(o,a)))}getBrokenPromises(){let e=Date.now(),t=new Map,n=0;return this.promises.forEach((s,o)=>{s.forEach((i,a)=>{i<e&&(t.set(a,(t.get(a)??0)+1),s.delete(a),n++)}),s.size===0&&this.promises.delete(o)}),this.metrics?.iwantPromiseBroken.inc(n),t}deliverMessage(e,t=!1){this.trackMessage(e);let n=this.promises.get(e);n!=null&&(this.promises.delete(e),this.metrics!=null&&(this.metrics.iwantPromiseResolved.inc(1),t&&this.metrics.iwantPromiseResolvedFromDuplicate.inc(1),this.metrics.iwantPromiseResolvedPeers.inc(n.size)))}rejectMessage(e,t){switch(this.trackMessage(e),t){case Vt.Error:return;default:break}this.promises.delete(e)}clear(){this.promises.clear()}prune(){let e=Date.now()-this.requestMsByMsgExpire,t=0;for(let[n,s]of this.requestMsByMsg.entries())if(s<e)this.requestMsByMsg.delete(n),t++;else break;this.metrics?.iwantMessagePruned.inc(t)}trackMessage(e){if(this.metrics!=null){let t=this.requestMsByMsg.get(e);t!==void 0&&(this.metrics.iwantPromiseDeliveryTime.observe((Date.now()-t)/1e3),this.requestMsByMsg.delete(e))}}};var V6={};z(V6,{base64:()=>VV,base64pad:()=>GV,base64url:()=>q6,base64urlpad:()=>WV});var VV=Ye({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),GV=Ye({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),q6=Ye({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),WV=Ye({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});bt();te();ce();var EP=D("libp2p-pubsub:");async function SP(r,e,t,n){switch(r.type){case Us.Signing:{let s={from:r.author.toMultihash().bytes,data:n,seqno:k1(8),topic:e,signature:void 0,key:void 0},o=Ee([EP,Qn.Message.encode(s)]);s.signature=await r.privateKey.sign(o),s.key=r.key;let i={type:"signed",from:r.author,data:t,sequenceNumber:BigInt(`0x${P(s.seqno??new Uint8Array(0),"base16")}`),topic:e,signature:s.signature,key:R6(s.key)};return{raw:s,msg:i}}case Us.Anonymous:return{raw:{from:void 0,data:n,seqno:void 0,topic:e,signature:void 0,key:void 0},msg:{type:"unsigned",data:t,topic:e}};default:throw new Error("Unreachable")}}async function IP(r,e){switch(r){case Na:return e.signature!=null?{valid:!1,error:Lt.SignaturePresent}:e.seqno!=null?{valid:!1,error:Lt.SeqnoPresent}:e.from!=null?{valid:!1,error:Lt.FromPresent}:{valid:!0,message:{type:"unsigned",topic:e.topic,data:e.data??new Uint8Array(0)}};case $o:{if(e.seqno==null)return{valid:!1,error:Lt.InvalidSeqno};if(e.seqno.length!==8)return{valid:!1,error:Lt.InvalidSeqno};if(e.signature==null)return{valid:!1,error:Lt.InvalidSignature};if(e.from==null)return{valid:!1,error:Lt.InvalidPeerId};let t;try{t=qa(Yn(e.from))}catch{return{valid:!1,error:Lt.InvalidPeerId}}let n;if(e.key!=null){if(n=R6(e.key),t.publicKey!==void 0&&!n.equals(t.publicKey))return{valid:!1,error:Lt.InvalidPeerId}}else{if(t.publicKey==null)return{valid:!1,error:Lt.InvalidPeerId};n=t.publicKey}let s={from:e.from,data:e.data,seqno:e.seqno,topic:e.topic,signature:void 0,key:void 0},o=Ee([EP,Qn.Message.encode(s)]);return await n.verify(o,e.signature)?{valid:!0,message:{type:"signed",from:t,data:e.data??new Uint8Array(0),sequenceNumber:BigInt(`0x${P(e.seqno,"base16")}`),topic:e.topic,signature:e.signature,key:n}}:{valid:!1,error:Lt.InvalidSignature}}default:throw new Error("Unreachable")}}function qr(r=[],e){return{subscriptions:[],messages:r,control:e!==void 0?{graft:e.graft??[],prune:e.prune??[],ihave:e.ihave??[],iwant:e.iwant??[],idontwant:e.idontwant??[]}:void 0}}function G6(r){return r.control===void 0&&(r.control={graft:[],prune:[],ihave:[],iwant:[],idontwant:[]}),r}function xn(r){if(r.length<=1)return r;let e=()=>Math.floor(Math.random()*Math.floor(r.length));for(let t=0;t<r.length;t++){let n=e(),s=r[t];r[t]=r[n],r[n]=s}return r}ce();function AP(r){return P(r,"base64")}function CP(r,e,t){switch(r){case $o:return{type:Us.Signing,author:e,key:Bs(t.publicKey),privateKey:t};case Na:return{type:Us.Anonymous};default:throw new Error(`Unknown signature policy "${r}"`)}}var BCe=new Uint8Array(0);function J1(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var jV=PP,TP=128,YV=127,XV=~YV,QV=Math.pow(2,31);function PP(r,e,t){e=e||[],t=t||0;for(var n=t;r>=QV;)e[t++]=r&255|TP,r/=128;for(;r&XV;)e[t++]=r&255|TP,r>>>=7;return e[t]=r|0,PP.bytes=t-n+1,e}var JV=W6,ZV=128,_P=127;function W6(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw W6.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&_P)<<s:(i&_P)*Math.pow(2,s),s+=7}while(i>=ZV);return W6.bytes=o-n,t}var eG=Math.pow(2,7),tG=Math.pow(2,14),rG=Math.pow(2,21),nG=Math.pow(2,28),sG=Math.pow(2,35),oG=Math.pow(2,42),iG=Math.pow(2,49),aG=Math.pow(2,56),cG=Math.pow(2,63),lG=function(r){return r<eG?1:r<tG?2:r<rG?3:r<nG?4:r<sG?5:r<oG?6:r<iG?7:r<aG?8:r<cG?9:10},uG={encode:jV,decode:JV,encodingLength:lG},hG=uG,j6=hG;function Y6(r,e,t=0){return j6.encode(r,e,t),e}function X6(r){return j6.encodingLength(r)}function DP(r,e){let t=e.byteLength,n=X6(r),s=n+X6(t),o=new Uint8Array(s+t);return Y6(r,o,0),Y6(t,o,n),o.set(e,s),new Q6(r,t,e,o)}var Q6=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};wr();var vn;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(vn||(vn={}));var J6;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(J6||(J6={}));(function(r){r.codec=()=>sr(J6)})(vn||(vn={}));var Z1;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),vn.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=vn.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(Z1||(Z1={}));var Z6;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),vn.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=vn.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(Z6||(Z6={}));function LP(r){return Z1.encode({Type:vn[r.type],Data:r.raw})}var r5=ie(ee("crypto"),1);var pG=20;function t5({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new e5(r,e,t,n,s)}var e5=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??pG,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?MP(n,this.code,t?.truncate):n.then(s=>MP(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function MP(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return DP(e,r)}var mG=t5({name:"sha2-256",code:18,encode:r=>J1(r5.default.createHash("sha256").update(r).digest())}),YCe=t5({name:"sha2-512",code:19,encode:r=>J1(r5.default.createHash("sha512").update(r).digest())});te();ce();var OP=(r,e)=>{let t=D(e.toString(16).padStart(16,"0"),"base16"),n=LP(r),s=new Uint8Array(n.byteLength+t.length);return s.set(n,0),s.set(t,n.byteLength),s};function RP(r){if(r.type!=="signed")throw new Error("expected signed message type");if(r.sequenceNumber==null)throw Error("missing seqno field");return OP(r.from.publicKey??r.key,r.sequenceNumber)}async function NP(r){return Vu.encode(r.data)}te();ce();var Jn=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Zn=class extends Error{static name="ValidationError";name="ValidationError"};var em=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var n5={};z(n5,{base10:()=>gG});var gG=Ms({prefix:"9",name:"base10",alphabet:"0123456789"});var s5={};z(s5,{base16:()=>yG,base16upper:()=>bG});var yG=Ye({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),bG=Ye({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var o5={};z(o5,{base2:()=>wG});var wG=Ye({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var i5={};z(i5,{base256emoji:()=>IG});var BP=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),xG=BP.reduce((r,e,t)=>(r[t]=e,r),[]),vG=BP.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function EG(r){return r.reduce((e,t)=>(e+=xG[t],e),"")}function SG(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=vG[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var IG=Ua({prefix:"\u{1F680}",name:"base256emoji",encode:EG,decode:SG});var a5={};z(a5,{base8:()=>AG});var AG=Ye({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var c5={};z(c5,{identity:()=>CG});var CG=Ua({prefix:"\0",name:"identity",encode:r=>E_(r),decode:r=>v_(r)});var ITe=new TextEncoder,ATe=new TextDecoder;var UP={...c5,...o5,...a5,...n5,...s5,...u6,...h6,...l6,...V6,...i5},_Te={...K6,...p6};bt();te();ce();function u5(r){return e=>P(e,r)}function h5(r){return e=>D(e,r)}function Ya(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Vo(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function KP(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=D(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Vo(n);return Ee([t,s],t.length+s.length)}function FP(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=Os.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Vo(n);return Ee([t,s],t.length+s.length)}function d5(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=P(e,"base32"),s=Ya(t);return`${n}:${s}`}var f5=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let s=parseInt(t,10);if(isNaN(s)||s<0||s>255)throw new Jn("Invalid byte value in IP address");e[n]=s}),e},zP=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=(0,fe.isIPv4)(t[n]),i;o&&(i=f5(t[n]),t[n]=P(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,P(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new Jn("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},$P=function(r){if(r.byteLength!==4)throw new Jn("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},HP=function(r){if(r.byteLength!==16)throw new Jn("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Jn(`Invalid IPv6 address "${t}"`)}};function qP(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Jn(`Invalid IPv6 address "${r}"`)}}var l5=Object.values(UP).map(r=>r.decoder),PG=(function(){let r=l5[0].or(l5[1]);return l5.slice(2).forEach(e=>r=r.or(e)),r})();function VP(r){return PG.decode(r)}function GP(r){return e=>r.encoder.encode(e)}function DG(r){if(parseInt(r).toString()!==r)throw new Zn("Value must be an integer")}function kG(r){if(r<0)throw new Zn("Value must be a positive integer, or zero")}function LG(r){return e=>{if(e>r)throw new Zn(`Value must be smaller than or equal to ${r}`)}}function MG(...r){return e=>{for(let t of r)t(e)}}var Xu=MG(DG,kG,LG(65535));var fr=-1,p5=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new em(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},m5=new p5,xW=[{code:4,name:"ip4",size:32,valueToBytes:f5,bytesToValue:$P,validate:r=>{if(!(0,fe.isIPv4)(r))throw new Zn(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Vo,bytesToValue:Ya,validate:Xu},{code:273,name:"udp",size:16,valueToBytes:Vo,bytesToValue:Ya,validate:Xu},{code:33,name:"dccp",size:16,valueToBytes:Vo,bytesToValue:Ya,validate:Xu},{code:41,name:"ip6",size:128,valueToBytes:zP,bytesToValue:HP,stringToValue:qP,validate:r=>{if(!(0,fe.isIPv6)(r))throw new Zn(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:fr},{code:43,name:"ipcidr",size:8,bytesToValue:u5("base10"),valueToBytes:h5("base10")},{code:53,name:"dns",size:fr,resolvable:!0},{code:54,name:"dns4",size:fr,resolvable:!0},{code:55,name:"dns6",size:fr,resolvable:!0},{code:56,name:"dnsaddr",size:fr,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:Vo,bytesToValue:Ya,validate:Xu},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:fr,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:fr,bytesToValue:u5("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?h5("base58btc")(r):lt.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:d5,valueToBytes:KP},{code:445,name:"onion3",size:296,bytesToValue:d5,valueToBytes:FP},{code:446,name:"garlic64",size:fr},{code:447,name:"garlic32",size:fr},{code:448,name:"tls"},{code:449,name:"sni",size:fr},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:fr,bytesToValue:GP(q6),valueToBytes:VP},{code:480,name:"http"},{code:481,name:"http-path",size:fr,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:fr}];xW.forEach(r=>{m5.addProtocol(r)});function WP(r,e){return m5.getProtocol(r).bytesToValue?.(e)??P(e,"base16")}var tm;(function(r){r[r.ip4=4]="ip4",r[r.ip6=41]="ip6"})(tm||(tm={}));function jP(r){for(let e of r.tuples())switch(e[0]){case tm.ip4:case tm.ip6:return WP(e[0],e[1]);default:break}return null}var Xa=class{entries=new Map;validityMs;constructor(e){this.validityMs=e.validityMs}get size(){return this.entries.size}put(e,t){return this.entries.has(e)?!0:(this.entries.set(e,{value:t,validUntilMs:Date.now()+this.validityMs}),!1)}prune(){let e=Date.now();for(let[t,n]of this.entries.entries())if(n.validUntilMs<e)this.entries.delete(t);else break}has(e){return this.entries.has(e)}get(e){let t=this.entries.get(e);return t!=null&&t.validUntilMs>=Date.now()?t.value:void 0}clear(){this.entries.clear()}};var pr;(function(r){r[r.started=0]="started",r[r.stopped=1]="stopped"})(pr||(pr={}));var g5=class extends me{globalSignaturePolicy;multicodecs=[H1,iP,$6];publishConfig;dataTransform;peers=new Map;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=Ot({objectMode:!0});direct=new Set;floodsubPeers=new Set;seenCache;acceptFromWhitelist=new Map;topics=new Map;subscriptions=new Set;mesh=new Map;fanout=new Map;fanoutLastpub=new Map;gossip=new Map;control=new Map;peerhave=new Map;iasked=new Map;backoff=new Map;outbound=new Map;msgIdFn;fastMsgIdFn;msgIdToStrFn;fastMsgIdCache;publishedMessageIds;mcache;score;topicValidators=new Map;log;heartbeatTicks=0;gossipTracer;idontwantCounts=new Map;idontwants=new Map;components;directPeerInitial=null;static multicodec=H1;opts;decodeRpcLimits;metrics;status={code:pr.stopped};maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;allowedTopics;heartbeatTimer=null;constructor(e,t={}){super();let n={fallbackToFloodsub:!0,floodPublish:!0,batchPublish:!1,tagMeshPeers:!0,doPX:!1,directPeers:[],D:6,Dlo:4,Dhi:12,Dscore:4,Dout:2,Dlazy:6,heartbeatInterval:1e3,fanoutTTL:6e4,mcacheLength:5,mcacheGossip:3,seenTTL:12e4,gossipsubIWantFollowupMs:3e3,prunePeers:16,pruneBackoff:6e4,unsubcribeBackoff:1e4,graftFloodThreshold:1e4,opportunisticGraftPeers:2,opportunisticGraftTicks:60,directConnectTicks:300,gossipFactor:.25,idontwantMinDataSize:512,idontwantMaxMessages:512,...t,scoreParams:fP(t.scoreParams),scoreThresholds:mP(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=n.decodeRpcLimits??lP,this.globalSignaturePolicy=n.globalSignaturePolicy??$o,n.fallbackToFloodsub&&this.multicodecs.push(z6),this.log=e.logger.forComponent(n.debugName??"libp2p:gossipsub"),this.opts=n,this.direct=new Set(n.directPeers.map(s=>s.id.toString())),this.seenCache=new Xa({validityMs:n.seenTTL}),this.publishedMessageIds=new Xa({validityMs:n.seenTTL}),t.msgIdFn!=null)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case $o:this.msgIdFn=RP;break;case Na:this.msgIdFn=NP;break;default:throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(t.fastMsgIdFn!=null&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new Xa({validityMs:n.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??AP,this.mcache=t.messageCache??new q1(n.mcacheGossip,n.mcacheLength,this.msgIdToStrFn),t.dataTransform!=null&&(this.dataTransform=t.dataTransform),t.metricsRegister!=null){if(t.metricsTopicStrToLabel==null)throw Error("Must set metricsTopicStrToLabel with metrics");let s=Math.max(...Object.values(n.scoreParams.topics).map(i=>i.meshMessageDeliveriesWindow),1e3),o=dP(t.metricsRegister,t.metricsTopicStrToLabel,{gossipPromiseExpireSec:this.opts.gossipsubIWantFollowupMs/1e3,behaviourPenaltyThreshold:n.scoreParams.behaviourPenaltyThreshold,maxMeshMessageDeliveriesWindowSec:s/1e3});o.mcacheSize.addCollect(()=>{this.onScrapeMetrics(o)});for(let i of this.multicodecs)o.protocolsEnabled.set({protocol:i},1);this.metrics=o}else this.metrics=null;this.gossipTracer=new Q1(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new j1(this.opts.scoreParams,this.metrics,this.components.logger,{scoreCacheValidityMs:n.heartbeatInterval}),this.maxInboundStreams=t.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams,this.runOnLimitedConnection=t.runOnLimitedConnection,this.allowedTopics=n.allowedTopics!=null?new Set(n.allowedTopics):null}[Symbol.toStringTag]="@chainsafe/libp2p-gossipsub";[b_]=["@libp2p/pubsub"];[w_]=["@libp2p/identify"];getPeers(){return[...this.peers.values()]}isStarted(){return this.status.code===pr.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=CP(this.globalSignaturePolicy,this.components.peerId,this.components.privateKey),this.outboundInflightQueue=Ot({objectMode:!0}),ht(this.outboundInflightQueue,async o=>{for await(let{peerId:i,connection:a}of o)await this.createOutboundStream(i,a)}).catch(o=>{this.log.error("outbound inflight queue error",o)}),await Promise.all(this.opts.directPeers.map(async o=>{await this.components.peerStore.merge(o.id,{multiaddrs:o.addrs})}));let e=this.components.registrar;await Promise.all(this.multicodecs.map(async o=>e.handle(o,this.onIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection})));let t={onConnect:this.onPeerConnected.bind(this),onDisconnect:this.onPeerDisconnected.bind(this),notifyOnLimitedConnection:this.runOnLimitedConnection},n=await Promise.all(this.multicodecs.map(async o=>e.register(o,t))),s=setTimeout(this.runHeartbeat,100);this.status={code:pr.started,registrarTopologyIds:n,heartbeatTimeout:s,hearbeatStartMs:Date.now()+100},this.score.start(),this.directPeerInitial=setTimeout(()=>{Promise.resolve().then(async()=>{await Promise.all(Array.from(this.direct).map(async o=>this.connect(o)))}).catch(o=>{this.log(o)})},1e3),this.opts.tagMeshPeers&&(this.addEventListener("gossipsub:graft",this.tagMeshPeer),this.addEventListener("gossipsub:prune",this.untagMeshPeer)),this.log("started")}async stop(){if(this.log("stopping"),this.status.code!==pr.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:pr.stopped},this.opts.tagMeshPeers&&(this.removeEventListener("gossipsub:graft",this.tagMeshPeer),this.removeEventListener("gossipsub:prune",this.untagMeshPeer));let t=this.components.registrar;await Promise.all(this.multicodecs.map(async s=>t.unhandle(s))),e.forEach(s=>{t.unregister(s)}),this.outboundInflightQueue.end();let n=[];for(let s of this.streamsOutbound.values())n.push(s.close());this.streamsOutbound.clear();for(let s of this.streamsInbound.values())n.push(s.close());this.streamsInbound.clear(),await Promise.all(n),this.peers.clear(),this.subscriptions.clear(),this.heartbeatTimer!=null&&(this.heartbeatTimer.cancel(),this.heartbeatTimer=null),this.score.stop(),this.mesh.clear(),this.fanout.clear(),this.fanoutLastpub.clear(),this.gossip.clear(),this.control.clear(),this.peerhave.clear(),this.iasked.clear(),this.backoff.clear(),this.outbound.clear(),this.gossipTracer.clear(),this.seenCache.clear(),this.fastMsgIdCache!=null&&this.fastMsgIdCache.clear(),this.directPeerInitial!=null&&clearTimeout(this.directPeerInitial),this.idontwantCounts.clear(),this.idontwants.clear(),this.log("stopped")}dumpPeerScoreStats(){return this.score.dumpPeerScoreStats()}onIncomingStream({stream:e,connection:t}){if(!this.isStarted())return;let n=t.remotePeer;this.addPeer(n,t.direction,t.remoteAddr),this.createInboundStream(n,e),this.outboundInflightQueue.push({peerId:n,connection:t})}onPeerConnected(e,t){this.metrics?.newConnectionCount.inc({status:t.status}),!(!this.isStarted()||t.status!=="open")&&(this.addPeer(e,t.direction,t.remoteAddr),this.outboundInflightQueue.push({peerId:e,connection:t}))}onPeerDisconnected(e){this.log("connection ended %p",e),this.removePeer(e)}async createOutboundStream(e,t){if(!this.isStarted())return;let n=e.toString();if(this.peers.has(n)&&!this.streamsOutbound.has(n))try{let s=new Y1(await t.newStream(this.multicodecs,{runOnLimitedConnection:this.runOnLimitedConnection}),i=>{this.log.error("outbound pipe error",i)},{maxBufferSize:this.opts.maxOutboundBufferSize});this.log("create outbound stream %p",e),this.streamsOutbound.set(n,s);let o=s.protocol;o===z6&&this.floodsubPeers.add(n),this.metrics?.peersPerProtocol.inc({protocol:o},1),this.subscriptions.size>0&&(this.log("send subscriptions to",n),this.sendSubscriptions(n,Array.from(this.subscriptions),!0))}catch(s){this.log.error("createOutboundStream error",s)}}createInboundStream(e,t){if(!this.isStarted())return;let n=e.toString();if(!this.peers.has(n))return;let s=this.streamsInbound.get(n);s!==void 0&&(this.log("replacing existing inbound steam %s",n),s.close().catch(i=>{this.log.error(i)})),this.log("create inbound stream %s",n);let o=new X1(t,{maxDataLength:this.opts.maxInboundDataLength});this.streamsInbound.set(n,o),this.pipePeerReadStream(e,o.source).catch(i=>{this.log(i)})}addPeer(e,t,n){let s=e.toString();if(!this.peers.has(s)){this.log("new peer %p",e),this.peers.set(s,e),this.score.addPeer(s);let o=jP(n);o!==null?this.score.addIP(s,o):this.log("Added peer has no IP in current address %s %s",s,n.toString()),this.outbound.has(s)||this.outbound.set(s,t==="outbound")}}removePeer(e){let t=e.toString();if(!this.peers.has(t))return;this.log("delete peer %p",e),this.peers.delete(t);let n=this.streamsOutbound.get(t),s=this.streamsInbound.get(t);n!=null&&this.metrics?.peersPerProtocol.inc({protocol:n.protocol},-1),n?.close().catch(o=>{this.log.error(o)}),s?.close().catch(o=>{this.log.error(o)}),this.streamsOutbound.delete(t),this.streamsInbound.delete(t);for(let o of this.topics.values())o.delete(t);for(let[o,i]of this.mesh)i.delete(t)&&this.metrics?.onRemoveFromMesh(o,Hr.Dc,1);for(let o of this.fanout.values())o.delete(t);this.floodsubPeers.delete(t),this.gossip.delete(t),this.control.delete(t),this.outbound.delete(t),this.idontwantCounts.delete(t),this.idontwants.delete(t),this.score.removePeer(t),this.acceptFromWhitelist.delete(t)}get started(){return this.status.code===pr.started}getMeshPeers(e){let t=this.mesh.get(e);return t!=null?Array.from(t):[]}getSubscribers(e){let t=this.topics.get(e);return(t!=null?Array.from(t):[]).map(n=>this.peers.get(n)??Ho(n))}getTopics(){return Array.from(this.subscriptions)}async pipePeerReadStream(e,t){try{await ht(t,async n=>{for await(let s of n)try{let o=s.subarray(),i=Qn.decode(o,{limits:{subscriptions:this.decodeRpcLimits.maxSubscriptions,messages:this.decodeRpcLimits.maxMessages,control$:{ihave:this.decodeRpcLimits.maxIhaveMessageIDs,iwant:this.decodeRpcLimits.maxIwantMessageIDs,graft:this.decodeRpcLimits.maxControlMessages,prune:this.decodeRpcLimits.maxControlMessages,prune$:{peers:this.decodeRpcLimits.maxPeerInfos},idontwant:this.decodeRpcLimits.maxControlMessages,idontwant$:{messageIDs:this.decodeRpcLimits.maxIdontwantMessageIDs}}}});if(this.metrics?.onRpcRecv(i,o.length),this.opts.awaitRpcHandler)try{await this.handleReceivedRpc(e,i)}catch(a){this.metrics?.onRpcRecvError(),this.log(a)}else this.handleReceivedRpc(e,i).catch(a=>{this.metrics?.onRpcRecvError(),this.log(a)})}catch(o){this.metrics?.onRpcDataError(),this.log(o)}})}catch(n){this.metrics?.onPeerReadStreamError(),this.handlePeerReadStreamError(n,e)}}handlePeerReadStreamError(e,t){this.log.error(e),this.onPeerDisconnected(t)}async handleReceivedRpc(e,t){if(!this.acceptFrom(e.toString())){this.log("received message from unacceptable peer %p",e),this.metrics?.rpcRecvNotAccepted.inc();return}let n=t.subscriptions!=null?t.subscriptions.length:0,s=t.messages!=null?t.messages.length:0,o=0,i=0,a=0,c=0;if(t.control!=null&&(t.control.ihave!=null&&(o=t.control.ihave.length),t.control.iwant!=null&&(i=t.control.iwant.length),t.control.graft!=null&&(a=t.control.graft.length),t.control.prune!=null&&(c=t.control.prune.length)),this.log(`rpc.from ${e.toString()} subscriptions ${n} messages ${s} ihave ${o} iwant ${i} graft ${a} prune ${c}`),t.subscriptions!=null&&t.subscriptions.length>0){let l=[];t.subscriptions.forEach(u=>{let h=u.topic,p=u.subscribe===!0;if(h!=null){if(this.allowedTopics!=null&&!this.allowedTopics.has(h))return;this.handleReceivedSubscription(e,h,p),l.push({topic:h,subscribe:p})}}),this.safeDispatchEvent("subscription-change",{detail:{peerId:e,subscriptions:l}})}for(let l of t.messages){if(this.allowedTopics!=null&&!this.allowedTopics.has(l.topic))continue;let u=this.handleReceivedMessage(e,l).catch(h=>{this.metrics?.onMsgRecvError(l.topic),this.log(h)});this.opts.awaitRpcMessageHandler&&await u}t.control!=null&&await this.handleControlMessage(e.toString(),t.control)}handleReceivedSubscription(e,t,n){this.log("subscription update from %p topic %s",e,t);let s=this.topics.get(t);s==null&&(s=new Set,this.topics.set(t,s)),n?s.add(e.toString()):s.delete(e.toString())}async handleReceivedMessage(e,t){this.metrics?.onMsgRecvPreValidation(t.topic);let n=await this.validateReceivedMessage(e,t);this.metrics?.onPrevalidationResult(t.topic,n.code);let s=n.code;switch(s){case Mt.duplicate:this.score.duplicateMessage(e.toString(),n.msgIdStr,t.topic),this.gossipTracer.deliverMessage(n.msgIdStr,!0),this.mcache.observeDuplicate(n.msgIdStr,e.toString());return;case Mt.invalid:if(n.msgIdStr!=null){let o=n.msgIdStr;this.score.rejectMessage(e.toString(),o,t.topic,n.reason),this.gossipTracer.rejectMessage(o,n.reason)}else this.score.rejectInvalidMessage(e.toString(),t.topic);this.metrics?.onMsgRecvInvalid(t.topic,n);return;case Mt.valid:this.score.validateMessage(n.messageId.msgIdStr),this.gossipTracer.deliverMessage(n.messageId.msgIdStr),this.mcache.put(n.messageId,t,!this.opts.asyncValidation),this.subscriptions.has(t.topic)&&(!this.components.peerId.equals(e)||this.opts.emitSelf)&&(super.dispatchEvent(new CustomEvent("gossipsub:message",{detail:{propagationSource:e,msgId:n.messageId.msgIdStr,msg:n.msg}})),super.dispatchEvent(new CustomEvent("message",{detail:n.msg}))),this.opts.asyncValidation||this.forwardMessage(n.messageId.msgIdStr,t,e.toString());break;default:throw new Error(`Invalid validation result: ${s}`)}}async validateReceivedMessage(e,t){let n=this.fastMsgIdFn?.(t),s=n!==void 0?this.fastMsgIdCache?.get(n):void 0;if(s!=null)return{code:Mt.duplicate,msgIdStr:s};let o=await IP(this.globalSignaturePolicy,t);if(!o.valid)return{code:Mt.invalid,reason:Vt.Error,error:o.error};let i=o.message;try{this.dataTransform!=null&&(i.data=this.dataTransform.inboundTransform(t.topic,i.data))}catch(h){return this.log("Invalid message, transform failed",h),{code:Mt.invalid,reason:Vt.Error,error:Lt.TransformFailed}}let a=await this.msgIdFn(i),c=this.msgIdToStrFn(a),l={msgId:a,msgIdStr:c};if(n!==void 0&&this.fastMsgIdCache!=null&&this.fastMsgIdCache.put(n,c)&&this.metrics?.fastMsgIdCacheCollision.inc(),this.seenCache.has(c))return{code:Mt.duplicate,msgIdStr:c};this.seenCache.put(c),(t.data?.length??0)>=this.opts.idontwantMinDataSize&&this.sendIDontWants(a,t.topic,e.toString());let u=this.topicValidators.get(t.topic);if(u!=null){let h;try{h=await u(e,i)}catch(p){let f=p.code;f===cP&&(h=qt.Ignore),f===aP?h=qt.Reject:h=qt.Ignore}if(h!==qt.Accept)return{code:Mt.invalid,reason:H6(h),msgIdStr:c}}return{code:Mt.valid,messageId:l,msg:i}}getScore(e){return this.score.score(e)}sendSubscriptions(e,t,n){this.sendRpc(e,{subscriptions:t.map(s=>({topic:s,subscribe:n})),messages:[]})}async handleControlMessage(e,t){if(t===void 0)return;let n=t.ihave?.length>0?this.handleIHave(e,t.ihave):[],s=t.iwant?.length>0?this.handleIWant(e,t.iwant):[],o=t.graft?.length>0?await this.handleGraft(e,t.graft):[];if(t.prune?.length>0&&await this.handlePrune(e,t.prune),t.idontwant?.length>0&&this.handleIdontwant(e,t.idontwant),n.length===0&&s.length===0&&o.length===0)return;let i=this.sendRpc(e,qr(s,{iwant:n,prune:o})),a=n[0]?.messageIDs;a!=null&&(i?this.gossipTracer.addPromise(e,a):this.metrics?.iwantPromiseUntracked.inc(1))}acceptFrom(e){if(this.direct.has(e))return!0;let t=Date.now(),n=this.acceptFromWhitelist.get(e);if(n!=null&&n.messagesAccepted<128&&n.acceptUntil>=t)return n.messagesAccepted+=1,!0;let s=this.score.score(e);return s>=0?this.acceptFromWhitelist.set(e,{messagesAccepted:0,acceptUntil:t+1e3}):this.acceptFromWhitelist.delete(e),s>=this.opts.scoreThresholds.graylistThreshold}handleIHave(e,t){if(t.length===0)return[];let n=this.score.score(e);if(n<this.opts.scoreThresholds.gossipThreshold)return this.log("IHAVE: ignoring peer %s with score below threshold [ score = %d ]",e,n),this.metrics?.ihaveRcvIgnored.inc({reason:ja.LowScore}),[];let s=(this.peerhave.get(e)??0)+1;if(this.peerhave.set(e,s),s>10)return this.log("IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring",e,s),this.metrics?.ihaveRcvIgnored.inc({reason:ja.MaxIhave}),[];let o=this.iasked.get(e)??0;if(o>=5e3)return this.log("IHAVE: peer %s has already advertised too many messages (%d); ignoring",e,o),this.metrics?.ihaveRcvIgnored.inc({reason:ja.MaxIasked}),[];let i=new Map;if(t.forEach(({topicID:l,messageIDs:u})=>{if(l==null||u==null||!this.mesh.has(l))return;let h=0;u.forEach(p=>{let f=this.msgIdToStrFn(p);this.seenCache.has(f)||(i.set(f,p),h++)}),this.metrics?.onIhaveRcv(l,u.length,h)}),i.size===0)return[];let a=i.size;a+o>5e3&&(a=5e3-o),this.log("IHAVE: Asking for %d out of %d messages from %s",a,i.size,e);let c=Array.from(i.values());return xn(c),c=c.slice(0,a),this.iasked.set(e,o+a),[{messageIDs:c}]}handleIWant(e,t){if(t.length===0)return[];let n=this.score.score(e);if(n<this.opts.scoreThresholds.gossipThreshold)return this.log("IWANT: ignoring peer %s with score below threshold [score = %d]",e,n),[];let s=new Map,o=new Map,i=0;return t.forEach(({messageIDs:a})=>{a?.forEach(c=>{let l=this.msgIdToStrFn(c),u=this.mcache.getWithIWantCount(l,e);if(u==null){i++;return}if(o.set(u.msg.topic,1+(o.get(u.msg.topic)??0)),u.count>3){this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,c);return}s.set(l,u.msg)})}),this.metrics?.onIwantRcv(o,i),s.size===0?(this.log("IWANT: Could not provide any wanted messages to %s",e),[]):(this.log("IWANT: Sending %d messages to %s",s.size,e),Array.from(s.values()))}async handleGraft(e,t){let n=[],s=this.score.score(e),o=Date.now(),i=this.opts.doPX;if(t.forEach(({topicID:c})=>{if(c==null)return;let l=this.mesh.get(c);if(l==null){i=!1;return}if(l.has(e))return;let u=this.backoff.get(c)?.get(e);if(this.direct.has(e))this.log("GRAFT: ignoring request from direct peer %s",e),n.push(c),i=!1;else if(typeof u=="number"&&o<u){this.log("GRAFT: ignoring backed off peer %s",e),this.score.addPenalty(e,1,Wa.GraftBackoff),i=!1;let h=u+this.opts.graftFloodThreshold-this.opts.pruneBackoff;o<h&&this.score.addPenalty(e,1,Wa.GraftBackoff),this.addBackoff(e,c),n.push(c)}else s<0?(this.log("GRAFT: ignoring peer %s with negative score: score=%d, topic=%s",e,s,c),n.push(c),i=!1,this.addBackoff(e,c)):l.size>=this.opts.Dhi&&!(this.outbound.get(e)??!1)?(n.push(c),this.addBackoff(e,c)):(this.log("GRAFT: Add mesh link from %s in %s",e,c),this.score.graft(e,c),l.add(e),this.metrics?.onAddToMesh(c,Gt.Subscribed,1));this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:c,direction:"inbound"}})}),n.length===0)return[];let a=!1;return Promise.all(n.map(async c=>this.makePrune(e,c,i,a)))}async handlePrune(e,t){let n=this.score.score(e);for(let{topicID:s,backoff:o,peers:i}of t){if(s==null)continue;let a=this.mesh.get(s);if(a==null)return;this.log("PRUNE: Remove mesh link to %s in %s",e,s),this.score.prune(e,s),a.has(e)&&(a.delete(e),this.metrics?.onRemoveFromMesh(s,Hr.Prune,1)),typeof o=="number"&&o>0?this.doAddBackoff(e,s,o*1e3):this.addBackoff(e,s),i!=null&&i.length>0&&(n<this.opts.scoreThresholds.acceptPXThreshold?this.log("PRUNE: ignoring PX from peer %s with insufficient score [score = %d, topic = %s]",e,n,s):await this.pxConnect(i)),this.safeDispatchEvent("gossipsub:prune",{detail:{peerId:e,topic:s,direction:"inbound"}})}}handleIdontwant(e,t){let n=this.idontwantCounts.get(e)??0;if(n>=this.opts.idontwantMaxMessages)return;let s=n,o=this.idontwants.get(e);o==null&&(o=new Map,this.idontwants.set(e,o));let i=0;e:for(let{messageIDs:c}of t)for(let l of c){if(n>=this.opts.idontwantMaxMessages)break e;n++;let u=this.msgIdToStrFn(l);o.set(u,this.heartbeatTicks),this.mcache.msgs.has(u)||i++}this.idontwantCounts.set(e,n);let a=n-s;this.metrics?.onIdontwantRcv(a,i)}addBackoff(e,t){this.doAddBackoff(e,t,this.opts.pruneBackoff)}doAddBackoff(e,t,n){let s=this.backoff.get(t);s==null&&(s=new Map,this.backoff.set(t,s));let o=Date.now()+n;(s.get(e)??0)<o&&s.set(e,o)}applyIwantPenalties(){this.gossipTracer.getBrokenPromises().forEach((e,t)=>{this.log("peer %s didn't follow up in %d IWANT requests; adding penalty",t,e),this.score.addPenalty(t,e,Wa.BrokenPromise)})}clearBackoff(){if(this.heartbeatTicks%15!==0)return;let e=Date.now();this.backoff.forEach((t,n)=>{t.forEach((s,o)=>{s+1*this.opts.heartbeatInterval<e&&t.delete(o)}),t.size===0&&this.backoff.delete(n)})}async directConnect(){let e=[];this.direct.forEach(t=>{this.streamsOutbound.has(t)||e.push(t)}),await Promise.all(e.map(async t=>this.connect(t)))}async pxConnect(e){e.length>this.opts.prunePeers&&(xn(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async n=>{if(n.peerID==null)return;let s=qa(Yn(n.peerID)),o=s.toString();if(!this.peers.has(o)){if(n.signedPeerRecord==null){t.push(o);return}try{if(!await this.components.peerStore.consumePeerRecord(n.signedPeerRecord,s)){this.log("bogus peer record obtained through px: could not add peer record to address book");return}t.push(o)}catch{this.log("bogus peer record obtained through px: invalid signature or not a peer record")}}})),t.length!==0&&await Promise.all(t.map(async n=>this.connect(n)))}async connect(e){this.log("Initiating connection with %s",e);let t=Ho(e),n=await this.components.connectionManager.openConnection(t);for(let s of this.multicodecs)for(let o of this.components.registrar.getTopologies(s))o.onConnect?.(t,n)}subscribe(e){if(this.status.code!==pr.started)throw new Error("Pubsub has not started");if(!this.subscriptions.has(e)){this.subscriptions.add(e);for(let t of this.peers.keys())this.sendSubscriptions(t,[e],!0)}this.join(e)}unsubscribe(e){if(this.status.code!==pr.started)throw new Error("Pubsub is not started");let t=this.subscriptions.delete(e);if(this.log("unsubscribe from %s - am subscribed %s",e,t),t)for(let n of this.peers.keys())this.sendSubscriptions(n,[e],!1);this.leave(e)}join(e){if(this.status.code!==pr.started)throw new Error("Gossipsub has not started");if(this.mesh.has(e))return;this.log("JOIN %s",e),this.metrics?.onJoin(e);let t=new Set,n=this.backoff.get(e),s=this.fanout.get(e);if(s!=null&&(this.fanout.delete(e),this.fanoutLastpub.delete(e),s.forEach(o=>{!this.direct.has(o)&&this.score.score(o)>=0&&n?.has(o)!==!0&&t.add(o)}),this.metrics?.onAddToMesh(e,Gt.Fanout,t.size)),t.size<this.opts.D){let o=t.size;this.getRandomGossipPeers(e,this.opts.D,a=>!t.has(a)&&!this.direct.has(a)&&this.score.score(a)>=0&&n?.has(a)!==!0).forEach(a=>{t.add(a)}),this.metrics?.onAddToMesh(e,Gt.Random,t.size-o)}this.mesh.set(e,t),t.forEach(o=>{this.log("JOIN: Add mesh link to %s in %s",o,e),this.sendGraft(o,e)})}leave(e){if(this.status.code!==pr.started)throw new Error("Gossipsub has not started");this.log("LEAVE %s",e),this.metrics?.onLeave(e);let t=this.mesh.get(e);t!=null&&(Promise.all(Array.from(t).map(async n=>{this.log("LEAVE: Remove mesh link to %s in %s",n,e),await this.sendPrune(n,e)})).catch(n=>{this.log("Error sending prunes to mesh peers",n)}),this.mesh.delete(e))}selectPeersToForward(e,t,n){let s=new Set,o=this.topics.get(e);o!=null&&(this.direct.forEach(a=>{o.has(a)&&t!==a&&!(n?.has(a)??!1)&&s.add(a)}),this.floodsubPeers.forEach(a=>{o.has(a)&&t!==a&&!(n?.has(a)??!1)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold&&s.add(a)}));let i=this.mesh.get(e);return i!=null&&i.size>0&&i.forEach(a=>{t!==a&&!(n?.has(a)??!1)&&s.add(a)}),s}selectPeersToPublish(e){let t=new Set,n={direct:0,floodsub:0,mesh:0,fanout:0},s=this.topics.get(e);if(s!=null)if(this.opts.floodPublish)s.forEach(o=>{this.direct.has(o)?(t.add(o),n.direct++):this.score.score(o)>=this.opts.scoreThresholds.publishThreshold&&(t.add(o),n.floodsub++)});else{this.direct.forEach(i=>{s.has(i)&&(t.add(i),n.direct++)}),this.floodsubPeers.forEach(i=>{s.has(i)&&this.score.score(i)>=this.opts.scoreThresholds.publishThreshold&&(t.add(i),n.floodsub++)});let o=this.mesh.get(e);if(o!=null&&o.size>0)o.forEach(i=>{t.add(i),n.mesh++}),o.size<this.opts.D&&this.getRandomGossipPeers(e,this.opts.D-o.size,a=>!o.has(a)&&!this.direct.has(a)&&!this.floodsubPeers.has(a)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold).forEach(a=>{t.add(a),n.mesh++});else{let i=this.fanout.get(e);if(i!=null&&i.size>0)i.forEach(a=>{t.add(a),n.fanout++});else{let a=this.getRandomGossipPeers(e,this.opts.D,c=>this.score.score(c)>=this.opts.scoreThresholds.publishThreshold);a.size>0&&(this.fanout.set(e,a),a.forEach(c=>{t.add(c),n.fanout++}))}this.fanoutLastpub.set(e,Date.now())}}return{tosend:t,tosendCount:n}}forwardMessage(e,t,n,s){n!=null&&this.score.deliverMessage(n,e,t.topic);let o=this.selectPeersToForward(t.topic,n,s);o.forEach(i=>{this.sendRpc(i,qr([t]))}),this.metrics?.onForwardMsg(t.topic,o.size)}async publish(e,t,n){let s=Date.now(),o=this.dataTransform!=null?this.dataTransform.outboundTransform(e,t):t;if(this.publishConfig==null)throw Error("PublishError.Uninitialized");let{raw:i,msg:a}=await SP(this.publishConfig,e,t,o),c=await this.msgIdFn(a),l=this.msgIdToStrFn(c),u=n?.ignoreDuplicatePublishError??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(l)){if(u)return this.metrics?.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}let{tosend:h,tosendCount:p}=this.selectPeersToPublish(e),f=this.opts.emitSelf&&this.subscriptions.has(e),d=n?.allowPublishToZeroTopicPeers??this.opts.allowPublishToZeroTopicPeers;if(h.size===0&&!d&&!f)throw Error("PublishError.NoPeersSubscribedToTopic");this.seenCache.put(l),this.mcache.put({msgId:c,msgIdStr:l},i,!0),this.gossipTracer.deliverMessage(l),this.publishedMessageIds.put(l);let m=n?.batchPublish??this.opts.batchPublish,g=qr([i]);if(m)this.sendRpcInBatch(h,g);else for(let b of h)this.sendRpc(b,g)||h.delete(b);let y=Date.now()-s;return this.metrics?.onPublishMsg(e,p,h.size,i.data!=null?i.data.length:0,y),f&&(h.add(this.components.peerId.toString()),super.dispatchEvent(new CustomEvent("gossipsub:message",{detail:{propagationSource:this.components.peerId,msgId:l,msg:a}})),super.dispatchEvent(new CustomEvent("message",{detail:a}))),{recipients:Array.from(h.values()).map(b=>this.peers.get(b)??Ho(b))}}sendRpcInBatch(e,t){let n=Qn.encode(t),s=Va.single(n);for(let o of e){let i=this.streamsOutbound.get(o);if(i==null){this.log(`Cannot send RPC to ${o} as there is no open stream to it available`),e.delete(o);continue}try{i.pushPrefixed(s)}catch(a){e.delete(o),this.log.error(`Cannot send rpc to ${o}`,a)}this.metrics?.onRpcSent(t,n.length)}}reportMessageValidationResult(e,t,n){let s;if(n===qt.Accept){if(s=this.mcache.validate(e),s!=null){let{message:i,originatingPeers:a}=s;this.score.deliverMessage(t,e,i.topic),this.forwardMessage(e,s.message,t,a)}}else if(s=this.mcache.remove(e),s!=null){let i=H6(n),{message:a,originatingPeers:c}=s;this.score.rejectMessage(t,e,a.topic,i);for(let l of c)this.score.rejectMessage(l,e,a.topic,i)}let o=this.score.messageFirstSeenTimestampMs(e);this.metrics?.onReportValidation(s,n,o)}sendGraft(e,t){let s=qr([],{graft:[{topicID:t}]});this.sendRpc(e,s)}async sendPrune(e,t){let s=[await this.makePrune(e,t,this.opts.doPX,!0)],o=qr([],{prune:s});this.sendRpc(e,o)}sendIDontWants(e,t,n){let s=this.mesh.get(t);if(s==null)return;let o=new Set(s);o.delete(n);for(let a of o)this.streamsOutbound.get(a)?.protocol!==H1&&o.delete(a);let i=qr([],{idontwant:[{messageIDs:[e]}]});this.sendRpcInBatch(o,i)}sendRpc(e,t){let n=this.streamsOutbound.get(e);if(n==null)return this.log(`Cannot send RPC to ${e} as there is no open stream to it available`),!1;let s=this.control.get(e);s!=null&&(this.piggybackControl(e,t,s),this.control.delete(e));let o=this.gossip.get(e);o!=null&&(this.piggybackGossip(e,t,o),this.gossip.delete(e));let i=Qn.encode(t);try{n.push(i)}catch(a){return this.log.error(`Cannot send rpc to ${e}`,a),s!=null&&this.control.set(e,s),o!=null&&this.gossip.set(e,o),!1}if(this.metrics?.onRpcSent(t,i.length),t.control?.graft!=null)for(let a of t.control?.graft)a.topicID!=null&&this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:a.topicID,direction:"outbound"}});if(t.control?.prune!=null)for(let a of t.control?.prune)a.topicID!=null&&this.safeDispatchEvent("gossipsub:prune",{detail:{peerId:e,topic:a.topicID,direction:"outbound"}});return!0}piggybackControl(e,t,n){let s=G6(t);for(let o of n.graft)o.topicID!=null&&(this.mesh.get(o.topicID)?.has(e)??!1)&&s.control.graft.push(o);for(let o of n.prune)o.topicID!=null&&!(this.mesh.get(o.topicID)?.has(e)??!1)&&s.control.prune.push(o)}piggybackGossip(e,t,n){let s=G6(t);s.control.ihave=n}async sendGraftPrune(e,t,n){let s=this.opts.doPX,o=!1;for(let[i,a]of e){let c=a.map(h=>({topicID:h})),l=[],u=t.get(i);u!=null&&(l=await Promise.all(u.map(async h=>this.makePrune(i,h,s&&!(n.get(i)??!1),o))),t.delete(i)),this.sendRpc(i,qr([],{graft:c,prune:l}))}for(let[i,a]of t){let c=await Promise.all(a.map(async l=>this.makePrune(i,l,s&&!(n.get(i)??!1),o)));this.sendRpc(i,qr([],{prune:c}))}}emitGossip(e){let t=this.mcache.getGossipIDs(new Set(e.keys()));for(let[n,s]of e)this.doEmitGossip(n,s,t.get(n)??[])}doEmitGossip(e,t,n){if(n.length===0||(xn(n),n.length>5e3&&this.log("too many messages for gossip; will truncate IHAVE list (%d messages)",n.length),t.size===0))return;let s=this.opts.Dlazy,i=this.opts.gossipFactor*t.size,a=t;i>s&&(s=i),s>a.size?s=a.size:a=xn(Array.from(a)).slice(0,s),a.forEach(c=>{let l=n;n.length>5e3&&(l=xn(l.slice()).slice(0,5e3)),this.pushGossip(c,{topicID:e,messageIDs:l})})}flush(){for(let[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,qr([],{ihave:t}));for(let[e,t]of this.control.entries()){this.control.delete(e);let n=qr([],{graft:t.graft,prune:t.prune});this.sendRpc(e,n)}}pushGossip(e,t){this.log("Add gossip to %s",e);let n=this.gossip.get(e)??[];this.gossip.set(e,n.concat(t))}async makePrune(e,t,n,s){if(this.score.prune(e,t),this.streamsOutbound.get(e)?.protocol===$6)return{topicID:t,peers:[]};let o=s?this.opts.unsubcribeBackoff:this.opts.pruneBackoff,i=o/1e3;if(this.doAddBackoff(e,t,o),!n)return{topicID:t,peers:[],backoff:i};let a=this.getRandomGossipPeers(t,this.opts.prunePeers,l=>l!==e&&this.score.score(l)>=0),c=await Promise.all(Array.from(a).map(async l=>{let u=this.peers.get(l)??Ho(l),h;try{h=await this.components.peerStore.get(u)}catch(p){if(p.name!=="NotFoundError")throw p}return{peerID:u.toMultihash().bytes,signedPeerRecord:h?.peerRecordEnvelope}}));return{topicID:t,peers:c,backoff:i}}runHeartbeat=()=>{let e=this.metrics?.heartbeatDuration.startTimer();this.heartbeat().catch(t=>{this.log("Error running heartbeat",t)}).finally(()=>{if(e?.(),this.status.code===pr.started){clearTimeout(this.status.heartbeatTimeout);let t=this.opts.heartbeatInterval-(Date.now()-this.status.hearbeatStartMs)%this.opts.heartbeatInterval;t<this.opts.heartbeatInterval*.25&&(t+=this.opts.heartbeatInterval,this.metrics?.heartbeatSkipped.inc()),this.status.heartbeatTimeout=setTimeout(this.runHeartbeat,t)}})};async heartbeat(){let{D:e,Dlo:t,Dhi:n,Dscore:s,Dout:o,fanoutTTL:i}=this.opts;this.heartbeatTicks++;let a=new Map,c=d=>{let m=a.get(d);return m===void 0&&(m=this.score.score(d),a.set(d,m)),m},l=new Map,u=new Map,h=new Map;this.clearBackoff(),this.peerhave.clear(),this.metrics?.cacheSize.set({cache:"iasked"},this.iasked.size),this.iasked.clear(),this.applyIwantPenalties(),this.idontwantCounts.clear();for(let d of this.idontwants.values())for(let[m,g]of d)this.heartbeatTicks-g>=this.opts.mcacheLength&&d.delete(m);this.heartbeatTicks%this.opts.directConnectTicks===0&&await this.directConnect(),this.fastMsgIdCache?.prune(),this.seenCache.prune(),this.gossipTracer.prune(),this.publishedMessageIds.prune();let p=new Map;this.mesh.forEach((d,m)=>{let g=this.topics.get(m),y=new Set,b=new Set;if(p.set(m,b),g!=null){let v=xn(Array.from(g)),S=this.backoff.get(m);for(let E of v){let I=this.streamsOutbound.get(E);if(I!=null&&this.multicodecs.includes(I.protocol)&&!d.has(E)&&!this.direct.has(E)){let A=c(E);S?.has(E)!==!0&&A>=0&&y.add(E),A>=this.opts.scoreThresholds.gossipThreshold&&b.add(E)}}}let w=(v,S)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",v,m),this.addBackoff(v,m),d.delete(v),c(v)>=this.opts.scoreThresholds.gossipThreshold&&b.add(v),this.metrics?.onRemoveFromMesh(m,S,1);let E=u.get(v);E==null?u.set(v,[m]):E.push(m)},x=(v,S)=>{this.log("HEARTBEAT: Add mesh link to %s in %s",v,m),this.score.graft(v,m),d.add(v),b.delete(v),this.metrics?.onAddToMesh(m,S,1);let E=l.get(v);E==null?l.set(v,[m]):E.push(m)};if(d.forEach(v=>{let S=c(v);S<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",v,S,m),w(v,Hr.BadScore),h.set(v,!0))}),d.size<t){let v=e-d.size;gP(y,v).forEach(E=>{x(E,Gt.NotEnough)})}if(d.size>n){let v=Array.from(d);v.sort((E,I)=>c(I)-c(E)),v=v.slice(0,s).concat(xn(v.slice(s)));let S=0;if(v.slice(0,e).forEach(E=>{(this.outbound.get(E)??!1)&&S++}),S<o){let E=A=>{let X=v[A];for(let ne=A;ne>0;ne--)v[ne]=v[ne-1];v[0]=X};if(S>0){let A=S;for(let X=1;X<e&&A>0;X++)(this.outbound.get(v[X])??!1)&&(E(X),A--)}let I=e-S;for(let A=e;A<v.length&&I>0;A++)(this.outbound.get(v[A])??!1)&&(E(A),I--)}v.slice(e).forEach(E=>{w(E,Hr.Excess)})}if(d.size>=t){let v=0;if(d.forEach(S=>{(this.outbound.get(S)??!1)&&v++}),v<o){let S=o-v;G1(y,S,I=>this.outbound.get(I)===!0).forEach(I=>{x(I,Gt.Outbound)})}}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks===0&&d.size>1){let v=Array.from(d).sort((I,A)=>c(I)-c(A)),S=Math.floor(d.size/2),E=c(v[S]);if(E<this.opts.scoreThresholds.opportunisticGraftThreshold){let I=this.opts.opportunisticGraftPeers,A=G1(y,I,X=>c(X)>E);for(let X of A)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",X,m),x(X,Gt.Opportunistic)}}});let f=Date.now();this.fanoutLastpub.forEach((d,m)=>{d+i<f&&(this.fanout.delete(m),this.fanoutLastpub.delete(m))}),this.fanout.forEach((d,m)=>{let g=this.topics.get(m);d.forEach(x=>{(!(g?.has(x)??!1)||c(x)<this.opts.scoreThresholds.publishThreshold)&&d.delete(x)});let y=this.topics.get(m),b=[],w=new Set;if(p.set(m,w),y!=null){let x=xn(Array.from(y));for(let v of x){let S=this.streamsOutbound.get(v);if(S!=null&&this.multicodecs.includes(S.protocol)&&!d.has(v)&&!this.direct.has(v)){let E=c(v);E>=this.opts.scoreThresholds.publishThreshold&&b.push(v),E>=this.opts.scoreThresholds.gossipThreshold&&w.add(v)}}}if(d.size<e){let x=e-d.size;b.slice(0,x).forEach(v=>{d.add(v),w?.delete(v)})}}),this.emitGossip(p),await this.sendGraftPrune(l,u,h),this.flush(),this.mcache.shift(),this.dispatchEvent(new CustomEvent("gossipsub:heartbeat"))}getRandomGossipPeers(e,t,n=()=>!0){let s=this.topics.get(e);if(s==null)return new Set;let o=[];return s.forEach(i=>{let a=this.streamsOutbound.get(i);a!=null&&this.multicodecs.includes(a.protocol)&&n(i)&&o.push(i)}),o=xn(o),t>0&&o.length>t&&(o=o.slice(0,t)),new Set(o)}onScrapeMetrics(e){e.mcacheSize.set(this.mcache.size),e.mcacheNotValidatedCount.set(this.mcache.notValidatedCount),e.cacheSize.set({cache:"direct"},this.direct.size),e.cacheSize.set({cache:"seenCache"},this.seenCache.size),e.cacheSize.set({cache:"fastMsgIdCache"},this.fastMsgIdCache?.size??0),e.cacheSize.set({cache:"publishedMessageIds"},this.publishedMessageIds.size),e.cacheSize.set({cache:"mcache"},this.mcache.size),e.cacheSize.set({cache:"score"},this.score.size),e.cacheSize.set({cache:"gossipTracer.promises"},this.gossipTracer.size),e.cacheSize.set({cache:"gossipTracer.requests"},this.gossipTracer.requestMsByMsgSize),e.cacheSize.set({cache:"topics"},this.topics.size),e.cacheSize.set({cache:"subscriptions"},this.subscriptions.size),e.cacheSize.set({cache:"mesh"},this.mesh.size),e.cacheSize.set({cache:"fanout"},this.fanout.size),e.cacheSize.set({cache:"peers"},this.peers.size),e.cacheSize.set({cache:"streamsOutbound"},this.streamsOutbound.size),e.cacheSize.set({cache:"streamsInbound"},this.streamsInbound.size),e.cacheSize.set({cache:"acceptFromWhitelist"},this.acceptFromWhitelist.size),e.cacheSize.set({cache:"gossip"},this.gossip.size),e.cacheSize.set({cache:"control"},this.control.size),e.cacheSize.set({cache:"peerhave"},this.peerhave.size),e.cacheSize.set({cache:"outbound"},this.outbound.size);let t=0,n=Date.now();e.connectedPeersBackoffSec.reset();for(let c of this.backoff.values()){t+=c.size;for(let[l,u]of c.entries())this.peers.has(l)&&e.connectedPeersBackoffSec.observe(Math.max(0,u-n)/1e3)}e.cacheSize.set({cache:"backoff"},t);let s=0;for(let c of this.idontwants.values())s+=c.size;e.cacheSize.set({cache:"idontwants"},s);for(let[c,l]of this.topics)e.topicPeersCount.set({topicStr:c},l.size);for(let[c,l]of this.mesh)e.meshPeerCounts.set({topicStr:c},l.size);let o=[],i=new Map;e.behaviourPenalty.reset();for(let c of this.peers.keys()){let l=this.score.score(c);o.push(l),i.set(c,l),e.behaviourPenalty.observe(this.score.peerStats.get(c)?.behaviourPenalty??0)}e.registerScores(o,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,i);let a=vP(this.peers.keys(),this.score.peerStats,this.score.params,this.score.peerIPs,e.topicStrToLabel);e.registerScoreWeights(a)}tagMeshPeer=e=>{let{peerId:t,topic:n}=e.detail;this.components.peerStore.merge(this.peers.get(t)??Ho(t),{tags:{[n]:{value:100}}}).catch(s=>{this.log.error("Error tagging peer %s with topic %s",t,n,s)})};untagMeshPeer=e=>{let{peerId:t,topic:n}=e.detail;this.components.peerStore.merge(this.peers.get(t)??Ho(t),{tags:{[n]:void 0}}).catch(s=>{this.log.error("Error untagging peer %s with topic %s",t,n,s)})}};function XP(r={}){return e=>new g5(e,r)}V();ke();Ue();var jW="bootstrap",YW=50,XW=1e3,y5=class extends me{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(t.list==null||t.list.length===0)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??XW,this.list=t.list.map(n=>q(n)).filter(n=>ap.matches(n)?n.getComponents().findLast(o=>o.code===421)?.value==null?(this.log.error("invalid bootstrap multiaddr without peer id"),!1):!0:(this.log.error("invalid multiaddr %a",n),!1)).map(n=>({id:de(n.getComponents().findLast(s=>s.code===421)?.value??""),multiaddrs:[n]})),this._init=t}[pc]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[nt]=["@libp2p/peer-discovery"];isStarted(){return!!this.timer}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(e=>{this.log.error("failed to discover bootstrap peers - %e",e)})},this.timeout))}async _discoverBootstrapPeers(){if(this.timer!=null)for(let e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??jW]:{value:this._init.tagValue??YW,ttl:this._init.tagTTL}},multiaddrs:e.multiaddrs}),this.timer==null)return;this.safeDispatchEvent("peer",{detail:e}),this.components.connectionManager.openConnection(e.id).catch(t=>{this.log.error("could not dial bootstrap peer %p - %e",e.id,t)})}}stop(){this.timer!=null&&clearTimeout(this.timer),this.timer=void 0}};function QP(r){return e=>new y5(e,r)}Bt();ke();Ue();var R_e=new Uint8Array(0);function JP(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function es(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var QW=tD,ZP=128,JW=127,ZW=~JW,ej=Math.pow(2,31);function tD(r,e,t){e=e||[],t=t||0;for(var n=t;r>=ej;)e[t++]=r&255|ZP,r/=128;for(;r&ZW;)e[t++]=r&255|ZP,r>>>=7;return e[t]=r|0,tD.bytes=t-n+1,e}var tj=b5,rj=128,eD=127;function b5(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw b5.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&eD)<<s:(i&eD)*Math.pow(2,s),s+=7}while(i>=rj);return b5.bytes=o-n,t}var nj=Math.pow(2,7),sj=Math.pow(2,14),oj=Math.pow(2,21),ij=Math.pow(2,28),aj=Math.pow(2,35),cj=Math.pow(2,42),lj=Math.pow(2,49),uj=Math.pow(2,56),hj=Math.pow(2,63),dj=function(r){return r<nj?1:r<sj?2:r<oj?3:r<ij?4:r<aj?5:r<cj?6:r<lj?7:r<uj?8:r<hj?9:10},fj={encode:QW,decode:tj,encodingLength:dj},pj=fj,Qu=pj;function Ju(r,e=0){return[Qu.decode(r,e),Qu.decode.bytes]}function Ja(r,e,t=0){return Qu.encode(r,e,t),e}function Za(r){return Qu.encodingLength(r)}function rm(r,e){let t=e.byteLength,n=Za(r),s=n+Za(t),o=new Uint8Array(s+t);return Ja(r,o,0),Ja(t,o,n),o.set(e,s),new ec(r,t,e,o)}function tc(r){let e=es(r),[t,n]=Ju(e),[s,o]=Ju(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new ec(t,s,i,e)}function nD(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&JP(r.bytes,t.bytes)}}var ec=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};V();var w5=1e3,sD=60*w5,oD=15,iD=120*sD,aD=1,sm=5e3,cD=100,x5="circuit-relay-source",Zu=`${mc}-circuit-relay`,lD=2*sD,uD=BigInt(1<<17),En="/libp2p/circuit/relay/0.2.0/hop",eh="/libp2p/circuit/relay/0.2.0/stop",hD=30*w5,z_e=30*w5,th=300,dD=4096,fD=.001;wr();rt();var Ce;(function(r){let e;(function(s){s.RESERVE="RESERVE",s.CONNECT="CONNECT",s.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(s){s[s.RESERVE=0]="RESERVE",s[s.CONNECT=1]="CONNECT",s[s.STATUS=2]="STATUS"})(t||(t={})),(function(s){s.codec=()=>sr(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Z((s,o,i={})=>{i.lengthDelimited!==!1&&o.fork(),s.type!=null&&(o.uint32(8),r.Type.codec().encode(s.type,o)),s.peer!=null&&(o.uint32(18),rc.codec().encode(s.peer,o)),s.reservation!=null&&(o.uint32(26),om.codec().encode(s.reservation,o)),s.limit!=null&&(o.uint32(34),nc.codec().encode(s.limit,o)),s.status!=null&&(o.uint32(40),le.codec().encode(s.status,o)),i.lengthDelimited!==!1&&o.ldelim()},(s,o,i={})=>{let a={},c=o==null?s.len:s.pos+o;for(;s.pos<c;){let l=s.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(s);break}case 2:{a.peer=rc.codec().decode(s,s.uint32(),{limits:i.limits?.peer});break}case 3:{a.reservation=om.codec().decode(s,s.uint32(),{limits:i.limits?.reservation});break}case 4:{a.limit=nc.codec().decode(s,s.uint32(),{limits:i.limits?.limit});break}case 5:{a.status=le.codec().decode(s);break}default:{s.skipType(l&7);break}}}return a})),n),r.encode=s=>J(s,r.codec()),r.decode=(s,o)=>Q(s,r.codec(),o)})(Ce||(Ce={}));var mr;(function(r){let e;(function(s){s.CONNECT="CONNECT",s.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(s){s[s.CONNECT=0]="CONNECT",s[s.STATUS=1]="STATUS"})(t||(t={})),(function(s){s.codec=()=>sr(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Z((s,o,i={})=>{i.lengthDelimited!==!1&&o.fork(),s.type!=null&&(o.uint32(8),r.Type.codec().encode(s.type,o)),s.peer!=null&&(o.uint32(18),rc.codec().encode(s.peer,o)),s.limit!=null&&(o.uint32(26),nc.codec().encode(s.limit,o)),s.status!=null&&(o.uint32(32),le.codec().encode(s.status,o)),i.lengthDelimited!==!1&&o.ldelim()},(s,o,i={})=>{let a={},c=o==null?s.len:s.pos+o;for(;s.pos<c;){let l=s.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(s);break}case 2:{a.peer=rc.codec().decode(s,s.uint32(),{limits:i.limits?.peer});break}case 3:{a.limit=nc.codec().decode(s,s.uint32(),{limits:i.limits?.limit});break}case 4:{a.status=le.codec().decode(s);break}default:{s.skipType(l&7);break}}}return a})),n),r.encode=s=>J(s,r.codec()),r.decode=(s,o)=>Q(s,r.codec(),o)})(mr||(mr={}));var rc;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.id!=null&&t.id.byteLength>0&&(n.uint32(10),n.bytes(t.id)),t.addrs!=null)for(let o of t.addrs)n.uint32(18),n.bytes(o);s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={id:ae(0),addrs:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.id=t.bytes();break}case 2:{if(s.limits?.addrs!=null&&o.addrs.length===s.limits.addrs)throw new _e('Decode error - map field "addrs" had too many elements');o.addrs.push(t.bytes());break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(rc||(rc={}));var om;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.expire!=null&&t.expire!==0n&&(n.uint32(8),n.uint64(t.expire)),t.addrs!=null)for(let o of t.addrs)n.uint32(18),n.bytes(o);t.voucher!=null&&(n.uint32(26),im.codec().encode(t.voucher,n)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={expire:0n,addrs:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.expire=t.uint64();break}case 2:{if(s.limits?.addrs!=null&&o.addrs.length===s.limits.addrs)throw new _e('Decode error - map field "addrs" had too many elements');o.addrs.push(t.bytes());break}case 3:{o.voucher=im.codec().decode(t,t.uint32(),{limits:s.limits?.voucher});break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(om||(om={}));var nc;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.duration!=null&&(n.uint32(8),n.uint32(t.duration)),t.data!=null&&(n.uint32(16),n.uint64(t.data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.duration=t.uint32();break}case 2:{o.data=t.uint64();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(nc||(nc={}));var le;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(le||(le={}));var v5;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(v5||(v5={}));(function(r){r.codec=()=>sr(v5)})(le||(le={}));var sc;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.relay!=null&&t.relay.byteLength>0&&(n.uint32(10),n.bytes(t.relay)),t.peer!=null&&t.peer.byteLength>0&&(n.uint32(18),n.bytes(t.peer)),t.expiration!=null&&t.expiration!==0n&&(n.uint32(24),n.uint64(t.expiration)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={relay:ae(0),peer:ae(0),expiration:0n},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.relay=t.bytes();break}case 2:{o.peer=t.bytes();break}case 3:{o.expiration=t.uint64();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(sc||(sc={}));var im;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&(n.uint32(26),sc.codec().encode(t.payload,n)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={publicKey:ae(0),payloadType:ae(0),signature:ae(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.publicKey=t.bytes();break}case 2:{o.payloadType=t.bytes();break}case 3:{o.payload=sc.codec().decode(t,t.uint32(),{limits:s.limits?.payload});break}case 5:{o.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(im||(im={}));V();function mj(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var v=d[y],S=0,E=w-1;(v!==0||S<g)&&E!==-1;E--,S++)v+=256*x[E]>>>0,x[E]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var A=c.repeat(m);I<w;++I)A+=r.charAt(x[I]);return A}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*w[S]>>>0,w[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(d[m]!==" "){for(var E=b-y;E!==b&&w[E]===0;)E++;for(var I=new Uint8Array(g+(b-E)),A=g;E!==b;)I[A++]=w[E++];return I}}}function f(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:f}}var gj=mj,yj=gj,pD=yj;var E5=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},S5=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return mD(this,e)}},I5=class{decoders;constructor(e){this.decoders=e}or(e){return mD(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function mD(r,e){return new I5({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var A5=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new E5(e,t,n),this.decoder=new S5(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function gD({name:r,prefix:e,encode:t,decode:n}){return new A5(r,e,t,n)}function oc({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=pD(t,r);return gD({prefix:e,name:r,encode:n,decode:o=>es(s(o))})}function bj(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function wj(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function xj(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Sn({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=xj(n);return gD({prefix:e,name:r,encode(o){return wj(o,n,t)},decode(o){return bj(o,s,t,r)}})}var rh=Sn({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Q_e=Sn({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),J_e=Sn({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Z_e=Sn({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ePe=Sn({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),tPe=Sn({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),rPe=Sn({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),nPe=Sn({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),sPe=Sn({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var am=oc({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),aPe=oc({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ts=oc({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),uPe=oc({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});function yD(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Ej(t,C5(r),e??ts.encoder);default:return Sj(t,C5(r),e??rh.encoder)}}var bD=new WeakMap;function C5(r){let e=bD.get(r);if(e==null){let t=new Map;return bD.set(r,t),t}return e}var T5=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==nh)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Ij)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=rm(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&nD(e.multihash,n.multihash)}toString(e){return yD(this,e)}toJSON(){return{"/":yD(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??wD(n,s,o.bytes))}else if(t[Aj]===!0){let{version:n,multihash:s,code:o}=t,i=tc(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==nh)throw new Error(`Version 0 CID must use dag-pb (code: ${nh}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=wD(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,nh,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=es(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new ec(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,p]=Ju(e.subarray(t));return t+=p,h},s=n(),o=nh;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=vj(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return C5(o).set(n,e),o}};function vj(r,e){switch(r[0]){case"Q":{let t=e??ts;return[ts.prefix,t.decode(`${ts.prefix}${r}`)]}case ts.prefix:{let t=e??ts;return[ts.prefix,t.decode(r)]}case rh.prefix:{let t=e??rh;return[rh.prefix,t.decode(r)]}case am.prefix:{let t=e??am;return[am.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Ej(r,e,t){let{prefix:n}=t;if(n!==ts.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function Sj(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var nh=112,Ij=18;function wD(r,e,t){let n=Za(r),s=n+Za(e),o=new Uint8Array(s+t.byteLength);return Ja(r,o,0),Ja(e,o,n),o.set(t,s),o}var Aj=Symbol.for("@ipld/js-cid/CID");var D5=ie(ee("crypto"),1);var Cj=20;function P5({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new _5(r,e,t,n,s)}var _5=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??Cj,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?xD(n,this.code,t?.truncate):n.then(s=>xD(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function xD(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return rm(e,r)}var Tj=P5({name:"sha2-256",code:18,encode:r=>es(D5.default.createHash("sha256").update(r).digest())}),vPe=P5({name:"sha2-512",code:19,encode:r=>es(D5.default.createHash("sha512").update(r).digest())});var cm=class extends Error{constructor(e="Transfer limit error"){super(e),this.name="TransferLimitError"}},lm=class extends Error{constructor(e="Duration limit error"){super(e),this.name="DurationLimitError"}},sh=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},um=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},hm=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};function vD(r,e,t){let n=e.remaining,s=o=>{let i=BigInt(o.data.byteLength);e.remaining-=i,e.remaining<0&&r.abort(new cm(`data limit of ${n} bytes exceeded`))};r.addEventListener("message",s)}function ED(r,e,t,n,s){function o(u){r.abort(u),e.abort(u)}let i=[t,n.signal];if(n.limit?.duration!=null){s.log("limiting relayed connection duration to %dms",n.limit.duration);let u=AbortSignal.timeout(n.limit.duration);j(1/0,u),i.push(u)}let a=$t(i);j(1/0,a);let c;n.limit?.data!=null&&(c={remaining:n.limit.data});let l=()=>{let u;t.aborted?u=t.reason:u=new lm(`duration limit of ${n.limit?.duration} ms exceeded`),o(u)};a.addEventListener("abort",l,{once:!0}),c!=null&&(vD(e,c,s),vD(r,c,s)),_8(r,e,r).catch(u=>{o(u)}).finally(()=>{a.clear()})}function k5(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var oh=class{expires;bytes;constructor(e){e?.duration!=null&&e?.duration!==0&&(this.expires=Date.now()+e.duration*1e3),this.bytes=e?.data,this.bytes===0n&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(e){this.bytes!=null&&(this.bytes-=BigInt(e.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(this.expires==null&&this.bytes==null)return;let e={};if(this.bytes!=null){let t=this;Object.defineProperty(e,"bytes",{get(){return t.bytes}})}if(this.expires!=null){let t=this;Object.defineProperty(e,"seconds",{get(){return Math.round(((t.expires??0)-Date.now())/1e3)}})}return e}},dm=De(we(ap.matchers[0],Pe(290))),fm=De(Pe(290));var L5=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};function SD(r,e){let t=new L5(e?.errorMessage,e?.errorCode,e?.errorName),n=new AbortController,s=()=>{n.abort(t)},o=AbortSignal.timeout(r);o.addEventListener("abort",s);let i=n.signal;return i.reset=a=>{o?.removeEventListener("abort",s),o=AbortSignal.timeout(a??r),o.addEventListener("abort",()=>{n.abort(t)})},i.clear=()=>{o?.removeEventListener("abort",s),o=void 0},i}var pm=class{reservations;maxReservations;applyDefaultLimit;reservationTtl;defaultDurationLimit;defaultDataLimit;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:circuit-relay:server:reservation-store"),this.maxReservations=t.maxReservations??oD,this.applyDefaultLimit=t.applyDefaultLimit!==!1,this.reservationTtl=t.reservationTtl??iD,this.defaultDurationLimit=t.defaultDurationLimit??lD,this.defaultDataLimit=t.defaultDataLimit??uD,this.reservations=ru({metrics:e.metrics,name:"libp2p_circuit_relay_server_reservations_total"})}reserve(e,t,n){let s=this.reservations.get(e);if(this.reservations.size>=this.maxReservations&&s==null)return{status:le.RESERVATION_REFUSED};let o=new Date(Date.now()+this.reservationTtl),i;return this.applyDefaultLimit&&(i=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),s!=null?(this.log("refreshing reservation for client %p",e),s.signal.reset(this.reservationTtl)):(this.log("creating new reservation for client %p",e),s={addr:t,expiry:o,limit:i,signal:SD(this.reservationTtl)}),this.reservations.set(e,s),s.signal.addEventListener("abort",()=>{this.reservations.delete(e)}),{status:le.OK,expire:Math.round(o.getTime()/1e3)}}removeReservation(e){this.reservations.delete(e)}get(e){return this.reservations.get(e)}clear(){this.reservations.clear()}};var mm=class r{domain="libp2p-relay-rsvp";codec=new Uint8Array([3,2]);relay;peer;expiration;constructor({relay:e,peer:t,expiration:n}){this.relay=e,this.peer=t,this.expiration=n}marshal(){return sc.encode({relay:this.relay.toMultihash().bytes,peer:this.peer.toMultihash().bytes,expiration:BigInt(this.expiration)})}equals(e){return!(!(e instanceof r)||!this.peer.equals(e.peer)||!this.relay.equals(e.relay)||this.expiration!==e.expiration)}};var _j={maxOutboundStopStreams:th},gm=class extends me{components;reservationStore;started;hopTimeout;shutdownController;maxInboundHopStreams;maxOutboundHopStreams;maxOutboundStopStreams;log;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:server"),this.components=e,this.started=!1,this.hopTimeout=t?.hopTimeout??hD,this.maxInboundHopStreams=t.maxInboundHopStreams,this.maxOutboundHopStreams=t.maxOutboundHopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??_j.maxOutboundStopStreams,this.reservationStore=new pm(e,t.reservations),this.shutdownController=new AbortController,j(1/0,this.shutdownController.signal),this.onHop=this.onHop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-server";isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(En,this.onHop,{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){this.reservationStore.clear(),this.shutdownController.abort(),await this.components.registrar.unhandle(En),this.started=!1}async onHop(e,t){this.log("received circuit v2 hop protocol stream from %p",t.remotePeer);let n=AbortSignal.timeout(this.hopTimeout);j(1/0,n);let s={signal:n},o=zr(e);try{let i=await o.pb(Ce).read(s);if(i?.type==null)throw new Error("request was invalid, could not read from stream");this.log("received",i.type),await this.handleHopProtocol({connection:t,stream:o,request:i},s)}catch(i){this.log.error("error while handling hop - %e",i),await o.pb(Ce).write({type:Ce.Type.STATUS,status:le.MALFORMED_MESSAGE},s),e.abort(i)}}async handleHopProtocol({stream:e,request:t,connection:n},s){switch(this.log("received hop message"),t.type){case Ce.Type.RESERVE:await this.handleReserve({stream:e,request:t,connection:n},s);break;case Ce.Type.CONNECT:await this.handleConnect({stream:e,request:t,connection:n},s);break;default:this.log.error("invalid hop request type %s via peer %p",t.type,n.remotePeer),await e.pb(Ce).write({type:Ce.Type.STATUS,status:le.UNEXPECTED_MESSAGE})}}async handleReserve({stream:e,connection:t},n){let s=e.pb(Ce);if(this.log("hop reserve request from %p",t.remotePeer),er.exactMatch(t.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",t.remotePeer),await s.write({type:Ce.Type.STATUS,status:le.PERMISSION_DENIED},n);return}if(await this.components.connectionGater.denyInboundRelayReservation?.(t.remotePeer)===!0){this.log.error("reservation for %p denied by connection gater",t.remotePeer),await s.write({type:Ce.Type.STATUS,status:le.PERMISSION_DENIED},n);return}let o=this.reservationStore.reserve(t.remotePeer,t.remoteAddr);try{if(o.status!==le.OK){await s.write({type:Ce.Type.STATUS,status:o.status},n);return}if(o.expire!=null){let i=o.expire*1e3-Date.now();await this.components.peerStore.merge(t.remotePeer,{tags:{[x5]:{value:1,ttl:i}}},n)}await s.write({type:Ce.Type.STATUS,status:le.OK,reservation:await this.makeReservation(t.remotePeer,BigInt(o.expire??0)),limit:this.reservationStore.get(t.remotePeer)?.limit},n),this.log("sent confirmation response to %s",t.remotePeer),await s.unwrap().unwrap().close(n)}catch(i){this.log.error("failed to send confirmation response to %p - %e",t.remotePeer,i),this.reservationStore.removeReservation(t.remotePeer);try{await this.components.peerStore.merge(t.remotePeer,{tags:{[x5]:void 0}},n)}catch(a){this.log.error("failed to untag relay source peer %p - %e",t.remotePeer,a)}}}async makeReservation(e,t){let n=[];for(let o of this.components.addressManager.getAddresses())o.toString().includes("/p2p-circuit")||n.push(o.bytes);let s=await lr.seal(new mm({peer:e,relay:this.components.peerId,expiration:t}),this.components.privateKey);return{addrs:n,expire:t,voucher:{publicKey:dt(s.publicKey),payloadType:s.payloadType,payload:{peer:e.toMultihash().bytes,relay:this.components.peerId.toMultihash().bytes,expiration:t},signature:s.signature}}}async handleConnect({stream:e,request:t,connection:n},s){let o=e.pb(Ce);if(er.matches(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await o.write({type:Ce.Type.STATUS,status:le.PERMISSION_DENIED},s);return}this.log("hop connect request from %p",n.remotePeer);let i;try{if(t.peer==null)throw this.log.error("no peer info in hop connect request"),new Error("no peer info in request");t.peer.addrs.forEach(q),i=Br(tc(t.peer.id))}catch(h){this.log.error("invalid hop connect request via peer %p - %e",n.remotePeer,h),await o.write({type:Ce.Type.STATUS,status:le.MALFORMED_MESSAGE},s);return}let a=this.reservationStore.get(i);if(a==null){this.log.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",i,n.remotePeer,le.NO_RESERVATION),await o.write({type:Ce.Type.STATUS,status:le.NO_RESERVATION},s);return}if(await this.components.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,i)===!0){this.log.error("hop connect for %p to %p denied by connection gater",n.remotePeer,i),await o.write({type:Ce.Type.STATUS,status:le.PERMISSION_DENIED},s);return}let c=this.components.connectionManager.getConnections(i);if(c.length===0){this.log("hop connect denied for destination peer %p not having a connection for %p as there is no destination connection",i,n.remotePeer),await o.write({type:Ce.Type.STATUS,status:le.NO_RESERVATION},s);return}let l=c[0],u=await this.stopHop({connection:l,request:{type:mr.Type.CONNECT,peer:{id:n.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},s);if(u==null){this.log.error("failed to open stream to destination peer %p",l?.remotePeer),await o.write({type:Ce.Type.STATUS,status:le.CONNECTION_FAILED},s);return}await o.write({type:Ce.Type.STATUS,status:le.OK,limit:a?.limit},s),this.log("connection from %p to %p established - merging streams",n.remotePeer,i),ED(e.unwrap(),u,this.shutdownController.signal,a,{log:this.log})}async stopHop({connection:e,request:t},n){this.log("starting circuit relay v2 stop request to %s",e.remotePeer);let s=await e.newStream(eh,{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),o=zr(s),i=o.pb(mr);await i.write(t,n);let a;try{a=await i.read(n)}catch(c){this.log.error("error parsing stop message response from %p - %e",e.remotePeer,c)}if(a==null){this.log.error("could not read response from %p",e.remotePeer),await s.close(n);return}if(a.status===le.OK)return this.log("stop request to %p was successful",e.remotePeer),o.unwrap();this.log("stop request failed with code %d",a.status),await s.close(n)}get reservations(){return this.reservationStore.reservations}};V();ke();Ue();Ue();ce();var ym=class extends me{components;started;running;topologyId;log;discoveryController;filter;queue;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.components=e,this.started=!1,this.running=!1,this.filter=t.filter,this.discoveryController=new AbortController,j(1/0,this.discoveryController.signal),this.dialPeer=this.dialPeer.bind(this),this.onPeer=this.onPeer.bind(this)}isStarted(){return this.started}async start(){this.topologyId=await this.components.registrar.register(En,{filter:this.filter,onConnect:e=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",e,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:e})}}),this.started=!0}stop(){this.topologyId!=null&&this.components.registrar.unregister(this.topologyId),this.running&&this.stopDiscovery(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,j(1/0,this.discoveryController.signal),this.components.events.addEventListener("peer:discovery",this.onPeer),Promise.resolve().then(async()=>{this.log("searching peer store for relays");let e=await this.components.peerStore.all({filters:[n=>n.protocols.includes(En)],orders:[()=>Math.random()<.5?1:-1,(n,s)=>{let o=ID(n),i=ID(s);return o>i?-1:i>o?1:0}]});for(let n of e)this.log.trace("found relay peer %p in peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});this.log("found %d relay peers in peer store",e.length);let t=this.queue=new Ps({concurrency:5});this.log("start random walk");for await(let n of this.components.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),t.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.components.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(s=>s.toString()));continue}t.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await t.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,t.size,t.running),t.add(this.dialPeer,{peerId:n.id,signal:this.discoveryController.signal}).catch(s=>{this.log.error("error opening connection to random peer %p - %e",n.id,s)})}this.log("stop random walk"),await t.onIdle()}).catch(e=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network - %e",e)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort(),this.queue?.clear(),this.components.events.removeEventListener("peer:discovery",this.onPeer)}onPeer(e){this.log.trace("maybe dialing discovered peer %p",e.detail.id),this.maybeDialPeer(e).catch(t=>{this.log.trace("error dialing discovered peer %p - %e",e.detail.id,t)})}async maybeDialPeer(e){if(this.queue==null)return;let t=e.detail.id,n=e.detail.multiaddrs;if(this.queue.has(t)){this.log.trace("random peer %p was already in queue",t);return}if(this.components.connectionManager.getConnections(t)?.length>0){this.log.trace("random peer %p was already connected",t);return}if(!await this.components.connectionManager.isDialable(n)){this.log.trace("random peer %p was not dialable",t);return}this.queue?.add(this.dialPeer,{peerId:e.detail.id,signal:this.discoveryController.signal}).catch(s=>{this.log.error("error opening connection to discovered peer %p - %e",e.detail.id,s)})}async dialPeer({peerId:e,signal:t}){let n=$t([AbortSignal.timeout(5e3),t]);j(1/0,n);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}};function ID(r){let e=r.metadata.get("last-dial-success");return e==null?0:new Date(P(e)).getTime()}V();Ue();var M5=class extends me{connectionManager;addressManager;reservationStore;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=e.connectionManager,this.addressManager=e.addressManager,this.reservationStore=e.reservationStore,this.listeningAddrs=[],this.listenTimeout=t.listenTimeout??sm,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}_onRemoveRelayPeer=e=>{this.log("relay removed %p our relay %p",e.detail.relay,this.relay,this.relay?.equals(e.detail.relay)),this.relay?.equals(e.detail.relay)===!0&&(this.log("relay peer removed %p",e.detail.relay),this.listeningAddrs.forEach(t=>{this.addressManager.removeObservedAddr(t)}),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=e=>{let{details:t}=e.detail;t.type!=="configured"&&t.id===this.reservationId&&this.addedRelay(e.detail)};async listen(e){if(fm.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(dm.exactMatch(e)){this.log("listen on specific relay server %a",e);let t=AbortSignal.timeout(this.listenTimeout);j(1/0,t);let n=e.decapsulate("/p2p-circuit"),s=await this.connectionManager.openConnection(n,{signal:t});if(!this.reservationStore.hasReservation(s.remotePeer)){this.log("making reservation on peer %p",s.remotePeer);let o=await this.reservationStore.addRelay(s.remotePeer,"configured");this.addedRelay(o)}}else throw new Hs(`Could not listen on p2p-circuit address "${e}"`)}getAddrs(){return[...this.listeningAddrs.values()].flat()}updateAnnounceAddrs(){}async close(){this.reservationStore.cancelReservations(),this.listeningAddrs=[],this.reservationStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),queueMicrotask(()=>{this.safeDispatchEvent("close")})}addedRelay(e){this.log("relay peer added %p",e.relay),this.relay=e.relay,this.listeningAddrs=e.details.reservation.addrs.map(t=>q(t).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(t=>{this.addressManager.confirmObservedAddr(t,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function AD(r){return new M5(r)}V();Ue();var O5=ee("node:crypto");var CD="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Pj=128,Go,ic;function Dj(r){!Go||Go.length<r?(Go=Buffer.allocUnsafe(r*Pj),O5.webcrypto.getRandomValues(Go),ic=0):ic+r>Go.length&&(O5.webcrypto.getRandomValues(Go),ic=0),ic+=r}function TD(r=21){Dj(r|=0);let e="";for(let t=ic-r;t<ic;t++)e+=CD[Go[t]&63];return e}var kj=60*1e3*10,Lj=60*1e3*5,Mj=30*1e3,bm=class extends me{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(e,t){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new Zt,this.pendingReservations=[],this.maxReservationQueueLength=t?.maxReservationQueueLength??cD,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??sm,this.started=!1,this.relayFilter=ln(100),this.reserveQueue=new Ps({concurrency:t?.reservationConcurrency??aD,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(o=>o.connection===n.detail.id)!=null&&this.#t(n.detail.remotePeer).catch(o=>{this.log("could not remove relay %p - %e",n.detail,o)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(Zu)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async t=>{await this.peerStore.merge(t.id,{tags:{[Zu]:void 0}})})),this.log("redialing %d old relays",e.length),await Promise.all(e.map(async t=>this.addRelay(t.id,"discovered"))),this.#r()}).catch(e=>{this.log.error("failed to clean up and redial old relays during afterStart - %e",e)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}reserveRelay(){let e=TD();return this.pendingReservations.push(e),this.#r(),e}async addRelay(e,t){if(this.peerId.equals(e))throw this.log.trace("not trying to use self as relay"),new Hs("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new hm("The reservation queue is full");let n=this.reserveQueue.find(e);if(n!=null)return this.log.trace("potential relay peer %p is already in the reservation queue",e),n.join();if(this.relayFilter.has(e.toMultihash().bytes))throw new Hs("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",e),this.reserveQueue.add(async()=>{let s=Date.now();try{let o=this.reservations.get(e);if(o!=null){let d=this.connectionManager.getConnections(e),m=!1;if(d.length===0&&this.log("already have relay reservation with %p but we are no longer connected",e),d.map(g=>g.id).includes(o.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",e),m=!0),m&&k5(o.reservation.expire)>kj)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",e),{relay:e,details:o};await this.#t(e)}if(t==="discovered"&&this.pendingReservations.length===0)throw new sh("Not making reservation on discovered relay because we do not need any more relays");let i=AbortSignal.timeout(this.reservationCompletionTimeout);j(1/0,i);let a=await this.connectionManager.openConnection(e,{signal:i});if(er.matches(a.remoteAddr))throw new um("not creating reservation over relayed connection");let c=await this.#e(a,{signal:i}),l=k5(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",e,new Date(Date.now()+l).toString());let u=Math.min(Math.max(l-Lj,Mj),Math.pow(2,31)-1),h=setTimeout(()=>{this.log("refresh reservation to relay %p",e),this.addRelay(e,t).catch(async d=>{this.log.error("could not refresh reservation to relay %p - %e",e,d),await this.#t(e)}).catch(d=>{this.log.error("could not remove expired reservation to relay %p - %e",e,d)})},u),p;if(t==="discovered"){let d=this.pendingReservations.pop();if(d==null)throw new sh("Made reservation on relay but did not need any more discovered relays");p={timeout:h,reservation:c,type:t,connection:a.id,id:d}}else p={timeout:h,reservation:c,type:t,connection:a.id};this.reservations.set(e,p),await this.peerStore.merge(e,{tags:{[Zu]:{value:1,ttl:l}}}),this.#r();let f={relay:e,details:p};return this.safeDispatchEvent("relay:created-reservation",{detail:f}),f}catch(o){throw t==="discovered"&&o.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-s,o),(o.name==="DialError"||o.name==="UnsupportedProtocolError")&&this.relayFilter.add(e.toMultihash().bytes),this.#t(e).catch(i=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",e,i)}),o}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}reservationCount(e){return e==null?this.reservations.size:[...this.reservations.values()].reduce((t,n)=>(n.type===e&&t++,t),0)}cancelReservations(){[...this.reservations.values()].forEach(e=>{clearTimeout(e.timeout)}),this.reservations.clear()}async#e(e,t){t.signal?.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);let n=await e.newStream(En,t),o=zr(n).pb(Ce);this.log.trace("send RESERVE to %p",e.remotePeer),await o.write({type:Ce.Type.RESERVE},t);let i;try{this.log.trace("reading response from %p",e.remotePeer),i=await o.read(t)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(t)}if(this.log.trace("read response %s",i.status),i.status===le.OK&&i.reservation!=null){let c=new Set;c.add(e.remoteAddr.toString());for(let l of i.reservation.addrs){let u=q(l);u.getComponents().find(h=>h.code===421)==null&&(u=u.encapsulate(`/p2p/${e.remotePeer}`)),u=q(u.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),c.add(u.toString())}return i.reservation.addrs=[...c].map(l=>q(l).bytes),i.reservation}let a=`reservation failed with status ${i.status??"undefined"}`;throw this.log.error(a),new Error(a)}async#t(e){let t=this.reservations.get(e);t!=null&&(this.log("removing relay reservation with %p from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),t.type==="discovered"&&this.pendingReservations.push(t.id),await this.peerStore.merge(e,{tags:{[Zu]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:e,details:t}}),this.#r())}#r(){if(this.pendingReservations.length===0){this.log.trace("have discovered enough relays"),this.reserveQueue.clear(),this.safeDispatchEvent("relay:found-enough-relays");return}this.relayFilter=ln(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};Be();var R5=class extends da{stream;init;constructor(e){super({...e,direction:e.stream.direction}),this.init=e,this.stream=e.stream,this.stream.addEventListener("close",t=>{this.onTransportClosed(t.error)}),this.stream.addEventListener("remoteCloseWrite",t=>{this.onRemoteCloseWrite(),this.close().catch(n=>{this.abort(n)})}),this.stream.addEventListener("message",t=>{e.onDataRead?.(t.data),this.onData(t.data)}),this.stream.addEventListener("drain",()=>{this.safeDispatchEvent("drain")})}sendData(e){return this.init.onDataWrite?.(e),{sentBytes:e.byteLength,canSendMore:this.stream.send(e)}}async sendClose(e){await this.stream.close(e)}sendReset(){this.stream.abort(new Error("An error occurred"))}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}};function N5(r){return new R5(r)}var Oj=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(q)}catch{return!1}return!0},_D={maxInboundStopStreams:th,maxOutboundStopStreams:th,stopTimeout:3e4},wm=class{components;discovery;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:circuit-relay:transport"),this.maxInboundStopStreams=t.maxInboundStopStreams??_D.maxInboundStopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??_D.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new ym(e,{filter:t.discoveryFilter??Ib(dD,fD)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(s=>{s.name!=="HadEnoughRelaysError"&&s.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p - %e",n.detail,s)})}),this.reservationStore=new bm(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.startDiscovery()}),this.reservationStore.addEventListener("relay:found-enough-relays",()=>{this.discovery?.stopDiscovery()}),this.started=!1,this.onStop=this.onStop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[nt]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[yc](){return this.discovery!=null?["@libp2p/identify"]:[]}[Mh]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,j(1/0,this.shutdownController.signal),await this.components.registrar.handle(eh,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await kh(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Lh(this.discovery,this.reservationStore),await this.components.registrar.unhandle(eh),this.started=!1}async dial(e,t){let n=e.toString().split("/p2p-circuit"),s=q(n[0]),o=q(n[n.length-1]),i=s.getComponents().find(f=>f.code===421)?.value,a=o.getComponents().find(f=>f.code===421)?.value;if(i==null||a==null){let f=`ircuit relay dial to ${e.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${f}`),new os(`C${f}`)}let c=de(i),l=de(a),h=this.components.connectionManager.getConnections(c)[0];h==null?(await this.components.peerStore.merge(c,{multiaddrs:[s]}),t.onProgress?.(new Le("circuit-relay:open-connection")),h=await this.components.connectionManager.openConnection(c,t)):t.onProgress?.(new Le("circuit-relay:reuse-connection"));let p;try{t.onProgress?.(new Le("circuit-relay:open-hop-stream")),p=await h.newStream(En,t);let f=zr(p).pb(Ce);t.onProgress?.(new Le("circuit-relay:write-connect-message")),await f.write({type:Ce.Type.CONNECT,peer:{id:l.toMultihash().bytes,addrs:[q(o).bytes]}},t),t.onProgress?.(new Le("circuit-relay:read-connect-response"));let d=await f.read(t);if(d.status!==le.OK)throw new Rt(`failed to connect via relay with status ${d?.status?.toString()??"undefined"}`);let m=new oh(d.limit),g=N5({stream:f.unwrap().unwrap(),remoteAddr:e,localAddr:s.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:m.onData,onDataWrite:m.onData,log:p.log.newScope("circuit-relay:connection")}),y=await this.components.upgrader.upgradeOutbound(g,{...t,limits:m.getLimits()});return y.log("outbound relayed connection established to %p with limits %o, over connection %s",y.remotePeer,d.limit??"none",h.id),y}catch(f){throw this.log.error("circuit relay dial to destination %p via relay %p failed - %e",l,c,f),p?.abort(f),f}}createListener(e){return AD({peerId:this.components.peerId,connectionManager:this.components.connectionManager,addressManager:this.components.addressManager,reservationStore:this.reservationStore,logger:this.components.logger})}listenFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>dm.exactMatch(t)||fm.exactMatch(t))}dialFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>er.exactMatch(t))}async onStop(e,t){let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);try{if(!this.reservationStore.hasReservation(t.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.components.transportManager.listen([t.remoteAddr.encapsulate("/p2p-circuit")])}catch(h){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on - %e",h)}let s=zr(e).pb(mr),o=await s.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,o.type),o?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await s.write({type:mr.Type.STATUS,status:le.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(o.type!==mr.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:mr.Type.STATUS,status:le.UNEXPECTED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(!Oj(o)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:mr.Type.STATUS,status:le.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let i=Br(tc(o.peer.id));if(await this.components.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,i)===!0){this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await s.write({type:mr.Type.STATUS,status:le.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await s.write({type:mr.Type.STATUS,status:le.OK},{signal:n});let a=new oh(o.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${i.toString()}`),l=this.components.addressManager.getAddresses()[0],u=N5({stream:s.unwrap().unwrap(),remoteAddr:c,localAddr:l,onDataRead:a.onData,onDataWrite:a.onData,log:e.log.newScope("circuit-relay:connection")});await this.components.upgrader.upgradeInbound(u,{limits:a.getLimits(),signal:n}),u.log("inbound relayed connection established to %p with limits %o, over connection %s",i,o.limit??"none",t.id)}finally{n?.clear()}}};function PD(r={}){return e=>new gm(e,r)}function DD(r={}){return e=>new wm(e,r)}ke();var xm=class{components;running=!1;log;cfg;readyPromise=null;coordinatorCache=new Map;clusterCache=new Map;lastEstimate=null;blacklist=new Map;libp2pRef;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("db-p2p:network-manager"),this.cfg={clusterSize:t.clusterSize??1,seedKeys:t.seedKeys??[],estimation:t.estimation??{samples:8,kth:5,timeoutMs:1e3,ttlMs:6e4},readiness:t.readiness??{minPeers:1,maxWaitMs:2e3},cacheTTLs:t.cacheTTLs??{coordinatorMs:30*6e4,clusterMs:5*6e4},expectedRemotes:t.expectedRemotes??!1,allowClusterDownsize:t.allowClusterDownsize??!0,clusterSizeTolerance:t.clusterSizeTolerance??.5}}setLibp2p(e){this.libp2pRef=e}getLibp2p(){return this.libp2pRef??this.components.libp2p}getFret(){let e=this.getLibp2p();if(e)return e.services?.fret}get[Symbol.toStringTag](){return"@libp2p/network-manager"}async start(){this.running||(this.running=!0)}async stop(){this.running=!1}async ready(){return this.readyPromise?this.readyPromise:(this.readyPromise=(async()=>{let t=(await Promise.allSettled((this.cfg.seedKeys??[]).map(n=>this.seedKey(n)))).filter(n=>n.status==="rejected");t.length>0&&this.log("Failed to seed %d keys",t.length),await new Promise(n=>setTimeout(n,50))})(),this.readyPromise)}async seedKey(e){let t=this.getFret();if(!t)throw new Error("FRET service not available for seeding keys");let n=await ir(e),s=t.getNeighbors(n,"both",1)}toCacheKey(e){return Buffer.from(e).toString("base64url")}getKnownPeers(){let e=this.getLibp2p();if(!e)return[];let t=e.peerId,n=e.peerStore?.getPeers?.()??[],s=(e.getConnections?.()??[]).map(a=>a.remotePeer),o=[...n.map(a=>a.id),...s];return o.filter((a,c)=>o.findIndex(l=>l.toString()===a.toString())===c).filter(a=>a.toString()!==t.toString())}getStatus(){let e=this.getLibp2p();if(!e)return{mode:this.cfg.expectedRemotes?"degraded":"alone",connections:0};let n=(e.peerStore?.getPeers?.()??[]).filter(s=>s.id.toString()!==e.peerId.toString()).length;return n===0?{mode:this.cfg.expectedRemotes?"degraded":"alone",connections:0}:{mode:"healthy",connections:n}}async awaitHealthy(e,t){let n=Date.now();for(;Date.now()-n<t;){let o=this.getLibp2p();if(o){let i=o.getConnections?.()??[],a=new Set(i.map(c=>c.remotePeer.toString()));if(a.size>=e)return this.log("awaitHealthy: satisfied with %d connections",a.size),!0}await new Promise(i=>setTimeout(i,100))}let s=this.getLibp2p();if(s){let o=s.getConnections?.()??[],i=new Set(o.map(c=>c.remotePeer.toString())),a=i.size>=e;return this.log("awaitHealthy: timeout - %d connections (needed %d)",i.size,e),a}return!1}reportBadPeer(e,t=1,n=10*6e4){let s=e.toString(),i=(this.blacklist.get(s)?.score??0)+Math.max(1,t);this.blacklist.set(s,{score:i,expires:Date.now()+n})}isBlacklisted(e){let t=e.toString(),n=this.blacklist.get(t);return n?n.expires<=Date.now()?(this.blacklist.delete(t),!1):n.score>=3:!1}recordCoordinator(e,t){let n=this.toCacheKey(e);this.coordinatorCache.set(n,{id:t,expires:Date.now()+this.cfg.cacheTTLs.coordinatorMs})}async findNearestPeerToKey(e){let t=this.getFret(),n=this.getLibp2p();if(!n)throw new Error("Libp2p not initialized");if(t){let a=await ir(e),c=t.getNeighbors(a,"both",1);if(c.length>0){let l=c[0];if(l){let{peerIdFromString:u}=await Promise.resolve().then(()=>(ke(),V2)),h=u(l);if(!this.isBlacklisted(h))return h}}}let s=(n.getConnections?.()??[]).map(a=>a.remotePeer),o=[n.peerId,...s,...this.getKnownPeers()].filter((a,c,l)=>l.findIndex(u=>u.toString()===a.toString())===c).filter(a=>!this.isBlacklisted(a));return o.length===0?n.peerId:o.reduce((a,c)=>this.lexLess(this.xor(a.toMultihash().bytes,e),this.xor(c.toMultihash().bytes,e))?a:c,o[0])}async getCluster(e){let t=this.toCacheKey(e),n=this.clusterCache.get(t);if(n&&n.expires>Date.now())return n.ids;let s=this.getFret(),o=this.getLibp2p();if(!o)throw new Error("Libp2p not initialized");if(s){let f=await ir(e),d=s.getDiagnostics?.()??{},m=typeof d.estimate=="number"?d.estimate:typeof d.n=="number"?d.n:void 0,g=Math.max(1,Math.min(this.cfg.clusterSize,Number.isFinite(m)?m:this.cfg.clusterSize)),y=s.assembleCohort(f,g),{peerIdFromString:b}=await Promise.resolve().then(()=>(ke(),V2)),w=y.map(x=>{try{return b(x)}catch(v){return this.log("Invalid peer ID in cohort: %s, %o",x,v),null}}).filter(x=>x!==null&&!this.isBlacklisted(x));if(w.length>0)return this.clusterCache.set(t,{ids:w,expires:Date.now()+this.cfg.cacheTTLs.clusterMs}),this.lastEstimate=m!=null?{estimate:m,samples:d.samples??0,updated:Date.now()}:this.lastEstimate,w}let i=await this.findNearestPeerToKey(e),a=i.toMultihash().bytes,c=(o.getConnections?.()??[]).map(f=>f.remotePeer),u=[i,o.peerId,...c,...this.getKnownPeers()].filter((f,d,m)=>!this.isBlacklisted(f)&&m.findIndex(g=>g.toString()===f.toString())===d).sort((f,d)=>this.lexLess(this.xor(f.toMultihash().bytes,a),this.xor(d.toMultihash().bytes,a))?-1:1),h=Math.min(this.cfg.clusterSize,u.length),p=u.slice(0,h);return this.clusterCache.set(t,{ids:p,expires:Date.now()+this.cfg.cacheTTLs.clusterMs}),p}async getCoordinator(e){let t=this.toCacheKey(e),n=this.coordinatorCache.get(t);if(n){if(n.expires>Date.now())return n.id;this.coordinatorCache.delete(t)}let s=await this.getCluster(e),o=this.getLibp2p();if(!o)throw new Error("Libp2p not initialized");let i=s.find(a=>!this.isBlacklisted(a))??o.peerId;return this.recordCoordinator(e,i),i}xor(e,t){let n=Math.max(e.length,t.length),s=new Uint8Array(n);for(let o=0;o<n;o++){let i=e[e.length-1-o]??0,a=t[t.length-1-o]??0;s[n-1-o]=i^a}return s}lexLess(e,t){let n=Math.max(e.length,t.length);for(let s=0;s<n;s++){let o=e[s]??0,i=t[s]??0;if(o<i)return!0;if(o>i)return!1}return!1}};function B5(r={}){return e=>new xm(e,r)}var vm=class{peerStatuses=new Map;unreachableThreshold=3;rapidChurnThreshold=5;rapidChurnWindow=1e4;peerTimeoutMs=6e4;recordSuccess(e){let t=Date.now(),n=this.peerStatuses.get(e);n?(n.lastSeen=t,n.consecutiveFailures=0):this.peerStatuses.set(e,{peerId:e,lastSeen:t,consecutiveFailures:0}),this.cleanupOldPeers()}recordFailure(e){let t=Date.now(),n=this.peerStatuses.get(e);n?(n.consecutiveFailures++,n.lastSeen=t):this.peerStatuses.set(e,{peerId:e,lastSeen:t,consecutiveFailures:1})}recordGoodbye(e){let t=Date.now(),n=this.peerStatuses.get(e);n?(n.lastGoodbye=t,n.lastSeen=t):this.peerStatuses.set(e,{peerId:e,lastSeen:t,lastGoodbye:t,consecutiveFailures:0})}detectPartition(){let e=Date.now(),t=this.getRecentGoodbyes(this.rapidChurnWindow),n=Array.from(this.peerStatuses.values()).filter(o=>o.consecutiveFailures>=this.unreachableThreshold&&!o.lastGoodbye);return t.length+n.length>=this.rapidChurnThreshold}getUnreachablePeers(){return Array.from(this.peerStatuses.values()).filter(e=>e.consecutiveFailures>=this.unreachableThreshold&&!e.lastGoodbye).map(e=>e.peerId)}getRecentGoodbyes(e){let t=Date.now()-e;return Array.from(this.peerStatuses.values()).filter(n=>n.lastGoodbye&&n.lastGoodbye>t)}cleanupOldPeers(){let e=Date.now()-this.peerTimeoutMs;for(let[t,n]of this.peerStatuses.entries())n.lastSeen<e&&this.peerStatuses.delete(t)}getStatistics(){let e=this.getUnreachablePeers().length,t=this.getRecentGoodbyes(this.rapidChurnWindow).length;return{totalPeers:this.peerStatuses.size,unreachable:e,recentGoodbyes:t}}reset(){this.peerStatuses.clear()}};function Rj(r){return r?typeof r=="function"?r():r:new gl}async function Nj(r){let e=Rj(r.storage),t=async(w,x)=>{},n=new yl(w=>new Bi(w,e,t)),s,o,i={async update(w){if(!s)throw new Error("ClusterMember not initialized");return await s.update(w)}},a={async get(w,x){return await(o??n).get(w,x)},async pend(w,x){return await(o??n).pend(w,x)},async cancel(w,x){return await(o??n).cancel(w,x)},async commit(w,x){return await(o??n).commit(w,x)}},c=r.id?await de(r.id):void 0,l={start:!1,...c?{peerId:c}:{},addresses:{listen:[`/ip4/0.0.0.0/tcp/${r.port}`]},connectionManager:{autoDial:!0,minConnections:1,maxConnections:16,inboundConnectionUpgradeTimeout:1e4,dialQueue:{concurrency:2,attempts:2}},transports:[aT(),DD()],connectionEncrypters:[JT()],streamMuxers:[i_()],services:{identify:h_({protocolPrefix:`/optimystic/${r.networkName}`}),ping:y_(),pubsub:XP({allowPublishToZeroTopicPeers:!0,heartbeatInterval:7e3}),...r.relay?{relay:PD()}:{},cluster:w=>Yg({protocolPrefix:`/optimystic/${r.networkName}`,configuredClusterSize:r.clusterSize??10,allowClusterDownsize:r.clusterPolicy?.allowDownsize??!0,clusterSizeTolerance:r.clusterPolicy?.sizeTolerance??.5,responsibilityK:r.responsibilityK??1})({logger:w.logger,registrar:w.registrar,cluster:i}),repo:w=>Jg({protocolPrefix:`/optimystic/${r.networkName}`,responsibilityK:r.responsibilityK??1})({logger:w.logger,registrar:w.registrar,repo:a}),sync:w=>l3({protocolPrefix:`/optimystic/${r.networkName}`})({logger:w.logger,registrar:w.registrar,repo:a}),networkManager:w=>{let v=B5({clusterSize:r.clusterSize??10,expectedRemotes:(r.bootstrapNodes?.length??0)>0,allowClusterDownsize:r.clusterPolicy?.allowDownsize??!0,clusterSizeTolerance:r.clusterPolicy?.sizeTolerance??.5})(w);try{v.setLibp2p?.(w.libp2p)}catch{}return v},fret:w=>{let v=c3({k:15,m:8,capacity:2048,profile:r.fretProfile??((r.bootstrapNodes?.length??0)>0?"core":"edge"),networkName:r.networkName,bootstraps:r.bootstrapNodes??[]})(w);try{v.setLibp2p(w.libp2p)}catch{}return v}},peerDiscovery:[...r.bootstrapNodes?.length?[QP({list:r.bootstrapNodes})]:[]]},u=await rT(l);try{u.services?.fret?.setLibp2p?.(u)}catch{}try{u.services?.networkManager?.setLibp2p?.(u)}catch{}await u.start();let h=new Xl(u),p=`/optimystic/${r.networkName}`,f=w=>ro.create(w,h,p),d=new vm,m=u.services?.fret;s=jg({storageRepo:n,peerNetwork:h,peerId:u.peerId,protocolPrefix:p,partitionDetector:d,fretService:m,validator:r.validator});let g=Qg(h,f,{clusterSize:r.clusterSize??10,superMajorityThreshold:r.clusterPolicy?.superMajorityThreshold??.67,simpleMajorityThreshold:.51,minAbsoluteClusterSize:2,allowClusterDownsize:r.clusterPolicy?.allowDownsize??!0,clusterSizeTolerance:r.clusterPolicy?.sizeTolerance??.5,partitionDetectionWindow:6e4},m),y=async(w,x)=>{let v=new ho(w,h,p);try{let S=await v.requestBlock({blockId:x,rev:void 0});if(S.success&&S.archive){let E=Object.keys(S.archive.revisions).map(Number);if(E.length>0){let I=Math.max(...E),A=S.archive.revisions[I];if(A?.action)return{actionId:A.action.actionId,rev:I}}}}catch{}};if(o=g({storageRepo:n,localCluster:s,localPeerId:u.peerId,clusterLatestCallback:y}),r.arachnode?.enableRingZulu??!0){let w=u.logger?.forComponent?.("db-p2p:arachnode"),x=u.services?.fret;if(x){let v=new $l(x),S=new zl(e,r.arachnode?.storage??{}),E=new Fl(v,S,{minCapacity:100*1024*1024,thresholds:{moveOut:.85,moveIn:.4}}),I=u.peerId.toString(),A=await E.createArachnodeInfo(I);v.setArachnodeInfo(A),w?.("Announced Arachnode membership: Ring %d",A.ringDepth);let X=new Kl(v,{connect:(C,T)=>u.dialProtocol(C,[T])},`/optimystic/${r.networkName}`),ne=async(C,T)=>await X.restore(C,T);n.createBlockStorage=C=>new Bi(C,e,ne);let H=setInterval(async()=>{let C=await E.shouldTransition();if(C.shouldMove){w?.("Ring transition needed: moving %s to Ring %d",C.direction,C.newRingDepth);let T=await E.createArachnodeInfo(I);v.setArachnodeInfo(T)}},6e4),L=u.stop.bind(u);u.stop=async()=>{clearInterval(H),await L()}}else w?.("FRET service not available, Arachnode disabled")}return u.coordinatedRepo=o,u.storageRepo=n,u.keyNetwork=h,u}function kD(r,e){let t=Math.max(r.length,e.length),n=new Uint8Array(t);for(let s=0;s<t;s++){let o=r[r.length-1-s]??0,i=e[e.length-1-s]??0;n[t-1-s]=o^i}return n}function LD(r,e){let t=Math.max(r.length,e.length);for(let n=0;n<t;n++){let s=r[n]??0,o=e[n]??0;if(s<o)return!0;if(s>o)return!1}return!1}function MD(r,e){return r.map(t=>({p:t,d:kD(t.id.toMultihash().bytes,e)})).sort((t,n)=>LD(t.d,n.d)?-1:1).map(t=>t.p)}function Bj(r,e,t,n){let s=[e,...t],o=MD(s,r);if(s.length<=3)return{inCluster:o[0].id.equals(e.id),nearest:o};let i=Math.min(n,Math.max(1,Math.floor(s.length/2))),a=o.slice(0,i);return{inCluster:a.some(l=>l.id.equals(e.id)),nearest:a}}function Uj(r){let e={id:r.peerId,addrs:r.getMultiaddrs().map(o=>o.toString())},t=r.getConnections(),n={};for(let o of t){let i=o.remotePeer,a=i.toString(),c=n[a]??(n[a]={id:i,addrs:new Set}),l=o.remoteAddr?.toString?.();l&&c.addrs.add(l)}let s=Object.values(n).map(o=>({id:o.id,addrs:Array.from(o.addrs)}));return[e,...s]}var Kj=Sr("network:get-manager");function Fj(r){let e=r.services?.networkManager;if(e==null)throw new Error("networkManager service is not registered on this libp2p node");try{e.setLibp2p?.(r)}catch(t){Kj("getNetworkManager setLibp2p failed - %o",t)}return e}return $5(zj);})();
|
|
34
|
+
`),t),n('responded with "na" for "%s"',o)}}ke();Ue();V();Ue();var Iw=class extends me{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.closeTimeout=t.closeTimeout??1e3,this.direct=aw(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new as(n.local,n.error))})}[Symbol.toStringTag]="Connection";[X5]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new ks("Connection is not multiplexed");if(this.muxer.status!=="open")throw new zs(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new zs(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new fc("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let a=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);j(1/0,a),t={...t,signal:a}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await va(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let s=oH(n.protocol,this.components.registrar,t),o=JC(n.protocol,"outbound",this);if(o>s){let a=new Jo(`Too many outbound protocol streams for protocol "${n.protocol}" - ${o}/${s}`);throw n.abort(a),a}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol);return await this.runMiddlewareChain(n,this,i)}catch(s){throw n.status==="open"?n.abort(s):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,s),s}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);j(1/0,n),t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let l=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",l),t.protocol=await Ea(t,l,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let s=sH(t.protocol,this.components.registrar);if(JC(t.protocol,"inbound",this)>s)throw new Ah(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${s}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);let{handler:i,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new fc("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(l,u,h)=>{await i(l,u),h(l,u)}),await this.runMiddlewareChain(t,this,c)}catch(s){t.abort(s)}}async runMiddlewareChain(e,t,n){for(let s=0;s<n.length;s++){let o=n[s];e.log.trace("running middleware",s,o),await new Promise((i,a)=>{try{let c=o(e,t,(l,u)=>{e=l,t=u,i()});c instanceof Promise&&c.catch(a)}catch(c){a(c)}}),e.log.trace("ran middleware",s,o)}return e}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),e.signal==null){let t=AbortSignal.timeout(this.closeTimeout);j(1/0,t),e={...e,signal:t}}await this.muxer?.close(e),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}};function ZC(r,e){return new Iw(r,e)}function sH(r,e){try{let{options:t}=e.getHandler(r);if(t.maxInboundStreams!=null)return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return vw}function oH(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??Ew}function JC(r,e,t){let n=0;return t.streams.forEach(s=>{s.direction===e&&s.protocol===r&&n++}),n}var Vp=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=Pt({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=Pt({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new Ep(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=$t([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return j(1/0,t),t}async upgradeInbound(e,t){let n=!1,s=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new Sp("Connection denied");await Eu(this.shouldBlockConnection("denyInboundConnection",e),s),await this._performUpgrade(e,"inbound",{...t,signal:s})}catch(o){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[o.name??"Error"]:!0}),o}finally{s.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getComponents().findLast(i=>i.code===421)?.value,s;n!=null&&(s=de(n),await Eu(this.shouldBlockConnection("denyOutboundConnection",s,e),t.signal));let o="outbound";return t.initiator===!1&&(o="inbound"),await this._performUpgrade(e,o,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let s=e,o,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${l}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let h=this.components.connectionProtector;h!=null&&(e.log("protecting the %s connection",t),s=await h.protect(s,n))}try{if(iH(n)){if(n.remotePeer==null)throw new ss(`${t} connection that skipped encryption must have a peer id`);c="native",o=n.remotePeer}else{let h=e.remoteAddr.getComponents().findLast(f=>f.code===421)?.value,p;h!=null&&(p=de(h)),n?.onProgress?.(new Le(`upgrader:encrypt-${t}-connection`)),{connection:s,remotePeer:o,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(s,{...n,remotePeer:p}):this._encryptOutbound(s,{...n,remotePeer:p}))}if(o.equals(this.components.peerId)){let h=new Qo("Can not dial self");throw e.abort(h),h}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",o,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new Le(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(s,this.streamMuxers,n):this._multiplexOutbound(s,this.streamMuxers,n)))}catch(h){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,h),h}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(s)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",o,e);let u=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,stream:s,muxer:a,remotePeer:o,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return u.log("successfully upgraded connection"),u}_createConnection(e){let t=ZC(this.components,{...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout});return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let s=await Ea(e,n,t),o=this.connectionEncrypters.get(s);if(o==null)throw new Fo(`no crypto module found for ${s}`);return e.log("encrypting inbound connection using %s",s),{...await o.secureInbound(e,t),protocol:s}}catch(s){throw new Fo(s.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let s=await va(e,n,t),o=this.connectionEncrypters.get(s);if(o==null)throw new Fo(`no crypto module found for ${s}`);return e.log("encrypting outbound connection using %s",s),{...await o.secureOutbound(e,t),protocol:s}}catch(s){throw new Fo(s.message)}}async _multiplexOutbound(e,t,n){let s=Array.from(t.keys());e.log("outbound selecting muxer %s",s);try{e.log.trace("selecting stream muxer from %s",s);let o=await va(e,s,n),i=t.get(o);if(i==null)throw new ks(`No muxer configured for protocol "${o}"`);return e.log("selected %s as muxer protocol",o),i}catch(o){throw e.log.error("error multiplexing outbound connection - %e",o),new ks(String(o))}}async _multiplexInbound(e,t,n){let s=Array.from(t.keys());e.log("inbound handling muxers %s",s);try{e.log.trace("selecting stream muxer from %s",s);let o=await Ea(e,s,n),i=t.get(o);if(i==null)throw new ks(`No muxer configured for protocol "${o}"`);return e.log("selected %s as muxer protocol",o),i}catch(o){throw e.log.error("error multiplexing inbound connection - %e",o),o}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function iH(r){return r.skipEncryption===!0}var Ls=ie(ee("node:process"),1);var Gp="3.1.3",Wp="js-libp2p";function tT(r,e){let t="node",n=Ls.default.versions.node;return Ls.default.versions.deno!=null&&(t="deno",n=Ls.default.versions.deno),Ls.default.versions.bun!=null&&(t="bun",n=Ls.default.versions.bun),Ls.default.versions.electron!=null&&(t="electron",n=Ls.default.versions.electron),`${r??Wp}/${e??Gp} ${t}/${n.replaceAll("v","")}`}var jp=class extends me{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new me,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=n(l),h=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||h},j(1/0,t),this.peerId=e.peerId,this.logger=e.logger??bf(),this.log=this.logger.forComponent("libp2p"),this.services={};let s=e.nodeInfo?.name??Wp,o=e.nodeInfo?.version??Gp,i=this.components=kC({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:s,version:o,userAgent:e.nodeInfo?.userAgent??tT(s,o)},logger:this.logger,events:t,datastore:e.datastore??new tp,connectionGater:MC(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",mC(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(h=>h.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Vp(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new qp(this.components,e.transportManager)),this.configureComponent("connectionManager",new Bp(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Up(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Hp(this.components)),this.configureComponent("addressManager",new fp(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new zp(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Kp(this.components,{routers:c})),this.configureComponent("randomWalk",new $p(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",p=>{this.#e(p)})}),e.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let u=e.services[l],h=u(this.components);if(h==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=h,this.configureComponent(l,h),h[Mm]!=null&&(this.log("registering service %s for content routing",l),c.push(h[Mm])),h[Om]!=null&&(this.log("registering service %s for peer routing",l),a.push(h[Om])),h[pc]!=null&&(this.log("registering service %s for peer discovery",l),h[pc].addEventListener?.("peer",p=>{this.#e(p)}))}LC(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started with peer id %p",this.peerId)}catch(e){throw this.log.error("an error occurred starting libp2p - %e",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new xo;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new R("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new R("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){As(e)&&(e=de(e.getComponents().findLast(n=>n.code===421)?.value??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Ee([D("/pk/"),e.toMultihash().bytes]),s=await this.contentRouting.get(n,t),o=Ft(s);return await this.peerStore.patch(e,{publicKey:o},t),o}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async s=>{await this.components.registrar.handle(s,t,n)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.unhandle(n,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}use(e,t){this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){this.components.registrar.unuse(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error("could not update multiaddrs of discovered peer - %e",n)})}};async function rT(r={}){r.privateKey??=await dE("Ed25519");let e=new jp({...await GA(r),peerId:q2(r.privateKey)});return r.start!==!1&&await e.start(),e}var iT=ie(ee("net"),1);V();var oT=ie(ee("node:net"),1);V();Ue();V();var Aw=class extends da{socket;constructor(e){let t=e.remoteAddr;if(e.localAddr!=null&&cp.matches(e.localAddr))t=e.localAddr;else if(t==null){if(e.socket.remoteAddress==null||e.socket.remotePort==null)throw new R("Could not determine remote address or port");t=T8(e.socket.remoteAddress,e.socket.remotePort)}super({...e,remoteAddr:t}),this.socket=e.socket,this.socket.on("data",n=>{this.onData(n)}),this.socket.on("error",n=>{this.log("tcp error",t,n),this.abort(n)}),this.socket.setTimeout(e.inactivityTimeout??120*1e3),this.socket.once("timeout",()=>{this.log("tcp timeout",t),this.abort(new Gr)}),this.socket.once("end",()=>{this.log("tcp end",t),this.onTransportClosed()}),this.socket.once("close",n=>{if(this.log("tcp close",t),n){this.abort(new Error("TCP transmission error"));return}this.onTransportClosed()}),this.socket.on("drain",()=>{this.log("tcp drain"),this.safeDispatchEvent("drain")})}sendData(e){let t=0,n=!0;for(let s of e)if(t+=s.byteLength,n=this.socket.write(s),!n)break;return{sentBytes:t,canSendMore:n}}async sendClose(e){this.socket.destroyed||(this.socket.destroySoon(),await Re(this.socket,"close",e))}sendReset(){this.socket.resetAndDestroy()}sendPause(){this.socket.pause()}sendResume(){this.socket.resume()}},Yp=r=>new Aw(r);var nT=ie(ee("os"),1),sT=ie(ee("path"),1);V();function Xp(r,e={}){if(cp.exactMatch(r)){let o=r.getComponents().find(i=>i.code===400)?.value;if(o==null)throw new R(`Multiaddr ${r} was not a Unix address`);return nT.default.platform()==="win32"?{path:sT.default.join("\\\\.\\pipe\\",o)}:{path:o}}let t=oe(r),n=t.host,s=t.port;return{host:n,port:s,ipv6Only:t.type==="ip6",...e}}var gt;(function(r){r[r.INACTIVE=0]="INACTIVE",r[r.ACTIVE=1]="ACTIVE",r[r.PAUSED=2]="PAUSED"})(gt||(gt={}));var Qp=class extends me{context;server;sockets=new Set;status={code:gt.INACTIVE};metrics;addr;log;shutdownController;constructor(e){if(super(),this.context=e,e.keepAlive=e.keepAlive??!0,e.noDelay=e.noDelay??!0,e.allowHalfOpen=e.allowHalfOpen??!1,this.shutdownController=new AbortController,j(1/0,this.shutdownController.signal),this.log=e.logger.forComponent("libp2p:tcp:listener"),this.addr="unknown",this.server=oT.default.createServer(e,this.onSocket.bind(this)),e.maxConnections!==void 0&&(this.server.maxConnections=e.maxConnections),e.closeServerOnMaxConnections!=null&&e.closeServerOnMaxConnections.closeAbove<e.closeServerOnMaxConnections.listenBelow)throw new R("closeAbove must be >= listenBelow");e.metrics?.registerMetricGroup("libp2p_tcp_inbound_connections_total",{label:"address",help:"Current active connections in TCP listener",calculate:()=>({[this.addr]:this.sockets.size})}),this.metrics={status:e.metrics?.registerMetricGroup("libp2p_tcp_listener_status_info",{label:"address",help:"Current status of the TCP listener socket"}),errors:e.metrics?.registerMetricGroup("libp2p_tcp_listener_errors_total",{label:"address",help:"Total count of TCP listener errors by type"}),events:e.metrics?.registerMetricGroup("libp2p_tcp_listener_events_total",{label:"address",help:"Total count of TCP listener events by type"})},this.server.on("listening",()=>{let t=this.server.address();t==null?this.addr="unknown":typeof t=="string"?this.addr=t:this.addr=`${t.address}:${t.port}`,this.metrics.status?.update({[this.addr]:gt.ACTIVE}),this.safeDispatchEvent("listening")}).on("error",t=>{this.metrics.errors?.increment({[`${this.addr} listen_error`]:!0}),this.safeDispatchEvent("error",{detail:t})}).on("close",()=>{this.metrics.status?.update({[this.addr]:this.status.code}),this.status.code!==gt.PAUSED&&this.safeDispatchEvent("close")}).on("drop",()=>{this.metrics.events?.increment({[`${this.addr} drop`]:!0})})}onSocket(e){if(this.metrics.events?.increment({[`${this.addr} connection`]:!0}),this.status.code!==gt.ACTIVE)throw e.destroy(),new Dr("Server is not listening yet");let t;try{t=Yp({socket:e,inactivityTimeout:this.context.inactivityTimeout,metrics:this.metrics?.events,metricPrefix:`${this.addr} `,direction:"inbound",localAddr:this.status.listeningAddr,log:this.context.logger.forComponent("libp2p:tcp:connection")})}catch(n){this.log.error("inbound connection failed - %e",n),this.metrics.errors?.increment({[`${this.addr} inbound_to_connection`]:!0}),e.destroy();return}this.log("new inbound connection %s",t.remoteAddr),this.sockets.add(e),this.context.upgrader.upgradeInbound(t,{signal:this.shutdownController.signal}).then(()=>{this.log("inbound connection upgraded %s",t.remoteAddr),e.once("close",()=>{this.sockets.delete(e),this.context.closeServerOnMaxConnections!=null&&this.sockets.size<this.context.closeServerOnMaxConnections.listenBelow&&this.resume().catch(n=>{this.log.error("error attempting to listen server once connection count under limit - %e",n),this.context.closeServerOnMaxConnections?.onListenError?.(n)})}),this.context.closeServerOnMaxConnections!=null&&this.sockets.size>=this.context.closeServerOnMaxConnections.closeAbove&&(this.log("pausing incoming connections as limit is exceeded - %d/%d",this.sockets.size,this.context.closeServerOnMaxConnections.closeAbove),this.pause())}).catch(async n=>{this.log.error("inbound connection upgrade failed - %e",n),this.metrics.errors?.increment({[`${this.addr} inbound_upgrade`]:!0}),this.sockets.delete(e),t.abort(n)})}getAddrs(){if(this.status.code===gt.INACTIVE)return[];let e=this.server.address();return e==null?[]:typeof e=="string"?[q(`/unix/${encodeURIComponent(e)}`)]:C8(this.status.listeningAddr,e.port)}updateAnnounceAddrs(){}async listen(e){if(this.status.code===gt.ACTIVE||this.status.code===gt.PAUSED)throw new Ih("server is already listening");try{this.status={code:gt.ACTIVE,listeningAddr:e,netConfig:Xp(e,this.context)},await this.resume()}catch(t){throw this.status={code:gt.INACTIVE},t}}async close(e){let t=[];this.server.listening&&t.push(Re(this.server,"close",e)),this.pause(!0),this.shutdownController.abort(),this.sockets.forEach(n=>{n.readable&&(t.push(Re(n,"close",e)),n.destroy())}),await Promise.all(t)}async resume(){if(this.server.listening||this.status.code===gt.INACTIVE)return;let e=this.status.netConfig;await new Promise((t,n)=>{this.server.once("error",n),this.server.listen(e,t)}),this.status={...this.status,code:gt.ACTIVE},this.log("listening on %s",this.server.address())}pause(e=!1){if(!this.server.listening&&this.status.code===gt.PAUSED&&e){this.status={code:gt.INACTIVE};return}!this.server.listening||this.status.code!==gt.ACTIVE||(this.log("%s server on %s",e?"closing":"pausing",this.server.address()),this.status=e?{code:gt.INACTIVE}:{...this.status,code:gt.PAUSED},this.server.close())}};var Jp=class{opts;metrics;components;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:tcp"),this.opts=t,this.components=e,e.metrics!=null&&(this.metrics={events:e.metrics.registerCounterGroup("libp2p_tcp_dialer_events_total",{label:"event",help:"Total count of TCP dialer events by type"}),errors:e.metrics.registerCounterGroup("libp2p_tcp_dialer_errors_total",{label:"event",help:"Total count of TCP dialer events by type"})})}[Mh]=!0;[Symbol.toStringTag]="@libp2p/tcp";[nt]=["@libp2p/transport"];async dial(e,t){t.keepAlive=t.keepAlive??!0,t.noDelay=t.noDelay??!0,t.allowHalfOpen=t.allowHalfOpen??!1;let n=await this._connect(e,t),s;try{s=Yp({socket:n,inactivityTimeout:this.opts.outboundSocketInactivityTimeout,metrics:this.metrics?.events,direction:"outbound",remoteAddr:e,log:this.log.newScope("connection")})}catch(o){throw this.metrics?.errors.increment({outbound_to_connection:!0}),n.destroy(o),o}try{return this.log("new outbound connection %s",s.remoteAddr),await t.upgrader.upgradeOutbound(s,t)}catch(o){throw this.metrics?.errors.increment({outbound_upgrade:!0}),this.log.error("error upgrading outbound connection - %e",o),s.abort(o),o}}async _connect(e,t){t.signal.throwIfAborted(),t.onProgress?.(new Le("tcp:open-connection"));let n;return new Promise((s,o)=>{let i=Date.now(),a=Xp(e,{...this.opts.dialOpts??{},...t});this.log("dialing %a with opts %o",e,a),n=iT.default.connect(a);let c=f=>{this.log.error("dial to %a errored - %e",e,f);let d=a.path??`${a.host??""}:${a.port}`;f.message=`connection error ${d}: ${f.message}`,this.metrics?.events.increment({error:!0}),p(f)},l=()=>{this.log("connection timeout %a",e),this.metrics?.events.increment({timeout:!0});let f=new Gr(`Connection timeout after ${Date.now()-i}ms`);n.emit("error",f)},u=()=>{this.log("connection opened %a",e),this.metrics?.events.increment({connect:!0}),p()},h=()=>{this.log("connection aborted %a",e),this.metrics?.events.increment({abort:!0}),p(new rr)},p=f=>{if(n.removeListener("error",c),n.removeListener("timeout",l),n.removeListener("connect",u),t.signal!=null&&t.signal.removeEventListener("abort",h),f!=null){o(f);return}s(n)};n.on("error",c),n.on("timeout",l),n.on("connect",u),t.signal.addEventListener("abort",h)}).catch(s=>{throw n?.destroy(),s})}createListener(e){return new Qp({...this.opts.listenOpts??{},...e,maxConnections:this.opts.maxConnections,backlog:this.opts.backlog,closeServerOnMaxConnections:this.opts.closeServerOnMaxConnections,inactivityTimeout:this.opts.inboundSocketInactivityTimeout,metrics:this.components.metrics,logger:this.components.logger})}listenFilter(e){return e.filter(t=>qn.exactMatch(t)||t.toString().startsWith("/unix/"))}dialFilter(e){return this.listenFilter(e)}};function aT(r={}){return e=>new Jp(e,r)}Bt();V();ke();rt();var Sa=!!globalThis.process?.env?.DUMP_SESSION_KEYS,Cw=16;var mn=ie(ee("node:crypto"),1),u1=ie(pT(),1);var IH=typeof process<"u"&&process.versions!=null&&process.versions.node!=null,mT=IH?CH:AH;function AH(r=0){return new Uint8Array(r)}function CH(r=0){let e=Buffer.allocUnsafe(r);return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var gT=Uint8Array.from([0,97,115,109,1,0,0,0,1,43,8,96,2,127,127,0,96,1,127,0,96,1,127,1,127,96,2,127,127,1,127,96,0,0,96,3,127,127,127,0,96,4,127,127,127,127,0,96,3,127,127,126,0,2,13,1,3,101,110,118,5,97,98,111,114,116,0,6,3,23,22,0,0,0,0,0,7,2,3,3,2,4,5,1,2,5,0,1,1,0,1,1,4,5,3,1,0,1,6,187,1,37,127,0,65,4,11,127,0,65,128,4,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,0,65,0,11,7,169,1,13,8,72,65,83,95,83,73,77,68,3,36,22,98,97,116,99,104,72,97,115,104,52,85,105,110,116,65,114,114,97,121,54,52,115,0,17,26,98,97,116,99,104,72,97,115,104,52,72,97,115,104,79,98,106,101,99,116,73,110,112,117,116,115,0,18,12,73,78,80,85,84,95,76,69,78,71,84,72,3,1,15,80,65,82,65,76,76,69,76,95,70,65,67,84,79,82,3,0,5,105,110,112,117,116,3,30,6,111,117,116,112,117,116,3,32,4,105,110,105,116,0,11,6,117,112,100,97,116,101,0,19,5,102,105,110,97,108,0,20,6,100,105,103,101,115,116,0,21,8,100,105,103,101,115,116,54,52,0,16,6,109,101,109,111,114,121,2,0,8,1,22,12,1,18,10,153,23,22,9,0,32,0,32,1,54,2,0,11,9,0,32,0,32,1,54,2,4,11,9,0,32,0,32,1,54,2,8,11,192,1,1,4,127,32,1,40,2,0,65,124,113,34,3,65,128,2,73,4,127,32,3,65,4,118,5,65,31,65,252,255,255,255,3,32,3,32,3,65,252,255,255,255,3,79,27,34,3,103,107,34,4,65,7,107,33,2,32,3,32,4,65,4,107,118,65,16,115,11,33,3,32,1,40,2,8,33,5,32,1,40,2,4,34,4,4,64,32,4,32,5,16,3,11,32,5,4,64,32,5,32,4,16,2,11,32,1,32,0,32,2,65,4,116,32,3,106,65,2,116,106,34,1,40,2,96,70,4,64,32,1,32,5,54,2,96,32,5,69,4,64,32,0,32,2,65,2,116,106,34,1,40,2,4,65,126,32,3,119,113,33,3,32,1,32,3,54,2,4,32,3,69,4,64,32,0,32,0,40,2,0,65,126,32,2,119,113,16,1,11,11,11,11,181,2,1,5,127,32,1,40,2,0,33,3,32,1,65,4,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,34,2,65,1,113,4,64,32,0,32,4,16,4,32,1,32,3,65,4,106,32,2,65,124,113,106,34,3,16,1,32,1,65,4,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,33,2,11,32,3,65,2,113,4,64,32,1,65,4,107,40,2,0,34,1,40,2,0,33,6,32,0,32,1,16,4,32,1,32,6,65,4,106,32,3,65,124,113,106,34,3,16,1,11,32,4,32,2,65,2,114,16,1,32,4,65,4,107,32,1,54,2,0,32,0,32,3,65,124,113,34,2,65,128,2,73,4,127,32,2,65,4,118,5,65,31,65,252,255,255,255,3,32,2,32,2,65,252,255,255,255,3,79,27,34,2,103,107,34,3,65,7,107,33,5,32,2,32,3,65,4,107,118,65,16,115,11,34,2,32,5,65,4,116,106,65,2,116,106,40,2,96,33,3,32,1,65,0,16,2,32,1,32,3,16,3,32,3,4,64,32,3,32,1,16,2,11,32,0,32,5,65,4,116,32,2,106,65,2,116,106,32,1,54,2,96,32,0,32,0,40,2,0,65,1,32,5,116,114,16,1,32,0,32,5,65,2,116,106,34,0,32,0,40,2,4,65,1,32,2,116,114,54,2,4,11,130,1,1,3,127,32,1,65,19,106,65,112,113,65,4,107,33,1,32,0,40,2,160,12,34,3,4,64,32,3,32,1,65,16,107,34,5,70,4,64,32,3,40,2,0,33,4,32,5,33,1,11,11,32,2,167,65,112,113,32,1,107,34,3,65,20,73,4,64,15,11,32,1,32,4,65,2,113,32,3,65,8,107,34,3,65,1,114,114,16,1,32,1,65,0,16,2,32,1,65,0,16,3,32,1,65,4,106,32,3,106,34,3,65,2,16,1,32,0,32,3,54,2,160,12,32,0,32,1,16,5,11,29,0,32,0,65,1,65,27,32,0,103,107,116,106,65,1,107,32,0,32,0,65,254,255,255,255,1,73,27,11,142,1,1,2,127,32,1,65,128,2,73,4,127,32,1,65,4,118,5,65,31,32,1,16,7,34,1,103,107,34,3,65,7,107,33,2,32,1,32,3,65,4,107,118,65,16,115,11,33,1,32,0,32,2,65,2,116,106,40,2,4,65,127,32,1,116,113,34,1,4,127,32,0,32,1,104,32,2,65,4,116,106,65,2,116,106,40,2,96,5,32,0,40,2,0,65,127,32,2,65,1,106,116,113,34,1,4,127,32,0,32,0,32,1,104,34,0,65,2,116,106,40,2,4,104,32,0,65,4,116,106,65,2,116,106,40,2,96,5,65,0,11,11,11,148,2,1,3,127,32,1,65,252,255,255,255,3,75,4,64,65,176,14,65,176,15,65,205,3,65,29,16,0,0,11,32,0,65,12,32,1,65,19,106,65,112,113,65,4,107,32,1,65,12,77,27,34,1,16,8,34,2,69,4,64,32,1,65,128,2,79,4,127,32,1,16,7,5,32,1,11,33,2,63,0,34,3,32,2,65,4,32,0,40,2,160,12,32,3,65,16,116,65,4,107,71,116,106,65,255,255,3,106,65,128,128,124,113,65,16,118,34,2,32,2,32,3,72,27,64,0,65,0,72,4,64,32,2,64,0,65,0,72,4,64,0,11,11,32,0,32,3,65,16,116,63,0,172,66,16,134,16,6,32,0,32,1,16,8,33,2,11,32,2,40,2,0,26,32,0,32,2,16,4,32,2,40,2,0,34,3,65,124,113,32,1,107,34,4,65,16,79,4,64,32,2,32,1,32,3,65,2,113,114,16,1,32,2,65,4,106,32,1,106,34,1,32,4,65,4,107,65,1,114,16,1,32,0,32,1,16,5,5,32,2,32,3,65,126,113,16,1,32,2,65,4,106,32,2,40,2,0,65,124,113,106,34,0,32,0,40,2,0,65,125,113,16,1,11,32,2,11,169,2,1,3,127,32,0,65,252,255,255,255,3,75,4,64,65,192,13,65,240,13,65,52,65,43,16,0,0,11,32,0,65,236,255,255,255,3,75,4,64,65,176,14,65,240,14,65,253,0,65,30,16,0,0,11,35,23,69,4,64,63,0,34,2,65,0,76,4,127,65,1,32,2,107,64,0,65,0,72,5,65,0,11,4,64,0,11,65,128,16,65,0,16,1,65,160,28,65,0,54,2,0,3,64,32,1,65,23,73,4,64,32,1,65,2,116,65,128,16,106,65,0,54,2,4,65,0,33,2,3,64,32,2,65,16,73,4,64,32,1,65,4,116,32,2,106,65,2,116,65,128,16,106,65,0,54,2,96,32,2,65,1,106,33,2,12,1,11,11,32,1,65,1,106,33,1,12,1,11,11,65,128,16,65,164,28,63,0,172,66,16,134,16,6,65,128,16,36,23,11,35,23,32,0,65,16,106,16,9,34,2,65,1,54,2,12,32,2,32,0,54,2,16,35,24,34,3,40,2,8,33,1,32,2,32,3,16,2,32,2,32,1,16,3,32,1,32,2,32,1,40,2,4,65,3,113,114,16,2,32,3,32,2,16,3,35,25,32,2,40,2,0,65,124,113,65,4,106,106,36,25,32,2,65,20,106,34,1,65,0,32,0,252,11,0,32,1,11,74,0,65,231,204,167,208,6,36,4,65,133,221,158,219,123,36,5,65,242,230,187,227,3,36,6,65,186,234,191,170,122,36,7,65,255,164,185,136,5,36,8,65,140,209,149,216,121,36,9,65,171,179,143,252,1,36,10,65,153,154,131,223,5,36,11,65,0,36,34,65,0,36,35,11,233,3,1,1,127,35,4,36,12,35,5,36,13,35,6,36,14,35,7,36,15,35,8,36,16,35,9,36,17,35,10,36,18,35,11,36,19,65,0,36,20,3,64,35,20,65,16,73,4,64,32,0,35,20,65,2,116,106,32,1,35,20,32,2,108,65,2,116,34,3,65,3,106,106,45,0,0,32,1,32,3,106,45,0,0,65,24,116,32,1,32,3,65,1,106,106,45,0,0,65,16,116,114,32,1,32,3,65,2,106,106,45,0,0,65,8,116,114,114,54,2,0,35,20,65,1,106,36,20,12,1,11,11,65,16,36,20,3,64,35,20,65,192,0,73,4,64,32,0,35,20,65,2,116,106,32,0,35,20,65,16,107,65,2,116,106,40,2,0,32,0,35,20,65,7,107,65,2,116,106,40,2,0,32,0,35,20,65,2,107,65,2,116,106,40,2,0,34,1,65,17,120,32,1,65,19,120,115,32,1,65,10,118,115,106,32,0,35,20,65,15,107,65,2,116,106,40,2,0,34,1,65,7,120,32,1,65,18,120,115,32,1,65,3,118,115,106,106,54,2,0,35,20,65,1,106,36,20,12,1,11,11,65,0,36,20,3,64,35,20,65,192,0,73,4,64,32,0,35,20,65,2,116,34,1,106,40,2,0,32,1,35,2,106,40,2,0,35,19,35,16,34,1,65,6,120,32,1,65,11,120,115,32,1,65,25,120,115,106,35,16,34,1,35,17,113,35,18,32,1,65,127,115,113,115,106,106,106,36,21,35,12,34,1,65,2,120,32,1,65,13,120,115,32,1,65,22,120,115,35,13,34,1,35,14,34,2,113,32,1,35,12,34,1,113,32,1,32,2,113,115,115,106,36,22,35,18,36,19,35,17,36,18,35,16,36,17,35,15,35,21,106,36,16,35,14,36,15,35,13,36,14,35,12,36,13,35,21,35,22,106,36,12,35,20,65,1,106,36,20,12,1,11,11,35,4,35,12,106,36,4,35,5,35,13,106,36,5,35,6,35,14,106,36,6,35,7,35,15,106,36,7,35,8,35,16,106,36,8,35,9,35,17,106,36,9,35,10,35,18,106,36,10,35,11,35,19,106,36,11,11,253,1,1,2,127,35,4,36,12,35,5,36,13,35,6,36,14,35,7,36,15,35,8,36,16,35,9,36,17,35,10,36,18,35,11,36,19,65,0,36,20,3,64,35,20,65,192,0,73,4,64,32,0,35,20,65,2,116,106,40,2,0,35,19,35,16,34,1,65,6,120,32,1,65,11,120,115,32,1,65,25,120,115,106,35,16,34,1,35,17,113,35,18,32,1,65,127,115,113,115,106,106,36,21,35,12,34,1,65,2,120,32,1,65,13,120,115,32,1,65,22,120,115,35,13,34,2,35,14,34,1,113,32,2,35,12,34,2,113,32,1,32,2,113,115,115,106,36,22,35,18,36,19,35,17,36,18,35,16,36,17,35,15,35,21,106,36,16,35,14,36,15,35,13,36,14,35,12,36,13,35,21,35,22,106,36,12,35,20,65,1,106,36,20,12,1,11,11,35,4,35,12,106,36,4,35,5,35,13,106,36,5,35,6,35,14,106,36,6,35,7,35,15,106,36,7,35,8,35,16,106,36,8,35,9,35,17,106,36,9,35,10,35,18,106,36,10,35,11,35,19,106,36,11,11,25,0,32,0,65,128,254,131,120,113,65,8,119,32,0,65,255,129,252,7,113,65,8,120,114,11,88,0,16,11,35,29,32,0,32,2,16,12,35,3,16,13,32,1,35,4,16,14,54,2,0,32,1,35,5,16,14,54,2,4,32,1,35,6,16,14,54,2,8,32,1,35,7,16,14,54,2,12,32,1,35,8,16,14,54,2,16,32,1,35,9,16,14,54,2,20,32,1,35,10,16,14,54,2,24,32,1,35,11,16,14,54,2,28,11,10,0,32,0,32,1,65,1,16,15,11,42,1,1,127,3,64,32,1,65,4,72,4,64,35,31,32,1,65,6,116,106,32,0,32,1,65,5,116,106,16,16,32,1,65,1,106,33,1,12,1,11,11,11,44,1,1,127,3,64,32,1,65,4,72,4,64,35,31,32,1,65,2,116,106,32,0,32,1,65,5,116,106,65,4,16,15,32,1,65,1,106,33,1,12,1,11,11,11,178,1,1,2,127,35,35,32,1,106,36,35,35,34,4,64,65,192,0,35,34,107,34,2,32,1,76,4,64,35,27,35,34,106,32,0,32,2,252,10,0,0,35,34,32,2,106,36,34,65,192,0,35,34,107,33,2,32,1,65,192,0,35,34,107,107,33,1,35,29,35,27,65,1,16,12,65,0,36,34,5,35,27,35,34,106,32,0,32,1,252,10,0,0,35,34,32,1,106,36,34,15,11,11,3,64,32,3,32,1,65,192,0,109,72,4,64,35,29,32,0,32,2,106,65,1,16,12,32,3,65,1,106,33,3,32,2,65,64,107,33,2,12,1,11,11,32,1,65,63,113,34,1,4,64,35,27,35,34,106,32,0,32,2,106,32,1,252,10,0,0,35,34,32,1,106,36,34,11,11,235,1,1,2,127,35,27,35,34,106,65,128,1,58,0,0,35,34,65,1,106,36,34,35,34,65,56,74,4,64,35,27,35,34,106,34,1,65,192,0,35,34,107,106,33,2,3,64,32,1,32,2,73,4,64,32,1,65,0,58,0,0,32,1,65,1,106,33,1,12,1,11,11,35,29,35,27,65,1,16,12,65,0,36,34,11,35,27,35,34,106,34,1,65,56,35,34,107,106,33,2,3,64,32,1,32,2,73,4,64,32,1,65,0,58,0,0,32,1,65,1,106,33,1,12,1,11,11,35,27,35,35,65,128,128,128,128,2,109,16,14,54,2,56,35,27,35,35,65,3,116,16,14,54,2,60,35,29,35,27,65,1,16,12,32,0,35,4,16,14,54,2,0,32,0,35,5,16,14,54,2,4,32,0,35,6,16,14,54,2,8,32,0,35,7,16,14,54,2,12,32,0,35,8,16,14,54,2,16,32,0,35,9,16,14,54,2,20,32,0,35,10,16,14,54,2,24,32,0,35,11,16,14,54,2,28,11,14,0,16,11,35,31,32,0,16,19,35,33,16,20,11,82,0,65,196,10,40,2,0,36,2,65,148,13,40,2,0,36,3,65,224,15,65,224,15,16,2,65,224,15,65,224,15,16,3,65,224,15,36,24,65,192,0,16,10,36,26,35,26,36,27,65,128,8,16,10,36,28,35,28,36,29,65,128,4,16,10,36,30,35,30,36,31,65,32,16,10,36,32,35,32,36,33,11,11,253,6,18,0,65,140,8,11,2,28,1,0,65,152,8,11,136,2,1,0,0,0,0,1,0,0,152,47,138,66,145,68,55,113,207,251,192,181,165,219,181,233,91,194,86,57,241,17,241,89,164,130,63,146,213,94,28,171,152,170,7,216,1,91,131,18,190,133,49,36,195,125,12,85,116,93,190,114,254,177,222,128,167,6,220,155,116,241,155,193,193,105,155,228,134,71,190,239,198,157,193,15,204,161,12,36,111,44,233,45,170,132,116,74,220,169,176,92,218,136,249,118,82,81,62,152,109,198,49,168,200,39,3,176,199,127,89,191,243,11,224,198,71,145,167,213,81,99,202,6,103,41,41,20,133,10,183,39,56,33,27,46,252,109,44,77,19,13,56,83,84,115,10,101,187,10,106,118,46,201,194,129,133,44,114,146,161,232,191,162,75,102,26,168,112,139,75,194,163,81,108,199,25,232,146,209,36,6,153,214,133,53,14,244,112,160,106,16,22,193,164,25,8,108,55,30,76,119,72,39,181,188,176,52,179,12,28,57,74,170,216,78,79,202,156,91,243,111,46,104,238,130,143,116,111,99,165,120,20,120,200,132,8,2,199,140,250,255,190,144,235,108,80,164,247,163,249,190,242,120,113,198,0,65,172,10,11,1,44,0,65,184,10,11,21,4,0,0,0,16,0,0,0,32,4,0,0,32,4,0,0,0,1,0,0,64,0,65,220,10,11,2,28,1,0,65,232,10,11,136,2,1,0,0,0,0,1,0,0,152,47,138,194,145,68,55,113,207,251,192,181,165,219,181,233,91,194,86,57,241,17,241,89,164,130,63,146,213,94,28,171,152,170,7,216,1,91,131,18,190,133,49,36,195,125,12,85,116,93,190,114,254,177,222,128,167,6,220,155,116,243,155,193,193,105,155,100,134,71,254,240,198,237,225,15,84,242,12,36,111,52,233,79,190,132,201,108,30,65,185,97,250,136,249,22,82,81,198,242,109,90,142,168,101,252,25,176,199,158,217,185,195,49,18,154,160,234,14,231,43,35,177,253,176,62,53,199,213,186,105,48,95,109,151,203,143,17,15,90,253,238,30,220,137,182,53,10,4,122,11,222,157,202,244,88,22,91,93,225,134,62,127,0,128,137,8,55,50,234,7,165,55,149,171,111,16,97,64,23,241,214,140,13,109,59,170,205,55,190,187,192,218,59,97,131,99,163,72,219,49,233,2,11,167,92,209,111,202,250,26,82,49,132,51,49,149,26,212,110,144,120,67,109,242,145,156,195,189,171,204,158,230,160,201,181,60,182,47,83,198,65,199,210,163,126,35,7,104,75,149,164,118,29,25,76,0,65,252,12,11,1,44,0,65,136,13,11,21,4,0,0,0,16,0,0,0,112,5,0,0,112,5,0,0,0,1,0,0,64,0,65,172,13,11,1,44,0,65,184,13,11,35,2,0,0,0,28,0,0,0,73,0,110,0,118,0,97,0,108,0,105,0,100,0,32,0,108,0,101,0,110,0,103,0,116,0,104,0,65,220,13,11,1,60,0,65,232,13,11,45,2,0,0,0,38,0,0,0,126,0,108,0,105,0,98,0,47,0,97,0,114,0,114,0,97,0,121,0,98,0,117,0,102,0,102,0,101,0,114,0,46,0,116,0,115,0,65,156,14,11,1,60,0,65,168,14,11,47,2,0,0,0,40,0,0,0,65,0,108,0,108,0,111,0,99,0,97,0,116,0,105,0,111,0,110,0,32,0,116,0,111,0,111,0,32,0,108,0,97,0,114,0,103,0,101,0,65,220,14,11,1,60,0,65,232,14,11,37,2,0,0,0,30,0,0,0,126,0,108,0,105,0,98,0,47,0,114,0,116,0,47,0,116,0,99,0,109,0,115,0,46,0,116,0,115,0,65,156,15,11,1,60,0,65,168,15,11,37,2,0,0,0,30,0,0,0,126,0,108,0,105,0,98,0,47,0,114,0,116,0,47,0,116,0,108,0,115,0,102,0,46,0,116,0,115]);var Lw=Uint8Array.from([0,97,115,109,1,0,0,0,1,37,7,96,2,127,127,0,96,1,127,1,127,96,2,127,127,1,127,96,1,127,0,96,0,0,96,4,127,127,127,127,0,96,3,127,127,126,0,2,13,1,3,101,110,118,5,97,98,111,114,116,0,5,3,30,29,0,0,0,0,0,6,1,2,2,2,1,2,1,1,2,4,4,1,0,3,3,4,0,0,3,3,3,0,4,5,3,1,0,1,6,227,4,61,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,127,1,65,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,0,65,4,11,127,0,65,128,4,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,0,65,1,11,7,169,1,13,8,72,65,83,95,83,73,77,68,3,60,22,98,97,116,99,104,72,97,115,104,52,85,105,110,116,65,114,114,97,121,54,52,115,0,20,26,98,97,116,99,104,72,97,115,104,52,72,97,115,104,79,98,106,101,99,116,73,110,112,117,116,115,0,21,12,73,78,80,85,84,95,76,69,78,71,84,72,3,28,15,80,65,82,65,76,76,69,76,95,70,65,67,84,79,82,3,27,5,105,110,112,117,116,3,54,6,111,117,116,112,117,116,3,56,4,105,110,105,116,0,22,6,117,112,100,97,116,101,0,24,5,102,105,110,97,108,0,25,6,100,105,103,101,115,116,0,26,8,100,105,103,101,115,116,54,52,0,28,6,109,101,109,111,114,121,2,0,8,1,29,12,1,38,10,243,111,29,9,0,32,0,32,1,54,2,0,11,9,0,32,0,32,1,54,2,4,11,9,0,32,0,32,1,54,2,8,11,192,1,1,4,127,32,1,40,2,0,65,124,113,34,3,65,128,2,73,4,127,32,3,65,4,118,5,65,31,65,252,255,255,255,3,32,3,32,3,65,252,255,255,255,3,79,27,34,3,103,107,34,4,65,7,107,33,2,32,3,32,4,65,4,107,118,65,16,115,11,33,3,32,1,40,2,8,33,5,32,1,40,2,4,34,4,4,64,32,4,32,5,16,3,11,32,5,4,64,32,5,32,4,16,2,11,32,1,32,0,32,2,65,4,116,32,3,106,65,2,116,106,34,1,40,2,96,70,4,64,32,1,32,5,54,2,96,32,5,69,4,64,32,0,32,2,65,2,116,106,34,1,40,2,4,65,126,32,3,119,113,33,3,32,1,32,3,54,2,4,32,3,69,4,64,32,0,32,0,40,2,0,65,126,32,2,119,113,16,1,11,11,11,11,181,2,1,5,127,32,1,40,2,0,33,3,32,1,65,4,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,34,2,65,1,113,4,64,32,0,32,4,16,4,32,1,32,3,65,4,106,32,2,65,124,113,106,34,3,16,1,32,1,65,4,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,33,2,11,32,3,65,2,113,4,64,32,1,65,4,107,40,2,0,34,1,40,2,0,33,6,32,0,32,1,16,4,32,1,32,6,65,4,106,32,3,65,124,113,106,34,3,16,1,11,32,4,32,2,65,2,114,16,1,32,4,65,4,107,32,1,54,2,0,32,0,32,3,65,124,113,34,2,65,128,2,73,4,127,32,2,65,4,118,5,65,31,65,252,255,255,255,3,32,2,32,2,65,252,255,255,255,3,79,27,34,2,103,107,34,3,65,7,107,33,5,32,2,32,3,65,4,107,118,65,16,115,11,34,2,32,5,65,4,116,106,65,2,116,106,40,2,96,33,3,32,1,65,0,16,2,32,1,32,3,16,3,32,3,4,64,32,3,32,1,16,2,11,32,0,32,5,65,4,116,32,2,106,65,2,116,106,32,1,54,2,96,32,0,32,0,40,2,0,65,1,32,5,116,114,16,1,32,0,32,5,65,2,116,106,34,0,32,0,40,2,4,65,1,32,2,116,114,54,2,4,11,130,1,1,3,127,32,1,65,19,106,65,112,113,65,4,107,33,1,32,0,40,2,160,12,34,3,4,64,32,3,32,1,65,16,107,34,5,70,4,64,32,3,40,2,0,33,4,32,5,33,1,11,11,32,2,167,65,112,113,32,1,107,34,3,65,20,73,4,64,15,11,32,1,32,4,65,2,113,32,3,65,8,107,34,3,65,1,114,114,16,1,32,1,65,0,16,2,32,1,65,0,16,3,32,1,65,4,106,32,3,106,34,3,65,2,16,1,32,0,32,3,54,2,160,12,32,0,32,1,16,5,11,29,0,32,0,65,1,65,27,32,0,103,107,116,106,65,1,107,32,0,32,0,65,254,255,255,255,1,73,27,11,142,1,1,2,127,32,1,65,128,2,73,4,127,32,1,65,4,118,5,65,31,32,1,16,7,34,1,103,107,34,3,65,7,107,33,2,32,1,32,3,65,4,107,118,65,16,115,11,33,1,32,0,32,2,65,2,116,106,40,2,4,65,127,32,1,116,113,34,1,4,127,32,0,32,1,104,32,2,65,4,116,106,65,2,116,106,40,2,96,5,32,0,40,2,0,65,127,32,2,65,1,106,116,113,34,1,4,127,32,0,32,0,32,1,104,34,0,65,2,116,106,40,2,4,104,32,0,65,4,116,106,65,2,116,106,40,2,96,5,65,0,11,11,11,148,2,1,3,127,32,1,65,252,255,255,255,3,75,4,64,65,176,14,65,176,15,65,205,3,65,29,16,0,0,11,32,0,65,12,32,1,65,19,106,65,112,113,65,4,107,32,1,65,12,77,27,34,1,16,8,34,2,69,4,64,32,1,65,128,2,79,4,127,32,1,16,7,5,32,1,11,33,2,63,0,34,3,32,2,65,4,32,0,40,2,160,12,32,3,65,16,116,65,4,107,71,116,106,65,255,255,3,106,65,128,128,124,113,65,16,118,34,2,32,2,32,3,72,27,64,0,65,0,72,4,64,32,2,64,0,65,0,72,4,64,0,11,11,32,0,32,3,65,16,116,63,0,172,66,16,134,16,6,32,0,32,1,16,8,33,2,11,32,2,40,2,0,26,32,0,32,2,16,4,32,2,40,2,0,34,3,65,124,113,32,1,107,34,4,65,16,79,4,64,32,2,32,1,32,3,65,2,113,114,16,1,32,2,65,4,106,32,1,106,34,1,32,4,65,4,107,65,1,114,16,1,32,0,32,1,16,5,5,32,2,32,3,65,126,113,16,1,32,2,65,4,106,32,2,40,2,0,65,124,113,106,34,0,32,0,40,2,0,65,125,113,16,1,11,32,2,11,133,2,1,2,127,32,0,65,236,255,255,255,3,75,4,64,65,176,14,65,240,14,65,253,0,65,30,16,0,0,11,35,20,69,4,64,63,0,34,3,65,0,76,4,127,65,1,32,3,107,64,0,65,0,72,5,65,0,11,4,64,0,11,65,208,21,65,0,16,1,65,240,33,65,0,54,2,0,3,64,32,2,65,23,73,4,64,32,2,65,2,116,65,208,21,106,65,0,54,2,4,65,0,33,3,3,64,32,3,65,16,73,4,64,32,2,65,4,116,32,3,106,65,2,116,65,208,21,106,65,0,54,2,96,32,3,65,1,106,33,3,12,1,11,11,32,2,65,1,106,33,2,12,1,11,11,65,208,21,65,244,33,63,0,172,66,16,134,16,6,65,208,21,36,20,11,35,20,32,0,65,16,106,16,9,34,2,32,1,54,2,12,32,2,32,0,54,2,16,35,21,34,0,40,2,8,33,1,32,2,32,0,16,2,32,2,32,1,16,3,32,1,32,2,32,1,40,2,4,65,3,113,114,16,2,32,0,32,2,16,3,35,22,32,2,40,2,0,65,124,113,65,4,106,106,36,22,32,2,65,20,106,11,46,1,1,127,32,0,65,252,255,255,255,3,75,4,64,65,192,13,65,240,13,65,52,65,43,16,0,0,11,32,0,65,1,16,10,34,1,65,0,32,0,252,11,0,32,1,11,41,0,32,1,32,0,40,2,12,79,4,64,65,144,16,65,208,16,65,242,0,65,42,16,0,0,11,32,0,40,2,4,32,1,65,2,116,106,40,2,0,11,181,1,1,4,127,32,0,69,4,64,65,192,18,15,11,65,0,32,0,107,32,0,32,0,65,31,118,65,1,116,34,1,27,34,0,65,10,79,65,1,106,32,0,65,144,206,0,79,65,3,106,32,0,65,232,7,79,106,32,0,65,228,0,73,27,32,0,65,192,132,61,79,65,6,106,32,0,65,128,148,235,220,3,79,65,8,106,32,0,65,128,194,215,47,79,106,32,0,65,128,173,226,4,73,27,32,0,65,160,141,6,73,27,34,2,65,1,116,32,1,106,65,2,16,10,34,3,32,1,106,33,4,3,64,32,4,32,2,65,1,107,34,2,65,1,116,106,32,0,65,10,112,65,48,106,59,1,0,32,0,65,10,110,34,0,13,0,11,32,1,4,64,32,3,65,45,59,1,0,11,32,3,11,13,0,32,0,65,20,107,40,2,16,65,1,118,11,64,1,3,127,32,0,16,14,65,1,116,34,2,32,1,16,14,65,1,116,34,3,106,34,4,69,4,64,65,160,20,15,11,32,4,65,2,16,10,34,4,32,0,32,2,252,10,0,0,32,2,32,4,106,32,1,32,3,252,10,0,0,32,4,11,145,16,2,2,127,1,123,65,224,15,65,224,15,16,2,65,224,15,65,224,15,16,3,65,224,15,36,21,65,128,8,16,11,36,23,35,23,36,24,2,64,3,64,32,0,65,192,0,72,4,64,35,24,33,1,65,192,10,32,0,16,12,253,17,33,2,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,32,0,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,67,11,32,1,32,2,253,11,4,0,12,63,11,32,1,32,2,253,11,4,16,12,62,11,32,1,32,2,253,11,4,32,12,61,11,32,1,32,2,253,11,4,48,12,60,11,32,1,32,2,253,11,4,64,12,59,11,32,1,32,2,253,11,4,80,12,58,11,32,1,32,2,253,11,4,96,12,57,11,32,1,32,2,253,11,4,112,12,56,11,32,1,32,2,253,11,4,128,1,12,55,11,32,1,32,2,253,11,4,144,1,12,54,11,32,1,32,2,253,11,4,160,1,12,53,11,32,1,32,2,253,11,4,176,1,12,52,11,32,1,32,2,253,11,4,192,1,12,51,11,32,1,32,2,253,11,4,208,1,12,50,11,32,1,32,2,253,11,4,224,1,12,49,11,32,1,32,2,253,11,4,240,1,12,48,11,32,1,32,2,253,11,4,128,2,12,47,11,32,1,32,2,253,11,4,144,2,12,46,11,32,1,32,2,253,11,4,160,2,12,45,11,32,1,32,2,253,11,4,176,2,12,44,11,32,1,32,2,253,11,4,192,2,12,43,11,32,1,32,2,253,11,4,208,2,12,42,11,32,1,32,2,253,11,4,224,2,12,41,11,32,1,32,2,253,11,4,240,2,12,40,11,32,1,32,2,253,11,4,128,3,12,39,11,32,1,32,2,253,11,4,144,3,12,38,11,32,1,32,2,253,11,4,160,3,12,37,11,32,1,32,2,253,11,4,176,3,12,36,11,32,1,32,2,253,11,4,192,3,12,35,11,32,1,32,2,253,11,4,208,3,12,34,11,32,1,32,2,253,11,4,224,3,12,33,11,32,1,32,2,253,11,4,240,3,12,32,11,32,1,32,2,253,11,4,128,4,12,31,11,32,1,32,2,253,11,4,144,4,12,30,11,32,1,32,2,253,11,4,160,4,12,29,11,32,1,32,2,253,11,4,176,4,12,28,11,32,1,32,2,253,11,4,192,4,12,27,11,32,1,32,2,253,11,4,208,4,12,26,11,32,1,32,2,253,11,4,224,4,12,25,11,32,1,32,2,253,11,4,240,4,12,24,11,32,1,32,2,253,11,4,128,5,12,23,11,32,1,32,2,253,11,4,144,5,12,22,11,32,1,32,2,253,11,4,160,5,12,21,11,32,1,32,2,253,11,4,176,5,12,20,11,32,1,32,2,253,11,4,192,5,12,19,11,32,1,32,2,253,11,4,208,5,12,18,11,32,1,32,2,253,11,4,224,5,12,17,11,32,1,32,2,253,11,4,240,5,12,16,11,32,1,32,2,253,11,4,128,6,12,15,11,32,1,32,2,253,11,4,144,6,12,14,11,32,1,32,2,253,11,4,160,6,12,13,11,32,1,32,2,253,11,4,176,6,12,12,11,32,1,32,2,253,11,4,192,6,12,11,11,32,1,32,2,253,11,4,208,6,12,10,11,32,1,32,2,253,11,4,224,6,12,9,11,32,1,32,2,253,11,4,240,6,12,8,11,32,1,32,2,253,11,4,128,7,12,7,11,32,1,32,2,253,11,4,144,7,12,6,11,32,1,32,2,253,11,4,160,7,12,5,11,32,1,32,2,253,11,4,176,7,12,4,11,32,1,32,2,253,11,4,192,7,12,3,11,32,1,32,2,253,11,4,208,7,12,2,11,32,1,32,2,253,11,4,224,7,12,1,11,32,1,32,2,253,11,4,240,7,11,32,0,65,1,106,33,0,12,1,11,11,65,128,8,16,11,36,25,35,25,36,26,65,0,33,0,3,64,32,0,65,192,0,72,4,64,35,26,33,1,65,144,13,32,0,16,12,253,17,33,2,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,32,0,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,67,11,32,1,32,2,253,11,4,0,12,63,11,32,1,32,2,253,11,4,16,12,62,11,32,1,32,2,253,11,4,32,12,61,11,32,1,32,2,253,11,4,48,12,60,11,32,1,32,2,253,11,4,64,12,59,11,32,1,32,2,253,11,4,80,12,58,11,32,1,32,2,253,11,4,96,12,57,11,32,1,32,2,253,11,4,112,12,56,11,32,1,32,2,253,11,4,128,1,12,55,11,32,1,32,2,253,11,4,144,1,12,54,11,32,1,32,2,253,11,4,160,1,12,53,11,32,1,32,2,253,11,4,176,1,12,52,11,32,1,32,2,253,11,4,192,1,12,51,11,32,1,32,2,253,11,4,208,1,12,50,11,32,1,32,2,253,11,4,224,1,12,49,11,32,1,32,2,253,11,4,240,1,12,48,11,32,1,32,2,253,11,4,128,2,12,47,11,32,1,32,2,253,11,4,144,2,12,46,11,32,1,32,2,253,11,4,160,2,12,45,11,32,1,32,2,253,11,4,176,2,12,44,11,32,1,32,2,253,11,4,192,2,12,43,11,32,1,32,2,253,11,4,208,2,12,42,11,32,1,32,2,253,11,4,224,2,12,41,11,32,1,32,2,253,11,4,240,2,12,40,11,32,1,32,2,253,11,4,128,3,12,39,11,32,1,32,2,253,11,4,144,3,12,38,11,32,1,32,2,253,11,4,160,3,12,37,11,32,1,32,2,253,11,4,176,3,12,36,11,32,1,32,2,253,11,4,192,3,12,35,11,32,1,32,2,253,11,4,208,3,12,34,11,32,1,32,2,253,11,4,224,3,12,33,11,32,1,32,2,253,11,4,240,3,12,32,11,32,1,32,2,253,11,4,128,4,12,31,11,32,1,32,2,253,11,4,144,4,12,30,11,32,1,32,2,253,11,4,160,4,12,29,11,32,1,32,2,253,11,4,176,4,12,28,11,32,1,32,2,253,11,4,192,4,12,27,11,32,1,32,2,253,11,4,208,4,12,26,11,32,1,32,2,253,11,4,224,4,12,25,11,32,1,32,2,253,11,4,240,4,12,24,11,32,1,32,2,253,11,4,128,5,12,23,11,32,1,32,2,253,11,4,144,5,12,22,11,32,1,32,2,253,11,4,160,5,12,21,11,32,1,32,2,253,11,4,176,5,12,20,11,32,1,32,2,253,11,4,192,5,12,19,11,32,1,32,2,253,11,4,208,5,12,18,11,32,1,32,2,253,11,4,224,5,12,17,11,32,1,32,2,253,11,4,240,5,12,16,11,32,1,32,2,253,11,4,128,6,12,15,11,32,1,32,2,253,11,4,144,6,12,14,11,32,1,32,2,253,11,4,160,6,12,13,11,32,1,32,2,253,11,4,176,6,12,12,11,32,1,32,2,253,11,4,192,6,12,11,11,32,1,32,2,253,11,4,208,6,12,10,11,32,1,32,2,253,11,4,224,6,12,9,11,32,1,32,2,253,11,4,240,6,12,8,11,32,1,32,2,253,11,4,128,7,12,7,11,32,1,32,2,253,11,4,144,7,12,6,11,32,1,32,2,253,11,4,160,7,12,5,11,32,1,32,2,253,11,4,176,7,12,4,11,32,1,32,2,253,11,4,192,7,12,3,11,32,1,32,2,253,11,4,208,7,12,2,11,32,1,32,2,253,11,4,224,7,12,1,11,32,1,32,2,253,11,4,240,7,11,32,0,65,1,106,33,0,12,1,11,11,15,11,65,192,19,32,0,16,13,16,15,65,192,20,65,201,1,65,7,16,0,0,11,192,10,2,2,123,2,127,35,0,36,8,35,1,36,9,35,2,36,10,35,3,36,11,35,4,36,12,35,5,36,13,35,6,36,14,35,7,36,15,65,0,36,18,3,64,35,18,65,192,0,72,4,64,35,15,35,12,34,0,65,6,253,173,1,32,0,65,26,253,171,1,253,80,32,0,65,11,253,173,1,32,0,65,21,253,171,1,253,80,253,81,32,0,65,25,253,173,1,32,0,65,7,253,171,1,253,80,253,81,253,174,1,35,12,34,0,35,13,253,78,32,0,253,77,35,14,253,78,253,81,253,174,1,33,1,35,26,33,2,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,34,3,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,11,32,2,253,0,4,0,33,0,12,64,11,32,2,253,0,4,16,33,0,12,63,11,32,2,253,0,4,32,33,0,12,62,11,32,2,253,0,4,48,33,0,12,61,11,32,2,253,0,4,64,33,0,12,60,11,32,2,253,0,4,80,33,0,12,59,11,32,2,253,0,4,96,33,0,12,58,11,32,2,253,0,4,112,33,0,12,57,11,32,2,253,0,4,128,1,33,0,12,56,11,32,2,253,0,4,144,1,33,0,12,55,11,32,2,253,0,4,160,1,33,0,12,54,11,32,2,253,0,4,176,1,33,0,12,53,11,32,2,253,0,4,192,1,33,0,12,52,11,32,2,253,0,4,208,1,33,0,12,51,11,32,2,253,0,4,224,1,33,0,12,50,11,32,2,253,0,4,240,1,33,0,12,49,11,32,2,253,0,4,128,2,33,0,12,48,11,32,2,253,0,4,144,2,33,0,12,47,11,32,2,253,0,4,160,2,33,0,12,46,11,32,2,253,0,4,176,2,33,0,12,45,11,32,2,253,0,4,192,2,33,0,12,44,11,32,2,253,0,4,208,2,33,0,12,43,11,32,2,253,0,4,224,2,33,0,12,42,11,32,2,253,0,4,240,2,33,0,12,41,11,32,2,253,0,4,128,3,33,0,12,40,11,32,2,253,0,4,144,3,33,0,12,39,11,32,2,253,0,4,160,3,33,0,12,38,11,32,2,253,0,4,176,3,33,0,12,37,11,32,2,253,0,4,192,3,33,0,12,36,11,32,2,253,0,4,208,3,33,0,12,35,11,32,2,253,0,4,224,3,33,0,12,34,11,32,2,253,0,4,240,3,33,0,12,33,11,32,2,253,0,4,128,4,33,0,12,32,11,32,2,253,0,4,144,4,33,0,12,31,11,32,2,253,0,4,160,4,33,0,12,30,11,32,2,253,0,4,176,4,33,0,12,29,11,32,2,253,0,4,192,4,33,0,12,28,11,32,2,253,0,4,208,4,33,0,12,27,11,32,2,253,0,4,224,4,33,0,12,26,11,32,2,253,0,4,240,4,33,0,12,25,11,32,2,253,0,4,128,5,33,0,12,24,11,32,2,253,0,4,144,5,33,0,12,23,11,32,2,253,0,4,160,5,33,0,12,22,11,32,2,253,0,4,176,5,33,0,12,21,11,32,2,253,0,4,192,5,33,0,12,20,11,32,2,253,0,4,208,5,33,0,12,19,11,32,2,253,0,4,224,5,33,0,12,18,11,32,2,253,0,4,240,5,33,0,12,17,11,32,2,253,0,4,128,6,33,0,12,16,11,32,2,253,0,4,144,6,33,0,12,15,11,32,2,253,0,4,160,6,33,0,12,14,11,32,2,253,0,4,176,6,33,0,12,13,11,32,2,253,0,4,192,6,33,0,12,12,11,32,2,253,0,4,208,6,33,0,12,11,11,32,2,253,0,4,224,6,33,0,12,10,11,32,2,253,0,4,240,6,33,0,12,9,11,32,2,253,0,4,128,7,33,0,12,8,11,32,2,253,0,4,144,7,33,0,12,7,11,32,2,253,0,4,160,7,33,0,12,6,11,32,2,253,0,4,176,7,33,0,12,5,11,32,2,253,0,4,192,7,33,0,12,4,11,32,2,253,0,4,208,7,33,0,12,3,11,32,2,253,0,4,224,7,33,0,12,2,11,32,2,253,0,4,240,7,33,0,12,1,11,65,128,21,32,3,16,13,16,15,65,192,20,65,213,2,65,7,16,0,0,11,32,1,32,0,253,174,1,36,16,35,8,34,0,65,2,253,173,1,32,0,65,30,253,171,1,253,80,32,0,65,13,253,173,1,32,0,65,19,253,171,1,253,80,253,81,32,0,65,22,253,173,1,32,0,65,10,253,171,1,253,80,253,81,35,8,34,0,35,9,34,1,253,78,32,0,35,10,34,0,253,78,253,81,32,1,32,0,253,78,253,81,253,174,1,36,17,35,14,36,15,35,13,36,14,35,12,36,13,35,11,35,16,253,174,1,36,12,35,10,36,11,35,9,36,10,35,8,36,9,35,16,35,17,253,174,1,36,8,35,18,65,1,106,36,18,12,1,11,11,35,0,35,8,253,174,1,36,0,35,1,35,9,253,174,1,36,1,35,2,35,10,253,174,1,36,2,35,3,35,11,253,174,1,36,3,35,4,35,12,253,174,1,36,4,35,5,35,13,253,174,1,36,5,35,6,35,14,253,174,1,36,6,35,7,35,15,253,174,1,36,7,11,25,0,32,0,65,128,254,131,120,113,65,8,119,32,0,65,255,129,252,7,113,65,8,120,114,11,157,57,2,2,123,2,127,253,12,103,230,9,106,103,230,9,106,103,230,9,106,103,230,9,106,36,0,253,12,133,174,103,187,133,174,103,187,133,174,103,187,133,174,103,187,36,1,253,12,114,243,110,60,114,243,110,60,114,243,110,60,114,243,110,60,36,2,253,12,58,245,79,165,58,245,79,165,58,245,79,165,58,245,79,165,36,3,253,12,127,82,14,81,127,82,14,81,127,82,14,81,127,82,14,81,36,4,253,12,140,104,5,155,140,104,5,155,140,104,5,155,140,104,5,155,36,5,253,12,171,217,131,31,171,217,131,31,171,217,131,31,171,217,131,31,36,6,253,12,25,205,224,91,25,205,224,91,25,205,224,91,25,205,224,91,36,7,253,12,103,230,9,106,103,230,9,106,103,230,9,106,103,230,9,106,36,8,253,12,133,174,103,187,133,174,103,187,133,174,103,187,133,174,103,187,36,9,253,12,114,243,110,60,114,243,110,60,114,243,110,60,114,243,110,60,36,10,253,12,58,245,79,165,58,245,79,165,58,245,79,165,58,245,79,165,36,11,253,12,127,82,14,81,127,82,14,81,127,82,14,81,127,82,14,81,36,12,253,12,140,104,5,155,140,104,5,155,140,104,5,155,140,104,5,155,36,13,253,12,171,217,131,31,171,217,131,31,171,217,131,31,171,217,131,31,36,14,253,12,25,205,224,91,25,205,224,91,25,205,224,91,25,205,224,91,36,15,65,0,36,18,2,64,3,64,35,18,65,192,0,72,4,64,35,18,65,16,72,4,123,2,123,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,34,4,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,68,11,32,0,253,0,4,0,12,63,11,32,0,253,0,4,16,12,62,11,32,0,253,0,4,32,12,61,11,32,0,253,0,4,48,12,60,11,32,0,253,0,4,64,12,59,11,32,0,253,0,4,80,12,58,11,32,0,253,0,4,96,12,57,11,32,0,253,0,4,112,12,56,11,32,0,253,0,4,128,1,12,55,11,32,0,253,0,4,144,1,12,54,11,32,0,253,0,4,160,1,12,53,11,32,0,253,0,4,176,1,12,52,11,32,0,253,0,4,192,1,12,51,11,32,0,253,0,4,208,1,12,50,11,32,0,253,0,4,224,1,12,49,11,32,0,253,0,4,240,1,12,48,11,32,0,253,0,4,128,2,12,47,11,32,0,253,0,4,144,2,12,46,11,32,0,253,0,4,160,2,12,45,11,32,0,253,0,4,176,2,12,44,11,32,0,253,0,4,192,2,12,43,11,32,0,253,0,4,208,2,12,42,11,32,0,253,0,4,224,2,12,41,11,32,0,253,0,4,240,2,12,40,11,32,0,253,0,4,128,3,12,39,11,32,0,253,0,4,144,3,12,38,11,32,0,253,0,4,160,3,12,37,11,32,0,253,0,4,176,3,12,36,11,32,0,253,0,4,192,3,12,35,11,32,0,253,0,4,208,3,12,34,11,32,0,253,0,4,224,3,12,33,11,32,0,253,0,4,240,3,12,32,11,32,0,253,0,4,128,4,12,31,11,32,0,253,0,4,144,4,12,30,11,32,0,253,0,4,160,4,12,29,11,32,0,253,0,4,176,4,12,28,11,32,0,253,0,4,192,4,12,27,11,32,0,253,0,4,208,4,12,26,11,32,0,253,0,4,224,4,12,25,11,32,0,253,0,4,240,4,12,24,11,32,0,253,0,4,128,5,12,23,11,32,0,253,0,4,144,5,12,22,11,32,0,253,0,4,160,5,12,21,11,32,0,253,0,4,176,5,12,20,11,32,0,253,0,4,192,5,12,19,11,32,0,253,0,4,208,5,12,18,11,32,0,253,0,4,224,5,12,17,11,32,0,253,0,4,240,5,12,16,11,32,0,253,0,4,128,6,12,15,11,32,0,253,0,4,144,6,12,14,11,32,0,253,0,4,160,6,12,13,11,32,0,253,0,4,176,6,12,12,11,32,0,253,0,4,192,6,12,11,11,32,0,253,0,4,208,6,12,10,11,32,0,253,0,4,224,6,12,9,11,32,0,253,0,4,240,6,12,8,11,32,0,253,0,4,128,7,12,7,11,32,0,253,0,4,144,7,12,6,11,32,0,253,0,4,160,7,12,5,11,32,0,253,0,4,176,7,12,4,11,32,0,253,0,4,192,7,12,3,11,32,0,253,0,4,208,7,12,2,11,32,0,253,0,4,224,7,12,1,11,32,0,253,0,4,240,7,11,5,2,123,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,65,2,107,34,4,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,68,11,32,0,253,0,4,0,12,63,11,32,0,253,0,4,16,12,62,11,32,0,253,0,4,32,12,61,11,32,0,253,0,4,48,12,60,11,32,0,253,0,4,64,12,59,11,32,0,253,0,4,80,12,58,11,32,0,253,0,4,96,12,57,11,32,0,253,0,4,112,12,56,11,32,0,253,0,4,128,1,12,55,11,32,0,253,0,4,144,1,12,54,11,32,0,253,0,4,160,1,12,53,11,32,0,253,0,4,176,1,12,52,11,32,0,253,0,4,192,1,12,51,11,32,0,253,0,4,208,1,12,50,11,32,0,253,0,4,224,1,12,49,11,32,0,253,0,4,240,1,12,48,11,32,0,253,0,4,128,2,12,47,11,32,0,253,0,4,144,2,12,46,11,32,0,253,0,4,160,2,12,45,11,32,0,253,0,4,176,2,12,44,11,32,0,253,0,4,192,2,12,43,11,32,0,253,0,4,208,2,12,42,11,32,0,253,0,4,224,2,12,41,11,32,0,253,0,4,240,2,12,40,11,32,0,253,0,4,128,3,12,39,11,32,0,253,0,4,144,3,12,38,11,32,0,253,0,4,160,3,12,37,11,32,0,253,0,4,176,3,12,36,11,32,0,253,0,4,192,3,12,35,11,32,0,253,0,4,208,3,12,34,11,32,0,253,0,4,224,3,12,33,11,32,0,253,0,4,240,3,12,32,11,32,0,253,0,4,128,4,12,31,11,32,0,253,0,4,144,4,12,30,11,32,0,253,0,4,160,4,12,29,11,32,0,253,0,4,176,4,12,28,11,32,0,253,0,4,192,4,12,27,11,32,0,253,0,4,208,4,12,26,11,32,0,253,0,4,224,4,12,25,11,32,0,253,0,4,240,4,12,24,11,32,0,253,0,4,128,5,12,23,11,32,0,253,0,4,144,5,12,22,11,32,0,253,0,4,160,5,12,21,11,32,0,253,0,4,176,5,12,20,11,32,0,253,0,4,192,5,12,19,11,32,0,253,0,4,208,5,12,18,11,32,0,253,0,4,224,5,12,17,11,32,0,253,0,4,240,5,12,16,11,32,0,253,0,4,128,6,12,15,11,32,0,253,0,4,144,6,12,14,11,32,0,253,0,4,160,6,12,13,11,32,0,253,0,4,176,6,12,12,11,32,0,253,0,4,192,6,12,11,11,32,0,253,0,4,208,6,12,10,11,32,0,253,0,4,224,6,12,9,11,32,0,253,0,4,240,6,12,8,11,32,0,253,0,4,128,7,12,7,11,32,0,253,0,4,144,7,12,6,11,32,0,253,0,4,160,7,12,5,11,32,0,253,0,4,176,7,12,4,11,32,0,253,0,4,192,7,12,3,11,32,0,253,0,4,208,7,12,2,11,32,0,253,0,4,224,7,12,1,11,32,0,253,0,4,240,7,11,34,2,65,17,253,173,1,32,2,65,15,253,171,1,253,80,32,2,65,19,253,173,1,32,2,65,13,253,171,1,253,80,253,81,32,2,65,10,253,173,1,253,81,2,123,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,65,7,107,34,4,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,68,11,32,0,253,0,4,0,12,63,11,32,0,253,0,4,16,12,62,11,32,0,253,0,4,32,12,61,11,32,0,253,0,4,48,12,60,11,32,0,253,0,4,64,12,59,11,32,0,253,0,4,80,12,58,11,32,0,253,0,4,96,12,57,11,32,0,253,0,4,112,12,56,11,32,0,253,0,4,128,1,12,55,11,32,0,253,0,4,144,1,12,54,11,32,0,253,0,4,160,1,12,53,11,32,0,253,0,4,176,1,12,52,11,32,0,253,0,4,192,1,12,51,11,32,0,253,0,4,208,1,12,50,11,32,0,253,0,4,224,1,12,49,11,32,0,253,0,4,240,1,12,48,11,32,0,253,0,4,128,2,12,47,11,32,0,253,0,4,144,2,12,46,11,32,0,253,0,4,160,2,12,45,11,32,0,253,0,4,176,2,12,44,11,32,0,253,0,4,192,2,12,43,11,32,0,253,0,4,208,2,12,42,11,32,0,253,0,4,224,2,12,41,11,32,0,253,0,4,240,2,12,40,11,32,0,253,0,4,128,3,12,39,11,32,0,253,0,4,144,3,12,38,11,32,0,253,0,4,160,3,12,37,11,32,0,253,0,4,176,3,12,36,11,32,0,253,0,4,192,3,12,35,11,32,0,253,0,4,208,3,12,34,11,32,0,253,0,4,224,3,12,33,11,32,0,253,0,4,240,3,12,32,11,32,0,253,0,4,128,4,12,31,11,32,0,253,0,4,144,4,12,30,11,32,0,253,0,4,160,4,12,29,11,32,0,253,0,4,176,4,12,28,11,32,0,253,0,4,192,4,12,27,11,32,0,253,0,4,208,4,12,26,11,32,0,253,0,4,224,4,12,25,11,32,0,253,0,4,240,4,12,24,11,32,0,253,0,4,128,5,12,23,11,32,0,253,0,4,144,5,12,22,11,32,0,253,0,4,160,5,12,21,11,32,0,253,0,4,176,5,12,20,11,32,0,253,0,4,192,5,12,19,11,32,0,253,0,4,208,5,12,18,11,32,0,253,0,4,224,5,12,17,11,32,0,253,0,4,240,5,12,16,11,32,0,253,0,4,128,6,12,15,11,32,0,253,0,4,144,6,12,14,11,32,0,253,0,4,160,6,12,13,11,32,0,253,0,4,176,6,12,12,11,32,0,253,0,4,192,6,12,11,11,32,0,253,0,4,208,6,12,10,11,32,0,253,0,4,224,6,12,9,11,32,0,253,0,4,240,6,12,8,11,32,0,253,0,4,128,7,12,7,11,32,0,253,0,4,144,7,12,6,11,32,0,253,0,4,160,7,12,5,11,32,0,253,0,4,176,7,12,4,11,32,0,253,0,4,192,7,12,3,11,32,0,253,0,4,208,7,12,2,11,32,0,253,0,4,224,7,12,1,11,32,0,253,0,4,240,7,11,253,174,1,2,123,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,65,15,107,34,4,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,68,11,32,0,253,0,4,0,12,63,11,32,0,253,0,4,16,12,62,11,32,0,253,0,4,32,12,61,11,32,0,253,0,4,48,12,60,11,32,0,253,0,4,64,12,59,11,32,0,253,0,4,80,12,58,11,32,0,253,0,4,96,12,57,11,32,0,253,0,4,112,12,56,11,32,0,253,0,4,128,1,12,55,11,32,0,253,0,4,144,1,12,54,11,32,0,253,0,4,160,1,12,53,11,32,0,253,0,4,176,1,12,52,11,32,0,253,0,4,192,1,12,51,11,32,0,253,0,4,208,1,12,50,11,32,0,253,0,4,224,1,12,49,11,32,0,253,0,4,240,1,12,48,11,32,0,253,0,4,128,2,12,47,11,32,0,253,0,4,144,2,12,46,11,32,0,253,0,4,160,2,12,45,11,32,0,253,0,4,176,2,12,44,11,32,0,253,0,4,192,2,12,43,11,32,0,253,0,4,208,2,12,42,11,32,0,253,0,4,224,2,12,41,11,32,0,253,0,4,240,2,12,40,11,32,0,253,0,4,128,3,12,39,11,32,0,253,0,4,144,3,12,38,11,32,0,253,0,4,160,3,12,37,11,32,0,253,0,4,176,3,12,36,11,32,0,253,0,4,192,3,12,35,11,32,0,253,0,4,208,3,12,34,11,32,0,253,0,4,224,3,12,33,11,32,0,253,0,4,240,3,12,32,11,32,0,253,0,4,128,4,12,31,11,32,0,253,0,4,144,4,12,30,11,32,0,253,0,4,160,4,12,29,11,32,0,253,0,4,176,4,12,28,11,32,0,253,0,4,192,4,12,27,11,32,0,253,0,4,208,4,12,26,11,32,0,253,0,4,224,4,12,25,11,32,0,253,0,4,240,4,12,24,11,32,0,253,0,4,128,5,12,23,11,32,0,253,0,4,144,5,12,22,11,32,0,253,0,4,160,5,12,21,11,32,0,253,0,4,176,5,12,20,11,32,0,253,0,4,192,5,12,19,11,32,0,253,0,4,208,5,12,18,11,32,0,253,0,4,224,5,12,17,11,32,0,253,0,4,240,5,12,16,11,32,0,253,0,4,128,6,12,15,11,32,0,253,0,4,144,6,12,14,11,32,0,253,0,4,160,6,12,13,11,32,0,253,0,4,176,6,12,12,11,32,0,253,0,4,192,6,12,11,11,32,0,253,0,4,208,6,12,10,11,32,0,253,0,4,224,6,12,9,11,32,0,253,0,4,240,6,12,8,11,32,0,253,0,4,128,7,12,7,11,32,0,253,0,4,144,7,12,6,11,32,0,253,0,4,160,7,12,5,11,32,0,253,0,4,176,7,12,4,11,32,0,253,0,4,192,7,12,3,11,32,0,253,0,4,208,7,12,2,11,32,0,253,0,4,224,7,12,1,11,32,0,253,0,4,240,7,11,34,2,65,7,253,173,1,32,2,65,25,253,171,1,253,80,32,2,65,18,253,173,1,32,2,65,14,253,171,1,253,80,253,81,32,2,65,3,253,173,1,253,81,253,174,1,2,123,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,65,16,107,34,4,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,68,11,32,0,253,0,4,0,12,63,11,32,0,253,0,4,16,12,62,11,32,0,253,0,4,32,12,61,11,32,0,253,0,4,48,12,60,11,32,0,253,0,4,64,12,59,11,32,0,253,0,4,80,12,58,11,32,0,253,0,4,96,12,57,11,32,0,253,0,4,112,12,56,11,32,0,253,0,4,128,1,12,55,11,32,0,253,0,4,144,1,12,54,11,32,0,253,0,4,160,1,12,53,11,32,0,253,0,4,176,1,12,52,11,32,0,253,0,4,192,1,12,51,11,32,0,253,0,4,208,1,12,50,11,32,0,253,0,4,224,1,12,49,11,32,0,253,0,4,240,1,12,48,11,32,0,253,0,4,128,2,12,47,11,32,0,253,0,4,144,2,12,46,11,32,0,253,0,4,160,2,12,45,11,32,0,253,0,4,176,2,12,44,11,32,0,253,0,4,192,2,12,43,11,32,0,253,0,4,208,2,12,42,11,32,0,253,0,4,224,2,12,41,11,32,0,253,0,4,240,2,12,40,11,32,0,253,0,4,128,3,12,39,11,32,0,253,0,4,144,3,12,38,11,32,0,253,0,4,160,3,12,37,11,32,0,253,0,4,176,3,12,36,11,32,0,253,0,4,192,3,12,35,11,32,0,253,0,4,208,3,12,34,11,32,0,253,0,4,224,3,12,33,11,32,0,253,0,4,240,3,12,32,11,32,0,253,0,4,128,4,12,31,11,32,0,253,0,4,144,4,12,30,11,32,0,253,0,4,160,4,12,29,11,32,0,253,0,4,176,4,12,28,11,32,0,253,0,4,192,4,12,27,11,32,0,253,0,4,208,4,12,26,11,32,0,253,0,4,224,4,12,25,11,32,0,253,0,4,240,4,12,24,11,32,0,253,0,4,128,5,12,23,11,32,0,253,0,4,144,5,12,22,11,32,0,253,0,4,160,5,12,21,11,32,0,253,0,4,176,5,12,20,11,32,0,253,0,4,192,5,12,19,11,32,0,253,0,4,208,5,12,18,11,32,0,253,0,4,224,5,12,17,11,32,0,253,0,4,240,5,12,16,11,32,0,253,0,4,128,6,12,15,11,32,0,253,0,4,144,6,12,14,11,32,0,253,0,4,160,6,12,13,11,32,0,253,0,4,176,6,12,12,11,32,0,253,0,4,192,6,12,11,11,32,0,253,0,4,208,6,12,10,11,32,0,253,0,4,224,6,12,9,11,32,0,253,0,4,240,6,12,8,11,32,0,253,0,4,128,7,12,7,11,32,0,253,0,4,144,7,12,6,11,32,0,253,0,4,160,7,12,5,11,32,0,253,0,4,176,7,12,4,11,32,0,253,0,4,192,7,12,3,11,32,0,253,0,4,208,7,12,2,11,32,0,253,0,4,224,7,12,1,11,32,0,253,0,4,240,7,11,253,174,1,11,36,19,35,18,65,16,78,4,64,35,19,33,2,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,34,4,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,11,32,0,32,2,253,11,4,0,12,64,11,32,0,32,2,253,11,4,16,12,63,11,32,0,32,2,253,11,4,32,12,62,11,32,0,32,2,253,11,4,48,12,61,11,32,0,32,2,253,11,4,64,12,60,11,32,0,32,2,253,11,4,80,12,59,11,32,0,32,2,253,11,4,96,12,58,11,32,0,32,2,253,11,4,112,12,57,11,32,0,32,2,253,11,4,128,1,12,56,11,32,0,32,2,253,11,4,144,1,12,55,11,32,0,32,2,253,11,4,160,1,12,54,11,32,0,32,2,253,11,4,176,1,12,53,11,32,0,32,2,253,11,4,192,1,12,52,11,32,0,32,2,253,11,4,208,1,12,51,11,32,0,32,2,253,11,4,224,1,12,50,11,32,0,32,2,253,11,4,240,1,12,49,11,32,0,32,2,253,11,4,128,2,12,48,11,32,0,32,2,253,11,4,144,2,12,47,11,32,0,32,2,253,11,4,160,2,12,46,11,32,0,32,2,253,11,4,176,2,12,45,11,32,0,32,2,253,11,4,192,2,12,44,11,32,0,32,2,253,11,4,208,2,12,43,11,32,0,32,2,253,11,4,224,2,12,42,11,32,0,32,2,253,11,4,240,2,12,41,11,32,0,32,2,253,11,4,128,3,12,40,11,32,0,32,2,253,11,4,144,3,12,39,11,32,0,32,2,253,11,4,160,3,12,38,11,32,0,32,2,253,11,4,176,3,12,37,11,32,0,32,2,253,11,4,192,3,12,36,11,32,0,32,2,253,11,4,208,3,12,35,11,32,0,32,2,253,11,4,224,3,12,34,11,32,0,32,2,253,11,4,240,3,12,33,11,32,0,32,2,253,11,4,128,4,12,32,11,32,0,32,2,253,11,4,144,4,12,31,11,32,0,32,2,253,11,4,160,4,12,30,11,32,0,32,2,253,11,4,176,4,12,29,11,32,0,32,2,253,11,4,192,4,12,28,11,32,0,32,2,253,11,4,208,4,12,27,11,32,0,32,2,253,11,4,224,4,12,26,11,32,0,32,2,253,11,4,240,4,12,25,11,32,0,32,2,253,11,4,128,5,12,24,11,32,0,32,2,253,11,4,144,5,12,23,11,32,0,32,2,253,11,4,160,5,12,22,11,32,0,32,2,253,11,4,176,5,12,21,11,32,0,32,2,253,11,4,192,5,12,20,11,32,0,32,2,253,11,4,208,5,12,19,11,32,0,32,2,253,11,4,224,5,12,18,11,32,0,32,2,253,11,4,240,5,12,17,11,32,0,32,2,253,11,4,128,6,12,16,11,32,0,32,2,253,11,4,144,6,12,15,11,32,0,32,2,253,11,4,160,6,12,14,11,32,0,32,2,253,11,4,176,6,12,13,11,32,0,32,2,253,11,4,192,6,12,12,11,32,0,32,2,253,11,4,208,6,12,11,11,32,0,32,2,253,11,4,224,6,12,10,11,32,0,32,2,253,11,4,240,6,12,9,11,32,0,32,2,253,11,4,128,7,12,8,11,32,0,32,2,253,11,4,144,7,12,7,11,32,0,32,2,253,11,4,160,7,12,6,11,32,0,32,2,253,11,4,176,7,12,5,11,32,0,32,2,253,11,4,192,7,12,4,11,32,0,32,2,253,11,4,208,7,12,3,11,32,0,32,2,253,11,4,224,7,12,2,11,32,0,32,2,253,11,4,240,7,12,1,11,65,192,19,32,4,16,13,16,15,65,192,20,65,201,1,65,7,16,0,0,11,11,35,15,35,12,34,2,65,6,253,173,1,32,2,65,26,253,171,1,253,80,32,2,65,11,253,173,1,32,2,65,21,253,171,1,253,80,253,81,32,2,65,25,253,173,1,32,2,65,7,253,171,1,253,80,253,81,253,174,1,35,12,34,2,35,13,253,78,32,2,253,77,35,14,253,78,253,81,253,174,1,33,3,35,24,33,4,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,34,5,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,11,32,4,253,0,4,0,33,2,12,64,11,32,4,253,0,4,16,33,2,12,63,11,32,4,253,0,4,32,33,2,12,62,11,32,4,253,0,4,48,33,2,12,61,11,32,4,253,0,4,64,33,2,12,60,11,32,4,253,0,4,80,33,2,12,59,11,32,4,253,0,4,96,33,2,12,58,11,32,4,253,0,4,112,33,2,12,57,11,32,4,253,0,4,128,1,33,2,12,56,11,32,4,253,0,4,144,1,33,2,12,55,11,32,4,253,0,4,160,1,33,2,12,54,11,32,4,253,0,4,176,1,33,2,12,53,11,32,4,253,0,4,192,1,33,2,12,52,11,32,4,253,0,4,208,1,33,2,12,51,11,32,4,253,0,4,224,1,33,2,12,50,11,32,4,253,0,4,240,1,33,2,12,49,11,32,4,253,0,4,128,2,33,2,12,48,11,32,4,253,0,4,144,2,33,2,12,47,11,32,4,253,0,4,160,2,33,2,12,46,11,32,4,253,0,4,176,2,33,2,12,45,11,32,4,253,0,4,192,2,33,2,12,44,11,32,4,253,0,4,208,2,33,2,12,43,11,32,4,253,0,4,224,2,33,2,12,42,11,32,4,253,0,4,240,2,33,2,12,41,11,32,4,253,0,4,128,3,33,2,12,40,11,32,4,253,0,4,144,3,33,2,12,39,11,32,4,253,0,4,160,3,33,2,12,38,11,32,4,253,0,4,176,3,33,2,12,37,11,32,4,253,0,4,192,3,33,2,12,36,11,32,4,253,0,4,208,3,33,2,12,35,11,32,4,253,0,4,224,3,33,2,12,34,11,32,4,253,0,4,240,3,33,2,12,33,11,32,4,253,0,4,128,4,33,2,12,32,11,32,4,253,0,4,144,4,33,2,12,31,11,32,4,253,0,4,160,4,33,2,12,30,11,32,4,253,0,4,176,4,33,2,12,29,11,32,4,253,0,4,192,4,33,2,12,28,11,32,4,253,0,4,208,4,33,2,12,27,11,32,4,253,0,4,224,4,33,2,12,26,11,32,4,253,0,4,240,4,33,2,12,25,11,32,4,253,0,4,128,5,33,2,12,24,11,32,4,253,0,4,144,5,33,2,12,23,11,32,4,253,0,4,160,5,33,2,12,22,11,32,4,253,0,4,176,5,33,2,12,21,11,32,4,253,0,4,192,5,33,2,12,20,11,32,4,253,0,4,208,5,33,2,12,19,11,32,4,253,0,4,224,5,33,2,12,18,11,32,4,253,0,4,240,5,33,2,12,17,11,32,4,253,0,4,128,6,33,2,12,16,11,32,4,253,0,4,144,6,33,2,12,15,11,32,4,253,0,4,160,6,33,2,12,14,11,32,4,253,0,4,176,6,33,2,12,13,11,32,4,253,0,4,192,6,33,2,12,12,11,32,4,253,0,4,208,6,33,2,12,11,11,32,4,253,0,4,224,6,33,2,12,10,11,32,4,253,0,4,240,6,33,2,12,9,11,32,4,253,0,4,128,7,33,2,12,8,11,32,4,253,0,4,144,7,33,2,12,7,11,32,4,253,0,4,160,7,33,2,12,6,11,32,4,253,0,4,176,7,33,2,12,5,11,32,4,253,0,4,192,7,33,2,12,4,11,32,4,253,0,4,208,7,33,2,12,3,11,32,4,253,0,4,224,7,33,2,12,2,11,32,4,253,0,4,240,7,33,2,12,1,11,65,128,21,32,5,16,13,16,15,65,192,20,65,213,2,65,7,16,0,0,11,32,3,32,2,253,174,1,35,19,253,174,1,36,16,35,8,34,2,65,2,253,173,1,32,2,65,30,253,171,1,253,80,32,2,65,13,253,173,1,32,2,65,19,253,171,1,253,80,253,81,32,2,65,22,253,173,1,32,2,65,10,253,171,1,253,80,253,81,35,8,34,2,35,9,34,3,253,78,32,2,35,10,34,2,253,78,253,81,32,3,32,2,253,78,253,81,253,174,1,36,17,35,14,36,15,35,13,36,14,35,12,36,13,35,11,35,16,253,174,1,36,12,35,10,36,11,35,9,36,10,35,8,36,9,35,16,35,17,253,174,1,36,8,35,18,65,1,106,36,18,12,1,11,11,35,0,35,8,253,174,1,36,0,35,1,35,9,253,174,1,36,1,35,2,35,10,253,174,1,36,2,35,3,35,11,253,174,1,36,3,35,4,35,12,253,174,1,36,4,35,5,35,13,253,174,1,36,5,35,6,35,14,253,174,1,36,6,35,7,35,15,253,174,1,36,7,16,17,32,1,35,0,253,27,0,16,18,54,2,0,32,1,35,1,253,27,0,16,18,54,2,4,32,1,35,2,253,27,0,16,18,54,2,8,32,1,35,3,253,27,0,16,18,54,2,12,32,1,35,4,253,27,0,16,18,54,2,16,32,1,35,5,253,27,0,16,18,54,2,20,32,1,35,6,253,27,0,16,18,54,2,24,32,1,35,7,253,27,0,16,18,54,2,28,32,1,35,0,253,27,1,16,18,54,2,32,32,1,35,1,253,27,1,16,18,54,2,36,32,1,35,2,253,27,1,16,18,54,2,40,32,1,35,3,253,27,1,16,18,54,2,44,32,1,35,4,253,27,1,16,18,54,2,48,32,1,35,5,253,27,1,16,18,54,2,52,32,1,35,6,253,27,1,16,18,54,2,56,32,1,35,7,253,27,1,16,18,54,2,60,32,1,65,64,107,35,0,253,27,2,16,18,54,2,0,32,1,35,1,253,27,2,16,18,54,2,68,32,1,35,2,253,27,2,16,18,54,2,72,32,1,35,3,253,27,2,16,18,54,2,76,32,1,35,4,253,27,2,16,18,54,2,80,32,1,35,5,253,27,2,16,18,54,2,84,32,1,35,6,253,27,2,16,18,54,2,88,32,1,35,7,253,27,2,16,18,54,2,92,32,1,35,0,253,27,3,16,18,54,2,96,32,1,35,1,253,27,3,16,18,54,2,100,32,1,35,2,253,27,3,16,18,54,2,104,32,1,35,3,253,27,3,16,18,54,2,108,32,1,35,4,253,27,3,16,18,54,2,112,32,1,35,5,253,27,3,16,18,54,2,116,32,1,35,6,253,27,3,16,18,54,2,120,32,1,35,7,253,27,3,16,18,54,2,124,15,11,65,128,21,32,4,16,13,16,15,65,192,20,65,213,2,65,7,16,0,0,11,203,2,1,5,127,3,64,32,1,65,16,72,4,64,32,1,65,2,116,34,2,65,1,106,33,3,35,53,32,2,65,2,116,106,32,2,65,3,106,34,4,35,55,34,5,106,45,0,0,32,2,32,5,106,45,0,0,65,24,116,32,3,32,5,106,45,0,0,65,16,116,114,32,2,65,2,106,34,2,32,5,106,45,0,0,65,8,116,114,114,54,2,0,35,53,32,3,65,2,116,106,35,55,34,3,32,1,65,16,106,65,2,116,34,5,65,3,106,106,45,0,0,32,3,32,5,106,45,0,0,65,24,116,32,5,65,1,106,32,3,106,45,0,0,65,16,116,114,32,5,65,2,106,32,3,106,45,0,0,65,8,116,114,114,54,2,0,35,53,32,2,65,2,116,106,35,55,34,2,32,1,65,32,106,65,2,116,34,3,65,3,106,106,45,0,0,32,2,32,3,106,45,0,0,65,24,116,32,3,65,1,106,32,2,106,45,0,0,65,16,116,114,32,3,65,2,106,32,2,106,45,0,0,65,8,116,114,114,54,2,0,35,53,32,4,65,2,116,106,35,55,34,2,32,1,65,48,106,65,2,116,34,3,65,3,106,106,45,0,0,32,2,32,3,106,45,0,0,65,24,116,32,3,65,1,106,32,2,106,45,0,0,65,16,116,114,32,3,65,2,106,32,2,106,45,0,0,65,8,116,114,114,54,2,0,32,1,65,1,106,33,1,12,1,11,11,35,53,32,0,16,19,11,99,1,3,127,3,64,32,2,65,192,0,72,4,64,32,2,65,2,116,34,1,35,53,106,35,55,34,3,32,1,65,3,106,106,45,0,0,32,1,32,3,106,45,0,0,65,24,116,32,1,65,1,106,32,3,106,45,0,0,65,16,116,114,32,1,65,2,106,32,3,106,45,0,0,65,8,116,114,114,54,2,0,32,2,65,1,106,33,2,12,1,11,11,35,53,32,0,16,19,11,74,0,65,231,204,167,208,6,36,31,65,133,221,158,219,123,36,32,65,242,230,187,227,3,36,33,65,186,234,191,170,122,36,34,65,255,164,185,136,5,36,35,65,140,209,149,216,121,36,36,65,171,179,143,252,1,36,37,65,153,154,131,223,5,36,38,65,0,36,58,65,0,36,59,11,227,3,1,2,127,35,31,36,39,35,32,36,40,35,33,36,41,35,34,36,42,35,35,36,43,35,36,36,44,35,37,36,45,35,38,36,46,65,0,36,47,3,64,35,47,65,16,73,4,64,35,47,65,2,116,34,2,32,0,106,32,1,32,2,65,3,106,106,45,0,0,32,1,32,2,106,45,0,0,65,24,116,32,1,32,2,65,1,106,106,45,0,0,65,16,116,114,32,1,32,2,65,2,106,106,45,0,0,65,8,116,114,114,54,2,0,35,47,65,1,106,36,47,12,1,11,11,65,16,36,47,3,64,35,47,65,192,0,73,4,64,32,0,35,47,65,2,116,106,32,0,35,47,65,16,107,65,2,116,106,40,2,0,32,0,35,47,65,7,107,65,2,116,106,40,2,0,32,0,35,47,65,2,107,65,2,116,106,40,2,0,34,1,65,17,120,32,1,65,19,120,115,32,1,65,10,118,115,106,32,0,35,47,65,15,107,65,2,116,106,40,2,0,34,1,65,7,120,32,1,65,18,120,115,32,1,65,3,118,115,106,106,54,2,0,35,47,65,1,106,36,47,12,1,11,11,65,0,36,47,3,64,35,47,65,192,0,73,4,64,35,47,65,2,116,34,1,32,0,106,40,2,0,32,1,35,29,106,40,2,0,35,46,35,43,34,1,65,6,120,32,1,65,11,120,115,32,1,65,25,120,115,106,35,43,34,1,35,44,113,35,45,32,1,65,127,115,113,115,106,106,106,36,48,35,39,34,1,65,2,120,32,1,65,13,120,115,32,1,65,22,120,115,35,40,34,2,35,41,34,3,113,35,39,34,1,32,2,113,32,1,32,3,113,115,115,106,36,49,35,45,36,46,35,44,36,45,35,43,36,44,35,42,35,48,106,36,43,35,41,36,42,35,40,36,41,35,39,36,40,35,48,35,49,106,36,39,35,47,65,1,106,36,47,12,1,11,11,35,31,35,39,106,36,31,35,32,35,40,106,36,32,35,33,35,41,106,36,33,35,34,35,42,106,36,34,35,35,35,43,106,36,35,35,36,35,44,106,36,36,35,37,35,45,106,36,37,35,38,35,46,106,36,38,11,174,1,1,2,127,35,59,32,1,106,36,59,35,58,4,64,65,192,0,35,58,107,34,2,32,1,76,4,64,35,51,35,58,106,32,0,32,2,252,10,0,0,35,58,32,2,106,36,58,65,192,0,35,58,107,33,2,32,1,65,192,0,35,58,107,107,33,1,35,53,35,51,16,23,65,0,36,58,5,35,51,35,58,106,32,0,32,1,252,10,0,0,35,58,32,1,106,36,58,15,11,11,3,64,32,3,32,1,65,192,0,109,72,4,64,35,53,32,0,32,2,106,16,23,32,3,65,1,106,33,3,32,2,65,64,107,33,2,12,1,11,11,32,1,65,63,113,34,1,4,64,35,51,35,58,106,32,0,32,2,106,32,1,252,10,0,0,35,58,32,1,106,36,58,11,11,231,1,1,2,127,35,51,35,58,106,65,128,1,58,0,0,35,58,65,1,106,36,58,35,58,65,56,74,4,64,35,51,35,58,106,34,1,65,192,0,35,58,107,106,33,2,3,64,32,1,32,2,73,4,64,32,1,65,0,58,0,0,32,1,65,1,106,33,1,12,1,11,11,35,53,35,51,16,23,65,0,36,58,11,35,51,35,58,106,34,1,65,56,35,58,107,106,33,2,3,64,32,1,32,2,73,4,64,32,1,65,0,58,0,0,32,1,65,1,106,33,1,12,1,11,11,35,51,35,59,65,128,128,128,128,2,109,16,18,54,2,56,35,51,35,59,65,3,116,16,18,54,2,60,35,53,35,51,16,23,32,0,35,31,16,18,54,2,0,32,0,35,32,16,18,54,2,4,32,0,35,33,16,18,54,2,8,32,0,35,34,16,18,54,2,12,32,0,35,35,16,18,54,2,16,32,0,35,36,16,18,54,2,20,32,0,35,37,16,18,54,2,24,32,0,35,38,16,18,54,2,28,11,14,0,16,22,35,55,32,0,16,24,35,57,16,25,11,253,1,1,2,127,35,31,36,39,35,32,36,40,35,33,36,41,35,34,36,42,35,35,36,43,35,36,36,44,35,37,36,45,35,38,36,46,65,0,36,47,3,64,35,47,65,192,0,73,4,64,32,0,35,47,65,2,116,106,40,2,0,35,46,35,43,34,1,65,6,120,32,1,65,11,120,115,32,1,65,25,120,115,106,35,43,34,1,35,44,113,35,45,32,1,65,127,115,113,115,106,106,36,48,35,39,34,1,65,2,120,32,1,65,13,120,115,32,1,65,22,120,115,35,40,34,2,35,41,34,1,113,32,2,35,39,34,2,113,32,1,32,2,113,115,115,106,36,49,35,45,36,46,35,44,36,45,35,43,36,44,35,42,35,48,106,36,43,35,41,36,42,35,40,36,41,35,39,36,40,35,48,35,49,106,36,39,35,47,65,1,106,36,47,12,1,11,11,35,31,35,39,106,36,31,35,32,35,40,106,36,32,35,33,35,41,106,36,33,35,34,35,42,106,36,34,35,35,35,43,106,36,35,35,36,35,44,106,36,36,35,37,35,45,106,36,37,35,38,35,46,106,36,38,11,86,0,16,22,35,53,32,0,16,23,35,30,16,27,32,1,35,31,16,18,54,2,0,32,1,35,32,16,18,54,2,4,32,1,35,33,16,18,54,2,8,32,1,35,34,16,18,54,2,12,32,1,35,35,16,18,54,2,16,32,1,35,36,16,18,54,2,20,32,1,35,37,16,18,54,2,24,32,1,35,38,16,18,54,2,28,11,63,0,16,16,65,196,10,40,2,0,36,29,65,148,13,40,2,0,36,30,65,192,0,16,11,36,50,35,50,36,51,65,128,8,16,11,36,52,35,52,36,53,65,128,4,16,11,36,54,35,54,36,55,65,32,16,11,36,56,35,56,36,57,11,11,141,12,38,0,65,140,8,11,2,28,1,0,65,152,8,11,136,2,1,0,0,0,0,1,0,0,152,47,138,66,145,68,55,113,207,251,192,181,165,219,181,233,91,194,86,57,241,17,241,89,164,130,63,146,213,94,28,171,152,170,7,216,1,91,131,18,190,133,49,36,195,125,12,85,116,93,190,114,254,177,222,128,167,6,220,155,116,241,155,193,193,105,155,228,134,71,190,239,198,157,193,15,204,161,12,36,111,44,233,45,170,132,116,74,220,169,176,92,218,136,249,118,82,81,62,152,109,198,49,168,200,39,3,176,199,127,89,191,243,11,224,198,71,145,167,213,81,99,202,6,103,41,41,20,133,10,183,39,56,33,27,46,252,109,44,77,19,13,56,83,84,115,10,101,187,10,106,118,46,201,194,129,133,44,114,146,161,232,191,162,75,102,26,168,112,139,75,194,163,81,108,199,25,232,146,209,36,6,153,214,133,53,14,244,112,160,106,16,22,193,164,25,8,108,55,30,76,119,72,39,181,188,176,52,179,12,28,57,74,170,216,78,79,202,156,91,243,111,46,104,238,130,143,116,111,99,165,120,20,120,200,132,8,2,199,140,250,255,190,144,235,108,80,164,247,163,249,190,242,120,113,198,0,65,172,10,11,1,44,0,65,184,10,11,21,4,0,0,0,16,0,0,0,32,4,0,0,32,4,0,0,0,1,0,0,64,0,65,220,10,11,2,28,1,0,65,232,10,11,136,2,1,0,0,0,0,1,0,0,152,47,138,194,145,68,55,113,207,251,192,181,165,219,181,233,91,194,86,57,241,17,241,89,164,130,63,146,213,94,28,171,152,170,7,216,1,91,131,18,190,133,49,36,195,125,12,85,116,93,190,114,254,177,222,128,167,6,220,155,116,243,155,193,193,105,155,100,134,71,254,240,198,237,225,15,84,242,12,36,111,52,233,79,190,132,201,108,30,65,185,97,250,136,249,22,82,81,198,242,109,90,142,168,101,252,25,176,199,158,217,185,195,49,18,154,160,234,14,231,43,35,177,253,176,62,53,199,213,186,105,48,95,109,151,203,143,17,15,90,253,238,30,220,137,182,53,10,4,122,11,222,157,202,244,88,22,91,93,225,134,62,127,0,128,137,8,55,50,234,7,165,55,149,171,111,16,97,64,23,241,214,140,13,109,59,170,205,55,190,187,192,218,59,97,131,99,163,72,219,49,233,2,11,167,92,209,111,202,250,26,82,49,132,51,49,149,26,212,110,144,120,67,109,242,145,156,195,189,171,204,158,230,160,201,181,60,182,47,83,198,65,199,210,163,126,35,7,104,75,149,164,118,29,25,76,0,65,252,12,11,1,44,0,65,136,13,11,21,4,0,0,0,16,0,0,0,112,5,0,0,112,5,0,0,0,1,0,0,64,0,65,172,13,11,1,44,0,65,184,13,11,35,2,0,0,0,28,0,0,0,73,0,110,0,118,0,97,0,108,0,105,0,100,0,32,0,108,0,101,0,110,0,103,0,116,0,104,0,65,220,13,11,1,60,0,65,232,13,11,45,2,0,0,0,38,0,0,0,126,0,108,0,105,0,98,0,47,0,97,0,114,0,114,0,97,0,121,0,98,0,117,0,102,0,102,0,101,0,114,0,46,0,116,0,115,0,65,156,14,11,1,60,0,65,168,14,11,47,2,0,0,0,40,0,0,0,65,0,108,0,108,0,111,0,99,0,97,0,116,0,105,0,111,0,110,0,32,0,116,0,111,0,111,0,32,0,108,0,97,0,114,0,103,0,101,0,65,220,14,11,1,60,0,65,232,14,11,37,2,0,0,0,30,0,0,0,126,0,108,0,105,0,98,0,47,0,114,0,116,0,47,0,116,0,99,0,109,0,115,0,46,0,116,0,115,0,65,156,15,11,1,60,0,65,168,15,11,37,2,0,0,0,30,0,0,0,126,0,108,0,105,0,98,0,47,0,114,0,116,0,47,0,116,0,108,0,115,0,102,0,46,0,116,0,115,0,65,252,15,11,1,60,0,65,136,16,11,43,2,0,0,0,36,0,0,0,73,0,110,0,100,0,101,0,120,0,32,0,111,0,117,0,116,0,32,0,111,0,102,0,32,0,114,0,97,0,110,0,103,0,101,0,65,188,16,11,1,44,0,65,200,16,11,33,2,0,0,0,26,0,0,0,126,0,108,0,105,0,98,0,47,0,97,0,114,0,114,0,97,0,121,0,46,0,116,0,115,0,65,236,16,11,1,124,0,65,248,16,11,107,2,0,0,0,100,0,0,0,116,0,111,0,83,0,116,0,114,0,105,0,110,0,103,0,40,0,41,0,32,0,114,0,97,0,100,0,105,0,120,0,32,0,97,0,114,0,103,0,117,0,109,0,101,0,110,0,116,0,32,0,109,0,117,0,115,0,116,0,32,0,98,0,101,0,32,0,98,0,101,0,116,0,119,0,101,0,101,0,110,0,32,0,50,0,32,0,97,0,110,0,100,0,32,0,51,0,54,0,65,236,17,11,1,60,0,65,248,17,11,45,2,0,0,0,38,0,0,0,126,0,108,0,105,0,98,0,47,0,117,0,116,0,105,0,108,0,47,0,110,0,117,0,109,0,98,0,101,0,114,0,46,0,116,0,115,0,65,172,18,11,1,28,0,65,184,18,11,9,2,0,0,0,2,0,0,0,48,0,65,204,18,11,1,92,0,65,216,18,11,79,2,0,0,0,72,0,0,0,48,0,49,0,50,0,51,0,52,0,53,0,54,0,55,0,56,0,57,0,97,0,98,0,99,0,100,0,101,0,102,0,103,0,104,0,105,0,106,0,107,0,108,0,109,0,110,0,111,0,112,0,113,0,114,0,115,0,116,0,117,0,118,0,119,0,120,0,121,0,122,0,65,172,19,11,1,92,0,65,184,19,11,79,2,0,0,0,72,0,0,0,115,0,101,0,116,0,86,0,49,0,50,0,56,0,58,0,32,0,101,0,120,0,112,0,101,0,99,0,116,0,32,0,105,0,32,0,102,0,114,0,111,0,109,0,32,0,48,0,32,0,116,0,111,0,32,0,54,0,51,0,44,0,32,0,103,0,111,0,116,0,32,0,65,140,20,11,1,28,0,65,152,20,11,1,2,0,65,172,20,11,1,60,0,65,184,20,11,51,2,0,0,0,44,0,0,0,97,0,115,0,115,0,101,0,109,0,98,0,108,0,121,0,47,0,117,0,116,0,105,0,108,0,115,0,47,0,118,0,49,0,50,0,56,0,46,0,116,0,115,0,65,236,20,11,1,92,0,65,248,20,11,79,2,0,0,0,72,0,0,0,103,0,101,0,116,0,86,0,49,0,50,0,56,0,58,0,32,0,101,0,120,0,112,0,101,0,99,0,116,0,32,0,105,0,32,0,102,0,114,0,111,0,109,0,32,0,48,0,32,0,116,0,111,0,32,0,54,0,51,0,44,0,32,0,103,0,111,0,116,0,32]);var yT={env:{abort:(r,e,t,n)=>{throw Error(`abort: ${r}:${e}:${t}:${n}`)}}};function Mw(r){return(r!==void 0?r:WebAssembly.validate(Lw))?new WebAssembly.Instance(new WebAssembly.Module(Lw),yT).exports:new WebAssembly.Instance(new WebAssembly.Module(gT),yT).exports}var it,TH,Aa,Iu,Au,_H,bT,PH;function DH(r){it=Mw(r),TH=!!it.HAS_SIMD.valueOf(),Aa=it.input.value,Iu=it.output.value,Au=new Uint8Array(it.memory.buffer,Aa,it.INPUT_LENGTH),_H=new Uint8Array(it.memory.buffer,Iu,it.PARALLEL_FACTOR*32),bT=new Uint8Array(it.memory.buffer,Iu,32),PH=new Uint32Array(it.memory.buffer,Aa,it.INPUT_LENGTH)}DH();function wT(r){return r.length===64?kH(r):r.length<=it.INPUT_LENGTH?(Au.set(r),it.digest(r.length),Ow()):(it.init(),LH(r),MH())}function kH(r){if(r.length===64)return Au.set(r),it.digest64(Aa,Iu),Ow();throw new Error("InvalidLengthForDigest64")}function LH(r){let e=it.INPUT_LENGTH;if(r.length>e)for(let t=0;t<r.length;t+=e){let n=r.subarray(t,t+e);Au.set(n),it.update(Aa,n.length)}else Au.set(r),it.update(Aa,r.length)}function MH(){return it.final(Iu),Ow()}function Ow(){let r=mT(32);return r.set(bT),r}Be();var ET=ie(vT(),1),RH=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,ST=(0,ET.default)();var IT=ST&&!RH;var s4e=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&globalThis.process.release.name==="node"&&!ST,o4e=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,i4e=typeof globalThis.process<"u"&&typeof globalThis.process.env<"u"&&globalThis.process.env["NODE"+"_"+"ENV"]==="test",a4e=typeof navigator<"u"&&navigator.product==="ReactNative";function NH(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function s1(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}function o1(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function yt(r,e,t=""){let n=NH(r),s=r?.length,o=e!==void 0;if(!n||o&&s!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function Rw(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function AT(r,e){yt(r,void 0,"output");let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Gn(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Wn(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function BH(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}var UH=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function CT(r,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(r,e)}function TT(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}var Nw=(r,e)=>{function t(n,...s){if(yt(n,void 0,"key"),!UH)throw new Error("Non little-endian hardware is not yet supported");if(r.nonceLength!==void 0){let u=s[0];yt(u,r.varSizeNonce?void 0:r.nonceLength,"nonce")}let o=r.tagLength;o&&s[1]!==void 0&&yt(s[1],void 0,"AAD");let i=e(n,...s),a=(u,h)=>{if(h!==void 0){if(u!==2)throw new Error("cipher output not supported");yt(h,void 0,"output")}},c=!1;return{encrypt(u,h){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,yt(u),a(i.encrypt.length,h),i.encrypt(u,h)},decrypt(u,h){if(yt(u),o&&u.length<o)throw new Error('"ciphertext" expected length bigger than tagLength='+o);return a(i.decrypt.length,h),i.decrypt(u,h)}}}return Object.assign(t,r),t};function Bw(r,e,t=!0){if(e===void 0)return new Uint8Array(r);if(e.length!==r)throw new Error('"output" expected Uint8Array of length '+r+", got: "+e.length);if(t&&!KH(e))throw new Error("invalid output, must be aligned");return e}function _T(r,e,t){s1(t);let n=new Uint8Array(16),s=BH(n);return s.setBigUint64(0,BigInt(e),t),s.setBigUint64(8,BigInt(r),t),n}function KH(r){return r.byteOffset%4===0}function Ca(r){return Uint8Array.from(r)}var DT=r=>Uint8Array.from(r.split(""),e=>e.charCodeAt(0)),FH=DT("expand 16-byte k"),zH=DT("expand 32-byte k"),$H=Gn(FH),HH=Gn(zH);function $(r,e){return r<<e|r>>>32-e}function Uw(r){return r.byteOffset%4===0}var i1=64,qH=16,kT=2**32-1,PT=Uint32Array.of();function VH(r,e,t,n,s,o,i,a){let c=s.length,l=new Uint8Array(i1),u=Gn(l),h=Uw(s)&&Uw(o),p=h?Gn(s):PT,f=h?Gn(o):PT;for(let d=0;d<c;i++){if(r(e,t,n,u,i,a),i>=kT)throw new Error("arx: counter overflow");let m=Math.min(i1,c-d);if(h&&m===i1){let g=d/4;if(d%4!==0)throw new Error("arx: invalid block position");for(let y=0,b;y<qH;y++)b=g+y,f[b]=p[b]^u[y];d+=i1;continue}for(let g=0,y;g<m;g++)y=d+g,o[y]=s[y]^l[g];d+=m}}function Kw(r,e){let{allowShortKeys:t,extendNonceFn:n,counterLength:s,counterRight:o,rounds:i}=CT({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof r!="function")throw new Error("core must be a function");return o1(s),o1(i),s1(o),s1(t),(a,c,l,u,h=0)=>{yt(a,void 0,"key"),yt(c,void 0,"nonce"),yt(l,void 0,"data");let p=l.length;if(u===void 0&&(u=new Uint8Array(p)),yt(u,void 0,"output"),o1(h),h<0||h>=kT)throw new Error("arx: counter overflow");if(u.length<p)throw new Error(`arx: output (${u.length}) is shorter than data (${p})`);let f=[],d=a.length,m,g;if(d===32)f.push(m=Ca(a)),g=HH;else if(d===16&&t)m=new Uint8Array(32),m.set(a),m.set(a,16),g=$H,f.push(m);else throw yt(a,32,"arx key"),new Error("invalid key size");Uw(c)||f.push(c=Ca(c));let y=Gn(m);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(g,y,Gn(c.subarray(0,16)),y),c=c.subarray(16)}let b=16-s;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let x=new Uint8Array(12);x.set(c,o?0:12-c.length),c=x,f.push(c)}let w=Gn(c);return VH(r,g,y,w,l,u,h,i),Wn(...f),u}}function It(r,e){return r[e++]&255|(r[e++]&255)<<8}var Fw=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;constructor(e){e=Ca(yt(e,32,"key"));let t=It(e,0),n=It(e,2),s=It(e,4),o=It(e,6),i=It(e,8),a=It(e,10),c=It(e,12),l=It(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|s<<6)&7939,this.r[3]=(s>>>7|o<<9)&8191,this.r[4]=(o>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=It(e,16+2*u)}process(e,t,n=!1){let s=n?0:2048,{h:o,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],h=i[4],p=i[5],f=i[6],d=i[7],m=i[8],g=i[9],y=It(e,t+0),b=It(e,t+2),w=It(e,t+4),x=It(e,t+6),v=It(e,t+8),S=It(e,t+10),E=It(e,t+12),I=It(e,t+14),A=o[0]+(y&8191),X=o[1]+((y>>>13|b<<3)&8191),ne=o[2]+((b>>>10|w<<6)&8191),H=o[3]+((w>>>7|x<<9)&8191),L=o[4]+((x>>>4|v<<12)&8191),C=o[5]+(v>>>1&8191),T=o[6]+((v>>>14|S<<2)&8191),M=o[7]+((S>>>11|E<<5)&8191),B=o[8]+((E>>>8|I<<8)&8191),N=o[9]+(I>>>5|s),k=0,O=k+A*a+X*(5*g)+ne*(5*m)+H*(5*d)+L*(5*f);k=O>>>13,O&=8191,O+=C*(5*p)+T*(5*h)+M*(5*u)+B*(5*l)+N*(5*c),k+=O>>>13,O&=8191;let K=k+A*c+X*a+ne*(5*g)+H*(5*m)+L*(5*d);k=K>>>13,K&=8191,K+=C*(5*f)+T*(5*p)+M*(5*h)+B*(5*u)+N*(5*l),k+=K>>>13,K&=8191;let F=k+A*l+X*c+ne*a+H*(5*g)+L*(5*m);k=F>>>13,F&=8191,F+=C*(5*d)+T*(5*f)+M*(5*p)+B*(5*h)+N*(5*u),k+=F>>>13,F&=8191;let ve=k+A*u+X*l+ne*c+H*a+L*(5*g);k=ve>>>13,ve&=8191,ve+=C*(5*m)+T*(5*d)+M*(5*f)+B*(5*p)+N*(5*h),k+=ve>>>13,ve&=8191;let ue=k+A*h+X*u+ne*l+H*c+L*a;k=ue>>>13,ue&=8191,ue+=C*(5*g)+T*(5*m)+M*(5*d)+B*(5*f)+N*(5*p),k+=ue>>>13,ue&=8191;let se=k+A*p+X*h+ne*u+H*l+L*c;k=se>>>13,se&=8191,se+=C*a+T*(5*g)+M*(5*m)+B*(5*d)+N*(5*f),k+=se>>>13,se&=8191;let pe=k+A*f+X*p+ne*h+H*u+L*l;k=pe>>>13,pe&=8191,pe+=C*c+T*a+M*(5*g)+B*(5*m)+N*(5*d),k+=pe>>>13,pe&=8191;let Te=k+A*d+X*f+ne*p+H*h+L*u;k=Te>>>13,Te&=8191,Te+=C*l+T*c+M*a+B*(5*g)+N*(5*m),k+=Te>>>13,Te&=8191;let Qe=k+A*m+X*d+ne*f+H*p+L*h;k=Qe>>>13,Qe&=8191,Qe+=C*u+T*l+M*c+B*a+N*(5*g),k+=Qe>>>13,Qe&=8191;let be=k+A*g+X*m+ne*d+H*f+L*p;k=be>>>13,be&=8191,be+=C*h+T*u+M*l+B*c+N*a,k+=be>>>13,be&=8191,k=(k<<2)+k|0,k=k+O|0,O=k&8191,k=k>>>13,K+=k,o[0]=O,o[1]=K,o[2]=F,o[3]=ve,o[4]=ue,o[5]=se,o[6]=pe,o[7]=Te,o[8]=Qe,o[9]=be}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),s=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=s,s=e[a]>>>13,e[a]&=8191;e[0]+=s*5,s=e[0]>>>13,e[0]&=8191,e[1]+=s,s=e[1]>>>13,e[1]&=8191,e[2]+=s,n[0]=e[0]+5,s=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+s,s=n[a]>>>13,n[a]&=8191;n[9]-=8192;let o=(s^1)-1;for(let a=0;a<10;a++)n[a]&=o;o=~o;for(let a=0;a<10;a++)e[a]=e[a]&o|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+t[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+t[a]|0)+(i>>>16)|0,e[a]=i&65535;Wn(n)}update(e){Rw(this),yt(e),e=Ca(e);let{buffer:t,blockLen:n}=this,s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);if(i===n){for(;n<=s-o;o+=n)this.process(e,o);continue}t.set(e.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){Wn(this.h,this.r,this.buffer,this.pad)}digestInto(e){Rw(this),AT(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:s}=this;if(s){for(t[s++]=1;s<16;s++)t[s]=0;this.process(t,0,!0)}this.finalize();let o=0;for(let i=0;i<8;i++)e[o++]=n[i]>>>0,e[o++]=n[i]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}};function GH(r){let e=(n,s)=>r(s).update(n).digest(),t=r(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=n=>r(n),e}var LT=GH(r=>new Fw(r));function RT(r,e,t,n,s,o=20){let i=r[0],a=r[1],c=r[2],l=r[3],u=e[0],h=e[1],p=e[2],f=e[3],d=e[4],m=e[5],g=e[6],y=e[7],b=s,w=t[0],x=t[1],v=t[2],S=i,E=a,I=c,A=l,X=u,ne=h,H=p,L=f,C=d,T=m,M=g,B=y,N=b,k=w,O=x,K=v;for(let ve=0;ve<o;ve+=2)S=S+X|0,N=$(N^S,16),C=C+N|0,X=$(X^C,12),S=S+X|0,N=$(N^S,8),C=C+N|0,X=$(X^C,7),E=E+ne|0,k=$(k^E,16),T=T+k|0,ne=$(ne^T,12),E=E+ne|0,k=$(k^E,8),T=T+k|0,ne=$(ne^T,7),I=I+H|0,O=$(O^I,16),M=M+O|0,H=$(H^M,12),I=I+H|0,O=$(O^I,8),M=M+O|0,H=$(H^M,7),A=A+L|0,K=$(K^A,16),B=B+K|0,L=$(L^B,12),A=A+L|0,K=$(K^A,8),B=B+K|0,L=$(L^B,7),S=S+ne|0,K=$(K^S,16),M=M+K|0,ne=$(ne^M,12),S=S+ne|0,K=$(K^S,8),M=M+K|0,ne=$(ne^M,7),E=E+H|0,N=$(N^E,16),B=B+N|0,H=$(H^B,12),E=E+H|0,N=$(N^E,8),B=B+N|0,H=$(H^B,7),I=I+L|0,k=$(k^I,16),C=C+k|0,L=$(L^C,12),I=I+L|0,k=$(k^I,8),C=C+k|0,L=$(L^C,7),A=A+X|0,O=$(O^A,16),T=T+O|0,X=$(X^T,12),A=A+X|0,O=$(O^A,8),T=T+O|0,X=$(X^T,7);let F=0;n[F++]=i+S|0,n[F++]=a+E|0,n[F++]=c+I|0,n[F++]=l+A|0,n[F++]=u+X|0,n[F++]=h+ne|0,n[F++]=p+H|0,n[F++]=f+L|0,n[F++]=d+C|0,n[F++]=m+T|0,n[F++]=g+M|0,n[F++]=y+B|0,n[F++]=b+N|0,n[F++]=w+k|0,n[F++]=x+O|0,n[F++]=v+K|0}function WH(r,e,t,n){let s=r[0],o=r[1],i=r[2],a=r[3],c=e[0],l=e[1],u=e[2],h=e[3],p=e[4],f=e[5],d=e[6],m=e[7],g=t[0],y=t[1],b=t[2],w=t[3];for(let v=0;v<20;v+=2)s=s+c|0,g=$(g^s,16),p=p+g|0,c=$(c^p,12),s=s+c|0,g=$(g^s,8),p=p+g|0,c=$(c^p,7),o=o+l|0,y=$(y^o,16),f=f+y|0,l=$(l^f,12),o=o+l|0,y=$(y^o,8),f=f+y|0,l=$(l^f,7),i=i+u|0,b=$(b^i,16),d=d+b|0,u=$(u^d,12),i=i+u|0,b=$(b^i,8),d=d+b|0,u=$(u^d,7),a=a+h|0,w=$(w^a,16),m=m+w|0,h=$(h^m,12),a=a+h|0,w=$(w^a,8),m=m+w|0,h=$(h^m,7),s=s+l|0,w=$(w^s,16),d=d+w|0,l=$(l^d,12),s=s+l|0,w=$(w^s,8),d=d+w|0,l=$(l^d,7),o=o+u|0,g=$(g^o,16),m=m+g|0,u=$(u^m,12),o=o+u|0,g=$(g^o,8),m=m+g|0,u=$(u^m,7),i=i+h|0,y=$(y^i,16),p=p+y|0,h=$(h^p,12),i=i+h|0,y=$(y^i,8),p=p+y|0,h=$(h^p,7),a=a+c|0,b=$(b^a,16),f=f+b|0,c=$(c^f,12),a=a+c|0,b=$(b^a,8),f=f+b|0,c=$(c^f,7);let x=0;n[x++]=s,n[x++]=o,n[x++]=i,n[x++]=a,n[x++]=g,n[x++]=y,n[x++]=b,n[x++]=w}var jH=Kw(RT,{counterRight:!1,counterLength:4,allowShortKeys:!1}),YH=Kw(RT,{counterRight:!1,counterLength:8,extendNonceFn:WH,allowShortKeys:!1});var XH=new Uint8Array(16),MT=(r,e)=>{r.update(e);let t=e.length%16;t&&r.update(XH.subarray(t))},QH=new Uint8Array(32);function OT(r,e,t,n,s){s!==void 0&&yt(s,void 0,"AAD");let o=r(e,t,QH),i=_T(n.length,s?s.length:0,!0),a=LT.create(o);s&&MT(a,s),MT(a,n),a.update(i);let c=a.digest();return Wn(o,i),c}var NT=r=>(e,t,n)=>({encrypt(o,i){let a=o.length;i=Bw(a+16,i,!1),i.set(o);let c=i.subarray(0,-16);r(e,t,c,c,1);let l=OT(r,e,t,c,n);return i.set(l,a),Wn(l),i},decrypt(o,i){i=Bw(o.length-16,i,!1);let a=o.subarray(0,-16),c=o.subarray(-16),l=OT(r,e,t,a,n);if(!TT(c,l))throw new Error("invalid tag");return i.set(o.subarray(0,-16)),r(e,t,i,i,1),Wn(l),i}}),zw=Nw({blockSize:64,nonceLength:12,tagLength:16},NT(jH)),S4e=Nw({blockSize:64,nonceLength:24,tagLength:16},NT(YH));yi();Wc();E2();yi();var Cu=BigInt(0),Ta=BigInt(1),a1=BigInt(2);function JH(r){return Qs(r,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...r})}function BT(r){let e=JH(r),{P:t,type:n,adjustScalarBytes:s,powPminus2:o,randomBytes:i}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i||Qr,l=a?255:448,u=a?32:56,h=BigInt(a?9:5),p=BigInt(a?121665:39081),f=a?a1**BigInt(254):a1**BigInt(447),d=a?BigInt(8)*a1**BigInt(251)-Ta:BigInt(4)*a1**BigInt(445)-Ta,m=f+d+Ta,g=C=>Ut(C,t),y=b(h);function b(C){return qc(g(C),u)}function w(C){let T=td(ge(C,u,"uCoordinate"));return a&&(T[31]&=127),g(mi(T))}function x(C){return mi(s(td(ge(C,u,"scalar"))))}function v(C,T){let M=X(w(T),x(C));if(M===Cu)throw new Error("invalid private or public key received");return b(M)}function S(C){return v(C,y)}let E=S,I=v;function A(C,T,M){let B=g(C*(T-M));return T=g(T-B),M=g(M+B),{x_2:T,x_3:M}}function X(C,T){Vc("u",C,Cu,t),Vc("scalar",T,f,m);let M=T,B=C,N=Ta,k=Cu,O=C,K=Ta,F=Cu;for(let ue=BigInt(l-1);ue>=Cu;ue--){let se=M>>ue&Ta;F^=se,{x_2:N,x_3:O}=A(F,N,O),{x_2:k,x_3:K}=A(F,k,K),F=se;let pe=N+k,Te=g(pe*pe),Qe=N-k,be=g(Qe*Qe),et=Te-be,Wo=O+K,ih=O-K,ac=g(ih*pe),U5=g(Wo*Qe),K5=ac+U5,F5=ac-U5;O=g(K5*K5),K=g(B*g(F5*F5)),N=g(Te*be),k=g(et*(Te+g(p*et)))}({x_2:N,x_3:O}=A(F,N,O)),{x_2:k,x_3:K}=A(F,k,K);let ve=o(k);return g(N*ve)}let ne={secretKey:u,publicKey:u,seed:u},H=(C=c(u))=>(ge(C,ne.seed,"seed"),C),L={randomSecretKey:H};return Object.freeze({keygen:nd(H,E),getSharedSecret:I,getPublicKey:E,scalarMult:v,scalarMultBase:S,utils:L,GuBytes:y.slice(),lengths:ne})}var ZH=BigInt(1),UT=BigInt(2),eq=BigInt(3),tq=BigInt(5),M4e=BigInt(8),KT=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");function rq(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),s=BigInt(80),o=KT,a=r*r%o*r%o,c=Me(a,UT,o)*a%o,l=Me(c,ZH,o)*r%o,u=Me(l,tq,o)*l%o,h=Me(u,e,o)*u%o,p=Me(h,t,o)*h%o,f=Me(p,n,o)*p%o,d=Me(f,s,o)*f%o,m=Me(d,s,o)*f%o,g=Me(m,e,o)*u%o;return{pow_p_5_8:Me(g,UT,o)*r%o,b2:a}}function nq(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Tu=(()=>{let r=KT;return BT({P:r,type:"x25519",powPminus2:e=>{let{pow_p_5_8:t,b2:n}=rq(e);return Ut(Me(t,eq,r)*n,r)},adjustScalarBytes:nq})})();S2();Jr();function zT(r,e,t){return js(r),t===void 0&&(t=new Uint8Array(r.outputLen)),wi(r,t,e)}var $w=Uint8Array.of(0),FT=Uint8Array.of();function $T(r,e,t,n=32){js(r),xr(n,"length");let s=r.outputLen;if(n>255*s)throw new Error("Length must be <= 255*HashLen");let o=Math.ceil(n/s);t===void 0?t=FT:ge(t,void 0,"info");let i=new Uint8Array(o*s),a=wi.create(r,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<o;u++)$w[0]=u+1,c.update(u===0?FT:l).update(t).update($w).digestInto(l),i.set(l,s*u),a._cloneInto(c);return a.destroy(),c.destroy(),kn(l,$w),i.slice(0,n)}Kc();var Hw={hashSHA256(r){return Yt(r.subarray())},getHKDF(r,e){let t=zT(Yt,e,r),s=$T(Yt,t,void 0,96),o=s.subarray(0,32),i=s.subarray(32,64),a=s.subarray(64,96);return[o,i,a]},generateX25519KeyPair(){let r=Tu.utils.randomSecretKey();return{publicKey:Tu.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:Tu.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,e){return Tu.getSharedSecret(r.subarray(),e.subarray())},chaCha20Poly1305Encrypt(r,e,t,n){return zw(n,e,t).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,e,t,n,s){return zw(n,e,t).decrypt(r.subarray(),s)}};var sq=(0,u1.newInstance)(),HT=new u1.ChaCha20Poly1305(sq),qT="chacha20-poly1305",_a=Buffer.from([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),_u=Buffer.from([48,42,48,5,6,3,43,101,110,3,33,0]);var qw={hashSHA256(r){let e=mn.default.createHash("sha256");if(r instanceof Uint8Array)return e.update(r).digest();for(let t of r)e.update(t);return e.digest()},chaCha20Poly1305Encrypt(r,e,t,n){let s=mn.default.createCipheriv(qT,n,e,{authTagLength:16});if(s.setAAD(t,{plaintextLength:r.byteLength}),r instanceof Uint8Array){let a=s.update(r),c=s.final(),l=s.getAuthTag();return Buffer.concat([a,c,l],a.byteLength+c.byteLength+l.byteLength)}let o=new U;for(let a of r)o.append(s.update(a));let i=s.final();return i.byteLength>0&&o.append(i),o.append(s.getAuthTag()),o},chaCha20Poly1305Decrypt(r,e,t,n,s){let o=r.subarray(r.length-16),i=mn.default.createDecipheriv(qT,n,e,{authTagLength:16}),a;if(r instanceof Uint8Array?a=r.subarray(0,r.length-16):a=r.sublist(0,r.length-16),i.setAAD(t,{plaintextLength:a.byteLength}),i.setAuthTag(o),a instanceof Uint8Array){let u=i.update(a),h=i.final();return h.byteLength>0?Buffer.concat([u,h],u.byteLength+h.byteLength):u}let c=new U;for(let u of a)c.append(i.update(u));let l=i.final();return l.byteLength>0&&c.append(l),c}},c1={hashSHA256(r){return wT(r.subarray())},chaCha20Poly1305Encrypt(r,e,t,n){return HT.seal(n,e,r.subarray(),t)},chaCha20Poly1305Decrypt(r,e,t,n,s){let o=HT.open(n,e,r.subarray(),t,s);if(!o)throw new Error("Invalid chacha20poly1305 decryption");return o}},l1={...Hw,hashSHA256(r){return qw.hashSHA256(r)},chaCha20Poly1305Encrypt(r,e,t,n){return r.byteLength<1200?c1.chaCha20Poly1305Encrypt(r,e,t,n):qw.chaCha20Poly1305Encrypt(r,e,t,n)},chaCha20Poly1305Decrypt(r,e,t,n,s){return r.byteLength<1200?c1.chaCha20Poly1305Decrypt(r,e,t,n,s):qw.chaCha20Poly1305Decrypt(r,e,t,n,s)},generateX25519KeyPair(){let{publicKey:r,privateKey:e}=mn.default.generateKeyPairSync("x25519",{publicKeyEncoding:{type:"spki",format:"der"},privateKeyEncoding:{type:"pkcs8",format:"der"}});return{publicKey:r.subarray(_u.length),privateKey:e.subarray(_a.length)}},generateX25519KeyPairFromSeed(r){let e=mn.default.createPrivateKey({key:Buffer.concat([_a,r],_a.byteLength+r.byteLength),type:"pkcs8",format:"der"});return{publicKey:mn.default.createPublicKey(e).export({type:"spki",format:"der"}).subarray(_u.length),privateKey:r}},generateX25519SharedKey(r,e){return e instanceof Uint8Array?e=Buffer.concat([_u,e],_u.byteLength+e.byteLength):e=new U(_u,e).subarray(),r instanceof Uint8Array?r=Buffer.concat([_a,r],_a.byteLength+r.byteLength):r=new U(_a,r).subarray(),mn.default.diffieHellman({publicKey:mn.default.createPublicKey({key:Buffer.from(e.buffer,e.byteOffset,e.byteLength),type:"spki",format:"der"}),privateKey:mn.default.createPrivateKey({key:Buffer.from(r.buffer,r.byteOffset,r.byteLength),type:"pkcs8",format:"der"})})}};IT&&(l1.chaCha20Poly1305Encrypt=c1.chaCha20Poly1305Encrypt,l1.chaCha20Poly1305Decrypt=c1.chaCha20Poly1305Decrypt);function VT(r){return{generateKeypair:r.generateX25519KeyPair,dh:(e,t)=>r.generateX25519SharedKey(e.privateKey,t).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}rt();var Pa=r=>{let e=tt(2);return e[0]=r>>8,e[1]=r,e};Pa.bytes=2;var Da=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let e=0;return e+=r[0]<<8,e+=r[1],e}return r.getUint16(0)};Da.bytes=2;function GT(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}ce();function Vw(r,e){!e.enabled||!Sa||(r?(e(`LOCAL_STATIC_PUBLIC_KEY ${P(r.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${P(r.privateKey,"hex")}`)):e("Missing local static keys."))}function Gw(r,e){!e.enabled||!Sa||(r?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${P(r.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${P(r.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function WT(r,e){!e.enabled||!Sa||e(r?`REMOTE_STATIC_PUBLIC_KEY ${P(r.subarray(),"hex")}`:"Missing remote static public key.")}function Ww(r,e){!e.enabled||!Sa||e(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${P(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function jw(r,e,t){!t.enabled||!Sa||(t(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&P(r.k,"hex")}`),t(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&P(e.k,"hex")}`))}Be();Ne();rt();cc();bt();te();ce();rt();var ka=class r extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};rt();var oq=0,iq=4294967295,aq="Cipherstate has reached maximum n, a new handshake must be performed",h1=class{n;bytes;view;constructor(e=oq){this.n=e,this.bytes=ae(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>iq)throw new Error(aq)}};var zo=ae(0),La=class{k;n;crypto;constructor(e,t=void 0,n=0){this.crypto=e,this.k=t,this.n=new h1(n)}hasKey(){return!!this.k}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();let n=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,t,n){if(!this.hasKey())return t;this.n.assertValue();let s=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,n);return this.n.increment(),s}},Yw=class{cs;ck;h;crypto;constructor(e,t){this.crypto=e;let n=D(t,"utf-8");this.h=cq(e,n),this.ck=this.h,this.cs=new La(e)}mixKey(e){let[t,n]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new La(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new U(this.h,e))}encryptAndHash(e){let t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){let t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){let[e,t]=this.crypto.hkdf(this.ck,zo);return[new La(this.crypto,e),new La(this.crypto,t)]}},Xw=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:t,protocolName:n,prologue:s,initiator:o,s:i,e:a,rs:c,re:l}=e;this.crypto=t,this.ss=new Yw(t,n),this.ss.mixHash(s),this.initiator=o,this.s=i,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,t=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw new Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+n)throw new Error("message is not long enough");let s=e.sublist(t,t+n);return this.rs=this.ss.decryptAndHash(s),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},Pu=class extends Xw{writeMessageA(e){return new U(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let t=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new U(t,n,this.ss.encryptAndHash(e))}writeMessageC(e){let t=this.writeS();return this.writeSE(),new U(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(t){throw new ka(`handshake stage 0 validation fail: ${t.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();let t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(t){throw new ka(`handshake stage 1 validation fail: ${t.message}`)}}readMessageC(e){try{let t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(t){throw new ka(`handshake stage 2 validation fail: ${t.message}`)}}};function cq(r,e){if(e.length<=32){let t=ae(32);return t.set(e),t}else return r.hash(e)}Bt();V();Be();bt();te();wr();rt();var d1;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.webtransportCerthashes!=null)for(let o of t.webtransportCerthashes)n.uint32(10),n.bytes(o);if(t.streamMuxers!=null)for(let o of t.streamMuxers)n.uint32(18),n.string(o);s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={webtransportCerthashes:[],streamMuxers:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{if(s.limits?.webtransportCerthashes!=null&&o.webtransportCerthashes.length===s.limits.webtransportCerthashes)throw new _e('Decode error - map field "webtransportCerthashes" had too many elements');o.webtransportCerthashes.push(t.bytes());break}case 2:{if(s.limits?.streamMuxers!=null&&o.streamMuxers.length===s.limits.streamMuxers)throw new _e('Decode error - map field "streamMuxers" had too many elements');o.streamMuxers.push(t.string());break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(d1||(d1={}));var Du;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.identityKey!=null&&t.identityKey.byteLength>0&&(n.uint32(10),n.bytes(t.identityKey)),t.identitySig!=null&&t.identitySig.byteLength>0&&(n.uint32(18),n.bytes(t.identitySig)),t.extensions!=null&&(n.uint32(34),d1.codec().encode(t.extensions,n)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={identityKey:ae(0),identitySig:ae(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.identityKey=t.bytes();break}case 2:{o.identitySig=t.bytes();break}case 4:{o.extensions=d1.codec().decode(t,t.uint32(),{limits:s.limits?.extensions});break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(Du||(Du={}));async function Jw(r,e,t){let n=await r.sign(YT(e));return Du.encode({identityKey:dt(r.publicKey),identitySig:n,extensions:t})}async function Zw(r,e,t){try{let n=Du.decode(r),s=Ft(n.identityKey);if(t?.equals(s)===!1)throw new Error(`Payload identity key ${s} does not match expected remote identity key ${t}`);if(!e)throw new Error("Remote static does not exist");let o=YT(e);if(!await s.verify(o,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new yh(n.message)}}function YT(r){let e=D("noise-libp2p-static-key:");return r instanceof Uint8Array?Ee([e,r],e.length+r.length):(r.prepend(e),r)}var Qw=class extends Ts{stream;handshake;metrics;decoder;constructor(e,t,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=t,this.metrics=n,this.decoder=new Lf({lengthDecoder:Da,maxBufferSize:16*1024*1024,encodingLength:()=>2});let s=c=>{try{for(let l of this.decoder.decode(c.data))this.onData(this.decrypt(l))}catch(l){this.abort(l)}};this.stream.addEventListener("message",s);let o=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",o);let i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);let a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){let t=new U;for(let n=0;n<e.byteLength;n+=65519){let s=n+65519;s>e.byteLength&&(s=e.byteLength);let o;e instanceof Uint8Array?o=this.handshake.encrypt(e.subarray(n,s)):o=this.handshake.encrypt(e.sublist(n,s)),this.metrics?.encryptedPackets.increment(),t.append(Pa(o.byteLength)),t.append(o)}return t}decrypt(e){let t=new U;for(let n=0;n<e.byteLength;n+=65535){let s=n+65535;if(s>e.byteLength&&(s=e.byteLength),s-Cw<n)throw new Error("Invalid chunk");let o;e instanceof Uint8Array?o=e.subarray(n,s):o=e.sublist(n,s);let i=e.subarray(n,s-Cw);try{let a=this.handshake.decrypt(o,i);this.metrics?.decryptedPackets.increment(),t.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return t}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}};function e6(r,e,t){return new Qw(r,e,t)}async function XT(r,e){let{log:t,connection:n,crypto:s,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Jw(o,a.publicKey,l),h=new Pu({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Vw(h.s,t),t.trace("Stage 0 - Initiator starting to send first message."),await n.write(h.writeMessageA(zo),e),t.trace("Stage 0 - Initiator finished sending first message."),Gw(h.e,t),t.trace("Stage 1 - Initiator waiting to receive first message from responder...");let p=h.readMessageB(await n.read(e));t.trace("Stage 1 - Initiator received the message."),Ww(h.re,t),WT(h.rs,t),t.trace("Initiator going to check remote's signature...");let f=await Zw(p,h.rs,c);t.trace("All good with the signature!"),t.trace("Stage 2 - Initiator sending third handshake message."),await n.write(h.writeMessageC(u),e),t.trace("Stage 2 - Initiator sent message with signed payload.");let[d,m]=h.ss.split();return jw(d,m,t),{payload:f,encrypt:g=>d.encryptWithAd(zo,g),decrypt:(g,y)=>m.decryptWithAd(zo,g,y)}}async function QT(r,e){let{log:t,connection:n,crypto:s,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Jw(o,a.publicKey,l),h=new Pu({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Vw(h.s,t),t.trace("Stage 0 - Responder waiting to receive first message."),h.readMessageA(await n.read(e)),t.trace("Stage 0 - Responder received first message."),Ww(h.re,t),t.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(h.writeMessageB(u),e),t.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Gw(h.e,t),t.trace("Stage 2 - Responder waiting for third handshake message...");let p=h.readMessageC(await n.read(e));t.trace("Stage 2 - Responder received the message, finished handshake.");let f=await Zw(p,h.rs,c),[d,m]=h.ss.split();return jw(d,m,t),{payload:f,encrypt:g=>m.encryptWithAd(zo,g),decrypt:(g,y)=>d.decryptWithAd(zo,g,y)}}var f1=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,t={}){let{staticNoiseKey:n,extensions:s,crypto:o,prologueBytes:i}=t,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");let c=o??l1;this.crypto=VT(c),this.extensions={webtransportCerthashes:[],...s},this.metrics=a?GT(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??ae(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[nt]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){let n=e.log?.newScope("noise")??this.log,s=_s(e,{lengthEncoder:Pa,lengthDecoder:Da,maxDataLength:65535}),o=await this.performHandshakeInitiator(s,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=Ft(o.payload.identityKey);return{connection:e6(s.unwrap(),o,this.metrics),remoteExtensions:o.payload.extensions,remotePeer:On(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(o.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;let t=this.components.upgrader.getStreamMuxers();if(t!=null)for(let n of e){let s=t.get(n);if(s!=null)return s}if(e.length)throw new bh("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,t){let n=e.log?.newScope("noise")??this.log,s=_s(e,{lengthEncoder:Pa,lengthDecoder:Da,maxDataLength:65535}),o=await this.performHandshakeResponder(s,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=Ft(o.payload.identityKey);return{connection:e6(s.unwrap(),o,this.metrics),remoteExtensions:o.payload.extensions,remotePeer:On(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(o.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,n,s,o){let i,a=o?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await XT({connection:e,privateKey:t,remoteIdentityKey:s,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(e,t,n,s,o){let i,a=o?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await QT({connection:e,privateKey:t,remoteIdentityKey:s,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}};function JT(r={}){return e=>new f1(e,r)}V();function lq(r){return r.reason}async function t6(r,e,t){if(e==null)return r;let n=t?.translateError??lq;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}Be();V();var Fe;(function(r){r[r.Data=0]="Data",r[r.WindowUpdate=1]="WindowUpdate",r[r.Ping=2]="Ping",r[r.GoAway=3]="GoAway"})(Fe||(Fe={}));var xe;(function(r){r[r.SYN=1]="SYN",r[r.ACK=2]="ACK",r[r.FIN=4]="FIN",r[r.RST=8]="RST"})(xe||(xe={}));var sEe=Object.values(xe).filter(r=>typeof r!="string"),ZT=0,at;(function(r){r[r.NormalTermination=0]="NormalTermination",r[r.ProtocolError=1]="ProtocolError",r[r.InternalError=2]="InternalError"})(at||(at={}));var gn=12;var jn=class extends Error{static name="ProtocolError";reason;constructor(e,t){super(e),this.name="ProtocolError",this.reason=t}};function e_(r){return r?.reason!==null}var dr=class extends jn{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e,at.ProtocolError),this.name="InvalidFrameError"}},Ma=class extends jn{static name="UnRequestedPingError";constructor(e="Un-requested ping error"){super(e,at.ProtocolError),this.name="UnRequestedPingError"}},Oa=class extends jn{static name="NotMatchingPingError";constructor(e="Not matching ping error"){super(e,at.ProtocolError),this.name="NotMatchingPingError"}};var p1=class extends jn{static name="StreamAlreadyExistsError";constructor(e="Stream already exists"){super(e,at.ProtocolError),this.name="StreamAlreadyExistsError"}},m1=class extends jn{static name="DecodeInvalidVersionError";constructor(e="Decode invalid version"){super(e,at.ProtocolError),this.name="DecodeInvalidVersionError"}},g1=class extends jn{static name="BothClientsError";constructor(e="Both clients"){super(e,at.ProtocolError),this.name="BothClientsError"}},Ra=class extends jn{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e,at.ProtocolError),this.name="ReceiveWindowExceededError"}};var lEe=new Set([dr.name,Ma.name,Oa.name,p1.name,m1.name,g1.name,Ra.name]),Lu=256*1024,y1=16*1024*1024;var Mu={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,maxMessageSize:64*1024,maxEarlyStreams:10,streamOptions:{initialStreamWindowSize:Lu,maxStreamWindowSize:y1,inactivityTimeout:12e4,maxReadBufferLength:4194304,maxWriteBufferLength:1/0}};function t_(r){if(r.keepAliveInterval!=null&&r.keepAliveInterval<=0)throw new R("keep-alive interval must be positive");if(r.maxInboundStreams!=null&&r.maxInboundStreams<0)throw new R("max inbound streams must be larger or equal 0");if(r.maxOutboundStreams!=null&&r.maxOutboundStreams<0)throw new R("max outbound streams must be larger or equal 0");if(r.maxMessageSize!=null&&r.maxMessageSize<1024)throw new R("MaxMessageSize must be greater than a kilobyte");if(r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize<Lu)throw new R("InitialStreamWindowSize must be larger or equal 256 kB");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize<r.streamOptions?.initialStreamWindowSize)throw new R("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize>2**32-1)throw new R("MaxStreamWindowSize must be less than equal MAX_UINT32")}Be();function n_(r){return r.header.type===Fe.Data&&r.data!==null}var r_=2**24;function uq(r){if(r[0]!==ZT)throw new dr("Invalid frame version");return{type:r[1],flag:(r[2]<<8)+r[3],streamID:r[4]*r_+(r[5]<<16)+(r[6]<<8)+r[7],length:r[8]*r_+(r[9]<<16)+(r[10]<<8)+r[11]}}var b1=class{buffer;constructor(){this.buffer=new U}*emitFrames(e){for(this.buffer.append(e);;){let t=this.readFrame();if(t===void 0)break;yield t}}readFrame(){let e=gn;if(this.buffer.byteLength<gn)return;let t=uq(this.buffer.subarray(0,gn));if(t.type===Fe.Data){if(e+=t.length,this.buffer.byteLength<e)return;let n=this.buffer.sublist(gn,e);return this.buffer.consume(e),{header:t,data:n}}return this.buffer.consume(e),{header:t}}};function r6(r){let e=new Uint8Array(gn);return e[1]=r.type,e[2]=r.flag>>>8,e[3]=r.flag,e[4]=r.streamID>>>24,e[5]=r.streamID>>>16,e[6]=r.streamID>>>8,e[7]=r.streamID,e[8]=r.length>>>24,e[9]=r.length>>>16,e[10]=r.length>>>8,e[11]=r.length,e}Be();var Ht;(function(r){r[r.Init=0]="Init",r[r.SYNSent=1]="SYNSent",r[r.SYNReceived=2]="SYNReceived",r[r.Established=3]="Established",r[r.Finished=4]="Finished",r[r.Paused=5]="Paused"})(Ht||(Ht={}));var w1=class extends Pf{streamId;state;sendWindowCapacity;recvWindow;recvWindowCapacity;maxStreamWindowSize;epochStart;getRTT;sendFrame;constructor(e){let t=e.initialStreamWindowSize??Lu;super({...e,maxMessageSize:t-gn}),this.streamId=e.streamId,this.state=e.state,this.sendWindowCapacity=t,this.recvWindow=t,this.recvWindowCapacity=this.recvWindow,this.maxStreamWindowSize=e.maxStreamWindowSize??y1,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.sendFrame=e.sendFrame;let n=()=>{this.state=Ht.Finished};this.addEventListener("close",n)}sendData(e){let t=e.byteLength,n=0,s=!0;for(this.log?.trace("send window capacity is %d bytes",this.sendWindowCapacity);e.byteLength>0;){if(this.sendWindowCapacity===0){s=!1,this.log?.trace("sent %d/%d bytes, exhausted send window, waiting for window update",n,t);break}let o=Math.min(this.sendWindowCapacity,e.byteLength),i=this.getSendFlags(),a=e.sublist(0,o);e.consume(o);let c=this.sendFrame({type:Fe.Data,flag:i,streamID:this.streamId,length:o},a);if(this.sendWindowCapacity-=o,n+=o,!c){s=c,this.log.trace("sent %d/%d bytes, wait for muxer to have more send capacity",n,t);break}}return{sentBytes:n,canSendMore:s}}sendReset(){this.sendFrame({type:Fe.WindowUpdate,flag:xe.RST,streamID:this.streamId,length:0})}async sendCloseWrite(){let e=this.getSendFlags()|xe.FIN;this.sendFrame({type:Fe.WindowUpdate,flag:e,streamID:this.streamId,length:0})}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){this.state=Ht.Paused}sendResume(){this.state=Ht.Established,this.sendWindowUpdate()}handleWindowUpdate(e){this.processFlags(e.header.flag),this.sendWindowCapacity+=e.header.length,this.maxMessageSize=this.sendWindowCapacity-gn,this.maxMessageSize<0&&(this.maxMessageSize=0),this.maxMessageSize!==0&&this.writeBuffer.byteLength>0&&(this.log?.trace("window update of %d bytes allows more data to be sent, have %d bytes queued, sending data %s",e.header.length,this.writeBuffer.byteLength,this.sendingData),this.safeDispatchEvent("drain"))}handleData(e){if(!n_(e))throw new dr("Frame was not data frame");if(this.processFlags(e.header.flag),this.recvWindowCapacity<e.header.length)throw new Ra("Receive window exceeded");this.recvWindowCapacity-=e.header.length,this.onData(e.data),this.sendWindowUpdate()}processFlags(e){(e&xe.ACK)===xe.ACK&&this.state===Ht.SYNSent&&(this.state=Ht.Established),(e&xe.FIN)===xe.FIN&&this.onRemoteCloseWrite(),(e&xe.RST)===xe.RST&&this.onRemoteReset()}getSendFlags(){switch(this.state){case Ht.Init:return this.state=Ht.SYNSent,xe.SYN;case Ht.SYNReceived:return this.state=Ht.Established,xe.ACK;default:return 0}}sendWindowUpdate(){if(this.state===Ht.Paused){this.epochStart=Date.now();return}let e=this.getSendFlags(),t=Date.now(),n=this.getRTT();if(e===0&&n>-1&&t-this.epochStart<=n*4&&(this.recvWindow=Math.min(this.recvWindow*2,this.maxStreamWindowSize)),this.recvWindowCapacity>=this.recvWindow&&e===0)return;let s=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:Fe.WindowUpdate,flag:e,streamID:this.streamId,length:s})}};function s_(r){return{type:Fe[r.type],flags:[(r.flag&xe.SYN)===xe.SYN?"SYN":void 0,(r.flag&xe.ACK)===xe.ACK?"ACK":void 0,(r.flag&xe.FIN)===xe.FIN?"FIN":void 0,(r.flag&xe.RST)===xe.RST?"RST":void 0].filter(Boolean),streamID:r.streamID,length:r.length}}var o_="/yamux/1.0.0",x1=class{protocol=o_;_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@chainsafe/libp2p-yamux";[nt]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new n6(e,{...this._init})}},n6=class extends _f{nextStreamID;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;decoder;keepAlive;enableKeepAlive;keepAliveInterval;maxInboundStreams;maxOutboundStreams;constructor(e,t={}){super(e,{...t,protocol:o_,name:"yamux"}),this.client=e.direction==="outbound",t_(t),this.enableKeepAlive=t.enableKeepAlive??Mu.enableKeepAlive,this.keepAliveInterval=t.keepAliveInterval??Mu.keepAliveInterval,this.maxInboundStreams=t.maxInboundStreams??Mu.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??Mu.maxOutboundStreams,this.decoder=new b1,this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,this.log.trace("muxer created"),this.enableKeepAlive&&(this.log.trace("muxer keepalive enabled interval=%s",this.keepAliveInterval),this.keepAlive=P8(async n=>{try{await this.ping(n)}catch(s){this.log.error("ping error: %s",s)}},this.keepAliveInterval,{runImmediately:!0}),this.keepAlive.start())}onData(e){for(let t of this.decoder.emitFrames(e))this.handleFrame(t)}onCreateStream(){if(this.remoteGoAway!==void 0)throw new Tn("Muxer closed remotely");if(this.localGoAway!==void 0)throw new Tn("Muxer closed locally");let e=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.maxOutboundStreams)throw new Jo("max outbound streams exceeded");this.log.trace("new outgoing stream id=%s",e);let t=this._newStream(e,Ht.Init,"outbound");return this.numOutboundStreams++,queueMicrotask(()=>{t.sendWindowUpdate()}),t}async ping(e){if(this.remoteGoAway!==void 0)throw new Tn("Muxer closed remotely");if(this.localGoAway!==void 0)throw new Tn("Muxer closed locally");if(this.activePing!=null)return t6(this.activePing.promise,e?.signal);this.activePing=Object.assign(Promise.withResolvers(),{id:this.nextPingID++,start:Date.now()}),this.sendPing(this.activePing.id);try{this.rtt=await t6(this.activePing.promise,e?.signal)}finally{this.activePing=void 0}return this.rtt}getRTT(){return this.rtt}async close(e={}){if(this.status==="open")try{let t=e?.reason??at.NormalTermination;this.log.trace("muxer close reason=%s",at[t]),await super.close(e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}abort(e){if(this.status==="open")try{super.abort(e);let t=at.InternalError;e_(e)&&(t=e.reason),this.log.error("muxer abort reason=%s error=%s",t,e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}onTransportClosed(){try{super.onTransportClosed()}finally{this.keepAlive?.stop()}}_newStream(e,t,n){if(this.streams.find(o=>o.streamId===e)!=null)throw new R("Stream already exists with that id");let s=new w1({...this.streamOptions,id:`${e}`,streamId:e,state:t,direction:n,sendFrame:this.sendFrame.bind(this),log:this.log.newScope(`${n}:${e}`),getRTT:this.getRTT.bind(this)});return s.addEventListener("close",()=>{this.closeStream(e)},{once:!0}),s}closeStream(e){this.client===(e%2===0)?this.numInboundStreams--:this.numOutboundStreams--}handleFrame(e){let{streamID:t,type:n,length:s}=e.header;if(this.log.trace("received frame %o",s_(e.header)),t===0)switch(n){case Fe.Ping:{this.handlePing(e.header);return}case Fe.GoAway:{this.handleGoAway(s);return}default:throw new dr("Invalid frame type")}else switch(e.header.type){case Fe.Data:case Fe.WindowUpdate:{this.handleStreamMessage(e);return}default:throw new dr("Invalid frame type")}}handlePing(e){if(e.flag===xe.SYN)this.log.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,xe.ACK);else if(e.flag===xe.ACK)this.log.trace("received ping response pingId=%s",e.length),this.handlePingResponse(e.length);else throw new dr("Invalid frame flag")}handlePingResponse(e){if(this.activePing===void 0)throw new Ma("ping not requested");if(this.activePing.id!==e)throw new Oa("ping doesn't match our id");this.activePing.resolve(Date.now()-this.activePing.start)}handleGoAway(e){this.log.trace("received GoAway reason=%s",at[e]??"unknown"),this.remoteGoAway=e,e===at.NormalTermination?this.onTransportClosed():this.abort(new Error("Remote sent GoAway"))}handleStreamMessage(e){let{streamID:t,flag:n,type:s}=e.header;(n&xe.SYN)===xe.SYN&&this.incomingStream(t);let o=this.streams.find(i=>i.streamId===t);if(o===void 0){this.log.trace("frame for missing stream id=%s",t);return}switch(s){case Fe.WindowUpdate:{o.handleWindowUpdate(e);return}case Fe.Data:{o.handleData(e);return}default:throw new Error("unreachable")}}incomingStream(e){if(this.client!==(e%2===0))throw new R("Both endpoints are clients");if(this.streams.find(n=>n.streamId===e))return;if(this.log.trace("new incoming stream id=%s",e),this.localGoAway!==void 0){this.sendFrame({type:Fe.WindowUpdate,flag:xe.RST,streamID:e,length:0});return}if(this.numInboundStreams>=this.maxInboundStreams){this.log("maxIncomingStreams exceeded, forcing stream reset"),this.sendFrame({type:Fe.WindowUpdate,flag:xe.RST,streamID:e,length:0});return}let t=this._newStream(e,Ht.SYNReceived,"inbound");this.numInboundStreams++,this.onRemoteStream(t)}sendFrame(e,t){let n;if(e.type===Fe.Data){if(t==null)throw new dr("Invalid frame");n=new U(r6(e),t)}else n=r6(e);return this.log.trace("sending frame %o",s_(e)),this.send(n)}sendPing(e,t=xe.SYN){t===xe.SYN?this.log.trace("sending ping request pingId=%s",e):this.log.trace("sending ping response pingId=%s",e),this.sendFrame({type:Fe.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=at.NormalTermination){this.log("sending GoAway reason=%s",at[e]),this.localGoAway=e,this.sendFrame({type:Fe.GoAway,flag:0,streamID:0,length:e})}};function i_(r={}){return()=>new x1(r)}var a_="0.1.0";var c_="1.0.0";wr();var Ou;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.protocolVersion!=null&&(n.uint32(42),n.string(t.protocolVersion)),t.agentVersion!=null&&(n.uint32(50),n.string(t.agentVersion)),t.publicKey!=null&&(n.uint32(10),n.bytes(t.publicKey)),t.listenAddrs!=null)for(let o of t.listenAddrs)n.uint32(18),n.bytes(o);if(t.observedAddr!=null&&(n.uint32(34),n.bytes(t.observedAddr)),t.protocols!=null)for(let o of t.protocols)n.uint32(26),n.string(o);t.signedPeerRecord!=null&&(n.uint32(66),n.bytes(t.signedPeerRecord)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={listenAddrs:[],protocols:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 5:{o.protocolVersion=t.string();break}case 6:{o.agentVersion=t.string();break}case 1:{o.publicKey=t.bytes();break}case 2:{if(s.limits?.listenAddrs!=null&&o.listenAddrs.length===s.limits.listenAddrs)throw new _e('Decode error - map field "listenAddrs" had too many elements');o.listenAddrs.push(t.bytes());break}case 4:{o.observedAddr=t.bytes();break}case 3:{if(s.limits?.protocols!=null&&o.protocols.length===s.limits.protocols)throw new _e('Decode error - map field "protocols" had too many elements');o.protocols.push(t.string());break}case 8:{o.signedPeerRecord=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(Ou||(Ou={}));Bt();V();ke();te();var yn={protocolPrefix:"ipfs",timeout:5e3,maxInboundStreams:1,maxOutboundStreams:1,maxObservedAddresses:10,maxMessageSize:8192,runOnConnectionOpen:!0,runOnSelfUpdate:!0,runOnLimitedConnection:!0,concurrency:32};function l_(r){if(r!=null&&r.length>0)try{return q(r)}catch{}}async function u_(r,e,t,n,s){if(t("received identify from %p",n.remotePeer),s==null)throw new Rt("message was null or undefined");let o={};if(s.listenAddrs.length>0&&(o.addresses=s.listenAddrs.map(c=>({isCertified:!1,multiaddr:q(c)}))),s.protocols.length>0&&(o.protocols=s.protocols),s.publicKey!=null){let c=Ft(s.publicKey);if(!On(c).equals(n.remotePeer))throw new Rt("public key did not match remote PeerId");o.publicKey=c}let i;if(s.signedPeerRecord!=null){t.trace("received signedPeerRecord from %p",n.remotePeer);let c=s.signedPeerRecord,l=await lr.openAndCertify(c,ur.DOMAIN),u=ur.createFromProtobuf(l.payload),h=en(l.publicKey.toCID());if(!u.peerId.equals(h))throw new Rt("signing key does not match PeerId in the PeerRecord");if(!n.remotePeer.equals(u.peerId))throw new Rt("signing key does not match remote PeerId");let p;try{p=await r.get(u.peerId)}catch(f){if(f.name!=="NotFoundError")throw f}if(p!=null&&(o.metadata=p.metadata,p.peerRecordEnvelope!=null)){let f=lr.createFromProtobuf(p.peerRecordEnvelope),d=ur.createFromProtobuf(f.payload);d.seqNumber>=u.seqNumber&&(t("sequence number was lower or equal to existing sequence number - stored: %d received: %d",d.seqNumber,u.seqNumber),u=d,c=p.peerRecordEnvelope)}o.peerRecordEnvelope=c,o.addresses=u.multiaddrs.map(f=>({isCertified:!0,multiaddr:f})),i={seq:u.seqNumber,addresses:u.multiaddrs}}else t("%p did not send a signed peer record",n.remotePeer);if(t.trace("patching %p with",n.remotePeer,o),await r.patch(n.remotePeer,o),s.agentVersion!=null||s.protocolVersion!=null){let c={};s.agentVersion!=null&&(c.AgentVersion=D(s.agentVersion)),s.protocolVersion!=null&&(c.ProtocolVersion=D(s.protocolVersion)),t.trace("merging %p metadata",n.remotePeer,c),await r.merge(n.remotePeer,{metadata:c})}let a={peerId:n.remotePeer,protocolVersion:s.protocolVersion,agentVersion:s.agentVersion,publicKey:s.publicKey,listenAddrs:s.listenAddrs.map(c=>q(c)),observedAddr:s.observedAddr==null?void 0:q(s.observedAddr),protocols:s.protocols,signedPeerRecord:i,connection:n};return e.safeDispatchEvent("peer:identify",{detail:a}),a}var v1=class{host;components;protocol;started;timeout;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxObservedAddresses;runOnLimitedConnection;log;constructor(e,t){this.protocol=t.protocol,this.started=!1,this.components=e,this.log=t.log,this.timeout=t.timeout??yn.timeout,this.maxInboundStreams=t.maxInboundStreams??yn.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??yn.maxOutboundStreams,this.maxMessageSize=t.maxMessageSize??yn.maxMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??yn.maxObservedAddresses,this.runOnLimitedConnection=t.runOnLimitedConnection??yn.runOnLimitedConnection,this.host={protocolVersion:`${t.protocolPrefix??yn.protocolPrefix}/${a_}`,agentVersion:e.nodeInfo.userAgent},this.handleProtocol=this.handleProtocol.bind(this)}isStarted(){return this.started}async start(){this.started||(await this.components.peerStore.merge(this.components.peerId,{metadata:{AgentVersion:D(this.host.agentVersion),ProtocolVersion:D(this.host.protocolVersion)}}),await this.components.registrar.handle(this.protocol,this.handleProtocol,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}};Bt();V();ke();Ue();var E1=class extends v1{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??yn.protocolPrefix}/${"id"}/${c_}`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??yn.runOnConnectionOpen)&&e.events.addEventListener("connection:open",n=>{let s=n.detail;this.identify(s).catch(()=>{})})}[nt]=["@libp2p/identify"];async _identify(e,t={}){let n,s;if(t.signal==null){let o=AbortSignal.timeout(this.timeout);j(1/0,o),t={...t,signal:o}}this.log("run identify on new connection %a",e.remoteAddr);try{n=await e.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection}),s=n.log.newScope("identify");let o=zr(n,{maxDataLength:this.maxMessageSize}).pb(Ou),i=await o.read(t);return await o.unwrap().unwrap().close(t),i}catch(o){throw s?.error("identify failed - %e",o),n?.abort(o),o}}async identify(e,t={}){let n=await this._identify(e,t),{publicKey:s,protocols:o,observedAddr:i}=n;if(s==null)throw new Rt("Public key was missing from identify message");let a=Ft(s),c=en(a.toCID());if(!e.remotePeer.equals(c))throw new Rt("Identified peer does not match the expected peer");if(this.components.peerId.equals(c))throw new Rt("Identified peer is our own peer id?");return this.maybeAddObservedAddress(i),this.log("completed for peer %p and protocols %o",c,o),u_(this.components.peerStore,this.components.events,this.log,e,n)}maybeAddObservedAddress(e){let t=l_(e);if(t==null||(this.log.trace("our observed address was %a",t),Fn(t)))return;let n=t.getComponents();if((n[0].code===41||n[0].code===42&&n[1].code===41)&&!y8(t)){this.log.trace("our observed address was IPv6 but not a global unicast address");return}qn.exactMatch(t)||(this.log.trace("storing the observed address"),this.components.addressManager.addObservedAddr(t))}async handleProtocol(e,t){let n=e.log.newScope("identify");n("responding to identify");let s=AbortSignal.timeout(this.timeout);j(1/0,s);let o=await this.components.peerStore.get(this.components.peerId,{signal:s}),i=this.components.addressManager.getAddresses().map(u=>u.decapsulateCode(421)),a=o.peerRecordEnvelope;if(i.length>0&&a==null){let u=new ur({peerId:this.components.peerId,multiaddrs:i});a=(await lr.seal(u,this.components.privateKey,{signal:s})).marshal().subarray()}let c=t.remoteAddr.bytes;vC.matches(t.remoteAddr)||(c=void 0);let l=zr(e).pb(Ou);n("send response"),await l.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:dt(this.components.privateKey.publicKey),listenAddrs:i.map(u=>u.bytes),signedPeerRecord:a,observedAddr:c,protocols:o.protocols},{signal:s}),n("close write"),await l.unwrap().unwrap().close({signal:s})}};function h_(r={}){return e=>new E1(e,r)}V();function pq(r){return r.reason}async function d_(r,e,t){if(e==null)return r;let n=t?.translateError??pq;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}Be();Ne();var f_="1.0.0",p_="ping",m_="ipfs";var S1=class{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;constructor(e,t={}){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix??m_}/${p_}/${f_}`,this.timeout=t.timeout??1e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??1,this.runOnLimitedConnection=t.runOnLimitedConnection??!0,this.handlePing=this.handlePing.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[nt]=["@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(e,t){let n=e.log.newScope("ping");n.trace("ping from %p",t.remotePeer);let s=AbortSignal.timeout(this.timeout);j(1/0,s),s.addEventListener("abort",()=>{e.abort(new Gr("Ping timed out"))});let o=Date.now();for await(let i of e){if(e.status!=="open"){n("stream status changed to %s",e.status);break}e.send(i)||(n("waiting for stream to drain"),await Re(e,"drain",{rejectionEvents:["close"],signal:s}),n("stream drained"))}n("ping from %p complete in %dms",t.remotePeer,Date.now()-o),await e.close({signal:s})}async ping(e,t={}){let n=fs(32),s=await this.components.connectionManager.openStream(e,this.protocol,{runOnLimitedConnection:this.runOnLimitedConnection,...t}),o=s.log.newScope("ping");try{let i=Date.now(),a=Promise.withResolvers(),c=new U,l=u=>{if(c.append(u.data),c.byteLength===32){s.removeEventListener("message",l);let h=Date.now()-i;Promise.all([s.closeRead(t)]).then(()=>{if(W(n,c.subarray()))a.resolve(h);else throw new Sh(`Received wrong ping ack after ${h}ms`)}).catch(p=>{s.abort(p),a.reject(p)})}};return s.addEventListener("message",l),s.send(n),await s.close(t),await d_(a.promise,t.signal)}catch(i){throw o.error("error while pinging %o - %e",e,i),s?.abort(i),i}finally{s?.close()}}};function y_(r={}){return e=>new S1(e,r)}var s6=Symbol.for("@libp2p/peer-id");var $o="StrictSign",Na="StrictNoSign",qt;(function(r){r.Accept="accept",r.Ignore="ignore",r.Reject="reject"})(qt||(qt={}));var CSe=Symbol.for("@libp2p/pubsub");var I1=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var A1=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},C1=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};Ue();var b_=Symbol.for("@libp2p/service-capabilities"),w_=Symbol.for("@libp2p/service-dependencies");var ct=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Ba=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Ru=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var l6={};z(l6,{base58btc:()=>Xe,base58flickr:()=>Iq});var QSe=new Uint8Array(0);function x_(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function _r(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function v_(r){return new TextEncoder().encode(r)}function E_(r){return new TextDecoder().decode(r)}function bq(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var v=d[y],S=0,E=w-1;(v!==0||S<g)&&E!==-1;E--,S++)v+=256*x[E]>>>0,x[E]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var A=c.repeat(m);I<w;++I)A+=r.charAt(x[I]);return A}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*w[S]>>>0,w[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(d[m]!==" "){for(var E=b-y;E!==b&&w[E]===0;)E++;for(var I=new Uint8Array(g+(b-E)),A=g;E!==b;)I[A++]=w[E++];return I}}}function f(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:f}}var wq=bq,xq=wq,I_=xq;var o6=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},i6=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return A_(this,e)}},a6=class{decoders;constructor(e){this.decoders=e}or(e){return A_(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function A_(r,e){return new a6({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var c6=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new o6(e,t,n),this.decoder=new i6(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ua({name:r,prefix:e,encode:t,decode:n}){return new c6(r,e,t,n)}function Ms({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=I_(t,r);return Ua({prefix:e,name:r,encode:n,decode:o=>_r(s(o))})}function vq(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function Eq(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function Sq(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Ye({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=Sq(n);return Ua({prefix:e,name:r,encode(o){return Eq(o,n,t)},decode(o){return vq(o,s,t,r)}})}var Xe=Ms({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Iq=Ms({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var u6={};z(u6,{base32:()=>Os,base32hex:()=>_q,base32hexpad:()=>Dq,base32hexpadupper:()=>kq,base32hexupper:()=>Pq,base32pad:()=>Cq,base32padupper:()=>Tq,base32upper:()=>Aq,base32z:()=>Lq});var Os=Ye({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Aq=Ye({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Cq=Ye({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Tq=Ye({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),_q=Ye({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Pq=Ye({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Dq=Ye({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),kq=Ye({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Lq=Ye({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var h6={};z(h6,{base36:()=>Nu,base36upper:()=>Mq});var Nu=Ms({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Mq=Ms({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Oq=__,C_=128,Rq=127,Nq=~Rq,Bq=Math.pow(2,31);function __(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Bq;)e[t++]=r&255|C_,r/=128;for(;r&Nq;)e[t++]=r&255|C_,r>>>=7;return e[t]=r|0,__.bytes=t-n+1,e}var Uq=d6,Kq=128,T_=127;function d6(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw d6.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&T_)<<s:(i&T_)*Math.pow(2,s),s+=7}while(i>=Kq);return d6.bytes=o-n,t}var Fq=Math.pow(2,7),zq=Math.pow(2,14),$q=Math.pow(2,21),Hq=Math.pow(2,28),qq=Math.pow(2,35),Vq=Math.pow(2,42),Gq=Math.pow(2,49),Wq=Math.pow(2,56),jq=Math.pow(2,63),Yq=function(r){return r<Fq?1:r<zq?2:r<$q?3:r<Hq?4:r<qq?5:r<Vq?6:r<Gq?7:r<Wq?8:r<jq?9:10},Xq={encode:Oq,decode:Uq,encodingLength:Yq},Qq=Xq,Bu=Qq;function Uu(r,e=0){return[Bu.decode(r,e),Bu.decode.bytes]}function Ka(r,e,t=0){return Bu.encode(r,e,t),e}function Fa(r){return Bu.encodingLength(r)}function bn(r,e){let t=e.byteLength,n=Fa(r),s=n+Fa(t),o=new Uint8Array(s+t);return Ka(r,o,0),Ka(t,o,n),o.set(e,s),new za(r,t,e,o)}function Yn(r){let e=_r(r),[t,n]=Uu(e),[s,o]=Uu(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new za(t,s,i,e)}function P_(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&x_(r.bytes,t.bytes)}}var za=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function D_(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Zq(t,f6(r),e??Xe.encoder);default:return eV(t,f6(r),e??Os.encoder)}}var k_=new WeakMap;function f6(r){let e=k_.get(r);if(e==null){let t=new Map;return k_.set(r,t),t}return e}var lt=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Ku)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==tV)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=bn(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&P_(e.multihash,n.multihash)}toString(e){return D_(this,e)}toJSON(){return{"/":D_(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??L_(n,s,o.bytes))}else if(t[rV]===!0){let{version:n,multihash:s,code:o}=t,i=Yn(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Ku)throw new Error(`Version 0 CID must use dag-pb (code: ${Ku}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=L_(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ku,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=_r(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new za(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,p]=Uu(e.subarray(t));return t+=p,h},s=n(),o=Ku;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=Jq(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return f6(o).set(n,e),o}};function Jq(r,e){switch(r[0]){case"Q":{let t=e??Xe;return[Xe.prefix,t.decode(`${Xe.prefix}${r}`)]}case Xe.prefix:{let t=e??Xe;return[Xe.prefix,t.decode(r)]}case Os.prefix:{let t=e??Os;return[Os.prefix,t.decode(r)]}case Nu.prefix:{let t=e??Nu;return[Nu.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Zq(r,e,t){let{prefix:n}=t;if(n!==Xe.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function eV(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var Ku=112,tV=18;function L_(r,e,t){let n=Fa(r),s=n+Fa(e),o=new Uint8Array(s+t.byteLength);return Ka(r,o,0),Ka(e,o,n),o.set(t,s),o}var rV=Symbol.for("@ipld/js-cid/CID");var p6={};z(p6,{identity:()=>$r});var M_=0,nV="identity",O_=_r;function sV(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return bn(M_,O_(r))}var $r={code:M_,name:nV,encode:O_,digest:sV};Ne();Be();te();ce();Be();var oV=parseInt("11111",2),m6=parseInt("10000000",2),iV=parseInt("01111111",2),R_={0:Fu,1:Fu,2:aV,3:uV,4:hV,5:lV,6:cV,16:Fu,22:Fu,48:Fu};function Xn(r,e={offset:0}){let t=r[e.offset]&oV;if(e.offset++,R_[t]!=null)return R_[t](r,e);throw new Error("No decoder for tag "+t)}function zu(r,e){let t=0;if((r[e.offset]&m6)===m6){let n=r[e.offset]&iV,s="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)s+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(s,16)}else t=r[e.offset],e.offset++;return t}function Fu(r,e){zu(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=Xn(r,e);if(n===null)break;t.push(n)}return t}function aV(r,e){let t=zu(r,e),n=e.offset,s=e.offset+t,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function cV(r,e){let t=zu(r,e),n=e.offset+t,s=r[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let h=0;h<c.length;h++)u+=c[h]<<h*7;a+=`.${u}`,c=[]}}return a}function lV(r,e){return e.offset++,null}function uV(r,e){let t=zu(r,e),n=r[e.offset];e.offset++;let s=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function hV(r,e){let t=zu(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function dV(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new U;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function g6(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=dV(r.byteLength);return new U(Uint8Array.from([e.byteLength|m6]),e)}function tr(r){let e=new U,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new U(Uint8Array.from([2]),g6(e),e)}function _1(r){let e=Uint8Array.from([0]),t=new U(e,r);return new U(Uint8Array.from([3]),g6(t),t)}function Ns(r,e=48){let t=new U;for(let n of r)t.append(n);return new U(Uint8Array.from([e]),g6(t),t)}async function N_(r,e,t,n){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,e,t.subarray());return n?.signal?.throwIfAborted(),o}var fV=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),pV=Uint8Array.from([6,5,43,129,4,0,34]),mV=Uint8Array.from([6,5,43,129,4,0,35]),gV={ext:!0,kty:"EC",crv:"P-256"},yV={ext:!0,kty:"EC",crv:"P-384"},bV={ext:!0,kty:"EC",crv:"P-521"},y6=32,b6=48,w6=66;function x6(r){let e=Xn(r);return B_(e)}function B_(r){let e=r[1][1][0],t=1,n,s;if(e.byteLength===y6*2+1)return n=P(e.subarray(t,t+y6),"base64url"),s=P(e.subarray(t+y6),"base64url"),new $a({...gV,key_ops:["verify"],x:n,y:s});if(e.byteLength===b6*2+1)return n=P(e.subarray(t,t+b6),"base64url"),s=P(e.subarray(t+b6),"base64url"),new $a({...yV,key_ops:["verify"],x:n,y:s});if(e.byteLength===w6*2+1)return n=P(e.subarray(t,t+w6),"base64url"),s=P(e.subarray(t+w6),"base64url"),new $a({...bV,key_ops:["verify"],x:n,y:s});throw new ct(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function U_(r){return Ns([tr(Uint8Array.from([1])),Ns([wV(r.crv)],160),Ns([_1(new U(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function wV(r){if(r==="P-256")return fV;if(r==="P-384")return pV;if(r==="P-521")return mV;throw new ct(`Invalid curve ${r}`)}var $a=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=U_(this.jwk)),this._raw}toMultihash(){return $r.digest(Bs(this))}toCID(){return lt.createV1(114,this.toMultihash())}toString(){return Xe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}async verify(e,t,n){return N_(this.jwk,t,e,n)}};var P1=ie(ee("crypto"),1);bt();te();ce();var FIe=P1.default.generateKeyPairSync,$u=32;var xV=64;function K_(r,e,t){if(r.byteLength!==$u)throw new TypeError('"key" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');if(e.byteLength!==xV)throw new TypeError('"sig" must be 64 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"sig" must be a node.js Buffer, or Uint8Array.');let n=P1.default.createPublicKey({format:"jwk",key:{crv:"Ed25519",x:P(r,"base64url"),kty:"OKP"}});return P1.default.verify(null,t instanceof Uint8Array?t:t.subarray(),n,e)}Ne();bt();te();function z_(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var D1=class{type="Ed25519";raw;constructor(e){this.raw=v6(e,$u)}toMultihash(){return $r.digest(Bs(this))}toCID(){return lt.createV1(114,this.toMultihash())}toString(){return Xe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let s=K_(this.raw,t,e);return z_(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}};function E6(r){return r=v6(r,$u),new D1(r)}function v6(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new ct(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}wr();var Ze;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Ze||(Ze={}));var S6;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(S6||(S6={}));(function(r){r.codec=()=>sr(S6)})(Ze||(Ze={}));var wn;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Ze.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=Ze.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(wn||(wn={}));var I6;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Ze.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=Ze.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(I6||(I6={}));var L1=ie(ee("node:crypto"),1),X_=ee("node:util");te();Jr();function k1(r){if(isNaN(r)||r<=0)throw new ct("random bytes length must be a Number bigger than 0");return Qr(r)}var qu={};z(qu,{MAX_RSA_KEY_SIZE:()=>A6,generateRSAKeyPair:()=>G_,jwkToJWKKeyPair:()=>W_,jwkToPkcs1:()=>AV,jwkToPkix:()=>P6,jwkToRSAPrivateKey:()=>M6,pkcs1MessageToJwk:()=>T6,pkcs1MessageToRSAPrivateKey:()=>D6,pkcs1ToJwk:()=>IV,pkcs1ToRSAPrivateKey:()=>V_,pkixMessageToJwk:()=>_6,pkixMessageToRSAPublicKey:()=>L6,pkixToJwk:()=>CV,pkixToRSAPublicKey:()=>k6});Kc();te();ce();Ne();var Ha=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=qu.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return lt.createV1(114,this._multihash)}toString(){return Xe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){return q_(this.jwk,t,e,n)}},Hu=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=qu.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}sign(e,t){return H_(this.jwk,e,t)}};var A6=8192,C6=18,EV=1062,SV=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function IV(r){let e=Xn(r);return T6(e)}function T6(r){return{n:P(r[1],"base64url"),e:P(r[2],"base64url"),d:P(r[3],"base64url"),p:P(r[4],"base64url"),q:P(r[5],"base64url"),dp:P(r[6],"base64url"),dq:P(r[7],"base64url"),qi:P(r[8],"base64url"),kty:"RSA"}}function AV(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new ct("JWK was missing components");return Ns([tr(Uint8Array.from([0])),tr(D(r.n,"base64url")),tr(D(r.e,"base64url")),tr(D(r.d,"base64url")),tr(D(r.p,"base64url")),tr(D(r.q,"base64url")),tr(D(r.dp,"base64url")),tr(D(r.dq,"base64url")),tr(D(r.qi,"base64url"))]).subarray()}function CV(r){let e=Xn(r,{offset:0});return _6(e)}function _6(r){let e=Xn(r[1],{offset:0});return{kty:"RSA",n:P(e[0],"base64url"),e:P(e[1],"base64url")}}function P6(r){if(r.n==null||r.e==null)throw new ct("JWK was missing components");return Ns([SV,_1(Ns([tr(D(r.n,"base64url")),tr(D(r.e,"base64url"))]))]).subarray()}function V_(r){let e=Xn(r);return D6(e)}function D6(r){let e=T6(r);return M6(e)}function k6(r,e){if(r.byteLength>=EV)throw new Ba("Key size is too large");let t=Xn(r,{offset:0});return L6(t,r,e)}function L6(r,e,t){let n=_6(r);if(t==null){let s=Yt(wn.encode({Type:Ze.RSA,Data:e}));t=bn(C6,s)}return new Ha(n,t)}function M6(r){if(Y_(r)>A6)throw new ct("Key size is too large");let e=W_(r),t=Yt(wn.encode({Type:Ze.RSA,Data:P6(e.publicKey)})),n=bn(C6,t);return new Hu(e.privateKey,new Ha(e.publicKey,n))}async function G_(r){if(r>A6)throw new ct("Key size is too large");let e=await j_(r),t=Yt(wn.encode({Type:Ze.RSA,Data:P6(e.publicKey)})),n=bn(C6,t);return new Hu(e.privateKey,new Ha(e.publicKey,n))}function W_(r){if(r==null)throw new ct("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var TV=(0,X_.promisify)(L1.default.generateKeyPair);async function j_(r,e){let t=await TV("rsa",{modulusLength:r,publicKeyEncoding:{type:"pkcs1",format:"jwk"},privateKeyEncoding:{type:"pkcs1",format:"jwk"}});return e?.signal?.throwIfAborted(),{privateKey:t.privateKey,publicKey:t.publicKey}}function H_(r,e,t){t?.signal?.throwIfAborted();let n=L1.default.createSign("RSA-SHA256");if(e instanceof Uint8Array)n.update(e);else for(let s of e)n.update(s);return n.sign({format:"jwk",key:r})}function q_(r,e,t,n){n?.signal?.throwIfAborted();let s=L1.default.createVerify("RSA-SHA256");if(t instanceof Uint8Array)s.update(t);else for(let o of t)s.update(o);return s.verify({format:"jwk",key:r},e)}function Y_(r){if(r.kty!=="RSA")throw new ct("Invalid key type");if(r.n==null)throw new ct("Invalid key modulus");return D(r.n,"base64url").length*8}var Q_=ie(ee("node:crypto"),1);eo();var M1=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}};function J_(r,e,t,n){n?.signal?.throwIfAborted();let s=Q_.default.createHash("sha256");if(t instanceof Uint8Array)s.update(t);else for(let i of t)s.update(i);let o=s.digest();try{return st.verify(e,o,r,{prehash:!1,format:"der"})}catch(i){throw new M1(String(i))}}eo();Ne();var O1=class{type="secp256k1";raw;_key;constructor(e){this._key=eP(e),this.raw=Z_(this._key)}toMultihash(){return $r.digest(Bs(this))}toCID(){return lt.createV1(114,this.toMultihash())}toString(){return Xe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){return J_(this._key,t,e,n)}};function O6(r){return new O1(r)}function Z_(r){return st.Point.fromBytes(r).toBytes()}function eP(r){try{return st.Point.fromBytes(r),r}catch(e){throw new Ba(String(e))}}function R6(r,e){let{Type:t,Data:n}=wn.decode(r),s=n??new Uint8Array;switch(t){case Ze.RSA:return k6(s,e);case Ze.Ed25519:return E6(s);case Ze.secp256k1:return O6(s);case Ze.ECDSA:return x6(s);default:throw new Ru}}function tP(r){let{Type:e,Data:t}=wn.decode(r.digest),n=t??new Uint8Array;switch(e){case Ze.Ed25519:return E6(n);case Ze.secp256k1:return O6(n);case Ze.ECDSA:return x6(n);default:throw new Ru}}function Bs(r){return wn.encode({Type:Ze[r.type],Data:r.raw})}var K6={};z(K6,{sha256:()=>Vu,sha512:()=>PV});var U6=ie(ee("crypto"),1);var _V=20;function B6({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new N6(r,e,t,n,s)}var N6=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??_V,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?rP(n,this.code,t?.truncate):n.then(s=>rP(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function rP(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return bn(e,r)}var Vu=B6({name:"sha2-256",code:18,encode:r=>_r(U6.default.createHash("sha256").update(r).digest())}),PV=B6({name:"sha2-512",code:19,encode:r=>_r(U6.default.createHash("sha512").update(r).digest())});ce();Ne();te();ce();var sP=Symbol.for("nodejs.util.inspect.custom"),DV=114,Gu=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[s6]=!0;toString(){return this.string==null&&(this.string=Xe.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return lt.createV1(DV,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return W(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return W(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[sP](){return`PeerId(${this.toString()})`}},R1=class extends Gu{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},N1=class extends Gu{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},B1=class extends Gu{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},kV=2336,Wu=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=$r.digest(D(this.url))}[sP](){return`PeerId(${this.url})`}[s6]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return lt.createV1(kV,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=P(e)),e.toString()===this.toString())}};var LV=114,oP=2336;function Ho(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Yn(Xe.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return MV(lt.parse(r));if(e==null)throw new I1('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Yn(e.decode(r))}return qa(t)}function qa(r){if(RV(r))return new R1({multihash:r});if(OV(r))try{let e=tP(r);if(e.type==="Ed25519")return new N1({multihash:r,publicKey:e});if(e.type==="secp256k1")return new B1({multihash:r,publicKey:e})}catch{let t=P(r.digest);return new Wu(new URL(t))}throw new C1("Supplied PeerID Multihash is invalid")}function MV(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==LV&&r.code!==oP)throw new A1("Supplied PeerID CID is invalid");if(r.code===oP){let e=P(r.multihash.digest);return new Wu(new URL(e))}return qa(r.multihash)}function OV(r){return r.code===$r.code}function RV(r){return r.code===Vu.code}gr();Be();rt();function U1(r){return r[Symbol.asyncIterator]!=null}var K1=r=>{let e=Ae(r),t=tt(e);return Vr(r,t),K1.bytes=e,t};K1.bytes=0;function Va(r,e){e=e??{};let t=e.lengthEncoder??K1;function*n(s){let o=t(s.byteLength);o instanceof Uint8Array?yield o:yield*o,s instanceof Uint8Array?yield s:yield*s}return U1(r)?(async function*(){for await(let s of r)yield*n(s)})():(function*(){for(let s of r)yield*n(s)})()}Va.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??K1;return new U(t(r.byteLength),r)};gr();Be();var F1=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},z1=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},$1=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},ju=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var NV=8,BV=1024*1024*4,qo;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(qo||(qo={}));var F6=r=>{let e=jt(r);return F6.bytes=Ae(e),e};F6.bytes=0;function Yu(r,e){let t=new U,n=qo.LENGTH,s=-1,o=e?.lengthDecoder??F6,i=e?.maxLengthLength??NV,a=e?.maxDataLength??BV;function*c(){for(;t.byteLength>0;){if(n===qo.LENGTH)try{if(s=o(t),s<0)throw new F1("Invalid message length");if(s>a)throw new z1("Message length too long");let l=o.bytes;t.consume(l),e?.onLength!=null&&e.onLength(s),n=qo.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new $1("Message length length too long");break}throw l}if(n===qo.DATA){if(t.byteLength<s)break;let l=t.sublist(0,s);t.consume(s),e?.onData!=null&&e.onData(l),yield l,n=qo.LENGTH}}}return U1(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new ju("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new ju("Unexpected end of input")})()}Yu.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:o,value:i}=await r.next(t);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}})();return Yu(n,{...e??{},onLength:o=>{t=o}})};var z6="/floodsub/1.0.0",$6="/meshsub/1.0.0",iP="/meshsub/1.1.0",H1="/meshsub/1.2.0";var aP="ERR_TOPIC_VALIDATOR_REJECT",cP="ERR_TOPIC_VALIDATOR_IGNORE";var lP={maxSubscriptions:1/0,maxMessages:1/0,maxIhaveMessageIDs:1/0,maxIwantMessageIDs:1/0,maxIdontwantMessageIDs:1/0,maxControlMessages:1/0,maxPeerInfos:1/0};wr();var Qn;(function(r){let e;(function(h){let p;h.codec=()=>(p==null&&(p=Z((f,d,m={})=>{m.lengthDelimited!==!1&&d.fork(),f.subscribe!=null&&(d.uint32(8),d.bool(f.subscribe)),f.topic!=null&&(d.uint32(18),d.string(f.topic)),m.lengthDelimited!==!1&&d.ldelim()},(f,d,m={})=>{let g={},y=d==null?f.len:f.pos+d;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{g.subscribe=f.bool();break}case 2:{g.topic=f.string();break}default:{f.skipType(b&7);break}}}return g})),p),h.encode=f=>J(f,h.codec()),h.decode=(f,d)=>Q(f,h.codec(),d)})(e=r.SubOpts||(r.SubOpts={}));let t;(function(h){let p;h.codec=()=>(p==null&&(p=Z((f,d,m={})=>{m.lengthDelimited!==!1&&d.fork(),f.from!=null&&(d.uint32(10),d.bytes(f.from)),f.data!=null&&(d.uint32(18),d.bytes(f.data)),f.seqno!=null&&(d.uint32(26),d.bytes(f.seqno)),f.topic!=null&&f.topic!==""&&(d.uint32(34),d.string(f.topic)),f.signature!=null&&(d.uint32(42),d.bytes(f.signature)),f.key!=null&&(d.uint32(50),d.bytes(f.key)),m.lengthDelimited!==!1&&d.ldelim()},(f,d,m={})=>{let g={topic:""},y=d==null?f.len:f.pos+d;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{g.from=f.bytes();break}case 2:{g.data=f.bytes();break}case 3:{g.seqno=f.bytes();break}case 4:{g.topic=f.string();break}case 5:{g.signature=f.bytes();break}case 6:{g.key=f.bytes();break}default:{f.skipType(b&7);break}}}return g})),p),h.encode=f=>J(f,h.codec()),h.decode=(f,d)=>Q(f,h.codec(),d)})(t=r.Message||(r.Message={}));let n;(function(h){let p;h.codec=()=>(p==null&&(p=Z((f,d,m={})=>{if(m.lengthDelimited!==!1&&d.fork(),f.ihave!=null)for(let g of f.ihave)d.uint32(10),r.ControlIHave.codec().encode(g,d);if(f.iwant!=null)for(let g of f.iwant)d.uint32(18),r.ControlIWant.codec().encode(g,d);if(f.graft!=null)for(let g of f.graft)d.uint32(26),r.ControlGraft.codec().encode(g,d);if(f.prune!=null)for(let g of f.prune)d.uint32(34),r.ControlPrune.codec().encode(g,d);if(f.idontwant!=null)for(let g of f.idontwant)d.uint32(42),r.ControlIDontWant.codec().encode(g,d);m.lengthDelimited!==!1&&d.ldelim()},(f,d,m={})=>{let g={ihave:[],iwant:[],graft:[],prune:[],idontwant:[]},y=d==null?f.len:f.pos+d;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{if(m.limits?.ihave!=null&&g.ihave.length===m.limits.ihave)throw new _e('Decode error - map field "ihave" had too many elements');g.ihave.push(r.ControlIHave.codec().decode(f,f.uint32(),{limits:m.limits?.ihave$}));break}case 2:{if(m.limits?.iwant!=null&&g.iwant.length===m.limits.iwant)throw new _e('Decode error - map field "iwant" had too many elements');g.iwant.push(r.ControlIWant.codec().decode(f,f.uint32(),{limits:m.limits?.iwant$}));break}case 3:{if(m.limits?.graft!=null&&g.graft.length===m.limits.graft)throw new _e('Decode error - map field "graft" had too many elements');g.graft.push(r.ControlGraft.codec().decode(f,f.uint32(),{limits:m.limits?.graft$}));break}case 4:{if(m.limits?.prune!=null&&g.prune.length===m.limits.prune)throw new _e('Decode error - map field "prune" had too many elements');g.prune.push(r.ControlPrune.codec().decode(f,f.uint32(),{limits:m.limits?.prune$}));break}case 5:{if(m.limits?.idontwant!=null&&g.idontwant.length===m.limits.idontwant)throw new _e('Decode error - map field "idontwant" had too many elements');g.idontwant.push(r.ControlIDontWant.codec().decode(f,f.uint32(),{limits:m.limits?.idontwant$}));break}default:{f.skipType(b&7);break}}}return g})),p),h.encode=f=>J(f,h.codec()),h.decode=(f,d)=>Q(f,h.codec(),d)})(n=r.ControlMessage||(r.ControlMessage={}));let s;(function(h){let p;h.codec=()=>(p==null&&(p=Z((f,d,m={})=>{if(m.lengthDelimited!==!1&&d.fork(),f.topicID!=null&&(d.uint32(10),d.string(f.topicID)),f.messageIDs!=null)for(let g of f.messageIDs)d.uint32(18),d.bytes(g);m.lengthDelimited!==!1&&d.ldelim()},(f,d,m={})=>{let g={messageIDs:[]},y=d==null?f.len:f.pos+d;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{g.topicID=f.string();break}case 2:{if(m.limits?.messageIDs!=null&&g.messageIDs.length===m.limits.messageIDs)throw new _e('Decode error - map field "messageIDs" had too many elements');g.messageIDs.push(f.bytes());break}default:{f.skipType(b&7);break}}}return g})),p),h.encode=f=>J(f,h.codec()),h.decode=(f,d)=>Q(f,h.codec(),d)})(s=r.ControlIHave||(r.ControlIHave={}));let o;(function(h){let p;h.codec=()=>(p==null&&(p=Z((f,d,m={})=>{if(m.lengthDelimited!==!1&&d.fork(),f.messageIDs!=null)for(let g of f.messageIDs)d.uint32(10),d.bytes(g);m.lengthDelimited!==!1&&d.ldelim()},(f,d,m={})=>{let g={messageIDs:[]},y=d==null?f.len:f.pos+d;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{if(m.limits?.messageIDs!=null&&g.messageIDs.length===m.limits.messageIDs)throw new _e('Decode error - map field "messageIDs" had too many elements');g.messageIDs.push(f.bytes());break}default:{f.skipType(b&7);break}}}return g})),p),h.encode=f=>J(f,h.codec()),h.decode=(f,d)=>Q(f,h.codec(),d)})(o=r.ControlIWant||(r.ControlIWant={}));let i;(function(h){let p;h.codec=()=>(p==null&&(p=Z((f,d,m={})=>{m.lengthDelimited!==!1&&d.fork(),f.topicID!=null&&(d.uint32(10),d.string(f.topicID)),m.lengthDelimited!==!1&&d.ldelim()},(f,d,m={})=>{let g={},y=d==null?f.len:f.pos+d;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{g.topicID=f.string();break}default:{f.skipType(b&7);break}}}return g})),p),h.encode=f=>J(f,h.codec()),h.decode=(f,d)=>Q(f,h.codec(),d)})(i=r.ControlGraft||(r.ControlGraft={}));let a;(function(h){let p;h.codec=()=>(p==null&&(p=Z((f,d,m={})=>{if(m.lengthDelimited!==!1&&d.fork(),f.topicID!=null&&(d.uint32(10),d.string(f.topicID)),f.peers!=null)for(let g of f.peers)d.uint32(18),r.PeerInfo.codec().encode(g,d);f.backoff!=null&&(d.uint32(24),d.uint64Number(f.backoff)),m.lengthDelimited!==!1&&d.ldelim()},(f,d,m={})=>{let g={peers:[]},y=d==null?f.len:f.pos+d;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{g.topicID=f.string();break}case 2:{if(m.limits?.peers!=null&&g.peers.length===m.limits.peers)throw new _e('Decode error - map field "peers" had too many elements');g.peers.push(r.PeerInfo.codec().decode(f,f.uint32(),{limits:m.limits?.peers$}));break}case 3:{g.backoff=f.uint64Number();break}default:{f.skipType(b&7);break}}}return g})),p),h.encode=f=>J(f,h.codec()),h.decode=(f,d)=>Q(f,h.codec(),d)})(a=r.ControlPrune||(r.ControlPrune={}));let c;(function(h){let p;h.codec=()=>(p==null&&(p=Z((f,d,m={})=>{m.lengthDelimited!==!1&&d.fork(),f.peerID!=null&&(d.uint32(10),d.bytes(f.peerID)),f.signedPeerRecord!=null&&(d.uint32(18),d.bytes(f.signedPeerRecord)),m.lengthDelimited!==!1&&d.ldelim()},(f,d,m={})=>{let g={},y=d==null?f.len:f.pos+d;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{g.peerID=f.bytes();break}case 2:{g.signedPeerRecord=f.bytes();break}default:{f.skipType(b&7);break}}}return g})),p),h.encode=f=>J(f,h.codec()),h.decode=(f,d)=>Q(f,h.codec(),d)})(c=r.PeerInfo||(r.PeerInfo={}));let l;(function(h){let p;h.codec=()=>(p==null&&(p=Z((f,d,m={})=>{if(m.lengthDelimited!==!1&&d.fork(),f.messageIDs!=null)for(let g of f.messageIDs)d.uint32(10),d.bytes(g);m.lengthDelimited!==!1&&d.ldelim()},(f,d,m={})=>{let g={messageIDs:[]},y=d==null?f.len:f.pos+d;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{if(m.limits?.messageIDs!=null&&g.messageIDs.length===m.limits.messageIDs)throw new _e('Decode error - map field "messageIDs" had too many elements');g.messageIDs.push(f.bytes());break}default:{f.skipType(b&7);break}}}return g})),p),h.encode=f=>J(f,h.codec()),h.decode=(f,d)=>Q(f,h.codec(),d)})(l=r.ControlIDontWant||(r.ControlIDontWant={}));let u;r.codec=()=>(u==null&&(u=Z((h,p,f={})=>{if(f.lengthDelimited!==!1&&p.fork(),h.subscriptions!=null)for(let d of h.subscriptions)p.uint32(10),r.SubOpts.codec().encode(d,p);if(h.messages!=null)for(let d of h.messages)p.uint32(18),r.Message.codec().encode(d,p);h.control!=null&&(p.uint32(26),r.ControlMessage.codec().encode(h.control,p)),f.lengthDelimited!==!1&&p.ldelim()},(h,p,f={})=>{let d={subscriptions:[],messages:[]},m=p==null?h.len:h.pos+p;for(;h.pos<m;){let g=h.uint32();switch(g>>>3){case 1:{if(f.limits?.subscriptions!=null&&d.subscriptions.length===f.limits.subscriptions)throw new _e('Decode error - map field "subscriptions" had too many elements');d.subscriptions.push(r.SubOpts.codec().decode(h,h.uint32(),{limits:f.limits?.subscriptions$}));break}case 2:{if(f.limits?.messages!=null&&d.messages.length===f.limits.messages)throw new _e('Decode error - map field "messages" had too many elements');d.messages.push(r.Message.codec().decode(h,h.uint32(),{limits:f.limits?.messages$}));break}case 3:{d.control=r.ControlMessage.codec().decode(h,h.uint32(),{limits:f.limits?.control});break}default:{h.skipType(g&7);break}}}return d})),u),r.encode=h=>J(h,r.codec()),r.decode=(h,p)=>Q(h,r.codec(),p)})(Qn||(Qn={}));var q1=class{gossip;msgs=new Map;msgIdToStrFn;history=[];notValidatedCount=0;constructor(e,t,n){this.gossip=e,this.msgIdToStrFn=n;for(let s=0;s<t;s++)this.history[s]=[]}get size(){return this.msgs.size}put(e,t,n=!1){let{msgIdStr:s}=e;return this.msgs.has(s)?!1:(this.msgs.set(s,{message:t,validated:n,originatingPeers:new Set,iwantCounts:new Map}),this.history[0].push({...e,topic:t.topic}),n||this.notValidatedCount++,!0)}observeDuplicate(e,t){let n=this.msgs.get(e);n!=null&&!n.validated&&n.originatingPeers.add(t)}get(e){return this.msgs.get(this.msgIdToStrFn(e))?.message}getWithIWantCount(e,t){let n=this.msgs.get(e);if(n==null)return null;let s=(n.iwantCounts.get(t)??0)+1;return n.iwantCounts.set(t,s),{msg:n.message,count:s}}getGossipIDs(e){let t=new Map;for(let n=0;n<this.gossip;n++)this.history[n].forEach(s=>{if((this.msgs.get(s.msgIdStr)?.validated??!1)&&e.has(s.topic)){let i=t.get(s.topic);i==null&&(i=[],t.set(s.topic,i)),i.push(s.msgId)}});return t}validate(e){let t=this.msgs.get(e);if(t==null)return null;t.validated||this.notValidatedCount--;let{message:n,originatingPeers:s}=t;return t.validated=!0,t.originatingPeers=new Set,{message:n,originatingPeers:s}}shift(){this.history[this.history.length-1].forEach(t=>{let n=this.msgs.get(t.msgIdStr);n!=null&&(this.msgs.delete(t.msgIdStr),n.validated||this.notValidatedCount--)}),this.history.pop(),this.history.unshift([])}remove(e){let t=this.msgs.get(e);return t==null?null:(this.msgs.delete(e),t)}};var uP;(function(r){r.StrictSign="StrictSign",r.StrictNoSign="StrictNoSign"})(uP||(uP={}));var Us;(function(r){r[r.Signing=0]="Signing",r[r.Anonymous=1]="Anonymous"})(Us||(Us={}));var Vt;(function(r){r.Error="error",r.Ignore="ignore",r.Reject="reject",r.Blacklisted="blacklisted"})(Vt||(Vt={}));var Lt;(function(r){r.InvalidSignature="invalid_signature",r.InvalidSeqno="invalid_seqno",r.InvalidPeerId="invalid_peerid",r.SignaturePresent="signature_present",r.SeqnoPresent="seqno_present",r.FromPresent="from_present",r.TransformFailed="transform_failed"})(Lt||(Lt={}));var Mt;(function(r){r.duplicate="duplicate",r.invalid="invalid",r.valid="valid"})(Mt||(Mt={}));function H6(r){switch(r){case qt.Ignore:return Vt.Ignore;case qt.Reject:return Vt.Reject;default:throw new Error("Unreachable")}}var hP;(function(r){r.forward="forward",r.publish="publish"})(hP||(hP={}));var Gt;(function(r){r.Fanout="fanout",r.Random="random",r.Subscribed="subscribed",r.Outbound="outbound",r.NotEnough="not_enough",r.Opportunistic="opportunistic"})(Gt||(Gt={}));var Hr;(function(r){r.Dc="disconnected",r.BadScore="bad_score",r.Prune="prune",r.Excess="excess"})(Hr||(Hr={}));var Wa;(function(r){r.GraftBackoff="graft_backoff",r.BrokenPromise="broken_promise",r.MessageDeficit="message_deficit",r.IPColocation="IP_colocation"})(Wa||(Wa={}));var ja;(function(r){r.LowScore="low_score",r.MaxIhave="max_ihave",r.MaxIasked="max_iasked"})(ja||(ja={}));var Ga;(function(r){r.graylist="graylist",r.publish="publish",r.gossip="gossip",r.mesh="mesh"})(Ga||(Ga={}));function dP(r,e,t){return{protocolsEnabled:r.gauge({name:"gossipsub_protocol",help:"Status of enabled protocols",labelNames:["protocol"]}),topicSubscriptionStatus:r.gauge({name:"gossipsub_topic_subscription_status",help:"Status of our subscription to this topic",labelNames:["topicStr"]}),topicPeersCount:r.gauge({name:"gossipsub_topic_peer_count",help:"Number of peers subscribed to each topic",labelNames:["topicStr"]}),meshPeerCounts:r.gauge({name:"gossipsub_mesh_peer_count",help:"Number of peers in our mesh",labelNames:["topicStr"]}),meshPeerInclusionEventsFanout:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_fanout_total",help:"Number of times we include peers in a topic mesh for fanout reasons",labelNames:["topic"]}),meshPeerInclusionEventsRandom:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_random_total",help:"Number of times we include peers in a topic mesh for random reasons",labelNames:["topic"]}),meshPeerInclusionEventsSubscribed:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_subscribed_total",help:"Number of times we include peers in a topic mesh for subscribed reasons",labelNames:["topic"]}),meshPeerInclusionEventsOutbound:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_outbound_total",help:"Number of times we include peers in a topic mesh for outbound reasons",labelNames:["topic"]}),meshPeerInclusionEventsNotEnough:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_not_enough_total",help:"Number of times we include peers in a topic mesh for not_enough reasons",labelNames:["topic"]}),meshPeerInclusionEventsOpportunistic:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_opportunistic_total",help:"Number of times we include peers in a topic mesh for opportunistic reasons",labelNames:["topic"]}),meshPeerInclusionEventsUnknown:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_unknown_total",help:"Number of times we include peers in a topic mesh for unknown reasons",labelNames:["topic"]}),meshPeerChurnEventsDisconnected:r.gauge({name:"gossipsub_peer_churn_events_disconnected_total",help:"Number of times we remove peers in a topic mesh for disconnected reasons",labelNames:["topic"]}),meshPeerChurnEventsBadScore:r.gauge({name:"gossipsub_peer_churn_events_bad_score_total",help:"Number of times we remove peers in a topic mesh for bad_score reasons",labelNames:["topic"]}),meshPeerChurnEventsPrune:r.gauge({name:"gossipsub_peer_churn_events_prune_total",help:"Number of times we remove peers in a topic mesh for prune reasons",labelNames:["topic"]}),meshPeerChurnEventsExcess:r.gauge({name:"gossipsub_peer_churn_events_excess_total",help:"Number of times we remove peers in a topic mesh for excess reasons",labelNames:["topic"]}),meshPeerChurnEventsUnknown:r.gauge({name:"gossipsub_peer_churn_events_unknown_total",help:"Number of times we remove peers in a topic mesh for unknown reasons",labelNames:["topic"]}),peersPerProtocol:r.gauge({name:"gossipsub_peers_per_protocol_count",help:"Peers connected for each topic",labelNames:["protocol"]}),heartbeatDuration:r.histogram({name:"gossipsub_heartbeat_duration_seconds",help:"The time it takes to complete one iteration of the heartbeat",buckets:[.01,.1,1]}),heartbeatSkipped:r.gauge({name:"gossipsub_heartbeat_skipped",help:"Heartbeat run took longer than heartbeat interval so next is skipped"}),acceptedMessagesTotal:r.gauge({name:"gossipsub_accepted_messages_total",help:"Total accepted messages for each topic",labelNames:["topic"]}),ignoredMessagesTotal:r.gauge({name:"gossipsub_ignored_messages_total",help:"Total ignored messages for each topic",labelNames:["topic"]}),rejectedMessagesTotal:r.gauge({name:"gossipsub_rejected_messages_total",help:"Total rejected messages for each topic",labelNames:["topic"]}),unknownValidationResultsTotal:r.gauge({name:"gossipsub_unknown_validation_results_total",help:"Total unknown validation results for each topic",labelNames:["topic"]}),asyncValidationMcacheHit:r.gauge({name:"gossipsub_async_validation_mcache_hit_total",help:"Async validation result reported by the user layer",labelNames:["hit"]}),asyncValidationDelayFromFirstSeenSec:r.histogram({name:"gossipsub_async_validation_delay_from_first_seen",help:"Async validation report delay from first seen in second",buckets:[.01,.03,.1,.3,1,3,10]}),asyncValidationUnknownFirstSeen:r.gauge({name:"gossipsub_async_validation_unknown_first_seen_count_total",help:"Async validation report unknown first seen value for message"}),peerReadStreamError:r.gauge({name:"gossipsub_peer_read_stream_err_count_total",help:"Peer read stream error"}),rpcRecvBytes:r.gauge({name:"gossipsub_rpc_recv_bytes_total",help:"RPC recv"}),rpcRecvCount:r.gauge({name:"gossipsub_rpc_recv_count_total",help:"RPC recv"}),rpcRecvSubscription:r.gauge({name:"gossipsub_rpc_recv_subscription_total",help:"RPC recv"}),rpcRecvMessage:r.gauge({name:"gossipsub_rpc_recv_message_total",help:"RPC recv"}),rpcRecvControl:r.gauge({name:"gossipsub_rpc_recv_control_total",help:"RPC recv"}),rpcRecvIHave:r.gauge({name:"gossipsub_rpc_recv_ihave_total",help:"RPC recv"}),rpcRecvIWant:r.gauge({name:"gossipsub_rpc_recv_iwant_total",help:"RPC recv"}),rpcRecvGraft:r.gauge({name:"gossipsub_rpc_recv_graft_total",help:"RPC recv"}),rpcRecvPrune:r.gauge({name:"gossipsub_rpc_recv_prune_total",help:"RPC recv"}),rpcDataError:r.gauge({name:"gossipsub_rpc_data_err_count_total",help:"RPC data error"}),rpcRecvError:r.gauge({name:"gossipsub_rpc_recv_err_count_total",help:"RPC recv error"}),rpcRecvNotAccepted:r.gauge({name:"gossipsub_rpc_rcv_not_accepted_total",help:"Total count of RPC dropped because acceptFrom() == false"}),rpcSentBytes:r.gauge({name:"gossipsub_rpc_sent_bytes_total",help:"RPC sent"}),rpcSentCount:r.gauge({name:"gossipsub_rpc_sent_count_total",help:"RPC sent"}),rpcSentSubscription:r.gauge({name:"gossipsub_rpc_sent_subscription_total",help:"RPC sent"}),rpcSentMessage:r.gauge({name:"gossipsub_rpc_sent_message_total",help:"RPC sent"}),rpcSentControl:r.gauge({name:"gossipsub_rpc_sent_control_total",help:"RPC sent"}),rpcSentIHave:r.gauge({name:"gossipsub_rpc_sent_ihave_total",help:"RPC sent"}),rpcSentIWant:r.gauge({name:"gossipsub_rpc_sent_iwant_total",help:"RPC sent"}),rpcSentGraft:r.gauge({name:"gossipsub_rpc_sent_graft_total",help:"RPC sent"}),rpcSentPrune:r.gauge({name:"gossipsub_rpc_sent_prune_total",help:"RPC sent"}),rpcSentIDontWant:r.gauge({name:"gossipsub_rpc_sent_idontwant_total",help:"RPC sent"}),msgPublishCount:r.gauge({name:"gossipsub_msg_publish_count_total",help:"Total count of msg published by topic",labelNames:["topic"]}),msgPublishPeersByTopic:r.gauge({name:"gossipsub_msg_publish_peers_total",help:"Total count of peers that we publish a msg to",labelNames:["topic"]}),directPeersPublishedTotal:r.gauge({name:"gossipsub_direct_peers_published_total",help:"Total direct peers that we publish a msg to",labelNames:["topic"]}),floodsubPeersPublishedTotal:r.gauge({name:"gossipsub_floodsub_peers_published_total",help:"Total floodsub peers that we publish a msg to",labelNames:["topic"]}),meshPeersPublishedTotal:r.gauge({name:"gossipsub_mesh_peers_published_total",help:"Total mesh peers that we publish a msg to",labelNames:["topic"]}),fanoutPeersPublishedTotal:r.gauge({name:"gossipsub_fanout_peers_published_total",help:"Total fanout peers that we publish a msg to",labelNames:["topic"]}),msgPublishBytes:r.gauge({name:"gossipsub_msg_publish_bytes_total",help:"Total count of msg publish data.length bytes",labelNames:["topic"]}),msgPublishTime:r.histogram({name:"gossipsub_msg_publish_seconds",help:"Total time in seconds to publish a message",buckets:[.001,.002,.005,.01,.1,.5,1],labelNames:["topic"]}),msgForwardCount:r.gauge({name:"gossipsub_msg_forward_count_total",help:"Total count of msg forwarded by topic",labelNames:["topic"]}),msgForwardPeers:r.gauge({name:"gossipsub_msg_forward_peers_total",help:"Total count of peers that we forward a msg to",labelNames:["topic"]}),msgReceivedPreValidation:r.gauge({name:"gossipsub_msg_received_prevalidation_total",help:"Total count of recv msgs before any validation",labelNames:["topic"]}),msgReceivedError:r.gauge({name:"gossipsub_msg_received_error_total",help:"Total count of recv msgs error",labelNames:["topic"]}),prevalidationInvalidTotal:r.gauge({name:"gossipsub_pre_validation_invalid_total",help:"Total count of invalid messages received",labelNames:["topic"]}),prevalidationValidTotal:r.gauge({name:"gossipsub_pre_validation_valid_total",help:"Total count of valid messages received",labelNames:["topic"]}),prevalidationDuplicateTotal:r.gauge({name:"gossipsub_pre_validation_duplicate_total",help:"Total count of duplicate messages received",labelNames:["topic"]}),prevalidationUnknownTotal:r.gauge({name:"gossipsub_pre_validation_unknown_status_total",help:"Total count of unknown_status messages received",labelNames:["topic"]}),msgReceivedInvalid:r.gauge({name:"gossipsub_msg_received_invalid_total",help:"Tracks specific reason of invalid",labelNames:["error"]}),msgReceivedInvalidByTopic:r.gauge({name:"gossipsub_msg_received_invalid_by_topic_total",help:"Tracks specific invalid message by topic",labelNames:["topic"]}),duplicateMsgDeliveryDelay:r.histogram({name:"gossisub_duplicate_msg_delivery_delay_seconds",help:"Time since the 1st duplicated message validated",labelNames:["topic"],buckets:[.25*t.maxMeshMessageDeliveriesWindowSec,.5*t.maxMeshMessageDeliveriesWindowSec,Number(t.maxMeshMessageDeliveriesWindowSec),2*t.maxMeshMessageDeliveriesWindowSec,4*t.maxMeshMessageDeliveriesWindowSec]}),duplicateMsgLateDelivery:r.gauge({name:"gossisub_duplicate_msg_late_delivery_total",help:"Total count of late duplicate message delivery by topic, which triggers P3 penalty",labelNames:["topic"]}),duplicateMsgIgnored:r.gauge({name:"gossisub_ignored_published_duplicate_msgs_total",help:"Total count of published duplicate message ignored by topic",labelNames:["topic"]}),scoreFnCalls:r.gauge({name:"gossipsub_score_fn_calls_total",help:"Total times score() is called"}),scoreFnRuns:r.gauge({name:"gossipsub_score_fn_runs_total",help:"Total times score() call actually computed computeScore(), no cache"}),scoreCachedDelta:r.histogram({name:"gossipsub_score_cache_delta",help:"Delta of score between cached values that expired",buckets:[10,100,1e3]}),peersByScoreThreshold:r.gauge({name:"gossipsub_peers_by_score_threshold_count",help:"Current count of peers by score threshold",labelNames:["threshold"]}),score:r.avgMinMax({name:"gossipsub_score",help:"Avg min max of gossip scores"}),scoreWeights:r.avgMinMax({name:"gossipsub_score_weights",help:"Separate score weights",labelNames:["topic","p"]}),scorePerMesh:r.avgMinMax({name:"gossipsub_score_per_mesh",help:"Histogram of the scores for each mesh topic",labelNames:["topic"]}),scoringPenalties:r.gauge({name:"gossipsub_scoring_penalties_total",help:"A counter of the kind of penalties being applied to peers",labelNames:["penalty"]}),behaviourPenalty:r.histogram({name:"gossipsub_peer_stat_behaviour_penalty",help:"Current peer stat behaviour_penalty at each scrape",buckets:[.25*t.behaviourPenaltyThreshold,.5*t.behaviourPenaltyThreshold,Number(t.behaviourPenaltyThreshold),2*t.behaviourPenaltyThreshold,4*t.behaviourPenaltyThreshold]}),ihaveRcvIgnored:r.gauge({name:"gossipsub_ihave_rcv_ignored_total",help:"Total received IHAVE messages that we ignore for some reason",labelNames:["reason"]}),ihaveRcvMsgids:r.gauge({name:"gossipsub_ihave_rcv_msgids_total",help:"Total received IHAVE messages by topic",labelNames:["topic"]}),ihaveRcvNotSeenMsgids:r.gauge({name:"gossipsub_ihave_rcv_not_seen_msgids_total",help:"Total messages per topic we do not have, not actual requests",labelNames:["topic"]}),iwantRcvMsgids:r.gauge({name:"gossipsub_iwant_rcv_msgids_total",help:"Total received IWANT messages by topic",labelNames:["topic"]}),iwantRcvDonthaveMsgids:r.gauge({name:"gossipsub_iwant_rcv_dont_have_msgids_total",help:"Total requested messageIDs that we do not have"}),idontwantRcvMsgids:r.gauge({name:"gossipsub_idontwant_rcv_msgids_total",help:"Total received IDONTWANT messages"}),idontwantRcvDonthaveMsgids:r.gauge({name:"gossipsub_idontwant_rcv_dont_have_msgids_total",help:"Total received IDONTWANT messageIDs that we do not have in mcache"}),iwantPromiseStarted:r.gauge({name:"gossipsub_iwant_promise_sent_total",help:"Total count of started IWANT promises"}),iwantPromiseResolved:r.gauge({name:"gossipsub_iwant_promise_resolved_total",help:"Total count of resolved IWANT promises"}),iwantPromiseResolvedFromDuplicate:r.gauge({name:"gossipsub_iwant_promise_resolved_from_duplicate_total",help:"Total count of resolved IWANT promises from duplicate messages"}),iwantPromiseResolvedPeers:r.gauge({name:"gossipsub_iwant_promise_resolved_peers",help:"Total count of peers we have asked IWANT promises that are resolved"}),iwantPromiseBroken:r.gauge({name:"gossipsub_iwant_promise_broken",help:"Total count of broken IWANT promises"}),iwantMessagePruned:r.gauge({name:"gossipsub_iwant_message_pruned",help:"Total count of pruned IWANT messages"}),iwantPromiseDeliveryTime:r.histogram({name:"gossipsub_iwant_promise_delivery_seconds",help:"Histogram of delivery time of resolved IWANT promises",buckets:[.5*t.gossipPromiseExpireSec,Number(t.gossipPromiseExpireSec),2*t.gossipPromiseExpireSec,4*t.gossipPromiseExpireSec]}),iwantPromiseUntracked:r.gauge({name:"gossip_iwant_promise_untracked",help:"Total count of untracked IWANT promise"}),connectedPeersBackoffSec:r.histogram({name:"gossipsub_connected_peers_backoff_seconds",help:"Backoff time in seconds",buckets:[1,2,4,10,20,60,120]}),cacheSize:r.gauge({name:"gossipsub_cache_size",help:"Unbounded cache sizes",labelNames:["cache"]}),mcacheSize:r.gauge({name:"gossipsub_mcache_size",help:"Current mcache msg count"}),mcacheNotValidatedCount:r.gauge({name:"gossipsub_mcache_not_validated_count",help:"Current mcache msg count not validated"}),fastMsgIdCacheCollision:r.gauge({name:"gossipsub_fastmsgid_cache_collision_total",help:"Total count of key collisions on fastmsgid cache put"}),newConnectionCount:r.gauge({name:"gossipsub_new_connection_total",help:"Total new connection by status",labelNames:["status"]}),topicStrToLabel:e,toTopic(n){return this.topicStrToLabel.get(n)??n},onJoin(n){this.topicSubscriptionStatus.set({topicStr:n},1),this.meshPeerCounts.set({topicStr:n},0)},onLeave(n){this.topicSubscriptionStatus.set({topicStr:n},0),this.meshPeerCounts.set({topicStr:n},0)},onAddToMesh(n,s,o){let i=this.toTopic(n);switch(s){case Gt.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:i},o);break;case Gt.Random:this.meshPeerInclusionEventsRandom.inc({topic:i},o);break;case Gt.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:i},o);break;case Gt.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:i},o);break;case Gt.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:i},o);break;case Gt.Opportunistic:this.meshPeerInclusionEventsOpportunistic.inc({topic:i},o);break;default:this.meshPeerInclusionEventsUnknown.inc({topic:i},o);break}},onRemoveFromMesh(n,s,o){let i=this.toTopic(n);switch(s){case Hr.Dc:this.meshPeerChurnEventsDisconnected.inc({topic:i},o);break;case Hr.BadScore:this.meshPeerChurnEventsBadScore.inc({topic:i},o);break;case Hr.Prune:this.meshPeerChurnEventsPrune.inc({topic:i},o);break;case Hr.Excess:this.meshPeerChurnEventsExcess.inc({topic:i},o);break;default:this.meshPeerChurnEventsUnknown.inc({topic:i},o);break}},onReportValidation(n,s,o){if(this.asyncValidationMcacheHit.inc({hit:n!=null?"hit":"miss"}),n!=null){let i=this.toTopic(n.message.topic);switch(s){case qt.Accept:this.acceptedMessagesTotal.inc({topic:i});break;case qt.Ignore:this.ignoredMessagesTotal.inc({topic:i});break;case qt.Reject:this.rejectedMessagesTotal.inc({topic:i});break;default:this.unknownValidationResultsTotal.inc({topic:i});break}}o!=null?this.asyncValidationDelayFromFirstSeenSec.observe((Date.now()-o)/1e3):this.asyncValidationUnknownFirstSeen.inc()},onScorePenalty(n){this.scoringPenalties.inc({penalty:n},1)},onIhaveRcv(n,s,o){let i=this.toTopic(n);this.ihaveRcvMsgids.inc({topic:i},s),this.ihaveRcvNotSeenMsgids.inc({topic:i},o)},onIwantRcv(n,s){for(let[o,i]of n){let a=this.toTopic(o);this.iwantRcvMsgids.inc({topic:a},i)}this.iwantRcvDonthaveMsgids.inc(s)},onIdontwantRcv(n,s){this.idontwantRcvMsgids.inc(n),this.idontwantRcvDonthaveMsgids.inc(s)},onForwardMsg(n,s){let o=this.toTopic(n);this.msgForwardCount.inc({topic:o},1),this.msgForwardPeers.inc({topic:o},s)},onPublishMsg(n,s,o,i,a){let c=this.toTopic(n);this.msgPublishCount.inc({topic:c},1),this.msgPublishBytes.inc({topic:c},o*i),this.msgPublishPeersByTopic.inc({topic:c},o),this.directPeersPublishedTotal.inc({topic:c},s.direct),this.floodsubPeersPublishedTotal.inc({topic:c},s.floodsub),this.meshPeersPublishedTotal.inc({topic:c},s.mesh),this.fanoutPeersPublishedTotal.inc({topic:c},s.fanout),this.msgPublishTime.observe({topic:c},a/1e3)},onMsgRecvPreValidation(n){let s=this.toTopic(n);this.msgReceivedPreValidation.inc({topic:s},1)},onMsgRecvError(n){let s=this.toTopic(n);this.msgReceivedError.inc({topic:s},1)},onPrevalidationResult(n,s){let o=this.toTopic(n);switch(s){case Mt.duplicate:this.prevalidationDuplicateTotal.inc({topic:o});break;case Mt.invalid:this.prevalidationInvalidTotal.inc({topic:o});break;case Mt.valid:this.prevalidationValidTotal.inc({topic:o});break;default:this.prevalidationUnknownTotal.inc({topic:o});break}},onMsgRecvInvalid(n,s){let o=this.toTopic(n),i=s.reason===Vt.Error?s.error:s.reason;this.msgReceivedInvalid.inc({error:i},1),this.msgReceivedInvalidByTopic.inc({topic:o},1)},onDuplicateMsgDelivery(n,s,o){let i=this.toTopic(n);this.duplicateMsgDeliveryDelay.observe({topic:i},s/1e3),o&&this.duplicateMsgLateDelivery.inc({topic:i},1)},onPublishDuplicateMsg(n){let s=this.toTopic(n);this.duplicateMsgIgnored.inc({topic:s},1)},onPeerReadStreamError(){this.peerReadStreamError.inc(1)},onRpcRecvError(){this.rpcRecvError.inc(1)},onRpcDataError(){this.rpcDataError.inc(1)},onRpcRecv(n,s){this.rpcRecvBytes.inc(s),this.rpcRecvCount.inc(1),n.subscriptions!=null&&this.rpcRecvSubscription.inc(n.subscriptions.length),n.messages!=null&&this.rpcRecvMessage.inc(n.messages.length),n.control!=null&&(this.rpcRecvControl.inc(1),n.control.ihave!=null&&this.rpcRecvIHave.inc(n.control.ihave.length),n.control.iwant!=null&&this.rpcRecvIWant.inc(n.control.iwant.length),n.control.graft!=null&&this.rpcRecvGraft.inc(n.control.graft.length),n.control.prune!=null&&this.rpcRecvPrune.inc(n.control.prune.length))},onRpcSent(n,s){if(this.rpcSentBytes.inc(s),this.rpcSentCount.inc(1),n.subscriptions!=null&&this.rpcSentSubscription.inc(n.subscriptions.length),n.messages!=null&&this.rpcSentMessage.inc(n.messages.length),n.control!=null){let o=n.control.ihave?.length??0,i=n.control.iwant?.length??0,a=n.control.graft?.length??0,c=n.control.prune?.length??0,l=n.control.idontwant?.length??0;o>0&&this.rpcSentIHave.inc(o),i>0&&this.rpcSentIWant.inc(i),a>0&&this.rpcSentGraft.inc(a),c>0&&this.rpcSentPrune.inc(c),l>0&&this.rpcSentIDontWant.inc(l),(o>0||i>0||a>0||c>0||l>0)&&this.rpcSentControl.inc(1)}},registerScores(n,s){let o=0,i=0,a=0,c=0;for(let l of n)l>=s.graylistThreshold&&o++,l>=s.publishThreshold&&i++,l>=s.gossipThreshold&&a++,l>=0&&c++;this.peersByScoreThreshold.set({threshold:Ga.graylist},o),this.peersByScoreThreshold.set({threshold:Ga.publish},i),this.peersByScoreThreshold.set({threshold:Ga.gossip},a),this.peersByScoreThreshold.set({threshold:Ga.mesh},c),this.score.set(n)},registerScoreWeights(n){for(let[s,o]of n.byTopic)this.scoreWeights.set({topic:s,p:"p1"},o.p1w),this.scoreWeights.set({topic:s,p:"p2"},o.p2w),this.scoreWeights.set({topic:s,p:"p3"},o.p3w),this.scoreWeights.set({topic:s,p:"p3b"},o.p3bw),this.scoreWeights.set({topic:s,p:"p4"},o.p4w);this.scoreWeights.set({p:"p5"},n.p5w),this.scoreWeights.set({p:"p6"},n.p6w),this.scoreWeights.set({p:"p7"},n.p7w)},registerScorePerMesh(n,s){let o=new Map;n.forEach((i,a)=>{let c=this.topicStrToLabel.get(a)??"unknown",l=o.get(c);l==null&&(l=new Set,o.set(c,l)),i.forEach(u=>l?.add(u))});for(let[i,a]of o){let c=[];a.forEach(l=>{c.push(s.get(l)??0)}),this.scorePerMesh.set({topic:i},c)}}}}var Ie=class extends Error{static name="InvalidPeerScoreParamsError";constructor(e="Invalid peer score params"){super(e),this.name="InvalidPeerScoreParamsError"}};var KV={topics:{},topicScoreCap:10,appSpecificScore:()=>0,appSpecificWeight:10,IPColocationFactorWeight:-5,IPColocationFactorThreshold:10,IPColocationFactorWhitelist:new Set,behaviourPenaltyWeight:-10,behaviourPenaltyThreshold:0,behaviourPenaltyDecay:.2,decayInterval:1e3,decayToZero:.1,retainScore:3600*1e3},FV={topicWeight:.5,timeInMeshWeight:1,timeInMeshQuantum:1,timeInMeshCap:3600,firstMessageDeliveriesWeight:1,firstMessageDeliveriesDecay:.5,firstMessageDeliveriesCap:2e3,meshMessageDeliveriesWeight:-1,meshMessageDeliveriesDecay:.5,meshMessageDeliveriesCap:100,meshMessageDeliveriesThreshold:20,meshMessageDeliveriesWindow:10,meshMessageDeliveriesActivation:5e3,meshFailurePenaltyWeight:-1,meshFailurePenaltyDecay:.5,invalidMessageDeliveriesWeight:-1,invalidMessageDeliveriesDecay:.3};function fP(r={}){return{...KV,...r,topics:r.topics!=null?Object.entries(r.topics).reduce((e,[t,n])=>(e[t]=zV(n),e),{}):{}}}function zV(r={}){return{...FV,...r}}function pP(r){for(let[e,t]of Object.entries(r.topics))try{$V(t)}catch(n){throw new Ie(`invalid score parameters for topic ${e}: ${n.message}`)}if(r.topicScoreCap<0)throw new Ie("invalid topic score cap; must be positive (or 0 for no cap)");if(r.appSpecificScore===null||r.appSpecificScore===void 0)throw new Ie("missing application specific score function");if(r.IPColocationFactorWeight>0)throw new Ie("invalid IPColocationFactorWeight; must be negative (or 0 to disable)");if(r.IPColocationFactorWeight!==0&&r.IPColocationFactorThreshold<1)throw new Ie("invalid IPColocationFactorThreshold; must be at least 1");if(r.behaviourPenaltyWeight>0)throw new Ie("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)");if(r.behaviourPenaltyWeight!==0&&(r.behaviourPenaltyDecay<=0||r.behaviourPenaltyDecay>=1))throw new Ie("invalid BehaviourPenaltyDecay; must be between 0 and 1");if(r.decayInterval<1e3)throw new Ie("invalid DecayInterval; must be at least 1s");if(r.decayToZero<=0||r.decayToZero>=1)throw new Ie("invalid DecayToZero; must be between 0 and 1")}function $V(r){if(r.topicWeight<0)throw new Ie("invalid topic weight; must be >= 0");if(r.timeInMeshQuantum===0)throw new Ie("invalid TimeInMeshQuantum; must be non zero");if(r.timeInMeshWeight<0)throw new Ie("invalid TimeInMeshWeight; must be positive (or 0 to disable)");if(r.timeInMeshWeight!==0&&r.timeInMeshQuantum<=0)throw new Ie("invalid TimeInMeshQuantum; must be positive");if(r.timeInMeshWeight!==0&&r.timeInMeshCap<=0)throw new Ie("invalid TimeInMeshCap; must be positive");if(r.firstMessageDeliveriesWeight<0)throw new Ie("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)");if(r.firstMessageDeliveriesWeight!==0&&(r.firstMessageDeliveriesDecay<=0||r.firstMessageDeliveriesDecay>=1))throw new Ie("invalid FirstMessageDeliveriesDecay; must be between 0 and 1");if(r.firstMessageDeliveriesWeight!==0&&r.firstMessageDeliveriesCap<=0)throw new Ie("invalid FirstMessageDeliveriesCap; must be positive");if(r.meshMessageDeliveriesWeight>0)throw new Ie("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)");if(r.meshMessageDeliveriesWeight!==0&&(r.meshMessageDeliveriesDecay<=0||r.meshMessageDeliveriesDecay>=1))throw new Ie("invalid MeshMessageDeliveriesDecay; must be between 0 and 1");if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesCap<=0)throw new Ie("invalid MeshMessageDeliveriesCap; must be positive");if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesThreshold<=0)throw new Ie("invalid MeshMessageDeliveriesThreshold; must be positive");if(r.meshMessageDeliveriesWindow<0)throw new Ie("invalid MeshMessageDeliveriesWindow; must be non-negative");if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesActivation<1e3)throw new Ie("invalid MeshMessageDeliveriesActivation; must be at least 1s");if(r.meshFailurePenaltyWeight>0)throw new Ie("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)");if(r.meshFailurePenaltyWeight!==0&&(r.meshFailurePenaltyDecay<=0||r.meshFailurePenaltyDecay>=1))throw new Ie("invalid MeshFailurePenaltyDecay; must be between 0 and 1");if(r.invalidMessageDeliveriesWeight>0)throw new Ie("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)");if(r.invalidMessageDeliveriesDecay<=0||r.invalidMessageDeliveriesDecay>=1)throw new Ie("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1")}var HV={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function mP(r={}){return{...HV,...r}}function G1(r,e,t=()=>!0){let n=new Set;if(e<=0)return n;for(let s of r){if(n.size>=e)break;t(s)&&(n.add(s),r.delete(s))}return n}function gP(r,e){return G1(r,e,()=>!0)}var V1=class extends Map{getDefault;constructor(e){super(),this.getDefault=e}getOrDefault(e){let t=super.get(e);return t===void 0&&(t=this.getDefault(),this.set(e,t)),t}};function yP(r,e,t,n){let s=0;Object.entries(e.topics).forEach(([i,a])=>{let c=t.topics[i];if(c===void 0)return;let l=0;if(a.inMesh){let f=a.meshTime/c.timeInMeshQuantum;f>c.timeInMeshCap&&(f=c.timeInMeshCap),l+=f*c.timeInMeshWeight}let u=a.firstMessageDeliveries;if(u>c.firstMessageDeliveriesCap&&(u=c.firstMessageDeliveriesCap),l+=u*c.firstMessageDeliveriesWeight,a.meshMessageDeliveriesActive&&a.meshMessageDeliveries<c.meshMessageDeliveriesThreshold){let f=c.meshMessageDeliveriesThreshold-a.meshMessageDeliveries,d=f*f;l+=d*c.meshMessageDeliveriesWeight}let h=a.meshFailurePenalty;l+=h*c.meshFailurePenaltyWeight;let p=a.invalidMessageDeliveries*a.invalidMessageDeliveries;l+=p*c.invalidMessageDeliveriesWeight,s+=l*c.topicWeight}),t.topicScoreCap>0&&s>t.topicScoreCap&&(s=t.topicScoreCap);let o=t.appSpecificScore(r);if(s+=o*t.appSpecificWeight,e.knownIPs.forEach(i=>{if(t.IPColocationFactorWhitelist.has(i))return;let a=n.get(i),c=a!=null?a.size:0;if(c>t.IPColocationFactorThreshold){let l=c-t.IPColocationFactorThreshold,u=l*l;s+=u*t.IPColocationFactorWeight}}),e.behaviourPenalty>t.behaviourPenaltyThreshold){let i=e.behaviourPenalty-t.behaviourPenaltyThreshold,a=i*i;s+=a*t.behaviourPenaltyWeight}return s}var xP=ie(wP(),1);var Wt;(function(r){r[r.unknown=0]="unknown",r[r.valid=1]="valid",r[r.invalid=2]="invalid",r[r.ignored=3]="ignored"})(Wt||(Wt={}));var W1=class{records;queue;constructor(){this.records=new Map,this.queue=new xP.default}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(t!=null)return t;t={status:Wt.unknown,firstSeenTsMs:Date.now(),validated:0,peers:new Set},this.records.set(e,t);let n={msgId:e,expire:Date.now()+12e4};return this.queue.push(n),t}gc(){let e=Date.now(),t=this.queue.peekFront();for(;t!=null&&t.expire<e;)this.records.delete(t.msgId),this.queue.shift(),t=this.queue.peekFront()}clear(){this.records.clear(),this.queue.clear()}};var j1=class{params;metrics;peerStats=new Map;peerIPs=new V1(()=>new Set);scoreCache=new Map;deliveryRecords=new W1;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,n,s){this.params=e,this.metrics=t,pP(e),this.scoreCacheValidityMs=s.scoreCacheValidityMs,this.computeScore=s.computeScore??yP,this.log=n.forComponent("libp2p:gossipsub:score")}get size(){return this.peerStats.size}start(){if(this._backgroundInterval!=null){this.log("Peer score already running");return}this._backgroundInterval=setInterval(()=>{this.background()},this.params.decayInterval),this.log("started")}stop(){if(this._backgroundInterval==null){this.log("Peer score already stopped");return}clearInterval(this._backgroundInterval),delete this._backgroundInterval,this.peerIPs.clear(),this.peerStats.clear(),this.deliveryRecords.clear(),this.log("stopped")}background(){this.refreshScores(),this.deliveryRecords.gc()}dumpPeerScoreStats(){return Object.fromEntries(Array.from(this.peerStats.entries()).map(([e,t])=>[e,t]))}messageFirstSeenTimestampMs(e){let t=this.deliveryRecords.getRecord(e);return t!=null?t.firstSeenTsMs:null}refreshScores(){let e=Date.now(),t=this.params.decayToZero;this.peerStats.forEach((n,s)=>{if(!n.connected){e>n.expire&&(this.removeIPsForPeer(s,n.knownIPs),this.peerStats.delete(s),this.scoreCache.delete(s));return}Object.entries(n.topics).forEach(([o,i])=>{let a=this.params.topics[o];a!==void 0&&(i.firstMessageDeliveries*=a.firstMessageDeliveriesDecay,i.firstMessageDeliveries<t&&(i.firstMessageDeliveries=0),i.meshMessageDeliveries*=a.meshMessageDeliveriesDecay,i.meshMessageDeliveries<t&&(i.meshMessageDeliveries=0),i.meshFailurePenalty*=a.meshFailurePenaltyDecay,i.meshFailurePenalty<t&&(i.meshFailurePenalty=0),i.invalidMessageDeliveries*=a.invalidMessageDeliveriesDecay,i.invalidMessageDeliveries<t&&(i.invalidMessageDeliveries=0),i.inMesh&&(i.meshTime=e-i.graftTime,i.meshTime>a.meshMessageDeliveriesActivation&&(i.meshMessageDeliveriesActive=!0)))}),n.behaviourPenalty*=this.params.behaviourPenaltyDecay,n.behaviourPenalty<t&&(n.behaviourPenalty=0)})}score(e){this.metrics?.scoreFnCalls.inc();let t=this.peerStats.get(e);if(t==null)return 0;let n=Date.now(),s=this.scoreCache.get(e);if(s!=null&&s.cacheUntil>n)return s.score;this.metrics?.scoreFnRuns.inc();let o=this.computeScore(e,t,this.params,this.peerIPs),i=n+this.scoreCacheValidityMs;return s!=null?(this.metrics?.scoreCachedDelta.observe(Math.abs(o-s.score)),s.score=o,s.cacheUntil=i):this.scoreCache.set(e,{score:o,cacheUntil:i}),o}addPenalty(e,t,n){let s=this.peerStats.get(e);s!=null&&(s.behaviourPenalty+=t,this.metrics?.onScorePenalty(n))}addPeer(e){let t={connected:!0,expire:0,topics:{},knownIPs:new Set,behaviourPenalty:0};this.peerStats.set(e,t)}addIP(e,t){let n=this.peerStats.get(e);n?.knownIPs.add(t),this.peerIPs.getOrDefault(t).add(e)}removeIP(e,t){let n=this.peerStats.get(e);n?.knownIPs.delete(t);let s=this.peerIPs.get(t);s!=null&&(s.delete(e),s.size===0&&this.peerIPs.delete(t))}removePeer(e){let t=this.peerStats.get(e);if(t!=null){if(this.score(e)>0){this.removeIPsForPeer(e,t.knownIPs),this.peerStats.delete(e);return}Object.entries(t.topics).forEach(([n,s])=>{s.firstMessageDeliveries=0;let o=this.params.topics[n].meshMessageDeliveriesThreshold;if(s.inMesh&&s.meshMessageDeliveriesActive&&s.meshMessageDeliveries<o){let i=o-s.meshMessageDeliveries;s.meshFailurePenalty+=i*i}s.inMesh=!1,s.meshMessageDeliveriesActive=!1}),t.connected=!1,t.expire=Date.now()+this.params.retainScore}}graft(e,t){let n=this.peerStats.get(e);if(n!=null){let s=this.getPtopicStats(n,t);s!=null&&(s.inMesh=!0,s.graftTime=Date.now(),s.meshTime=0,s.meshMessageDeliveriesActive=!1)}}prune(e,t){let n=this.peerStats.get(e);if(n!=null){let s=this.getPtopicStats(n,t);if(s!=null){let o=this.params.topics[t].meshMessageDeliveriesThreshold;if(s.meshMessageDeliveriesActive&&s.meshMessageDeliveries<o){let i=o-s.meshMessageDeliveries;s.meshFailurePenalty+=i*i}s.meshMessageDeliveriesActive=!1,s.inMesh=!1}}}validateMessage(e){this.deliveryRecords.ensureRecord(e)}deliverMessage(e,t,n){this.markFirstMessageDelivery(e,n);let s=this.deliveryRecords.ensureRecord(t),o=Date.now();if(s.status!==Wt.unknown){this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,o-s.firstSeenTsMs,Wt[s.status]);return}s.status=Wt.valid,s.validated=o,s.peers.forEach(i=>{i!==e.toString()&&this.markDuplicateMessageDelivery(i,n)})}rejectInvalidMessage(e,t){this.markInvalidMessageDelivery(e,t)}rejectMessage(e,t,n,s){switch(s){case Vt.Error:this.markInvalidMessageDelivery(e,n);return;case Vt.Blacklisted:return}let o=this.deliveryRecords.ensureRecord(t);if(o.status!==Wt.unknown){this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-o.firstSeenTsMs,Wt[o.status]);return}if(s===Vt.Ignore){o.status=Wt.ignored,o.peers.clear();return}o.status=Wt.invalid,this.markInvalidMessageDelivery(e,n),o.peers.forEach(i=>{this.markInvalidMessageDelivery(i,n)}),o.peers.clear()}duplicateMessage(e,t,n){let s=this.deliveryRecords.ensureRecord(t);if(!s.peers.has(e))switch(s.status){case Wt.unknown:s.peers.add(e);break;case Wt.valid:s.peers.add(e),this.markDuplicateMessageDelivery(e,n,s.validated);break;case Wt.invalid:this.markInvalidMessageDelivery(e,n);break;case Wt.ignored:break}}markInvalidMessageDelivery(e,t){let n=this.peerStats.get(e);if(n!=null){let s=this.getPtopicStats(n,t);s!=null&&(s.invalidMessageDeliveries+=1)}}markFirstMessageDelivery(e,t){let n=this.peerStats.get(e);if(n!=null){let s=this.getPtopicStats(n,t);if(s!=null){let o=this.params.topics[t].firstMessageDeliveriesCap;s.firstMessageDeliveries=Math.min(o,s.firstMessageDeliveries+1),s.inMesh&&(o=this.params.topics[t].meshMessageDeliveriesCap,s.meshMessageDeliveries=Math.min(o,s.meshMessageDeliveries+1))}}}markDuplicateMessageDelivery(e,t,n){let s=this.peerStats.get(e);if(s!=null){let o=n!==void 0?Date.now():0,i=this.getPtopicStats(s,t);if(i!=null&&i.inMesh){let a=this.params.topics[t];if(n!==void 0){let l=o-n,u=l>a.meshMessageDeliveriesWindow;if(this.metrics?.onDuplicateMsgDelivery(t,l,u),u)return}let c=a.meshMessageDeliveriesCap;i.meshMessageDeliveries=Math.min(c,i.meshMessageDeliveries+1)}}}removeIPsForPeer(e,t){for(let n of t){let s=this.peerIPs.get(n);s!=null&&(s.delete(e),s.size===0&&this.peerIPs.delete(n))}}getPtopicStats(e,t){let n=e.topics[t];return n!==void 0?n:this.params.topics[t]!==void 0?(n={inMesh:!1,graftTime:0,meshTime:0,firstMessageDeliveries:0,meshMessageDeliveries:0,meshMessageDeliveriesActive:!1,meshFailurePenalty:0,invalidMessageDeliveries:0},e.topics[t]=n,n):null}};function qV(r,e,t,n,s){let o=0,i=new Map;if(Object.entries(e.topics).forEach(([p,f])=>{let d=s.get(p)??"unknown",m=t.topics[p];if(m===void 0)return;let g=i.get(d);g==null&&(g={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},i.set(d,g));let y=0,b=0,w=0,x=0,v=0;if(f.inMesh){let A=Math.max(f.meshTime/m.timeInMeshQuantum,m.timeInMeshCap);y+=A*m.timeInMeshWeight}let S=f.firstMessageDeliveries;if(S>m.firstMessageDeliveriesCap&&(S=m.firstMessageDeliveriesCap),b+=S*m.firstMessageDeliveriesWeight,f.meshMessageDeliveriesActive&&f.meshMessageDeliveries<m.meshMessageDeliveriesThreshold){let A=m.meshMessageDeliveriesThreshold-f.meshMessageDeliveries,X=A*A;w+=X*m.meshMessageDeliveriesWeight}let E=f.meshFailurePenalty;x+=E*m.meshFailurePenaltyWeight;let I=f.invalidMessageDeliveries*f.invalidMessageDeliveries;v+=I*m.invalidMessageDeliveriesWeight,o+=(y+b+w+x+v)*m.topicWeight,g.p1w+=y,g.p2w+=b,g.p3w+=w,g.p3bw+=x,g.p4w+=v}),t.topicScoreCap>0&&o>t.topicScoreCap){o=t.topicScoreCap;let p=t.topicScoreCap/o;for(let f of i.values())f.p1w*=p,f.p2w*=p,f.p3w*=p,f.p3bw*=p,f.p4w*=p}let a=0,c=0,l=0,u=t.appSpecificScore(r);a+=u*t.appSpecificWeight,e.knownIPs.forEach(p=>{if(t.IPColocationFactorWhitelist.has(p))return;let f=n.get(p),d=f!=null?f.size:0;if(d>t.IPColocationFactorThreshold){let m=d-t.IPColocationFactorThreshold,g=m*m;c+=g*t.IPColocationFactorWeight}});let h=e.behaviourPenalty*e.behaviourPenalty;return l+=h*t.behaviourPenaltyWeight,o+=a+c+l,{byTopic:i,p5w:a,p6w:c,p7w:l,score:o}}function vP(r,e,t,n,s){let o={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(let i of r){let a=e.get(i);if(a!=null){let c=qV(i,a,t,n,s);for(let[l,u]of c.byTopic){let h=o.byTopic.get(l);h==null&&(h={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},o.byTopic.set(l,h)),h.p1w.push(u.p1w),h.p2w.push(u.p2w),h.p3w.push(u.p3w),h.p3bw.push(u.p3bw),h.p4w.push(u.p4w)}o.p5w.push(c.p5w),o.p6w.push(c.p6w),o.p7w.push(c.p7w),o.score.push(c.score)}else o.p5w.push(0),o.p6w.push(0),o.p7w.push(0),o.score.push(0)}return o}var Y1=class{rawStream;pushable;closeController;maxBufferSize;constructor(e,t,n){this.rawStream=e,this.pushable=Ot(),this.closeController=new AbortController,this.maxBufferSize=n.maxBufferSize??1/0,this.closeController.signal.addEventListener("abort",()=>{e.close().catch(s=>{e.abort(s)})}),ht(this.pushable,this.rawStream).catch(t)}get protocol(){return this.rawStream.protocol}push(e){if(this.pushable.readableLength>this.maxBufferSize)throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`);this.pushable.push(Va.single(e))}pushPrefixed(e){if(this.pushable.readableLength>this.maxBufferSize)throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`);this.pushable.push(e)}async close(){this.closeController.abort(),await this.pushable.return()}},X1=class{source;rawStream;closeController;constructor(e,t={}){this.rawStream=e,this.closeController=new AbortController,this.closeController.signal.addEventListener("abort",()=>{e.close().catch(n=>{e.abort(n)})}),this.source=ht(this.rawStream,n=>Yu(n,t))}async close(){this.closeController.abort()}};var Q1=class{gossipsubIWantFollowupMs;msgIdToStrFn;metrics;promises=new Map;requestMsByMsg=new Map;requestMsByMsgExpire;constructor(e,t,n){this.gossipsubIWantFollowupMs=e,this.msgIdToStrFn=t,this.metrics=n,this.requestMsByMsgExpire=10*e}get size(){return this.promises.size}get requestMsByMsgSize(){return this.requestMsByMsg.size}addPromise(e,t){let n=Math.floor(Math.random()*t.length),s=t[n],o=this.msgIdToStrFn(s),i=this.promises.get(o);i==null&&(i=new Map,this.promises.set(o,i));let a=Date.now();i.has(e)||(i.set(e,a+this.gossipsubIWantFollowupMs),this.metrics!=null&&(this.metrics.iwantPromiseStarted.inc(1),this.requestMsByMsg.has(o)||this.requestMsByMsg.set(o,a)))}getBrokenPromises(){let e=Date.now(),t=new Map,n=0;return this.promises.forEach((s,o)=>{s.forEach((i,a)=>{i<e&&(t.set(a,(t.get(a)??0)+1),s.delete(a),n++)}),s.size===0&&this.promises.delete(o)}),this.metrics?.iwantPromiseBroken.inc(n),t}deliverMessage(e,t=!1){this.trackMessage(e);let n=this.promises.get(e);n!=null&&(this.promises.delete(e),this.metrics!=null&&(this.metrics.iwantPromiseResolved.inc(1),t&&this.metrics.iwantPromiseResolvedFromDuplicate.inc(1),this.metrics.iwantPromiseResolvedPeers.inc(n.size)))}rejectMessage(e,t){switch(this.trackMessage(e),t){case Vt.Error:return;default:break}this.promises.delete(e)}clear(){this.promises.clear()}prune(){let e=Date.now()-this.requestMsByMsgExpire,t=0;for(let[n,s]of this.requestMsByMsg.entries())if(s<e)this.requestMsByMsg.delete(n),t++;else break;this.metrics?.iwantMessagePruned.inc(t)}trackMessage(e){if(this.metrics!=null){let t=this.requestMsByMsg.get(e);t!==void 0&&(this.metrics.iwantPromiseDeliveryTime.observe((Date.now()-t)/1e3),this.requestMsByMsg.delete(e))}}};var V6={};z(V6,{base64:()=>VV,base64pad:()=>GV,base64url:()=>q6,base64urlpad:()=>WV});var VV=Ye({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),GV=Ye({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),q6=Ye({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),WV=Ye({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});bt();te();ce();var EP=D("libp2p-pubsub:");async function SP(r,e,t,n){switch(r.type){case Us.Signing:{let s={from:r.author.toMultihash().bytes,data:n,seqno:k1(8),topic:e,signature:void 0,key:void 0},o=Ee([EP,Qn.Message.encode(s)]);s.signature=await r.privateKey.sign(o),s.key=r.key;let i={type:"signed",from:r.author,data:t,sequenceNumber:BigInt(`0x${P(s.seqno??new Uint8Array(0),"base16")}`),topic:e,signature:s.signature,key:R6(s.key)};return{raw:s,msg:i}}case Us.Anonymous:return{raw:{from:void 0,data:n,seqno:void 0,topic:e,signature:void 0,key:void 0},msg:{type:"unsigned",data:t,topic:e}};default:throw new Error("Unreachable")}}async function IP(r,e){switch(r){case Na:return e.signature!=null?{valid:!1,error:Lt.SignaturePresent}:e.seqno!=null?{valid:!1,error:Lt.SeqnoPresent}:e.from!=null?{valid:!1,error:Lt.FromPresent}:{valid:!0,message:{type:"unsigned",topic:e.topic,data:e.data??new Uint8Array(0)}};case $o:{if(e.seqno==null)return{valid:!1,error:Lt.InvalidSeqno};if(e.seqno.length!==8)return{valid:!1,error:Lt.InvalidSeqno};if(e.signature==null)return{valid:!1,error:Lt.InvalidSignature};if(e.from==null)return{valid:!1,error:Lt.InvalidPeerId};let t;try{t=qa(Yn(e.from))}catch{return{valid:!1,error:Lt.InvalidPeerId}}let n;if(e.key!=null){if(n=R6(e.key),t.publicKey!==void 0&&!n.equals(t.publicKey))return{valid:!1,error:Lt.InvalidPeerId}}else{if(t.publicKey==null)return{valid:!1,error:Lt.InvalidPeerId};n=t.publicKey}let s={from:e.from,data:e.data,seqno:e.seqno,topic:e.topic,signature:void 0,key:void 0},o=Ee([EP,Qn.Message.encode(s)]);return await n.verify(o,e.signature)?{valid:!0,message:{type:"signed",from:t,data:e.data??new Uint8Array(0),sequenceNumber:BigInt(`0x${P(e.seqno,"base16")}`),topic:e.topic,signature:e.signature,key:n}}:{valid:!1,error:Lt.InvalidSignature}}default:throw new Error("Unreachable")}}function qr(r=[],e){return{subscriptions:[],messages:r,control:e!==void 0?{graft:e.graft??[],prune:e.prune??[],ihave:e.ihave??[],iwant:e.iwant??[],idontwant:e.idontwant??[]}:void 0}}function G6(r){return r.control===void 0&&(r.control={graft:[],prune:[],ihave:[],iwant:[],idontwant:[]}),r}function xn(r){if(r.length<=1)return r;let e=()=>Math.floor(Math.random()*Math.floor(r.length));for(let t=0;t<r.length;t++){let n=e(),s=r[t];r[t]=r[n],r[n]=s}return r}ce();function AP(r){return P(r,"base64")}function CP(r,e,t){switch(r){case $o:return{type:Us.Signing,author:e,key:Bs(t.publicKey),privateKey:t};case Na:return{type:Us.Anonymous};default:throw new Error(`Unknown signature policy "${r}"`)}}var UCe=new Uint8Array(0);function J1(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var jV=PP,TP=128,YV=127,XV=~YV,QV=Math.pow(2,31);function PP(r,e,t){e=e||[],t=t||0;for(var n=t;r>=QV;)e[t++]=r&255|TP,r/=128;for(;r&XV;)e[t++]=r&255|TP,r>>>=7;return e[t]=r|0,PP.bytes=t-n+1,e}var JV=W6,ZV=128,_P=127;function W6(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw W6.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&_P)<<s:(i&_P)*Math.pow(2,s),s+=7}while(i>=ZV);return W6.bytes=o-n,t}var eG=Math.pow(2,7),tG=Math.pow(2,14),rG=Math.pow(2,21),nG=Math.pow(2,28),sG=Math.pow(2,35),oG=Math.pow(2,42),iG=Math.pow(2,49),aG=Math.pow(2,56),cG=Math.pow(2,63),lG=function(r){return r<eG?1:r<tG?2:r<rG?3:r<nG?4:r<sG?5:r<oG?6:r<iG?7:r<aG?8:r<cG?9:10},uG={encode:jV,decode:JV,encodingLength:lG},hG=uG,j6=hG;function Y6(r,e,t=0){return j6.encode(r,e,t),e}function X6(r){return j6.encodingLength(r)}function DP(r,e){let t=e.byteLength,n=X6(r),s=n+X6(t),o=new Uint8Array(s+t);return Y6(r,o,0),Y6(t,o,n),o.set(e,s),new Q6(r,t,e,o)}var Q6=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};wr();var vn;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(vn||(vn={}));var J6;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(J6||(J6={}));(function(r){r.codec=()=>sr(J6)})(vn||(vn={}));var Z1;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),vn.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=vn.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(Z1||(Z1={}));var Z6;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),vn.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=vn.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(Z6||(Z6={}));function LP(r){return Z1.encode({Type:vn[r.type],Data:r.raw})}var r5=ie(ee("crypto"),1);var pG=20;function t5({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new e5(r,e,t,n,s)}var e5=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??pG,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?MP(n,this.code,t?.truncate):n.then(s=>MP(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function MP(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return DP(e,r)}var mG=t5({name:"sha2-256",code:18,encode:r=>J1(r5.default.createHash("sha256").update(r).digest())}),XCe=t5({name:"sha2-512",code:19,encode:r=>J1(r5.default.createHash("sha512").update(r).digest())});te();ce();var OP=(r,e)=>{let t=D(e.toString(16).padStart(16,"0"),"base16"),n=LP(r),s=new Uint8Array(n.byteLength+t.length);return s.set(n,0),s.set(t,n.byteLength),s};function RP(r){if(r.type!=="signed")throw new Error("expected signed message type");if(r.sequenceNumber==null)throw Error("missing seqno field");return OP(r.from.publicKey??r.key,r.sequenceNumber)}async function NP(r){return Vu.encode(r.data)}te();ce();var Jn=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Zn=class extends Error{static name="ValidationError";name="ValidationError"};var em=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var n5={};z(n5,{base10:()=>gG});var gG=Ms({prefix:"9",name:"base10",alphabet:"0123456789"});var s5={};z(s5,{base16:()=>yG,base16upper:()=>bG});var yG=Ye({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),bG=Ye({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var o5={};z(o5,{base2:()=>wG});var wG=Ye({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var i5={};z(i5,{base256emoji:()=>IG});var BP=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),xG=BP.reduce((r,e,t)=>(r[t]=e,r),[]),vG=BP.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function EG(r){return r.reduce((e,t)=>(e+=xG[t],e),"")}function SG(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=vG[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var IG=Ua({prefix:"\u{1F680}",name:"base256emoji",encode:EG,decode:SG});var a5={};z(a5,{base8:()=>AG});var AG=Ye({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var c5={};z(c5,{identity:()=>CG});var CG=Ua({prefix:"\0",name:"identity",encode:r=>E_(r),decode:r=>v_(r)});var ATe=new TextEncoder,CTe=new TextDecoder;var UP={...c5,...o5,...a5,...n5,...s5,...u6,...h6,...l6,...V6,...i5},PTe={...K6,...p6};bt();te();ce();function u5(r){return e=>P(e,r)}function h5(r){return e=>D(e,r)}function Ya(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Vo(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function KP(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=D(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Vo(n);return Ee([t,s],t.length+s.length)}function FP(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=Os.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Vo(n);return Ee([t,s],t.length+s.length)}function d5(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=P(e,"base32"),s=Ya(t);return`${n}:${s}`}var f5=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let s=parseInt(t,10);if(isNaN(s)||s<0||s>255)throw new Jn("Invalid byte value in IP address");e[n]=s}),e},zP=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=(0,fe.isIPv4)(t[n]),i;o&&(i=f5(t[n]),t[n]=P(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,P(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new Jn("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},$P=function(r){if(r.byteLength!==4)throw new Jn("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},HP=function(r){if(r.byteLength!==16)throw new Jn("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Jn(`Invalid IPv6 address "${t}"`)}};function qP(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Jn(`Invalid IPv6 address "${r}"`)}}var l5=Object.values(UP).map(r=>r.decoder),PG=(function(){let r=l5[0].or(l5[1]);return l5.slice(2).forEach(e=>r=r.or(e)),r})();function VP(r){return PG.decode(r)}function GP(r){return e=>r.encoder.encode(e)}function DG(r){if(parseInt(r).toString()!==r)throw new Zn("Value must be an integer")}function kG(r){if(r<0)throw new Zn("Value must be a positive integer, or zero")}function LG(r){return e=>{if(e>r)throw new Zn(`Value must be smaller than or equal to ${r}`)}}function MG(...r){return e=>{for(let t of r)t(e)}}var Xu=MG(DG,kG,LG(65535));var fr=-1,p5=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new em(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},m5=new p5,xW=[{code:4,name:"ip4",size:32,valueToBytes:f5,bytesToValue:$P,validate:r=>{if(!(0,fe.isIPv4)(r))throw new Zn(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Vo,bytesToValue:Ya,validate:Xu},{code:273,name:"udp",size:16,valueToBytes:Vo,bytesToValue:Ya,validate:Xu},{code:33,name:"dccp",size:16,valueToBytes:Vo,bytesToValue:Ya,validate:Xu},{code:41,name:"ip6",size:128,valueToBytes:zP,bytesToValue:HP,stringToValue:qP,validate:r=>{if(!(0,fe.isIPv6)(r))throw new Zn(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:fr},{code:43,name:"ipcidr",size:8,bytesToValue:u5("base10"),valueToBytes:h5("base10")},{code:53,name:"dns",size:fr,resolvable:!0},{code:54,name:"dns4",size:fr,resolvable:!0},{code:55,name:"dns6",size:fr,resolvable:!0},{code:56,name:"dnsaddr",size:fr,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:Vo,bytesToValue:Ya,validate:Xu},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:fr,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:fr,bytesToValue:u5("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?h5("base58btc")(r):lt.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:d5,valueToBytes:KP},{code:445,name:"onion3",size:296,bytesToValue:d5,valueToBytes:FP},{code:446,name:"garlic64",size:fr},{code:447,name:"garlic32",size:fr},{code:448,name:"tls"},{code:449,name:"sni",size:fr},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:fr,bytesToValue:GP(q6),valueToBytes:VP},{code:480,name:"http"},{code:481,name:"http-path",size:fr,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:fr}];xW.forEach(r=>{m5.addProtocol(r)});function WP(r,e){return m5.getProtocol(r).bytesToValue?.(e)??P(e,"base16")}var tm;(function(r){r[r.ip4=4]="ip4",r[r.ip6=41]="ip6"})(tm||(tm={}));function jP(r){for(let e of r.tuples())switch(e[0]){case tm.ip4:case tm.ip6:return WP(e[0],e[1]);default:break}return null}var Xa=class{entries=new Map;validityMs;constructor(e){this.validityMs=e.validityMs}get size(){return this.entries.size}put(e,t){return this.entries.has(e)?!0:(this.entries.set(e,{value:t,validUntilMs:Date.now()+this.validityMs}),!1)}prune(){let e=Date.now();for(let[t,n]of this.entries.entries())if(n.validUntilMs<e)this.entries.delete(t);else break}has(e){return this.entries.has(e)}get(e){let t=this.entries.get(e);return t!=null&&t.validUntilMs>=Date.now()?t.value:void 0}clear(){this.entries.clear()}};var pr;(function(r){r[r.started=0]="started",r[r.stopped=1]="stopped"})(pr||(pr={}));var g5=class extends me{globalSignaturePolicy;multicodecs=[H1,iP,$6];publishConfig;dataTransform;peers=new Map;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=Ot({objectMode:!0});direct=new Set;floodsubPeers=new Set;seenCache;acceptFromWhitelist=new Map;topics=new Map;subscriptions=new Set;mesh=new Map;fanout=new Map;fanoutLastpub=new Map;gossip=new Map;control=new Map;peerhave=new Map;iasked=new Map;backoff=new Map;outbound=new Map;msgIdFn;fastMsgIdFn;msgIdToStrFn;fastMsgIdCache;publishedMessageIds;mcache;score;topicValidators=new Map;log;heartbeatTicks=0;gossipTracer;idontwantCounts=new Map;idontwants=new Map;components;directPeerInitial=null;static multicodec=H1;opts;decodeRpcLimits;metrics;status={code:pr.stopped};maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;allowedTopics;heartbeatTimer=null;constructor(e,t={}){super();let n={fallbackToFloodsub:!0,floodPublish:!0,batchPublish:!1,tagMeshPeers:!0,doPX:!1,directPeers:[],D:6,Dlo:4,Dhi:12,Dscore:4,Dout:2,Dlazy:6,heartbeatInterval:1e3,fanoutTTL:6e4,mcacheLength:5,mcacheGossip:3,seenTTL:12e4,gossipsubIWantFollowupMs:3e3,prunePeers:16,pruneBackoff:6e4,unsubcribeBackoff:1e4,graftFloodThreshold:1e4,opportunisticGraftPeers:2,opportunisticGraftTicks:60,directConnectTicks:300,gossipFactor:.25,idontwantMinDataSize:512,idontwantMaxMessages:512,...t,scoreParams:fP(t.scoreParams),scoreThresholds:mP(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=n.decodeRpcLimits??lP,this.globalSignaturePolicy=n.globalSignaturePolicy??$o,n.fallbackToFloodsub&&this.multicodecs.push(z6),this.log=e.logger.forComponent(n.debugName??"libp2p:gossipsub"),this.opts=n,this.direct=new Set(n.directPeers.map(s=>s.id.toString())),this.seenCache=new Xa({validityMs:n.seenTTL}),this.publishedMessageIds=new Xa({validityMs:n.seenTTL}),t.msgIdFn!=null)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case $o:this.msgIdFn=RP;break;case Na:this.msgIdFn=NP;break;default:throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(t.fastMsgIdFn!=null&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new Xa({validityMs:n.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??AP,this.mcache=t.messageCache??new q1(n.mcacheGossip,n.mcacheLength,this.msgIdToStrFn),t.dataTransform!=null&&(this.dataTransform=t.dataTransform),t.metricsRegister!=null){if(t.metricsTopicStrToLabel==null)throw Error("Must set metricsTopicStrToLabel with metrics");let s=Math.max(...Object.values(n.scoreParams.topics).map(i=>i.meshMessageDeliveriesWindow),1e3),o=dP(t.metricsRegister,t.metricsTopicStrToLabel,{gossipPromiseExpireSec:this.opts.gossipsubIWantFollowupMs/1e3,behaviourPenaltyThreshold:n.scoreParams.behaviourPenaltyThreshold,maxMeshMessageDeliveriesWindowSec:s/1e3});o.mcacheSize.addCollect(()=>{this.onScrapeMetrics(o)});for(let i of this.multicodecs)o.protocolsEnabled.set({protocol:i},1);this.metrics=o}else this.metrics=null;this.gossipTracer=new Q1(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new j1(this.opts.scoreParams,this.metrics,this.components.logger,{scoreCacheValidityMs:n.heartbeatInterval}),this.maxInboundStreams=t.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams,this.runOnLimitedConnection=t.runOnLimitedConnection,this.allowedTopics=n.allowedTopics!=null?new Set(n.allowedTopics):null}[Symbol.toStringTag]="@chainsafe/libp2p-gossipsub";[b_]=["@libp2p/pubsub"];[w_]=["@libp2p/identify"];getPeers(){return[...this.peers.values()]}isStarted(){return this.status.code===pr.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=CP(this.globalSignaturePolicy,this.components.peerId,this.components.privateKey),this.outboundInflightQueue=Ot({objectMode:!0}),ht(this.outboundInflightQueue,async o=>{for await(let{peerId:i,connection:a}of o)await this.createOutboundStream(i,a)}).catch(o=>{this.log.error("outbound inflight queue error",o)}),await Promise.all(this.opts.directPeers.map(async o=>{await this.components.peerStore.merge(o.id,{multiaddrs:o.addrs})}));let e=this.components.registrar;await Promise.all(this.multicodecs.map(async o=>e.handle(o,this.onIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection})));let t={onConnect:this.onPeerConnected.bind(this),onDisconnect:this.onPeerDisconnected.bind(this),notifyOnLimitedConnection:this.runOnLimitedConnection},n=await Promise.all(this.multicodecs.map(async o=>e.register(o,t))),s=setTimeout(this.runHeartbeat,100);this.status={code:pr.started,registrarTopologyIds:n,heartbeatTimeout:s,hearbeatStartMs:Date.now()+100},this.score.start(),this.directPeerInitial=setTimeout(()=>{Promise.resolve().then(async()=>{await Promise.all(Array.from(this.direct).map(async o=>this.connect(o)))}).catch(o=>{this.log(o)})},1e3),this.opts.tagMeshPeers&&(this.addEventListener("gossipsub:graft",this.tagMeshPeer),this.addEventListener("gossipsub:prune",this.untagMeshPeer)),this.log("started")}async stop(){if(this.log("stopping"),this.status.code!==pr.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:pr.stopped},this.opts.tagMeshPeers&&(this.removeEventListener("gossipsub:graft",this.tagMeshPeer),this.removeEventListener("gossipsub:prune",this.untagMeshPeer));let t=this.components.registrar;await Promise.all(this.multicodecs.map(async s=>t.unhandle(s))),e.forEach(s=>{t.unregister(s)}),this.outboundInflightQueue.end();let n=[];for(let s of this.streamsOutbound.values())n.push(s.close());this.streamsOutbound.clear();for(let s of this.streamsInbound.values())n.push(s.close());this.streamsInbound.clear(),await Promise.all(n),this.peers.clear(),this.subscriptions.clear(),this.heartbeatTimer!=null&&(this.heartbeatTimer.cancel(),this.heartbeatTimer=null),this.score.stop(),this.mesh.clear(),this.fanout.clear(),this.fanoutLastpub.clear(),this.gossip.clear(),this.control.clear(),this.peerhave.clear(),this.iasked.clear(),this.backoff.clear(),this.outbound.clear(),this.gossipTracer.clear(),this.seenCache.clear(),this.fastMsgIdCache!=null&&this.fastMsgIdCache.clear(),this.directPeerInitial!=null&&clearTimeout(this.directPeerInitial),this.idontwantCounts.clear(),this.idontwants.clear(),this.log("stopped")}dumpPeerScoreStats(){return this.score.dumpPeerScoreStats()}onIncomingStream({stream:e,connection:t}){if(!this.isStarted())return;let n=t.remotePeer;this.addPeer(n,t.direction,t.remoteAddr),this.createInboundStream(n,e),this.outboundInflightQueue.push({peerId:n,connection:t})}onPeerConnected(e,t){this.metrics?.newConnectionCount.inc({status:t.status}),!(!this.isStarted()||t.status!=="open")&&(this.addPeer(e,t.direction,t.remoteAddr),this.outboundInflightQueue.push({peerId:e,connection:t}))}onPeerDisconnected(e){this.log("connection ended %p",e),this.removePeer(e)}async createOutboundStream(e,t){if(!this.isStarted())return;let n=e.toString();if(this.peers.has(n)&&!this.streamsOutbound.has(n))try{let s=new Y1(await t.newStream(this.multicodecs,{runOnLimitedConnection:this.runOnLimitedConnection}),i=>{this.log.error("outbound pipe error",i)},{maxBufferSize:this.opts.maxOutboundBufferSize});this.log("create outbound stream %p",e),this.streamsOutbound.set(n,s);let o=s.protocol;o===z6&&this.floodsubPeers.add(n),this.metrics?.peersPerProtocol.inc({protocol:o},1),this.subscriptions.size>0&&(this.log("send subscriptions to",n),this.sendSubscriptions(n,Array.from(this.subscriptions),!0))}catch(s){this.log.error("createOutboundStream error",s)}}createInboundStream(e,t){if(!this.isStarted())return;let n=e.toString();if(!this.peers.has(n))return;let s=this.streamsInbound.get(n);s!==void 0&&(this.log("replacing existing inbound steam %s",n),s.close().catch(i=>{this.log.error(i)})),this.log("create inbound stream %s",n);let o=new X1(t,{maxDataLength:this.opts.maxInboundDataLength});this.streamsInbound.set(n,o),this.pipePeerReadStream(e,o.source).catch(i=>{this.log(i)})}addPeer(e,t,n){let s=e.toString();if(!this.peers.has(s)){this.log("new peer %p",e),this.peers.set(s,e),this.score.addPeer(s);let o=jP(n);o!==null?this.score.addIP(s,o):this.log("Added peer has no IP in current address %s %s",s,n.toString()),this.outbound.has(s)||this.outbound.set(s,t==="outbound")}}removePeer(e){let t=e.toString();if(!this.peers.has(t))return;this.log("delete peer %p",e),this.peers.delete(t);let n=this.streamsOutbound.get(t),s=this.streamsInbound.get(t);n!=null&&this.metrics?.peersPerProtocol.inc({protocol:n.protocol},-1),n?.close().catch(o=>{this.log.error(o)}),s?.close().catch(o=>{this.log.error(o)}),this.streamsOutbound.delete(t),this.streamsInbound.delete(t);for(let o of this.topics.values())o.delete(t);for(let[o,i]of this.mesh)i.delete(t)&&this.metrics?.onRemoveFromMesh(o,Hr.Dc,1);for(let o of this.fanout.values())o.delete(t);this.floodsubPeers.delete(t),this.gossip.delete(t),this.control.delete(t),this.outbound.delete(t),this.idontwantCounts.delete(t),this.idontwants.delete(t),this.score.removePeer(t),this.acceptFromWhitelist.delete(t)}get started(){return this.status.code===pr.started}getMeshPeers(e){let t=this.mesh.get(e);return t!=null?Array.from(t):[]}getSubscribers(e){let t=this.topics.get(e);return(t!=null?Array.from(t):[]).map(n=>this.peers.get(n)??Ho(n))}getTopics(){return Array.from(this.subscriptions)}async pipePeerReadStream(e,t){try{await ht(t,async n=>{for await(let s of n)try{let o=s.subarray(),i=Qn.decode(o,{limits:{subscriptions:this.decodeRpcLimits.maxSubscriptions,messages:this.decodeRpcLimits.maxMessages,control$:{ihave:this.decodeRpcLimits.maxIhaveMessageIDs,iwant:this.decodeRpcLimits.maxIwantMessageIDs,graft:this.decodeRpcLimits.maxControlMessages,prune:this.decodeRpcLimits.maxControlMessages,prune$:{peers:this.decodeRpcLimits.maxPeerInfos},idontwant:this.decodeRpcLimits.maxControlMessages,idontwant$:{messageIDs:this.decodeRpcLimits.maxIdontwantMessageIDs}}}});if(this.metrics?.onRpcRecv(i,o.length),this.opts.awaitRpcHandler)try{await this.handleReceivedRpc(e,i)}catch(a){this.metrics?.onRpcRecvError(),this.log(a)}else this.handleReceivedRpc(e,i).catch(a=>{this.metrics?.onRpcRecvError(),this.log(a)})}catch(o){this.metrics?.onRpcDataError(),this.log(o)}})}catch(n){this.metrics?.onPeerReadStreamError(),this.handlePeerReadStreamError(n,e)}}handlePeerReadStreamError(e,t){this.log.error(e),this.onPeerDisconnected(t)}async handleReceivedRpc(e,t){if(!this.acceptFrom(e.toString())){this.log("received message from unacceptable peer %p",e),this.metrics?.rpcRecvNotAccepted.inc();return}let n=t.subscriptions!=null?t.subscriptions.length:0,s=t.messages!=null?t.messages.length:0,o=0,i=0,a=0,c=0;if(t.control!=null&&(t.control.ihave!=null&&(o=t.control.ihave.length),t.control.iwant!=null&&(i=t.control.iwant.length),t.control.graft!=null&&(a=t.control.graft.length),t.control.prune!=null&&(c=t.control.prune.length)),this.log(`rpc.from ${e.toString()} subscriptions ${n} messages ${s} ihave ${o} iwant ${i} graft ${a} prune ${c}`),t.subscriptions!=null&&t.subscriptions.length>0){let l=[];t.subscriptions.forEach(u=>{let h=u.topic,p=u.subscribe===!0;if(h!=null){if(this.allowedTopics!=null&&!this.allowedTopics.has(h))return;this.handleReceivedSubscription(e,h,p),l.push({topic:h,subscribe:p})}}),this.safeDispatchEvent("subscription-change",{detail:{peerId:e,subscriptions:l}})}for(let l of t.messages){if(this.allowedTopics!=null&&!this.allowedTopics.has(l.topic))continue;let u=this.handleReceivedMessage(e,l).catch(h=>{this.metrics?.onMsgRecvError(l.topic),this.log(h)});this.opts.awaitRpcMessageHandler&&await u}t.control!=null&&await this.handleControlMessage(e.toString(),t.control)}handleReceivedSubscription(e,t,n){this.log("subscription update from %p topic %s",e,t);let s=this.topics.get(t);s==null&&(s=new Set,this.topics.set(t,s)),n?s.add(e.toString()):s.delete(e.toString())}async handleReceivedMessage(e,t){this.metrics?.onMsgRecvPreValidation(t.topic);let n=await this.validateReceivedMessage(e,t);this.metrics?.onPrevalidationResult(t.topic,n.code);let s=n.code;switch(s){case Mt.duplicate:this.score.duplicateMessage(e.toString(),n.msgIdStr,t.topic),this.gossipTracer.deliverMessage(n.msgIdStr,!0),this.mcache.observeDuplicate(n.msgIdStr,e.toString());return;case Mt.invalid:if(n.msgIdStr!=null){let o=n.msgIdStr;this.score.rejectMessage(e.toString(),o,t.topic,n.reason),this.gossipTracer.rejectMessage(o,n.reason)}else this.score.rejectInvalidMessage(e.toString(),t.topic);this.metrics?.onMsgRecvInvalid(t.topic,n);return;case Mt.valid:this.score.validateMessage(n.messageId.msgIdStr),this.gossipTracer.deliverMessage(n.messageId.msgIdStr),this.mcache.put(n.messageId,t,!this.opts.asyncValidation),this.subscriptions.has(t.topic)&&(!this.components.peerId.equals(e)||this.opts.emitSelf)&&(super.dispatchEvent(new CustomEvent("gossipsub:message",{detail:{propagationSource:e,msgId:n.messageId.msgIdStr,msg:n.msg}})),super.dispatchEvent(new CustomEvent("message",{detail:n.msg}))),this.opts.asyncValidation||this.forwardMessage(n.messageId.msgIdStr,t,e.toString());break;default:throw new Error(`Invalid validation result: ${s}`)}}async validateReceivedMessage(e,t){let n=this.fastMsgIdFn?.(t),s=n!==void 0?this.fastMsgIdCache?.get(n):void 0;if(s!=null)return{code:Mt.duplicate,msgIdStr:s};let o=await IP(this.globalSignaturePolicy,t);if(!o.valid)return{code:Mt.invalid,reason:Vt.Error,error:o.error};let i=o.message;try{this.dataTransform!=null&&(i.data=this.dataTransform.inboundTransform(t.topic,i.data))}catch(h){return this.log("Invalid message, transform failed",h),{code:Mt.invalid,reason:Vt.Error,error:Lt.TransformFailed}}let a=await this.msgIdFn(i),c=this.msgIdToStrFn(a),l={msgId:a,msgIdStr:c};if(n!==void 0&&this.fastMsgIdCache!=null&&this.fastMsgIdCache.put(n,c)&&this.metrics?.fastMsgIdCacheCollision.inc(),this.seenCache.has(c))return{code:Mt.duplicate,msgIdStr:c};this.seenCache.put(c),(t.data?.length??0)>=this.opts.idontwantMinDataSize&&this.sendIDontWants(a,t.topic,e.toString());let u=this.topicValidators.get(t.topic);if(u!=null){let h;try{h=await u(e,i)}catch(p){let f=p.code;f===cP&&(h=qt.Ignore),f===aP?h=qt.Reject:h=qt.Ignore}if(h!==qt.Accept)return{code:Mt.invalid,reason:H6(h),msgIdStr:c}}return{code:Mt.valid,messageId:l,msg:i}}getScore(e){return this.score.score(e)}sendSubscriptions(e,t,n){this.sendRpc(e,{subscriptions:t.map(s=>({topic:s,subscribe:n})),messages:[]})}async handleControlMessage(e,t){if(t===void 0)return;let n=t.ihave?.length>0?this.handleIHave(e,t.ihave):[],s=t.iwant?.length>0?this.handleIWant(e,t.iwant):[],o=t.graft?.length>0?await this.handleGraft(e,t.graft):[];if(t.prune?.length>0&&await this.handlePrune(e,t.prune),t.idontwant?.length>0&&this.handleIdontwant(e,t.idontwant),n.length===0&&s.length===0&&o.length===0)return;let i=this.sendRpc(e,qr(s,{iwant:n,prune:o})),a=n[0]?.messageIDs;a!=null&&(i?this.gossipTracer.addPromise(e,a):this.metrics?.iwantPromiseUntracked.inc(1))}acceptFrom(e){if(this.direct.has(e))return!0;let t=Date.now(),n=this.acceptFromWhitelist.get(e);if(n!=null&&n.messagesAccepted<128&&n.acceptUntil>=t)return n.messagesAccepted+=1,!0;let s=this.score.score(e);return s>=0?this.acceptFromWhitelist.set(e,{messagesAccepted:0,acceptUntil:t+1e3}):this.acceptFromWhitelist.delete(e),s>=this.opts.scoreThresholds.graylistThreshold}handleIHave(e,t){if(t.length===0)return[];let n=this.score.score(e);if(n<this.opts.scoreThresholds.gossipThreshold)return this.log("IHAVE: ignoring peer %s with score below threshold [ score = %d ]",e,n),this.metrics?.ihaveRcvIgnored.inc({reason:ja.LowScore}),[];let s=(this.peerhave.get(e)??0)+1;if(this.peerhave.set(e,s),s>10)return this.log("IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring",e,s),this.metrics?.ihaveRcvIgnored.inc({reason:ja.MaxIhave}),[];let o=this.iasked.get(e)??0;if(o>=5e3)return this.log("IHAVE: peer %s has already advertised too many messages (%d); ignoring",e,o),this.metrics?.ihaveRcvIgnored.inc({reason:ja.MaxIasked}),[];let i=new Map;if(t.forEach(({topicID:l,messageIDs:u})=>{if(l==null||u==null||!this.mesh.has(l))return;let h=0;u.forEach(p=>{let f=this.msgIdToStrFn(p);this.seenCache.has(f)||(i.set(f,p),h++)}),this.metrics?.onIhaveRcv(l,u.length,h)}),i.size===0)return[];let a=i.size;a+o>5e3&&(a=5e3-o),this.log("IHAVE: Asking for %d out of %d messages from %s",a,i.size,e);let c=Array.from(i.values());return xn(c),c=c.slice(0,a),this.iasked.set(e,o+a),[{messageIDs:c}]}handleIWant(e,t){if(t.length===0)return[];let n=this.score.score(e);if(n<this.opts.scoreThresholds.gossipThreshold)return this.log("IWANT: ignoring peer %s with score below threshold [score = %d]",e,n),[];let s=new Map,o=new Map,i=0;return t.forEach(({messageIDs:a})=>{a?.forEach(c=>{let l=this.msgIdToStrFn(c),u=this.mcache.getWithIWantCount(l,e);if(u==null){i++;return}if(o.set(u.msg.topic,1+(o.get(u.msg.topic)??0)),u.count>3){this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,c);return}s.set(l,u.msg)})}),this.metrics?.onIwantRcv(o,i),s.size===0?(this.log("IWANT: Could not provide any wanted messages to %s",e),[]):(this.log("IWANT: Sending %d messages to %s",s.size,e),Array.from(s.values()))}async handleGraft(e,t){let n=[],s=this.score.score(e),o=Date.now(),i=this.opts.doPX;if(t.forEach(({topicID:c})=>{if(c==null)return;let l=this.mesh.get(c);if(l==null){i=!1;return}if(l.has(e))return;let u=this.backoff.get(c)?.get(e);if(this.direct.has(e))this.log("GRAFT: ignoring request from direct peer %s",e),n.push(c),i=!1;else if(typeof u=="number"&&o<u){this.log("GRAFT: ignoring backed off peer %s",e),this.score.addPenalty(e,1,Wa.GraftBackoff),i=!1;let h=u+this.opts.graftFloodThreshold-this.opts.pruneBackoff;o<h&&this.score.addPenalty(e,1,Wa.GraftBackoff),this.addBackoff(e,c),n.push(c)}else s<0?(this.log("GRAFT: ignoring peer %s with negative score: score=%d, topic=%s",e,s,c),n.push(c),i=!1,this.addBackoff(e,c)):l.size>=this.opts.Dhi&&!(this.outbound.get(e)??!1)?(n.push(c),this.addBackoff(e,c)):(this.log("GRAFT: Add mesh link from %s in %s",e,c),this.score.graft(e,c),l.add(e),this.metrics?.onAddToMesh(c,Gt.Subscribed,1));this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:c,direction:"inbound"}})}),n.length===0)return[];let a=!1;return Promise.all(n.map(async c=>this.makePrune(e,c,i,a)))}async handlePrune(e,t){let n=this.score.score(e);for(let{topicID:s,backoff:o,peers:i}of t){if(s==null)continue;let a=this.mesh.get(s);if(a==null)return;this.log("PRUNE: Remove mesh link to %s in %s",e,s),this.score.prune(e,s),a.has(e)&&(a.delete(e),this.metrics?.onRemoveFromMesh(s,Hr.Prune,1)),typeof o=="number"&&o>0?this.doAddBackoff(e,s,o*1e3):this.addBackoff(e,s),i!=null&&i.length>0&&(n<this.opts.scoreThresholds.acceptPXThreshold?this.log("PRUNE: ignoring PX from peer %s with insufficient score [score = %d, topic = %s]",e,n,s):await this.pxConnect(i)),this.safeDispatchEvent("gossipsub:prune",{detail:{peerId:e,topic:s,direction:"inbound"}})}}handleIdontwant(e,t){let n=this.idontwantCounts.get(e)??0;if(n>=this.opts.idontwantMaxMessages)return;let s=n,o=this.idontwants.get(e);o==null&&(o=new Map,this.idontwants.set(e,o));let i=0;e:for(let{messageIDs:c}of t)for(let l of c){if(n>=this.opts.idontwantMaxMessages)break e;n++;let u=this.msgIdToStrFn(l);o.set(u,this.heartbeatTicks),this.mcache.msgs.has(u)||i++}this.idontwantCounts.set(e,n);let a=n-s;this.metrics?.onIdontwantRcv(a,i)}addBackoff(e,t){this.doAddBackoff(e,t,this.opts.pruneBackoff)}doAddBackoff(e,t,n){let s=this.backoff.get(t);s==null&&(s=new Map,this.backoff.set(t,s));let o=Date.now()+n;(s.get(e)??0)<o&&s.set(e,o)}applyIwantPenalties(){this.gossipTracer.getBrokenPromises().forEach((e,t)=>{this.log("peer %s didn't follow up in %d IWANT requests; adding penalty",t,e),this.score.addPenalty(t,e,Wa.BrokenPromise)})}clearBackoff(){if(this.heartbeatTicks%15!==0)return;let e=Date.now();this.backoff.forEach((t,n)=>{t.forEach((s,o)=>{s+1*this.opts.heartbeatInterval<e&&t.delete(o)}),t.size===0&&this.backoff.delete(n)})}async directConnect(){let e=[];this.direct.forEach(t=>{this.streamsOutbound.has(t)||e.push(t)}),await Promise.all(e.map(async t=>this.connect(t)))}async pxConnect(e){e.length>this.opts.prunePeers&&(xn(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async n=>{if(n.peerID==null)return;let s=qa(Yn(n.peerID)),o=s.toString();if(!this.peers.has(o)){if(n.signedPeerRecord==null){t.push(o);return}try{if(!await this.components.peerStore.consumePeerRecord(n.signedPeerRecord,s)){this.log("bogus peer record obtained through px: could not add peer record to address book");return}t.push(o)}catch{this.log("bogus peer record obtained through px: invalid signature or not a peer record")}}})),t.length!==0&&await Promise.all(t.map(async n=>this.connect(n)))}async connect(e){this.log("Initiating connection with %s",e);let t=Ho(e),n=await this.components.connectionManager.openConnection(t);for(let s of this.multicodecs)for(let o of this.components.registrar.getTopologies(s))o.onConnect?.(t,n)}subscribe(e){if(this.status.code!==pr.started)throw new Error("Pubsub has not started");if(!this.subscriptions.has(e)){this.subscriptions.add(e);for(let t of this.peers.keys())this.sendSubscriptions(t,[e],!0)}this.join(e)}unsubscribe(e){if(this.status.code!==pr.started)throw new Error("Pubsub is not started");let t=this.subscriptions.delete(e);if(this.log("unsubscribe from %s - am subscribed %s",e,t),t)for(let n of this.peers.keys())this.sendSubscriptions(n,[e],!1);this.leave(e)}join(e){if(this.status.code!==pr.started)throw new Error("Gossipsub has not started");if(this.mesh.has(e))return;this.log("JOIN %s",e),this.metrics?.onJoin(e);let t=new Set,n=this.backoff.get(e),s=this.fanout.get(e);if(s!=null&&(this.fanout.delete(e),this.fanoutLastpub.delete(e),s.forEach(o=>{!this.direct.has(o)&&this.score.score(o)>=0&&n?.has(o)!==!0&&t.add(o)}),this.metrics?.onAddToMesh(e,Gt.Fanout,t.size)),t.size<this.opts.D){let o=t.size;this.getRandomGossipPeers(e,this.opts.D,a=>!t.has(a)&&!this.direct.has(a)&&this.score.score(a)>=0&&n?.has(a)!==!0).forEach(a=>{t.add(a)}),this.metrics?.onAddToMesh(e,Gt.Random,t.size-o)}this.mesh.set(e,t),t.forEach(o=>{this.log("JOIN: Add mesh link to %s in %s",o,e),this.sendGraft(o,e)})}leave(e){if(this.status.code!==pr.started)throw new Error("Gossipsub has not started");this.log("LEAVE %s",e),this.metrics?.onLeave(e);let t=this.mesh.get(e);t!=null&&(Promise.all(Array.from(t).map(async n=>{this.log("LEAVE: Remove mesh link to %s in %s",n,e),await this.sendPrune(n,e)})).catch(n=>{this.log("Error sending prunes to mesh peers",n)}),this.mesh.delete(e))}selectPeersToForward(e,t,n){let s=new Set,o=this.topics.get(e);o!=null&&(this.direct.forEach(a=>{o.has(a)&&t!==a&&!(n?.has(a)??!1)&&s.add(a)}),this.floodsubPeers.forEach(a=>{o.has(a)&&t!==a&&!(n?.has(a)??!1)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold&&s.add(a)}));let i=this.mesh.get(e);return i!=null&&i.size>0&&i.forEach(a=>{t!==a&&!(n?.has(a)??!1)&&s.add(a)}),s}selectPeersToPublish(e){let t=new Set,n={direct:0,floodsub:0,mesh:0,fanout:0},s=this.topics.get(e);if(s!=null)if(this.opts.floodPublish)s.forEach(o=>{this.direct.has(o)?(t.add(o),n.direct++):this.score.score(o)>=this.opts.scoreThresholds.publishThreshold&&(t.add(o),n.floodsub++)});else{this.direct.forEach(i=>{s.has(i)&&(t.add(i),n.direct++)}),this.floodsubPeers.forEach(i=>{s.has(i)&&this.score.score(i)>=this.opts.scoreThresholds.publishThreshold&&(t.add(i),n.floodsub++)});let o=this.mesh.get(e);if(o!=null&&o.size>0)o.forEach(i=>{t.add(i),n.mesh++}),o.size<this.opts.D&&this.getRandomGossipPeers(e,this.opts.D-o.size,a=>!o.has(a)&&!this.direct.has(a)&&!this.floodsubPeers.has(a)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold).forEach(a=>{t.add(a),n.mesh++});else{let i=this.fanout.get(e);if(i!=null&&i.size>0)i.forEach(a=>{t.add(a),n.fanout++});else{let a=this.getRandomGossipPeers(e,this.opts.D,c=>this.score.score(c)>=this.opts.scoreThresholds.publishThreshold);a.size>0&&(this.fanout.set(e,a),a.forEach(c=>{t.add(c),n.fanout++}))}this.fanoutLastpub.set(e,Date.now())}}return{tosend:t,tosendCount:n}}forwardMessage(e,t,n,s){n!=null&&this.score.deliverMessage(n,e,t.topic);let o=this.selectPeersToForward(t.topic,n,s);o.forEach(i=>{this.sendRpc(i,qr([t]))}),this.metrics?.onForwardMsg(t.topic,o.size)}async publish(e,t,n){let s=Date.now(),o=this.dataTransform!=null?this.dataTransform.outboundTransform(e,t):t;if(this.publishConfig==null)throw Error("PublishError.Uninitialized");let{raw:i,msg:a}=await SP(this.publishConfig,e,t,o),c=await this.msgIdFn(a),l=this.msgIdToStrFn(c),u=n?.ignoreDuplicatePublishError??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(l)){if(u)return this.metrics?.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}let{tosend:h,tosendCount:p}=this.selectPeersToPublish(e),f=this.opts.emitSelf&&this.subscriptions.has(e),d=n?.allowPublishToZeroTopicPeers??this.opts.allowPublishToZeroTopicPeers;if(h.size===0&&!d&&!f)throw Error("PublishError.NoPeersSubscribedToTopic");this.seenCache.put(l),this.mcache.put({msgId:c,msgIdStr:l},i,!0),this.gossipTracer.deliverMessage(l),this.publishedMessageIds.put(l);let m=n?.batchPublish??this.opts.batchPublish,g=qr([i]);if(m)this.sendRpcInBatch(h,g);else for(let b of h)this.sendRpc(b,g)||h.delete(b);let y=Date.now()-s;return this.metrics?.onPublishMsg(e,p,h.size,i.data!=null?i.data.length:0,y),f&&(h.add(this.components.peerId.toString()),super.dispatchEvent(new CustomEvent("gossipsub:message",{detail:{propagationSource:this.components.peerId,msgId:l,msg:a}})),super.dispatchEvent(new CustomEvent("message",{detail:a}))),{recipients:Array.from(h.values()).map(b=>this.peers.get(b)??Ho(b))}}sendRpcInBatch(e,t){let n=Qn.encode(t),s=Va.single(n);for(let o of e){let i=this.streamsOutbound.get(o);if(i==null){this.log(`Cannot send RPC to ${o} as there is no open stream to it available`),e.delete(o);continue}try{i.pushPrefixed(s)}catch(a){e.delete(o),this.log.error(`Cannot send rpc to ${o}`,a)}this.metrics?.onRpcSent(t,n.length)}}reportMessageValidationResult(e,t,n){let s;if(n===qt.Accept){if(s=this.mcache.validate(e),s!=null){let{message:i,originatingPeers:a}=s;this.score.deliverMessage(t,e,i.topic),this.forwardMessage(e,s.message,t,a)}}else if(s=this.mcache.remove(e),s!=null){let i=H6(n),{message:a,originatingPeers:c}=s;this.score.rejectMessage(t,e,a.topic,i);for(let l of c)this.score.rejectMessage(l,e,a.topic,i)}let o=this.score.messageFirstSeenTimestampMs(e);this.metrics?.onReportValidation(s,n,o)}sendGraft(e,t){let s=qr([],{graft:[{topicID:t}]});this.sendRpc(e,s)}async sendPrune(e,t){let s=[await this.makePrune(e,t,this.opts.doPX,!0)],o=qr([],{prune:s});this.sendRpc(e,o)}sendIDontWants(e,t,n){let s=this.mesh.get(t);if(s==null)return;let o=new Set(s);o.delete(n);for(let a of o)this.streamsOutbound.get(a)?.protocol!==H1&&o.delete(a);let i=qr([],{idontwant:[{messageIDs:[e]}]});this.sendRpcInBatch(o,i)}sendRpc(e,t){let n=this.streamsOutbound.get(e);if(n==null)return this.log(`Cannot send RPC to ${e} as there is no open stream to it available`),!1;let s=this.control.get(e);s!=null&&(this.piggybackControl(e,t,s),this.control.delete(e));let o=this.gossip.get(e);o!=null&&(this.piggybackGossip(e,t,o),this.gossip.delete(e));let i=Qn.encode(t);try{n.push(i)}catch(a){return this.log.error(`Cannot send rpc to ${e}`,a),s!=null&&this.control.set(e,s),o!=null&&this.gossip.set(e,o),!1}if(this.metrics?.onRpcSent(t,i.length),t.control?.graft!=null)for(let a of t.control?.graft)a.topicID!=null&&this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:a.topicID,direction:"outbound"}});if(t.control?.prune!=null)for(let a of t.control?.prune)a.topicID!=null&&this.safeDispatchEvent("gossipsub:prune",{detail:{peerId:e,topic:a.topicID,direction:"outbound"}});return!0}piggybackControl(e,t,n){let s=G6(t);for(let o of n.graft)o.topicID!=null&&(this.mesh.get(o.topicID)?.has(e)??!1)&&s.control.graft.push(o);for(let o of n.prune)o.topicID!=null&&!(this.mesh.get(o.topicID)?.has(e)??!1)&&s.control.prune.push(o)}piggybackGossip(e,t,n){let s=G6(t);s.control.ihave=n}async sendGraftPrune(e,t,n){let s=this.opts.doPX,o=!1;for(let[i,a]of e){let c=a.map(h=>({topicID:h})),l=[],u=t.get(i);u!=null&&(l=await Promise.all(u.map(async h=>this.makePrune(i,h,s&&!(n.get(i)??!1),o))),t.delete(i)),this.sendRpc(i,qr([],{graft:c,prune:l}))}for(let[i,a]of t){let c=await Promise.all(a.map(async l=>this.makePrune(i,l,s&&!(n.get(i)??!1),o)));this.sendRpc(i,qr([],{prune:c}))}}emitGossip(e){let t=this.mcache.getGossipIDs(new Set(e.keys()));for(let[n,s]of e)this.doEmitGossip(n,s,t.get(n)??[])}doEmitGossip(e,t,n){if(n.length===0||(xn(n),n.length>5e3&&this.log("too many messages for gossip; will truncate IHAVE list (%d messages)",n.length),t.size===0))return;let s=this.opts.Dlazy,i=this.opts.gossipFactor*t.size,a=t;i>s&&(s=i),s>a.size?s=a.size:a=xn(Array.from(a)).slice(0,s),a.forEach(c=>{let l=n;n.length>5e3&&(l=xn(l.slice()).slice(0,5e3)),this.pushGossip(c,{topicID:e,messageIDs:l})})}flush(){for(let[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,qr([],{ihave:t}));for(let[e,t]of this.control.entries()){this.control.delete(e);let n=qr([],{graft:t.graft,prune:t.prune});this.sendRpc(e,n)}}pushGossip(e,t){this.log("Add gossip to %s",e);let n=this.gossip.get(e)??[];this.gossip.set(e,n.concat(t))}async makePrune(e,t,n,s){if(this.score.prune(e,t),this.streamsOutbound.get(e)?.protocol===$6)return{topicID:t,peers:[]};let o=s?this.opts.unsubcribeBackoff:this.opts.pruneBackoff,i=o/1e3;if(this.doAddBackoff(e,t,o),!n)return{topicID:t,peers:[],backoff:i};let a=this.getRandomGossipPeers(t,this.opts.prunePeers,l=>l!==e&&this.score.score(l)>=0),c=await Promise.all(Array.from(a).map(async l=>{let u=this.peers.get(l)??Ho(l),h;try{h=await this.components.peerStore.get(u)}catch(p){if(p.name!=="NotFoundError")throw p}return{peerID:u.toMultihash().bytes,signedPeerRecord:h?.peerRecordEnvelope}}));return{topicID:t,peers:c,backoff:i}}runHeartbeat=()=>{let e=this.metrics?.heartbeatDuration.startTimer();this.heartbeat().catch(t=>{this.log("Error running heartbeat",t)}).finally(()=>{if(e?.(),this.status.code===pr.started){clearTimeout(this.status.heartbeatTimeout);let t=this.opts.heartbeatInterval-(Date.now()-this.status.hearbeatStartMs)%this.opts.heartbeatInterval;t<this.opts.heartbeatInterval*.25&&(t+=this.opts.heartbeatInterval,this.metrics?.heartbeatSkipped.inc()),this.status.heartbeatTimeout=setTimeout(this.runHeartbeat,t)}})};async heartbeat(){let{D:e,Dlo:t,Dhi:n,Dscore:s,Dout:o,fanoutTTL:i}=this.opts;this.heartbeatTicks++;let a=new Map,c=d=>{let m=a.get(d);return m===void 0&&(m=this.score.score(d),a.set(d,m)),m},l=new Map,u=new Map,h=new Map;this.clearBackoff(),this.peerhave.clear(),this.metrics?.cacheSize.set({cache:"iasked"},this.iasked.size),this.iasked.clear(),this.applyIwantPenalties(),this.idontwantCounts.clear();for(let d of this.idontwants.values())for(let[m,g]of d)this.heartbeatTicks-g>=this.opts.mcacheLength&&d.delete(m);this.heartbeatTicks%this.opts.directConnectTicks===0&&await this.directConnect(),this.fastMsgIdCache?.prune(),this.seenCache.prune(),this.gossipTracer.prune(),this.publishedMessageIds.prune();let p=new Map;this.mesh.forEach((d,m)=>{let g=this.topics.get(m),y=new Set,b=new Set;if(p.set(m,b),g!=null){let v=xn(Array.from(g)),S=this.backoff.get(m);for(let E of v){let I=this.streamsOutbound.get(E);if(I!=null&&this.multicodecs.includes(I.protocol)&&!d.has(E)&&!this.direct.has(E)){let A=c(E);S?.has(E)!==!0&&A>=0&&y.add(E),A>=this.opts.scoreThresholds.gossipThreshold&&b.add(E)}}}let w=(v,S)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",v,m),this.addBackoff(v,m),d.delete(v),c(v)>=this.opts.scoreThresholds.gossipThreshold&&b.add(v),this.metrics?.onRemoveFromMesh(m,S,1);let E=u.get(v);E==null?u.set(v,[m]):E.push(m)},x=(v,S)=>{this.log("HEARTBEAT: Add mesh link to %s in %s",v,m),this.score.graft(v,m),d.add(v),b.delete(v),this.metrics?.onAddToMesh(m,S,1);let E=l.get(v);E==null?l.set(v,[m]):E.push(m)};if(d.forEach(v=>{let S=c(v);S<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",v,S,m),w(v,Hr.BadScore),h.set(v,!0))}),d.size<t){let v=e-d.size;gP(y,v).forEach(E=>{x(E,Gt.NotEnough)})}if(d.size>n){let v=Array.from(d);v.sort((E,I)=>c(I)-c(E)),v=v.slice(0,s).concat(xn(v.slice(s)));let S=0;if(v.slice(0,e).forEach(E=>{(this.outbound.get(E)??!1)&&S++}),S<o){let E=A=>{let X=v[A];for(let ne=A;ne>0;ne--)v[ne]=v[ne-1];v[0]=X};if(S>0){let A=S;for(let X=1;X<e&&A>0;X++)(this.outbound.get(v[X])??!1)&&(E(X),A--)}let I=e-S;for(let A=e;A<v.length&&I>0;A++)(this.outbound.get(v[A])??!1)&&(E(A),I--)}v.slice(e).forEach(E=>{w(E,Hr.Excess)})}if(d.size>=t){let v=0;if(d.forEach(S=>{(this.outbound.get(S)??!1)&&v++}),v<o){let S=o-v;G1(y,S,I=>this.outbound.get(I)===!0).forEach(I=>{x(I,Gt.Outbound)})}}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks===0&&d.size>1){let v=Array.from(d).sort((I,A)=>c(I)-c(A)),S=Math.floor(d.size/2),E=c(v[S]);if(E<this.opts.scoreThresholds.opportunisticGraftThreshold){let I=this.opts.opportunisticGraftPeers,A=G1(y,I,X=>c(X)>E);for(let X of A)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",X,m),x(X,Gt.Opportunistic)}}});let f=Date.now();this.fanoutLastpub.forEach((d,m)=>{d+i<f&&(this.fanout.delete(m),this.fanoutLastpub.delete(m))}),this.fanout.forEach((d,m)=>{let g=this.topics.get(m);d.forEach(x=>{(!(g?.has(x)??!1)||c(x)<this.opts.scoreThresholds.publishThreshold)&&d.delete(x)});let y=this.topics.get(m),b=[],w=new Set;if(p.set(m,w),y!=null){let x=xn(Array.from(y));for(let v of x){let S=this.streamsOutbound.get(v);if(S!=null&&this.multicodecs.includes(S.protocol)&&!d.has(v)&&!this.direct.has(v)){let E=c(v);E>=this.opts.scoreThresholds.publishThreshold&&b.push(v),E>=this.opts.scoreThresholds.gossipThreshold&&w.add(v)}}}if(d.size<e){let x=e-d.size;b.slice(0,x).forEach(v=>{d.add(v),w?.delete(v)})}}),this.emitGossip(p),await this.sendGraftPrune(l,u,h),this.flush(),this.mcache.shift(),this.dispatchEvent(new CustomEvent("gossipsub:heartbeat"))}getRandomGossipPeers(e,t,n=()=>!0){let s=this.topics.get(e);if(s==null)return new Set;let o=[];return s.forEach(i=>{let a=this.streamsOutbound.get(i);a!=null&&this.multicodecs.includes(a.protocol)&&n(i)&&o.push(i)}),o=xn(o),t>0&&o.length>t&&(o=o.slice(0,t)),new Set(o)}onScrapeMetrics(e){e.mcacheSize.set(this.mcache.size),e.mcacheNotValidatedCount.set(this.mcache.notValidatedCount),e.cacheSize.set({cache:"direct"},this.direct.size),e.cacheSize.set({cache:"seenCache"},this.seenCache.size),e.cacheSize.set({cache:"fastMsgIdCache"},this.fastMsgIdCache?.size??0),e.cacheSize.set({cache:"publishedMessageIds"},this.publishedMessageIds.size),e.cacheSize.set({cache:"mcache"},this.mcache.size),e.cacheSize.set({cache:"score"},this.score.size),e.cacheSize.set({cache:"gossipTracer.promises"},this.gossipTracer.size),e.cacheSize.set({cache:"gossipTracer.requests"},this.gossipTracer.requestMsByMsgSize),e.cacheSize.set({cache:"topics"},this.topics.size),e.cacheSize.set({cache:"subscriptions"},this.subscriptions.size),e.cacheSize.set({cache:"mesh"},this.mesh.size),e.cacheSize.set({cache:"fanout"},this.fanout.size),e.cacheSize.set({cache:"peers"},this.peers.size),e.cacheSize.set({cache:"streamsOutbound"},this.streamsOutbound.size),e.cacheSize.set({cache:"streamsInbound"},this.streamsInbound.size),e.cacheSize.set({cache:"acceptFromWhitelist"},this.acceptFromWhitelist.size),e.cacheSize.set({cache:"gossip"},this.gossip.size),e.cacheSize.set({cache:"control"},this.control.size),e.cacheSize.set({cache:"peerhave"},this.peerhave.size),e.cacheSize.set({cache:"outbound"},this.outbound.size);let t=0,n=Date.now();e.connectedPeersBackoffSec.reset();for(let c of this.backoff.values()){t+=c.size;for(let[l,u]of c.entries())this.peers.has(l)&&e.connectedPeersBackoffSec.observe(Math.max(0,u-n)/1e3)}e.cacheSize.set({cache:"backoff"},t);let s=0;for(let c of this.idontwants.values())s+=c.size;e.cacheSize.set({cache:"idontwants"},s);for(let[c,l]of this.topics)e.topicPeersCount.set({topicStr:c},l.size);for(let[c,l]of this.mesh)e.meshPeerCounts.set({topicStr:c},l.size);let o=[],i=new Map;e.behaviourPenalty.reset();for(let c of this.peers.keys()){let l=this.score.score(c);o.push(l),i.set(c,l),e.behaviourPenalty.observe(this.score.peerStats.get(c)?.behaviourPenalty??0)}e.registerScores(o,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,i);let a=vP(this.peers.keys(),this.score.peerStats,this.score.params,this.score.peerIPs,e.topicStrToLabel);e.registerScoreWeights(a)}tagMeshPeer=e=>{let{peerId:t,topic:n}=e.detail;this.components.peerStore.merge(this.peers.get(t)??Ho(t),{tags:{[n]:{value:100}}}).catch(s=>{this.log.error("Error tagging peer %s with topic %s",t,n,s)})};untagMeshPeer=e=>{let{peerId:t,topic:n}=e.detail;this.components.peerStore.merge(this.peers.get(t)??Ho(t),{tags:{[n]:void 0}}).catch(s=>{this.log.error("Error untagging peer %s with topic %s",t,n,s)})}};function XP(r={}){return e=>new g5(e,r)}V();ke();Ue();var jW="bootstrap",YW=50,XW=1e3,y5=class extends me{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(t.list==null||t.list.length===0)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??XW,this.list=t.list.map(n=>q(n)).filter(n=>ap.matches(n)?n.getComponents().findLast(o=>o.code===421)?.value==null?(this.log.error("invalid bootstrap multiaddr without peer id"),!1):!0:(this.log.error("invalid multiaddr %a",n),!1)).map(n=>({id:de(n.getComponents().findLast(s=>s.code===421)?.value??""),multiaddrs:[n]})),this._init=t}[pc]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[nt]=["@libp2p/peer-discovery"];isStarted(){return!!this.timer}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(e=>{this.log.error("failed to discover bootstrap peers - %e",e)})},this.timeout))}async _discoverBootstrapPeers(){if(this.timer!=null)for(let e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??jW]:{value:this._init.tagValue??YW,ttl:this._init.tagTTL}},multiaddrs:e.multiaddrs}),this.timer==null)return;this.safeDispatchEvent("peer",{detail:e}),this.components.connectionManager.openConnection(e.id).catch(t=>{this.log.error("could not dial bootstrap peer %p - %e",e.id,t)})}}stop(){this.timer!=null&&clearTimeout(this.timer),this.timer=void 0}};function QP(r){return e=>new y5(e,r)}Bt();ke();Ue();var N_e=new Uint8Array(0);function JP(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function es(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var QW=tD,ZP=128,JW=127,ZW=~JW,ej=Math.pow(2,31);function tD(r,e,t){e=e||[],t=t||0;for(var n=t;r>=ej;)e[t++]=r&255|ZP,r/=128;for(;r&ZW;)e[t++]=r&255|ZP,r>>>=7;return e[t]=r|0,tD.bytes=t-n+1,e}var tj=b5,rj=128,eD=127;function b5(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw b5.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&eD)<<s:(i&eD)*Math.pow(2,s),s+=7}while(i>=rj);return b5.bytes=o-n,t}var nj=Math.pow(2,7),sj=Math.pow(2,14),oj=Math.pow(2,21),ij=Math.pow(2,28),aj=Math.pow(2,35),cj=Math.pow(2,42),lj=Math.pow(2,49),uj=Math.pow(2,56),hj=Math.pow(2,63),dj=function(r){return r<nj?1:r<sj?2:r<oj?3:r<ij?4:r<aj?5:r<cj?6:r<lj?7:r<uj?8:r<hj?9:10},fj={encode:QW,decode:tj,encodingLength:dj},pj=fj,Qu=pj;function Ju(r,e=0){return[Qu.decode(r,e),Qu.decode.bytes]}function Ja(r,e,t=0){return Qu.encode(r,e,t),e}function Za(r){return Qu.encodingLength(r)}function rm(r,e){let t=e.byteLength,n=Za(r),s=n+Za(t),o=new Uint8Array(s+t);return Ja(r,o,0),Ja(t,o,n),o.set(e,s),new ec(r,t,e,o)}function tc(r){let e=es(r),[t,n]=Ju(e),[s,o]=Ju(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new ec(t,s,i,e)}function nD(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&JP(r.bytes,t.bytes)}}var ec=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};V();var w5=1e3,sD=60*w5,oD=15,iD=120*sD,aD=1,sm=5e3,cD=100,x5="circuit-relay-source",Zu=`${mc}-circuit-relay`,lD=2*sD,uD=BigInt(1<<17),En="/libp2p/circuit/relay/0.2.0/hop",eh="/libp2p/circuit/relay/0.2.0/stop",hD=30*w5,$_e=30*w5,th=300,dD=4096,fD=.001;wr();rt();var Ce;(function(r){let e;(function(s){s.RESERVE="RESERVE",s.CONNECT="CONNECT",s.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(s){s[s.RESERVE=0]="RESERVE",s[s.CONNECT=1]="CONNECT",s[s.STATUS=2]="STATUS"})(t||(t={})),(function(s){s.codec=()=>sr(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Z((s,o,i={})=>{i.lengthDelimited!==!1&&o.fork(),s.type!=null&&(o.uint32(8),r.Type.codec().encode(s.type,o)),s.peer!=null&&(o.uint32(18),rc.codec().encode(s.peer,o)),s.reservation!=null&&(o.uint32(26),om.codec().encode(s.reservation,o)),s.limit!=null&&(o.uint32(34),nc.codec().encode(s.limit,o)),s.status!=null&&(o.uint32(40),le.codec().encode(s.status,o)),i.lengthDelimited!==!1&&o.ldelim()},(s,o,i={})=>{let a={},c=o==null?s.len:s.pos+o;for(;s.pos<c;){let l=s.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(s);break}case 2:{a.peer=rc.codec().decode(s,s.uint32(),{limits:i.limits?.peer});break}case 3:{a.reservation=om.codec().decode(s,s.uint32(),{limits:i.limits?.reservation});break}case 4:{a.limit=nc.codec().decode(s,s.uint32(),{limits:i.limits?.limit});break}case 5:{a.status=le.codec().decode(s);break}default:{s.skipType(l&7);break}}}return a})),n),r.encode=s=>J(s,r.codec()),r.decode=(s,o)=>Q(s,r.codec(),o)})(Ce||(Ce={}));var mr;(function(r){let e;(function(s){s.CONNECT="CONNECT",s.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(s){s[s.CONNECT=0]="CONNECT",s[s.STATUS=1]="STATUS"})(t||(t={})),(function(s){s.codec=()=>sr(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Z((s,o,i={})=>{i.lengthDelimited!==!1&&o.fork(),s.type!=null&&(o.uint32(8),r.Type.codec().encode(s.type,o)),s.peer!=null&&(o.uint32(18),rc.codec().encode(s.peer,o)),s.limit!=null&&(o.uint32(26),nc.codec().encode(s.limit,o)),s.status!=null&&(o.uint32(32),le.codec().encode(s.status,o)),i.lengthDelimited!==!1&&o.ldelim()},(s,o,i={})=>{let a={},c=o==null?s.len:s.pos+o;for(;s.pos<c;){let l=s.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(s);break}case 2:{a.peer=rc.codec().decode(s,s.uint32(),{limits:i.limits?.peer});break}case 3:{a.limit=nc.codec().decode(s,s.uint32(),{limits:i.limits?.limit});break}case 4:{a.status=le.codec().decode(s);break}default:{s.skipType(l&7);break}}}return a})),n),r.encode=s=>J(s,r.codec()),r.decode=(s,o)=>Q(s,r.codec(),o)})(mr||(mr={}));var rc;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.id!=null&&t.id.byteLength>0&&(n.uint32(10),n.bytes(t.id)),t.addrs!=null)for(let o of t.addrs)n.uint32(18),n.bytes(o);s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={id:ae(0),addrs:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.id=t.bytes();break}case 2:{if(s.limits?.addrs!=null&&o.addrs.length===s.limits.addrs)throw new _e('Decode error - map field "addrs" had too many elements');o.addrs.push(t.bytes());break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(rc||(rc={}));var om;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.expire!=null&&t.expire!==0n&&(n.uint32(8),n.uint64(t.expire)),t.addrs!=null)for(let o of t.addrs)n.uint32(18),n.bytes(o);t.voucher!=null&&(n.uint32(26),im.codec().encode(t.voucher,n)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={expire:0n,addrs:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.expire=t.uint64();break}case 2:{if(s.limits?.addrs!=null&&o.addrs.length===s.limits.addrs)throw new _e('Decode error - map field "addrs" had too many elements');o.addrs.push(t.bytes());break}case 3:{o.voucher=im.codec().decode(t,t.uint32(),{limits:s.limits?.voucher});break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(om||(om={}));var nc;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.duration!=null&&(n.uint32(8),n.uint32(t.duration)),t.data!=null&&(n.uint32(16),n.uint64(t.data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.duration=t.uint32();break}case 2:{o.data=t.uint64();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(nc||(nc={}));var le;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(le||(le={}));var v5;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(v5||(v5={}));(function(r){r.codec=()=>sr(v5)})(le||(le={}));var sc;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.relay!=null&&t.relay.byteLength>0&&(n.uint32(10),n.bytes(t.relay)),t.peer!=null&&t.peer.byteLength>0&&(n.uint32(18),n.bytes(t.peer)),t.expiration!=null&&t.expiration!==0n&&(n.uint32(24),n.uint64(t.expiration)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={relay:ae(0),peer:ae(0),expiration:0n},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.relay=t.bytes();break}case 2:{o.peer=t.bytes();break}case 3:{o.expiration=t.uint64();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(sc||(sc={}));var im;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&(n.uint32(26),sc.codec().encode(t.payload,n)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={publicKey:ae(0),payloadType:ae(0),signature:ae(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.publicKey=t.bytes();break}case 2:{o.payloadType=t.bytes();break}case 3:{o.payload=sc.codec().decode(t,t.uint32(),{limits:s.limits?.payload});break}case 5:{o.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(im||(im={}));V();function mj(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var v=d[y],S=0,E=w-1;(v!==0||S<g)&&E!==-1;E--,S++)v+=256*x[E]>>>0,x[E]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var A=c.repeat(m);I<w;++I)A+=r.charAt(x[I]);return A}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*w[S]>>>0,w[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(d[m]!==" "){for(var E=b-y;E!==b&&w[E]===0;)E++;for(var I=new Uint8Array(g+(b-E)),A=g;E!==b;)I[A++]=w[E++];return I}}}function f(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:f}}var gj=mj,yj=gj,pD=yj;var E5=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},S5=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return mD(this,e)}},I5=class{decoders;constructor(e){this.decoders=e}or(e){return mD(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function mD(r,e){return new I5({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var A5=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new E5(e,t,n),this.decoder=new S5(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function gD({name:r,prefix:e,encode:t,decode:n}){return new A5(r,e,t,n)}function oc({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=pD(t,r);return gD({prefix:e,name:r,encode:n,decode:o=>es(s(o))})}function bj(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function wj(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function xj(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Sn({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=xj(n);return gD({prefix:e,name:r,encode(o){return wj(o,n,t)},decode(o){return bj(o,s,t,r)}})}var rh=Sn({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),J_e=Sn({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Z_e=Sn({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),ePe=Sn({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),tPe=Sn({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),rPe=Sn({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),nPe=Sn({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),sPe=Sn({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),oPe=Sn({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var am=oc({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),cPe=oc({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ts=oc({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),hPe=oc({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});function yD(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Ej(t,C5(r),e??ts.encoder);default:return Sj(t,C5(r),e??rh.encoder)}}var bD=new WeakMap;function C5(r){let e=bD.get(r);if(e==null){let t=new Map;return bD.set(r,t),t}return e}var T5=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==nh)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Ij)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=rm(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&nD(e.multihash,n.multihash)}toString(e){return yD(this,e)}toJSON(){return{"/":yD(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??wD(n,s,o.bytes))}else if(t[Aj]===!0){let{version:n,multihash:s,code:o}=t,i=tc(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==nh)throw new Error(`Version 0 CID must use dag-pb (code: ${nh}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=wD(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,nh,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=es(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new ec(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,p]=Ju(e.subarray(t));return t+=p,h},s=n(),o=nh;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=vj(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return C5(o).set(n,e),o}};function vj(r,e){switch(r[0]){case"Q":{let t=e??ts;return[ts.prefix,t.decode(`${ts.prefix}${r}`)]}case ts.prefix:{let t=e??ts;return[ts.prefix,t.decode(r)]}case rh.prefix:{let t=e??rh;return[rh.prefix,t.decode(r)]}case am.prefix:{let t=e??am;return[am.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Ej(r,e,t){let{prefix:n}=t;if(n!==ts.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function Sj(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var nh=112,Ij=18;function wD(r,e,t){let n=Za(r),s=n+Za(e),o=new Uint8Array(s+t.byteLength);return Ja(r,o,0),Ja(e,o,n),o.set(t,s),o}var Aj=Symbol.for("@ipld/js-cid/CID");var D5=ie(ee("crypto"),1);var Cj=20;function P5({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new _5(r,e,t,n,s)}var _5=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??Cj,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?xD(n,this.code,t?.truncate):n.then(s=>xD(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function xD(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return rm(e,r)}var Tj=P5({name:"sha2-256",code:18,encode:r=>es(D5.default.createHash("sha256").update(r).digest())}),EPe=P5({name:"sha2-512",code:19,encode:r=>es(D5.default.createHash("sha512").update(r).digest())});var cm=class extends Error{constructor(e="Transfer limit error"){super(e),this.name="TransferLimitError"}},lm=class extends Error{constructor(e="Duration limit error"){super(e),this.name="DurationLimitError"}},sh=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},um=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},hm=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};function vD(r,e,t){let n=e.remaining,s=o=>{let i=BigInt(o.data.byteLength);e.remaining-=i,e.remaining<0&&r.abort(new cm(`data limit of ${n} bytes exceeded`))};r.addEventListener("message",s)}function ED(r,e,t,n,s){function o(u){r.abort(u),e.abort(u)}let i=[t,n.signal];if(n.limit?.duration!=null){s.log("limiting relayed connection duration to %dms",n.limit.duration);let u=AbortSignal.timeout(n.limit.duration);j(1/0,u),i.push(u)}let a=$t(i);j(1/0,a);let c;n.limit?.data!=null&&(c={remaining:n.limit.data});let l=()=>{let u;t.aborted?u=t.reason:u=new lm(`duration limit of ${n.limit?.duration} ms exceeded`),o(u)};a.addEventListener("abort",l,{once:!0}),c!=null&&(vD(e,c,s),vD(r,c,s)),_8(r,e,r).catch(u=>{o(u)}).finally(()=>{a.clear()})}function k5(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var oh=class{expires;bytes;constructor(e){e?.duration!=null&&e?.duration!==0&&(this.expires=Date.now()+e.duration*1e3),this.bytes=e?.data,this.bytes===0n&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(e){this.bytes!=null&&(this.bytes-=BigInt(e.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(this.expires==null&&this.bytes==null)return;let e={};if(this.bytes!=null){let t=this;Object.defineProperty(e,"bytes",{get(){return t.bytes}})}if(this.expires!=null){let t=this;Object.defineProperty(e,"seconds",{get(){return Math.round(((t.expires??0)-Date.now())/1e3)}})}return e}},dm=De(we(ap.matchers[0],Pe(290))),fm=De(Pe(290));var L5=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};function SD(r,e){let t=new L5(e?.errorMessage,e?.errorCode,e?.errorName),n=new AbortController,s=()=>{n.abort(t)},o=AbortSignal.timeout(r);o.addEventListener("abort",s);let i=n.signal;return i.reset=a=>{o?.removeEventListener("abort",s),o=AbortSignal.timeout(a??r),o.addEventListener("abort",()=>{n.abort(t)})},i.clear=()=>{o?.removeEventListener("abort",s),o=void 0},i}var pm=class{reservations;maxReservations;applyDefaultLimit;reservationTtl;defaultDurationLimit;defaultDataLimit;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:circuit-relay:server:reservation-store"),this.maxReservations=t.maxReservations??oD,this.applyDefaultLimit=t.applyDefaultLimit!==!1,this.reservationTtl=t.reservationTtl??iD,this.defaultDurationLimit=t.defaultDurationLimit??lD,this.defaultDataLimit=t.defaultDataLimit??uD,this.reservations=ru({metrics:e.metrics,name:"libp2p_circuit_relay_server_reservations_total"})}reserve(e,t,n){let s=this.reservations.get(e);if(this.reservations.size>=this.maxReservations&&s==null)return{status:le.RESERVATION_REFUSED};let o=new Date(Date.now()+this.reservationTtl),i;return this.applyDefaultLimit&&(i=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),s!=null?(this.log("refreshing reservation for client %p",e),s.signal.reset(this.reservationTtl)):(this.log("creating new reservation for client %p",e),s={addr:t,expiry:o,limit:i,signal:SD(this.reservationTtl)}),this.reservations.set(e,s),s.signal.addEventListener("abort",()=>{this.reservations.delete(e)}),{status:le.OK,expire:Math.round(o.getTime()/1e3)}}removeReservation(e){this.reservations.delete(e)}get(e){return this.reservations.get(e)}clear(){this.reservations.clear()}};var mm=class r{domain="libp2p-relay-rsvp";codec=new Uint8Array([3,2]);relay;peer;expiration;constructor({relay:e,peer:t,expiration:n}){this.relay=e,this.peer=t,this.expiration=n}marshal(){return sc.encode({relay:this.relay.toMultihash().bytes,peer:this.peer.toMultihash().bytes,expiration:BigInt(this.expiration)})}equals(e){return!(!(e instanceof r)||!this.peer.equals(e.peer)||!this.relay.equals(e.relay)||this.expiration!==e.expiration)}};var _j={maxOutboundStopStreams:th},gm=class extends me{components;reservationStore;started;hopTimeout;shutdownController;maxInboundHopStreams;maxOutboundHopStreams;maxOutboundStopStreams;log;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:server"),this.components=e,this.started=!1,this.hopTimeout=t?.hopTimeout??hD,this.maxInboundHopStreams=t.maxInboundHopStreams,this.maxOutboundHopStreams=t.maxOutboundHopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??_j.maxOutboundStopStreams,this.reservationStore=new pm(e,t.reservations),this.shutdownController=new AbortController,j(1/0,this.shutdownController.signal),this.onHop=this.onHop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-server";isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(En,this.onHop,{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){this.reservationStore.clear(),this.shutdownController.abort(),await this.components.registrar.unhandle(En),this.started=!1}async onHop(e,t){this.log("received circuit v2 hop protocol stream from %p",t.remotePeer);let n=AbortSignal.timeout(this.hopTimeout);j(1/0,n);let s={signal:n},o=zr(e);try{let i=await o.pb(Ce).read(s);if(i?.type==null)throw new Error("request was invalid, could not read from stream");this.log("received",i.type),await this.handleHopProtocol({connection:t,stream:o,request:i},s)}catch(i){this.log.error("error while handling hop - %e",i),await o.pb(Ce).write({type:Ce.Type.STATUS,status:le.MALFORMED_MESSAGE},s),e.abort(i)}}async handleHopProtocol({stream:e,request:t,connection:n},s){switch(this.log("received hop message"),t.type){case Ce.Type.RESERVE:await this.handleReserve({stream:e,request:t,connection:n},s);break;case Ce.Type.CONNECT:await this.handleConnect({stream:e,request:t,connection:n},s);break;default:this.log.error("invalid hop request type %s via peer %p",t.type,n.remotePeer),await e.pb(Ce).write({type:Ce.Type.STATUS,status:le.UNEXPECTED_MESSAGE})}}async handleReserve({stream:e,connection:t},n){let s=e.pb(Ce);if(this.log("hop reserve request from %p",t.remotePeer),er.exactMatch(t.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",t.remotePeer),await s.write({type:Ce.Type.STATUS,status:le.PERMISSION_DENIED},n);return}if(await this.components.connectionGater.denyInboundRelayReservation?.(t.remotePeer)===!0){this.log.error("reservation for %p denied by connection gater",t.remotePeer),await s.write({type:Ce.Type.STATUS,status:le.PERMISSION_DENIED},n);return}let o=this.reservationStore.reserve(t.remotePeer,t.remoteAddr);try{if(o.status!==le.OK){await s.write({type:Ce.Type.STATUS,status:o.status},n);return}if(o.expire!=null){let i=o.expire*1e3-Date.now();await this.components.peerStore.merge(t.remotePeer,{tags:{[x5]:{value:1,ttl:i}}},n)}await s.write({type:Ce.Type.STATUS,status:le.OK,reservation:await this.makeReservation(t.remotePeer,BigInt(o.expire??0)),limit:this.reservationStore.get(t.remotePeer)?.limit},n),this.log("sent confirmation response to %s",t.remotePeer),await s.unwrap().unwrap().close(n)}catch(i){this.log.error("failed to send confirmation response to %p - %e",t.remotePeer,i),this.reservationStore.removeReservation(t.remotePeer);try{await this.components.peerStore.merge(t.remotePeer,{tags:{[x5]:void 0}},n)}catch(a){this.log.error("failed to untag relay source peer %p - %e",t.remotePeer,a)}}}async makeReservation(e,t){let n=[];for(let o of this.components.addressManager.getAddresses())o.toString().includes("/p2p-circuit")||n.push(o.bytes);let s=await lr.seal(new mm({peer:e,relay:this.components.peerId,expiration:t}),this.components.privateKey);return{addrs:n,expire:t,voucher:{publicKey:dt(s.publicKey),payloadType:s.payloadType,payload:{peer:e.toMultihash().bytes,relay:this.components.peerId.toMultihash().bytes,expiration:t},signature:s.signature}}}async handleConnect({stream:e,request:t,connection:n},s){let o=e.pb(Ce);if(er.matches(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await o.write({type:Ce.Type.STATUS,status:le.PERMISSION_DENIED},s);return}this.log("hop connect request from %p",n.remotePeer);let i;try{if(t.peer==null)throw this.log.error("no peer info in hop connect request"),new Error("no peer info in request");t.peer.addrs.forEach(q),i=Br(tc(t.peer.id))}catch(h){this.log.error("invalid hop connect request via peer %p - %e",n.remotePeer,h),await o.write({type:Ce.Type.STATUS,status:le.MALFORMED_MESSAGE},s);return}let a=this.reservationStore.get(i);if(a==null){this.log.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",i,n.remotePeer,le.NO_RESERVATION),await o.write({type:Ce.Type.STATUS,status:le.NO_RESERVATION},s);return}if(await this.components.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,i)===!0){this.log.error("hop connect for %p to %p denied by connection gater",n.remotePeer,i),await o.write({type:Ce.Type.STATUS,status:le.PERMISSION_DENIED},s);return}let c=this.components.connectionManager.getConnections(i);if(c.length===0){this.log("hop connect denied for destination peer %p not having a connection for %p as there is no destination connection",i,n.remotePeer),await o.write({type:Ce.Type.STATUS,status:le.NO_RESERVATION},s);return}let l=c[0],u=await this.stopHop({connection:l,request:{type:mr.Type.CONNECT,peer:{id:n.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},s);if(u==null){this.log.error("failed to open stream to destination peer %p",l?.remotePeer),await o.write({type:Ce.Type.STATUS,status:le.CONNECTION_FAILED},s);return}await o.write({type:Ce.Type.STATUS,status:le.OK,limit:a?.limit},s),this.log("connection from %p to %p established - merging streams",n.remotePeer,i),ED(e.unwrap(),u,this.shutdownController.signal,a,{log:this.log})}async stopHop({connection:e,request:t},n){this.log("starting circuit relay v2 stop request to %s",e.remotePeer);let s=await e.newStream(eh,{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),o=zr(s),i=o.pb(mr);await i.write(t,n);let a;try{a=await i.read(n)}catch(c){this.log.error("error parsing stop message response from %p - %e",e.remotePeer,c)}if(a==null){this.log.error("could not read response from %p",e.remotePeer),await s.close(n);return}if(a.status===le.OK)return this.log("stop request to %p was successful",e.remotePeer),o.unwrap();this.log("stop request failed with code %d",a.status),await s.close(n)}get reservations(){return this.reservationStore.reservations}};V();ke();Ue();Ue();ce();var ym=class extends me{components;started;running;topologyId;log;discoveryController;filter;queue;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.components=e,this.started=!1,this.running=!1,this.filter=t.filter,this.discoveryController=new AbortController,j(1/0,this.discoveryController.signal),this.dialPeer=this.dialPeer.bind(this),this.onPeer=this.onPeer.bind(this)}isStarted(){return this.started}async start(){this.topologyId=await this.components.registrar.register(En,{filter:this.filter,onConnect:e=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",e,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:e})}}),this.started=!0}stop(){this.topologyId!=null&&this.components.registrar.unregister(this.topologyId),this.running&&this.stopDiscovery(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,j(1/0,this.discoveryController.signal),this.components.events.addEventListener("peer:discovery",this.onPeer),Promise.resolve().then(async()=>{this.log("searching peer store for relays");let e=await this.components.peerStore.all({filters:[n=>n.protocols.includes(En)],orders:[()=>Math.random()<.5?1:-1,(n,s)=>{let o=ID(n),i=ID(s);return o>i?-1:i>o?1:0}]});for(let n of e)this.log.trace("found relay peer %p in peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});this.log("found %d relay peers in peer store",e.length);let t=this.queue=new Ps({concurrency:5});this.log("start random walk");for await(let n of this.components.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),t.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.components.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(s=>s.toString()));continue}t.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await t.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,t.size,t.running),t.add(this.dialPeer,{peerId:n.id,signal:this.discoveryController.signal}).catch(s=>{this.log.error("error opening connection to random peer %p - %e",n.id,s)})}this.log("stop random walk"),await t.onIdle()}).catch(e=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network - %e",e)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort(),this.queue?.clear(),this.components.events.removeEventListener("peer:discovery",this.onPeer)}onPeer(e){this.log.trace("maybe dialing discovered peer %p",e.detail.id),this.maybeDialPeer(e).catch(t=>{this.log.trace("error dialing discovered peer %p - %e",e.detail.id,t)})}async maybeDialPeer(e){if(this.queue==null)return;let t=e.detail.id,n=e.detail.multiaddrs;if(this.queue.has(t)){this.log.trace("random peer %p was already in queue",t);return}if(this.components.connectionManager.getConnections(t)?.length>0){this.log.trace("random peer %p was already connected",t);return}if(!await this.components.connectionManager.isDialable(n)){this.log.trace("random peer %p was not dialable",t);return}this.queue?.add(this.dialPeer,{peerId:e.detail.id,signal:this.discoveryController.signal}).catch(s=>{this.log.error("error opening connection to discovered peer %p - %e",e.detail.id,s)})}async dialPeer({peerId:e,signal:t}){let n=$t([AbortSignal.timeout(5e3),t]);j(1/0,n);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}};function ID(r){let e=r.metadata.get("last-dial-success");return e==null?0:new Date(P(e)).getTime()}V();Ue();var M5=class extends me{connectionManager;addressManager;reservationStore;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=e.connectionManager,this.addressManager=e.addressManager,this.reservationStore=e.reservationStore,this.listeningAddrs=[],this.listenTimeout=t.listenTimeout??sm,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}_onRemoveRelayPeer=e=>{this.log("relay removed %p our relay %p",e.detail.relay,this.relay,this.relay?.equals(e.detail.relay)),this.relay?.equals(e.detail.relay)===!0&&(this.log("relay peer removed %p",e.detail.relay),this.listeningAddrs.forEach(t=>{this.addressManager.removeObservedAddr(t)}),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=e=>{let{details:t}=e.detail;t.type!=="configured"&&t.id===this.reservationId&&this.addedRelay(e.detail)};async listen(e){if(fm.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(dm.exactMatch(e)){this.log("listen on specific relay server %a",e);let t=AbortSignal.timeout(this.listenTimeout);j(1/0,t);let n=e.decapsulate("/p2p-circuit"),s=await this.connectionManager.openConnection(n,{signal:t});if(!this.reservationStore.hasReservation(s.remotePeer)){this.log("making reservation on peer %p",s.remotePeer);let o=await this.reservationStore.addRelay(s.remotePeer,"configured");this.addedRelay(o)}}else throw new Hs(`Could not listen on p2p-circuit address "${e}"`)}getAddrs(){return[...this.listeningAddrs.values()].flat()}updateAnnounceAddrs(){}async close(){this.reservationStore.cancelReservations(),this.listeningAddrs=[],this.reservationStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),queueMicrotask(()=>{this.safeDispatchEvent("close")})}addedRelay(e){this.log("relay peer added %p",e.relay),this.relay=e.relay,this.listeningAddrs=e.details.reservation.addrs.map(t=>q(t).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(t=>{this.addressManager.confirmObservedAddr(t,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function AD(r){return new M5(r)}V();Ue();var O5=ee("node:crypto");var CD="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Pj=128,Go,ic;function Dj(r){!Go||Go.length<r?(Go=Buffer.allocUnsafe(r*Pj),O5.webcrypto.getRandomValues(Go),ic=0):ic+r>Go.length&&(O5.webcrypto.getRandomValues(Go),ic=0),ic+=r}function TD(r=21){Dj(r|=0);let e="";for(let t=ic-r;t<ic;t++)e+=CD[Go[t]&63];return e}var kj=60*1e3*10,Lj=60*1e3*5,Mj=30*1e3,bm=class extends me{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(e,t){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new Zt,this.pendingReservations=[],this.maxReservationQueueLength=t?.maxReservationQueueLength??cD,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??sm,this.started=!1,this.relayFilter=ln(100),this.reserveQueue=new Ps({concurrency:t?.reservationConcurrency??aD,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(o=>o.connection===n.detail.id)!=null&&this.#t(n.detail.remotePeer).catch(o=>{this.log("could not remove relay %p - %e",n.detail,o)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(Zu)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async t=>{await this.peerStore.merge(t.id,{tags:{[Zu]:void 0}})})),this.log("redialing %d old relays",e.length),await Promise.all(e.map(async t=>this.addRelay(t.id,"discovered"))),this.#r()}).catch(e=>{this.log.error("failed to clean up and redial old relays during afterStart - %e",e)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}reserveRelay(){let e=TD();return this.pendingReservations.push(e),this.#r(),e}async addRelay(e,t){if(this.peerId.equals(e))throw this.log.trace("not trying to use self as relay"),new Hs("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new hm("The reservation queue is full");let n=this.reserveQueue.find(e);if(n!=null)return this.log.trace("potential relay peer %p is already in the reservation queue",e),n.join();if(this.relayFilter.has(e.toMultihash().bytes))throw new Hs("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",e),this.reserveQueue.add(async()=>{let s=Date.now();try{let o=this.reservations.get(e);if(o!=null){let d=this.connectionManager.getConnections(e),m=!1;if(d.length===0&&this.log("already have relay reservation with %p but we are no longer connected",e),d.map(g=>g.id).includes(o.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",e),m=!0),m&&k5(o.reservation.expire)>kj)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",e),{relay:e,details:o};await this.#t(e)}if(t==="discovered"&&this.pendingReservations.length===0)throw new sh("Not making reservation on discovered relay because we do not need any more relays");let i=AbortSignal.timeout(this.reservationCompletionTimeout);j(1/0,i);let a=await this.connectionManager.openConnection(e,{signal:i});if(er.matches(a.remoteAddr))throw new um("not creating reservation over relayed connection");let c=await this.#e(a,{signal:i}),l=k5(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",e,new Date(Date.now()+l).toString());let u=Math.min(Math.max(l-Lj,Mj),Math.pow(2,31)-1),h=setTimeout(()=>{this.log("refresh reservation to relay %p",e),this.addRelay(e,t).catch(async d=>{this.log.error("could not refresh reservation to relay %p - %e",e,d),await this.#t(e)}).catch(d=>{this.log.error("could not remove expired reservation to relay %p - %e",e,d)})},u),p;if(t==="discovered"){let d=this.pendingReservations.pop();if(d==null)throw new sh("Made reservation on relay but did not need any more discovered relays");p={timeout:h,reservation:c,type:t,connection:a.id,id:d}}else p={timeout:h,reservation:c,type:t,connection:a.id};this.reservations.set(e,p),await this.peerStore.merge(e,{tags:{[Zu]:{value:1,ttl:l}}}),this.#r();let f={relay:e,details:p};return this.safeDispatchEvent("relay:created-reservation",{detail:f}),f}catch(o){throw t==="discovered"&&o.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-s,o),(o.name==="DialError"||o.name==="UnsupportedProtocolError")&&this.relayFilter.add(e.toMultihash().bytes),this.#t(e).catch(i=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",e,i)}),o}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}reservationCount(e){return e==null?this.reservations.size:[...this.reservations.values()].reduce((t,n)=>(n.type===e&&t++,t),0)}cancelReservations(){[...this.reservations.values()].forEach(e=>{clearTimeout(e.timeout)}),this.reservations.clear()}async#e(e,t){t.signal?.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);let n=await e.newStream(En,t),o=zr(n).pb(Ce);this.log.trace("send RESERVE to %p",e.remotePeer),await o.write({type:Ce.Type.RESERVE},t);let i;try{this.log.trace("reading response from %p",e.remotePeer),i=await o.read(t)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(t)}if(this.log.trace("read response %s",i.status),i.status===le.OK&&i.reservation!=null){let c=new Set;c.add(e.remoteAddr.toString());for(let l of i.reservation.addrs){let u=q(l);u.getComponents().find(h=>h.code===421)==null&&(u=u.encapsulate(`/p2p/${e.remotePeer}`)),u=q(u.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),c.add(u.toString())}return i.reservation.addrs=[...c].map(l=>q(l).bytes),i.reservation}let a=`reservation failed with status ${i.status??"undefined"}`;throw this.log.error(a),new Error(a)}async#t(e){let t=this.reservations.get(e);t!=null&&(this.log("removing relay reservation with %p from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),t.type==="discovered"&&this.pendingReservations.push(t.id),await this.peerStore.merge(e,{tags:{[Zu]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:e,details:t}}),this.#r())}#r(){if(this.pendingReservations.length===0){this.log.trace("have discovered enough relays"),this.reserveQueue.clear(),this.safeDispatchEvent("relay:found-enough-relays");return}this.relayFilter=ln(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};Be();var R5=class extends da{stream;init;constructor(e){super({...e,direction:e.stream.direction}),this.init=e,this.stream=e.stream,this.stream.addEventListener("close",t=>{this.onTransportClosed(t.error)}),this.stream.addEventListener("remoteCloseWrite",t=>{this.onRemoteCloseWrite(),this.close().catch(n=>{this.abort(n)})}),this.stream.addEventListener("message",t=>{e.onDataRead?.(t.data),this.onData(t.data)}),this.stream.addEventListener("drain",()=>{this.safeDispatchEvent("drain")})}sendData(e){return this.init.onDataWrite?.(e),{sentBytes:e.byteLength,canSendMore:this.stream.send(e)}}async sendClose(e){await this.stream.close(e)}sendReset(){this.stream.abort(new Error("An error occurred"))}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}};function N5(r){return new R5(r)}var Oj=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(q)}catch{return!1}return!0},_D={maxInboundStopStreams:th,maxOutboundStopStreams:th,stopTimeout:3e4},wm=class{components;discovery;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:circuit-relay:transport"),this.maxInboundStopStreams=t.maxInboundStopStreams??_D.maxInboundStopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??_D.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new ym(e,{filter:t.discoveryFilter??Ib(dD,fD)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(s=>{s.name!=="HadEnoughRelaysError"&&s.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p - %e",n.detail,s)})}),this.reservationStore=new bm(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.startDiscovery()}),this.reservationStore.addEventListener("relay:found-enough-relays",()=>{this.discovery?.stopDiscovery()}),this.started=!1,this.onStop=this.onStop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[nt]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[yc](){return this.discovery!=null?["@libp2p/identify"]:[]}[Mh]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,j(1/0,this.shutdownController.signal),await this.components.registrar.handle(eh,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await kh(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Lh(this.discovery,this.reservationStore),await this.components.registrar.unhandle(eh),this.started=!1}async dial(e,t){let n=e.toString().split("/p2p-circuit"),s=q(n[0]),o=q(n[n.length-1]),i=s.getComponents().find(f=>f.code===421)?.value,a=o.getComponents().find(f=>f.code===421)?.value;if(i==null||a==null){let f=`ircuit relay dial to ${e.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${f}`),new os(`C${f}`)}let c=de(i),l=de(a),h=this.components.connectionManager.getConnections(c)[0];h==null?(await this.components.peerStore.merge(c,{multiaddrs:[s]}),t.onProgress?.(new Le("circuit-relay:open-connection")),h=await this.components.connectionManager.openConnection(c,t)):t.onProgress?.(new Le("circuit-relay:reuse-connection"));let p;try{t.onProgress?.(new Le("circuit-relay:open-hop-stream")),p=await h.newStream(En,t);let f=zr(p).pb(Ce);t.onProgress?.(new Le("circuit-relay:write-connect-message")),await f.write({type:Ce.Type.CONNECT,peer:{id:l.toMultihash().bytes,addrs:[q(o).bytes]}},t),t.onProgress?.(new Le("circuit-relay:read-connect-response"));let d=await f.read(t);if(d.status!==le.OK)throw new Rt(`failed to connect via relay with status ${d?.status?.toString()??"undefined"}`);let m=new oh(d.limit),g=N5({stream:f.unwrap().unwrap(),remoteAddr:e,localAddr:s.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:m.onData,onDataWrite:m.onData,log:p.log.newScope("circuit-relay:connection")}),y=await this.components.upgrader.upgradeOutbound(g,{...t,limits:m.getLimits()});return y.log("outbound relayed connection established to %p with limits %o, over connection %s",y.remotePeer,d.limit??"none",h.id),y}catch(f){throw this.log.error("circuit relay dial to destination %p via relay %p failed - %e",l,c,f),p?.abort(f),f}}createListener(e){return AD({peerId:this.components.peerId,connectionManager:this.components.connectionManager,addressManager:this.components.addressManager,reservationStore:this.reservationStore,logger:this.components.logger})}listenFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>dm.exactMatch(t)||fm.exactMatch(t))}dialFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>er.exactMatch(t))}async onStop(e,t){let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);try{if(!this.reservationStore.hasReservation(t.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.components.transportManager.listen([t.remoteAddr.encapsulate("/p2p-circuit")])}catch(h){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on - %e",h)}let s=zr(e).pb(mr),o=await s.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,o.type),o?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await s.write({type:mr.Type.STATUS,status:le.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(o.type!==mr.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:mr.Type.STATUS,status:le.UNEXPECTED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(!Oj(o)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:mr.Type.STATUS,status:le.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let i=Br(tc(o.peer.id));if(await this.components.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,i)===!0){this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await s.write({type:mr.Type.STATUS,status:le.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await s.write({type:mr.Type.STATUS,status:le.OK},{signal:n});let a=new oh(o.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${i.toString()}`),l=this.components.addressManager.getAddresses()[0],u=N5({stream:s.unwrap().unwrap(),remoteAddr:c,localAddr:l,onDataRead:a.onData,onDataWrite:a.onData,log:e.log.newScope("circuit-relay:connection")});await this.components.upgrader.upgradeInbound(u,{limits:a.getLimits(),signal:n}),u.log("inbound relayed connection established to %p with limits %o, over connection %s",i,o.limit??"none",t.id)}finally{n?.clear()}}};function PD(r={}){return e=>new gm(e,r)}function DD(r={}){return e=>new wm(e,r)}ke();var xm=class{components;running=!1;log;cfg;readyPromise=null;coordinatorCache=new Map;clusterCache=new Map;lastEstimate=null;blacklist=new Map;libp2pRef;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("db-p2p:network-manager"),this.cfg={clusterSize:t.clusterSize??1,seedKeys:t.seedKeys??[],estimation:t.estimation??{samples:8,kth:5,timeoutMs:1e3,ttlMs:6e4},readiness:t.readiness??{minPeers:1,maxWaitMs:2e3},cacheTTLs:t.cacheTTLs??{coordinatorMs:30*6e4,clusterMs:5*6e4},expectedRemotes:t.expectedRemotes??!1,allowClusterDownsize:t.allowClusterDownsize??!0,clusterSizeTolerance:t.clusterSizeTolerance??.5}}setLibp2p(e){this.libp2pRef=e}getLibp2p(){return this.libp2pRef??this.components.libp2p}getFret(){let e=this.getLibp2p();if(e)return e.services?.fret}get[Symbol.toStringTag](){return"@libp2p/network-manager"}async start(){this.running||(this.running=!0)}async stop(){this.running=!1}async ready(){return this.readyPromise?this.readyPromise:(this.readyPromise=(async()=>{let t=(await Promise.allSettled((this.cfg.seedKeys??[]).map(n=>this.seedKey(n)))).filter(n=>n.status==="rejected");t.length>0&&this.log("Failed to seed %d keys",t.length),await new Promise(n=>setTimeout(n,50))})(),this.readyPromise)}async seedKey(e){let t=this.getFret();if(!t)throw new Error("FRET service not available for seeding keys");let n=await ir(e),s=t.getNeighbors(n,"both",1)}toCacheKey(e){return Buffer.from(e).toString("base64url")}getKnownPeers(){let e=this.getLibp2p();if(!e)return[];let t=e.peerId,n=e.peerStore?.getPeers?.()??[],s=(e.getConnections?.()??[]).map(a=>a.remotePeer),o=[...n.map(a=>a.id),...s];return o.filter((a,c)=>o.findIndex(l=>l.toString()===a.toString())===c).filter(a=>a.toString()!==t.toString())}getStatus(){let e=this.getLibp2p();if(!e)return{mode:this.cfg.expectedRemotes?"degraded":"alone",connections:0};let n=(e.peerStore?.getPeers?.()??[]).filter(s=>s.id.toString()!==e.peerId.toString()).length;return n===0?{mode:this.cfg.expectedRemotes?"degraded":"alone",connections:0}:{mode:"healthy",connections:n}}async awaitHealthy(e,t){let n=Date.now();for(;Date.now()-n<t;){let o=this.getLibp2p();if(o){let i=o.getConnections?.()??[],a=new Set(i.map(c=>c.remotePeer.toString()));if(a.size>=e)return this.log("awaitHealthy: satisfied with %d connections",a.size),!0}await new Promise(i=>setTimeout(i,100))}let s=this.getLibp2p();if(s){let o=s.getConnections?.()??[],i=new Set(o.map(c=>c.remotePeer.toString())),a=i.size>=e;return this.log("awaitHealthy: timeout - %d connections (needed %d)",i.size,e),a}return!1}reportBadPeer(e,t=1,n=10*6e4){let s=e.toString(),i=(this.blacklist.get(s)?.score??0)+Math.max(1,t);this.blacklist.set(s,{score:i,expires:Date.now()+n})}isBlacklisted(e){let t=e.toString(),n=this.blacklist.get(t);return n?n.expires<=Date.now()?(this.blacklist.delete(t),!1):n.score>=3:!1}recordCoordinator(e,t){let n=this.toCacheKey(e);this.coordinatorCache.set(n,{id:t,expires:Date.now()+this.cfg.cacheTTLs.coordinatorMs})}async findNearestPeerToKey(e){let t=this.getFret(),n=this.getLibp2p();if(!n)throw new Error("Libp2p not initialized");if(t){let a=await ir(e),c=t.getNeighbors(a,"both",1);if(c.length>0){let l=c[0];if(l){let{peerIdFromString:u}=await Promise.resolve().then(()=>(ke(),V2)),h=u(l);if(!this.isBlacklisted(h))return h}}}let s=(n.getConnections?.()??[]).map(a=>a.remotePeer),o=[n.peerId,...s,...this.getKnownPeers()].filter((a,c,l)=>l.findIndex(u=>u.toString()===a.toString())===c).filter(a=>!this.isBlacklisted(a));return o.length===0?n.peerId:o.reduce((a,c)=>this.lexLess(this.xor(a.toMultihash().bytes,e),this.xor(c.toMultihash().bytes,e))?a:c,o[0])}async getCluster(e){let t=this.toCacheKey(e),n=this.clusterCache.get(t);if(n&&n.expires>Date.now())return n.ids;let s=this.getFret(),o=this.getLibp2p();if(!o)throw new Error("Libp2p not initialized");if(s){let f=await ir(e),d=s.getDiagnostics?.()??{},m=typeof d.estimate=="number"?d.estimate:typeof d.n=="number"?d.n:void 0,g=Math.max(1,Math.min(this.cfg.clusterSize,Number.isFinite(m)?m:this.cfg.clusterSize)),y=s.assembleCohort(f,g),{peerIdFromString:b}=await Promise.resolve().then(()=>(ke(),V2)),w=y.map(x=>{try{return b(x)}catch(v){return this.log("Invalid peer ID in cohort: %s, %o",x,v),null}}).filter(x=>x!==null&&!this.isBlacklisted(x));if(w.length>0)return this.clusterCache.set(t,{ids:w,expires:Date.now()+this.cfg.cacheTTLs.clusterMs}),this.lastEstimate=m!=null?{estimate:m,samples:d.samples??0,updated:Date.now()}:this.lastEstimate,w}let i=await this.findNearestPeerToKey(e),a=i.toMultihash().bytes,c=(o.getConnections?.()??[]).map(f=>f.remotePeer),u=[i,o.peerId,...c,...this.getKnownPeers()].filter((f,d,m)=>!this.isBlacklisted(f)&&m.findIndex(g=>g.toString()===f.toString())===d).sort((f,d)=>this.lexLess(this.xor(f.toMultihash().bytes,a),this.xor(d.toMultihash().bytes,a))?-1:1),h=Math.min(this.cfg.clusterSize,u.length),p=u.slice(0,h);return this.clusterCache.set(t,{ids:p,expires:Date.now()+this.cfg.cacheTTLs.clusterMs}),p}async getCoordinator(e){let t=this.toCacheKey(e),n=this.coordinatorCache.get(t);if(n){if(n.expires>Date.now())return n.id;this.coordinatorCache.delete(t)}let s=await this.getCluster(e),o=this.getLibp2p();if(!o)throw new Error("Libp2p not initialized");let i=s.find(a=>!this.isBlacklisted(a))??o.peerId;return this.recordCoordinator(e,i),i}xor(e,t){let n=Math.max(e.length,t.length),s=new Uint8Array(n);for(let o=0;o<n;o++){let i=e[e.length-1-o]??0,a=t[t.length-1-o]??0;s[n-1-o]=i^a}return s}lexLess(e,t){let n=Math.max(e.length,t.length);for(let s=0;s<n;s++){let o=e[s]??0,i=t[s]??0;if(o<i)return!0;if(o>i)return!1}return!1}};function B5(r={}){return e=>new xm(e,r)}var vm=class{peerStatuses=new Map;unreachableThreshold=3;rapidChurnThreshold=5;rapidChurnWindow=1e4;peerTimeoutMs=6e4;recordSuccess(e){let t=Date.now(),n=this.peerStatuses.get(e);n?(n.lastSeen=t,n.consecutiveFailures=0):this.peerStatuses.set(e,{peerId:e,lastSeen:t,consecutiveFailures:0}),this.cleanupOldPeers()}recordFailure(e){let t=Date.now(),n=this.peerStatuses.get(e);n?(n.consecutiveFailures++,n.lastSeen=t):this.peerStatuses.set(e,{peerId:e,lastSeen:t,consecutiveFailures:1})}recordGoodbye(e){let t=Date.now(),n=this.peerStatuses.get(e);n?(n.lastGoodbye=t,n.lastSeen=t):this.peerStatuses.set(e,{peerId:e,lastSeen:t,lastGoodbye:t,consecutiveFailures:0})}detectPartition(){let e=Date.now(),t=this.getRecentGoodbyes(this.rapidChurnWindow),n=Array.from(this.peerStatuses.values()).filter(o=>o.consecutiveFailures>=this.unreachableThreshold&&!o.lastGoodbye);return t.length+n.length>=this.rapidChurnThreshold}getUnreachablePeers(){return Array.from(this.peerStatuses.values()).filter(e=>e.consecutiveFailures>=this.unreachableThreshold&&!e.lastGoodbye).map(e=>e.peerId)}getRecentGoodbyes(e){let t=Date.now()-e;return Array.from(this.peerStatuses.values()).filter(n=>n.lastGoodbye&&n.lastGoodbye>t)}cleanupOldPeers(){let e=Date.now()-this.peerTimeoutMs;for(let[t,n]of this.peerStatuses.entries())n.lastSeen<e&&this.peerStatuses.delete(t)}getStatistics(){let e=this.getUnreachablePeers().length,t=this.getRecentGoodbyes(this.rapidChurnWindow).length;return{totalPeers:this.peerStatuses.size,unreachable:e,recentGoodbyes:t}}reset(){this.peerStatuses.clear()}};function Rj(r){return r?typeof r=="function"?r():r:new gl}async function Nj(r){let e=Rj(r.storage),t=async(w,x)=>{},n=new yl(w=>new Bi(w,e,t)),s,o,i={async update(w){if(!s)throw new Error("ClusterMember not initialized");return await s.update(w)}},a={async get(w,x){return await(o??n).get(w,x)},async pend(w,x){return await(o??n).pend(w,x)},async cancel(w,x){return await(o??n).cancel(w,x)},async commit(w,x){return await(o??n).commit(w,x)}},c=r.id?await de(r.id):void 0,l={start:!1,...c?{peerId:c}:{},addresses:{listen:[`/ip4/0.0.0.0/tcp/${r.port}`]},connectionManager:{autoDial:!0,minConnections:1,maxConnections:16,inboundConnectionUpgradeTimeout:1e4,dialQueue:{concurrency:2,attempts:2}},transports:[aT(),DD()],connectionEncrypters:[JT()],streamMuxers:[i_()],services:{identify:h_({protocolPrefix:`/optimystic/${r.networkName}`}),ping:y_(),pubsub:XP({allowPublishToZeroTopicPeers:!0,heartbeatInterval:7e3}),...r.relay?{relay:PD()}:{},cluster:w=>Yg({protocolPrefix:`/optimystic/${r.networkName}`,configuredClusterSize:r.clusterSize??10,allowClusterDownsize:r.clusterPolicy?.allowDownsize??!0,clusterSizeTolerance:r.clusterPolicy?.sizeTolerance??.5,responsibilityK:r.responsibilityK??1})({logger:w.logger,registrar:w.registrar,cluster:i}),repo:w=>Jg({protocolPrefix:`/optimystic/${r.networkName}`,responsibilityK:r.responsibilityK??1})({logger:w.logger,registrar:w.registrar,repo:a}),sync:w=>l3({protocolPrefix:`/optimystic/${r.networkName}`})({logger:w.logger,registrar:w.registrar,repo:a}),networkManager:w=>{let v=B5({clusterSize:r.clusterSize??10,expectedRemotes:(r.bootstrapNodes?.length??0)>0,allowClusterDownsize:r.clusterPolicy?.allowDownsize??!0,clusterSizeTolerance:r.clusterPolicy?.sizeTolerance??.5})(w);try{v.setLibp2p?.(w.libp2p)}catch{}return v},fret:w=>{let v=c3({k:15,m:8,capacity:2048,profile:r.fretProfile??((r.bootstrapNodes?.length??0)>0?"core":"edge"),networkName:r.networkName,bootstraps:r.bootstrapNodes??[]})(w);try{v.setLibp2p(w.libp2p)}catch{}return v}},peerDiscovery:[...r.bootstrapNodes?.length?[QP({list:r.bootstrapNodes})]:[]]},u=await rT(l);try{u.services?.fret?.setLibp2p?.(u)}catch{}try{u.services?.networkManager?.setLibp2p?.(u)}catch{}await u.start();let h=new Xl(u),p=`/optimystic/${r.networkName}`,f=w=>ro.create(w,h,p),d=new vm,m=u.services?.fret;s=jg({storageRepo:n,peerNetwork:h,peerId:u.peerId,protocolPrefix:p,partitionDetector:d,fretService:m,validator:r.validator});let g=Qg(h,f,{clusterSize:r.clusterSize??10,superMajorityThreshold:r.clusterPolicy?.superMajorityThreshold??.67,simpleMajorityThreshold:.51,minAbsoluteClusterSize:2,allowClusterDownsize:r.clusterPolicy?.allowDownsize??!0,clusterSizeTolerance:r.clusterPolicy?.sizeTolerance??.5,partitionDetectionWindow:6e4},m),y=async(w,x)=>{let v=new ho(w,h,p);try{let S=await v.requestBlock({blockId:x,rev:void 0});if(S.success&&S.archive){let E=Object.keys(S.archive.revisions).map(Number);if(E.length>0){let I=Math.max(...E),A=S.archive.revisions[I];if(A?.action)return{actionId:A.action.actionId,rev:I}}}}catch{}};if(o=g({storageRepo:n,localCluster:s,localPeerId:u.peerId,clusterLatestCallback:y}),r.arachnode?.enableRingZulu??!0){let w=u.logger?.forComponent?.("db-p2p:arachnode"),x=u.services?.fret;if(x){let v=new $l(x),S=new zl(e,r.arachnode?.storage??{}),E=new Fl(v,S,{minCapacity:100*1024*1024,thresholds:{moveOut:.85,moveIn:.4}}),I=u.peerId.toString(),A=await E.createArachnodeInfo(I);v.setArachnodeInfo(A),w?.("Announced Arachnode membership: Ring %d",A.ringDepth);let X=new Kl(v,{connect:(C,T)=>u.dialProtocol(C,[T])},`/optimystic/${r.networkName}`),ne=async(C,T)=>await X.restore(C,T);n.createBlockStorage=C=>new Bi(C,e,ne);let H=setInterval(async()=>{let C=await E.shouldTransition();if(C.shouldMove){w?.("Ring transition needed: moving %s to Ring %d",C.direction,C.newRingDepth);let T=await E.createArachnodeInfo(I);v.setArachnodeInfo(T)}},6e4),L=u.stop.bind(u);u.stop=async()=>{clearInterval(H),await L()}}else w?.("FRET service not available, Arachnode disabled")}return u.coordinatedRepo=o,u.storageRepo=n,u.keyNetwork=h,u}function kD(r,e){let t=Math.max(r.length,e.length),n=new Uint8Array(t);for(let s=0;s<t;s++){let o=r[r.length-1-s]??0,i=e[e.length-1-s]??0;n[t-1-s]=o^i}return n}function LD(r,e){let t=Math.max(r.length,e.length);for(let n=0;n<t;n++){let s=r[n]??0,o=e[n]??0;if(s<o)return!0;if(s>o)return!1}return!1}function MD(r,e){return r.map(t=>({p:t,d:kD(t.id.toMultihash().bytes,e)})).sort((t,n)=>LD(t.d,n.d)?-1:1).map(t=>t.p)}function Bj(r,e,t,n){let s=[e,...t],o=MD(s,r);if(s.length<=3)return{inCluster:o[0].id.equals(e.id),nearest:o};let i=Math.min(n,Math.max(1,Math.floor(s.length/2))),a=o.slice(0,i);return{inCluster:a.some(l=>l.id.equals(e.id)),nearest:a}}function Uj(r){let e={id:r.peerId,addrs:r.getMultiaddrs().map(o=>o.toString())},t=r.getConnections(),n={};for(let o of t){let i=o.remotePeer,a=i.toString(),c=n[a]??(n[a]={id:i,addrs:new Set}),l=o.remoteAddr?.toString?.();l&&c.addrs.add(l)}let s=Object.values(n).map(o=>({id:o.id,addrs:Array.from(o.addrs)}));return[e,...s]}var Kj=Sr("network:get-manager");function Fj(r){let e=r.services?.networkManager;if(e==null)throw new Error("networkManager service is not registered on this libp2p node");try{e.setLibp2p?.(r)}catch(t){Kj("getNetworkManager setLibp2p failed - %o",t)}return e}return $5(zj);})();
|
|
35
35
|
/*! Bundled license information:
|
|
36
36
|
|
|
37
37
|
@noble/hashes/utils.js:
|