helia 5.1.0-dff82ec → 5.1.0-e58e49c
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 +2 -2
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +6 -6
- package/src/version.ts +1 -1
package/dist/index.min.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
`).map(o=>` ${o}`).join(`
|
|
5
5
|
`));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
|
|
6
6
|
${e.join(`
|
|
7
|
-
`)}`:`${t} :`}};k6=Io;G.Constructed=k6;Io.NAME="CONSTRUCTED";var su=class extends Dt{fromBER(e,t,n){return t}toBER(e){return Yr}};su.override="EndOfContentValueBlock";var C6,au=class extends xt{constructor(e={}){super(e,su),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};C6=au;G.EndOfContent=C6;au.NAME=Na;var P6,Kn=class extends xt{constructor(e={}){super(e,Dt),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};P6=Kn;G.Null=P6;Kn.NAME="NULL";var cu=class extends zn(Dt){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=ye.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,n){let o=ye.BufferSourceConverter.toUint8Array(e);return Wn(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,p2.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};cu.NAME="BooleanValueBlock";var R6,lu=class extends xt{constructor(e={}){super(e,cu),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};R6=lu;G.Boolean=R6;lu.NAME="BOOLEAN";var uu=class extends zn(wn){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=wn.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let i=0;i<this.value.length;i++){let s=this.value[i].constructor.NAME;if(s===Na){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(s!==A6)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,t,n),this.blockLength=n;return o}toBER(e,t){return this.isConstructed?wn.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};uu.NAME="OctetStringValueBlock";var L6,Hn=class r extends xt{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,i;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},uu),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let i=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(i.byteLength){let s=Uu(i,0,i.byteLength);s.offset!==-1&&s.offset===n&&(this.valueBlock.value=[s.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?Io.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${ye.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof r&&e.push(t.valueBlock.valueHexView);return ye.BufferSourceConverter.concat(e)}};L6=Hn;G.OctetString=L6;Hn.NAME=A6;var du=class extends zn(wn){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n){if(!n)return t;let o=-1;if(this.isConstructed){if(o=wn.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===Na){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==I6)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return o}let i=ye.BufferSourceConverter.toUint8Array(e);if(!Wn(this,i,t,n))return-1;let s=i.subarray(t,t+n);if(this.unusedBits=s[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=s.subarray(1);try{if(a.byteLength){let c=Uu(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=s.subarray(1),this.blockLength=s.length,t+n}toBER(e,t){if(this.isConstructed)return wn.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return Yr;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};du.NAME="BitStringValueBlock";var D6,us=class extends xt{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,i;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},du),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Io.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let o of t)e.push(o.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};D6=us;G.BitString=D6;us.NAME=I6;var N6;function ES(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,l=0,d=c<s?s:c,u=0;for(let f=d;f>=0;f--,u++){switch(!0){case u<a.length:l=i[s-u]+a[c-u]+t[0];break;default:l=i[s-u]+t[0]}switch(t[0]=l/10,!0){case u>=i.length:i=Jl(new Uint8Array([l%10]),i);break;default:i[s-u]=l%10}}return t[0]>0&&(i=Jl(t,i)),i}function S6(r){if(r>=La.length)for(let e=La.length;e<=r;e++){let t=new Uint8Array([0]),n=La[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let i=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=i[0]/10,n[o]=i[0]%10}t[0]>0&&(n=Jl(t,n)),La.push(n)}return La[r]}function vS(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,l,d=0;for(let u=c;u>=0;u--,d++)switch(l=i[s-d]-a[c-d]-t,!0){case l<0:t=1,i[s-d]=l+10;break;default:t=0,i[s-d]=l}if(t>0)for(let u=s-c+1;u>=0;u--,d++)if(l=i[s-d]-t,l<0)t=1,i[s-d]=l+10;else{t=0,i[s-d]=l;break}return i.slice()}var Ba=class extends zn(Dt){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=p2.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(x6(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let i=this.fromBER(e,t,n);if(i===-1)return i;let s=this.valueHexView;return s[0]===0&&s[1]&128?this.valueHexView=s.subarray(1):o!==0&&s.length<o&&(o-s.length>1&&(o=s.length+1),this.valueHexView=s.subarray(o-s.length)),i}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,o,i=this.valueHexView,s="",a=!1;for(let c=i.byteLength-1;c>=0;c--){o=i[c];for(let l=0;l<8;l++){if((o&1)===1)switch(n){case e:t=vS(S6(n),t),s="-";break;default:t=ES(t,S6(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(s+=v6.charAt(t[c]));return a===!1&&(s+=v6.charAt(0)),s}};N6=Ba;Ba.NAME="IntegerValueBlock";Object.defineProperty(N6.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var B6,tt=class r extends xt{constructor(e={}){super(e,Ba),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return eu(),BigInt(this.valueBlock.toString())}static fromBigInt(e){eu();let t=BigInt(e),n=new Da,o=t.toString(16).replace(/^-/,""),i=new Uint8Array(ye.Convert.FromHex(o));if(t<0){let a=new Uint8Array(i.length+(i[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${ye.Convert.ToHex(a)}`)+t,d=ye.BufferSourceConverter.toUint8Array(ye.Convert.FromHex(l.toString(16)));d[0]|=128,n.write(d)}else i[0]&128&&n.write(new Uint8Array([0])),n.write(i);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};B6=tt;G.Integer=B6;tt.NAME="INTEGER";var O6,fu=class extends tt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};O6=fu;G.Enumerated=O6;fu.NAME="ENUMERATED";var Oa=class extends zn(Dt){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=ye.BufferSourceConverter.toUint8Array(e);if(!Wn(this,o,t,n))return-1;let i=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=i[a]&127,this.blockLength++,!!(i[a]&128));a++);let s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)s[a]=this.valueHexView[a];return this.valueHexView=s,i[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=di(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){eu();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,i=new Uint8Array(this.blockLength);for(let s=0;s<this.blockLength-1;s++)i[s]=o[s]|128;return i[this.blockLength-1]=o[this.blockLength-1],i.buffer}let t=Ao(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Yr;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),i=t.byteLength-1;for(let s=0;s<i;s++)n[s]=o[s]|128;n[i]=o[i]}return n}toString(){let e="";if(this.isHexOnly)e=ye.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Oa.NAME="sidBlock";var hu=class extends Dt{constructor({value:e=ds,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let i=new Oa;if(o=i.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=i.error,o;this.value.length===0&&(i.isFirstSid=!0),this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,Yr;t.push(o)}return m2(t)}fromString(e){this.value=[];let t=0,n=0,o="",i=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,i){let s=this.value[0],a=0;switch(s.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;s.valueDec=c+a,i=!1}else{let s=new Oa;if(o>Number.MAX_SAFE_INTEGER){eu();let a=BigInt(o);s.valueBigInt=a}else if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return;this.value.length||(s.isFirstSid=!0,i=!0),this.value.push(s)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};hu.NAME="ObjectIdentifierValueBlock";var M6,Cr=class extends xt{constructor(e={}){super(e,hu),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};M6=Cr;G.ObjectIdentifier=M6;Cr.NAME="OBJECT IDENTIFIER";var Ma=class extends zn(Vn){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=ye.BufferSourceConverter.toUint8Array(e);if(!Wn(this,o,t,n))return-1;let i=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=i[a]&127,this.blockLength++,!!(i[a]&128));a++);let s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)s[a]=this.valueHexView[a];return this.valueHexView=s,i[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=di(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,i=new Uint8Array(this.blockLength);for(let s=0;s<this.blockLength-1;s++)i[s]=o[s]|128;return i[this.blockLength-1]=o[this.blockLength-1],i.buffer}let t=Ao(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Yr;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),i=t.byteLength-1;for(let s=0;s<i;s++)n[s]=o[s]|128;n[i]=o[i]}return n.buffer}toString(){let e="";return this.isHexOnly?e=ye.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Ma.NAME="relativeSidBlock";var pu=class extends Dt{constructor({value:e=ds,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let i=new Ma;if(o=i.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=i.error,o;this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let i=this.value[o].toBER(e);if(i.byteLength===0)return this.error=this.value[o].error,Yr;n.push(i)}return m2(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let i=new Ma;if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};pu.NAME="RelativeObjectIdentifierValueBlock";var U6,mu=class extends xt{constructor(e={}){super(e,pu),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};U6=mu;G.RelativeObjectIdentifier=U6;mu.NAME="RelativeObjectIdentifier";var F6,ft=class extends Io{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};F6=ft;G.Sequence=F6;ft.NAME="SEQUENCE";var $6,gu=class extends Io{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};$6=gu;G.Set=$6;gu.NAME="SET";var yu=class extends zn(Dt){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=ds}toJSON(){return{...super.toJSON(),value:this.value}}};yu.NAME="StringValueBlock";var wu=class extends yu{};wu.NAME="SimpleStringValueBlock";var Vt=class extends nu{constructor({...e}={}){super(e,wu)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,ye.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};Vt.NAME="SIMPLE STRING";var bu=class extends Vt{fromBuffer(e){this.valueBlock.valueHexView=ye.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=ye.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=ye.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(ye.Convert.FromUtf8String(e)),this.valueBlock.value=e}};bu.NAME="Utf8StringValueBlock";var V6,qn=class extends bu{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};V6=qn;G.Utf8String=V6;qn.NAME="UTF8String";var xu=class extends Vt{fromBuffer(e){this.valueBlock.value=ye.Convert.ToUtf16String(e),this.valueBlock.valueHexView=ye.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(ye.Convert.FromUtf16String(e))}};xu.NAME="BmpStringValueBlock";var K6,Eu=class extends xu{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};K6=Eu;G.BmpString=K6;Eu.NAME="BMPString";var vu=class extends Vt{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let i=Ao(e.charCodeAt(o),8),s=new Uint8Array(i);if(s.length>4)continue;let a=4-s.length;for(let c=s.length-1;c>=0;c--)n[o*4+c+a]=s[c]}this.valueBlock.value=e}};vu.NAME="UniversalStringValueBlock";var H6,Su=class extends vu{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};H6=Su;G.UniversalString=H6;Su.NAME="UniversalString";var q6,Au=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};q6=Au;G.NumericString=q6;Au.NAME="NumericString";var W6,Iu=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};W6=Iu;G.PrintableString=W6;Iu.NAME="PrintableString";var z6,_u=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};z6=_u;G.TeletexString=z6;_u.NAME="TeletexString";var G6,Tu=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};G6=Tu;G.VideotexString=G6;Tu.NAME="VideotexString";var Q6,ku=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Q6=ku;G.IA5String=Q6;ku.NAME="IA5String";var Y6,Cu=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Y6=Cu;G.GraphicString=Y6;Cu.NAME="GraphicString";var X6,Ua=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};X6=Ua;G.VisibleString=X6;Ua.NAME="VisibleString";var j6,Pu=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};j6=Pu;G.GeneralString=j6;Pu.NAME="GeneralString";var Z6,Ru=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Z6=Ru;G.CharacterString=Z6;Ru.NAME="CharacterString";var J6,Fa=class extends Ua{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,ye.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=tr(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=tr(this.month,2),t[2]=tr(this.day,2),t[3]=tr(this.hour,2),t[4]=tr(this.minute,2),t[5]=tr(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};J6=Fa;G.UTCTime=J6;Fa.NAME="UTCTime";var e8,Lu=class extends Fa{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t=!1,n="",o="",i=0,s,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let u=new Number(e[e.length-1]);if(isNaN(u.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let u=1,f=n.indexOf("+"),h="";if(f===-1&&(f=n.indexOf("-"),u=-1),f!==-1){if(h=n.substring(f+1),n=n.substring(0,f),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(h.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=u*p,h.length===4){if(p=parseInt(h.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=u*p}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let u=new Number(`0${n.substring(l)}`);if(isNaN(u.valueOf()))throw new Error("Wrong input string for conversion");i=u.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(s=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let u=60*i;this.minute=Math.floor(u),u=60*(u-this.minute),this.second=Math.floor(u),u=1e3*(u-this.second),this.millisecond=Math.floor(u)}break;case o.length===12:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let u=60*i;this.second=Math.floor(u),u=1e3*(u-this.second),this.millisecond=Math.floor(u)}break;case o.length===14:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let u=1e3*i;this.millisecond=Math.floor(u)}break;default:throw new Error("Wrong input string for conversion")}let d=s.exec(o);if(d===null)throw new Error("Wrong input string for conversion");for(let u=1;u<d.length;u++)switch(u){case 1:this.year=parseInt(d[u],10);break;case 2:this.month=parseInt(d[u],10);break;case 3:this.day=parseInt(d[u],10);break;case 4:this.hour=parseInt(d[u],10)+a;break;case 5:this.minute=parseInt(d[u],10)+c;break;case 6:this.second=parseInt(d[u],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let u=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=u.getUTCFullYear(),this.month=u.getUTCMonth(),this.day=u.getUTCDay(),this.hour=u.getUTCHours(),this.minute=u.getUTCMinutes(),this.second=u.getUTCSeconds(),this.millisecond=u.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(tr(this.year,4)),t.push(tr(this.month,2)),t.push(tr(this.day,2)),t.push(tr(this.hour,2)),t.push(tr(this.minute,2)),t.push(tr(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(tr(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};e8=Lu;G.GeneralizedTime=e8;Lu.NAME="GeneralizedTime";var t8,Du=class extends qn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};t8=Du;G.DATE=t8;Du.NAME="DATE";var r8,Nu=class extends qn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};r8=Nu;G.TimeOfDay=r8;Nu.NAME="TimeOfDay";var n8,Bu=class extends qn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};n8=Bu;G.DateTime=n8;Bu.NAME="DateTime";var o8,Ou=class extends qn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};o8=Ou;G.Duration=o8;Ou.NAME="Duration";var i8,Mu=class extends qn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};i8=Mu;G.TIME=i8;Mu.NAME="TIME";function V(r,e="utf8"){let t=Nl[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function Kt(r){if(isNaN(r)||r<=0)throw new C("random bytes length must be a Number bigger than 0");return si(r)}var $a=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},Va=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Fu=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var s8={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new Fu("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var rr=s8;async function a8(r){let e=await rr.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await SS(e);return{privateKey:t[0],publicKey:t[1]}}async function c8(r,e){let t=await rr.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await rr.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function l8(r,e,t){let n=await rr.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return rr.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function SS(r){if(r.privateKey==null||r.publicKey==null)throw new C("Private and public key are required");return Promise.all([rr.get().subtle.exportKey("jwk",r.privateKey),rr.get().subtle.exportKey("jwk",r.publicKey)])}function w2(r){if(r.kty!=="RSA")throw new C("invalid key type");if(r.n==null)throw new C("invalid key modulus");return M(r.n,"base64url").length*8}var fs=class{type="RSA";_key;_raw;_multihash;constructor(e,t){this._key=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Ka.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return X.createV1(114,this._multihash)}toString(){return Se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}verify(e,t){return l8(this._key,t,e)}},Ha=class{type="RSA";_key;_raw;publicKey;constructor(e,t){this._key=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Ka.jwkToPkcs1(this._key)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}sign(e){return c8(this._key,e)}};var $u=8192,b2=18;function u8(r){let{result:e}=fi(r),t=e.valueBlock.value;return{n:bn(t[1]),e:bn(t[2]),d:bn(t[3]),p:bn(t[4]),q:bn(t[5]),dp:bn(t[6]),dq:bn(t[7]),qi:bn(t[8]),kty:"RSA",alg:"RS256"}}function AS(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 C("JWK was missing components");let t=new ft({value:[new tt({value:0}),tt.fromBigInt(xn(M(r.n,"base64url"))),tt.fromBigInt(xn(M(r.e,"base64url"))),tt.fromBigInt(xn(M(r.d,"base64url"))),tt.fromBigInt(xn(M(r.p,"base64url"))),tt.fromBigInt(xn(M(r.q,"base64url"))),tt.fromBigInt(xn(M(r.dp,"base64url"))),tt.fromBigInt(xn(M(r.dq,"base64url"))),tt.fromBigInt(xn(M(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function d8(r){let{result:e}=fi(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:bn(t[0]),e:bn(t[1])}}function x2(r){if(r.n==null||r.e==null)throw new C("JWK was missing components");let t=new ft({value:[new ft({value:[new Cr({value:"1.2.840.113549.1.1.1"}),new Kn]}),new us({valueHex:new ft({value:[tt.fromBigInt(xn(M(r.n,"base64url"))),tt.fromBigInt(xn(M(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function bn(r){let e=r.valueBlock.valueHexView;for(;e[0]===0;)e=e.subarray(1);return V(e,"base64url")}function xn(r){let e=[];return r.forEach(function(t){let n=t.toString(16);n.length%2>0&&(n=`0${n}`),e.push(n)}),BigInt("0x"+e.join(""))}function Vu(r){let e=u8(r);return f8(e)}function E2(r){let e=d8(r);if(w2(e)>$u)throw new Rn("Key size is too large");let t=Tr(yn.encode({Type:Ye.RSA,Data:r})),n=Zt(b2,t);return new fs(e,n)}function f8(r){if(w2(r)>$u)throw new C("Key size is too large");let e=h8(r),t=Tr(yn.encode({Type:Ye.RSA,Data:x2(e.publicKey)})),n=Zt(b2,t);return new Ha(e.privateKey,new fs(e.publicKey,n))}async function v2(r){if(r>$u)throw new C("Key size is too large");let e=await a8(r),t=Tr(yn.encode({Type:Ye.RSA,Data:x2(e.publicKey)})),n=Zt(b2,t);return new Ha(e.privateKey,new fs(e.publicKey,n))}function h8(r){if(r==null)throw new C("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var Ku=class extends rs{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ni(e);let n=Wr(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,i=new Uint8Array(o);i.set(n.length>o?e.create().update(n).digest():n);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=e.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),i.fill(0)}update(e){return ts(this),this.iHash.update(e),this}digestInto(e){ts(this),es(e,this.outputLen),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||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},_o=(r,e,t)=>new Ku(r,e).update(t).digest();_o.create=(r,e)=>new Ku(r,e);function p8(r){r.lowS!==void 0&&zr("lowS",r.lowS),r.prehash!==void 0&&zr("prehash",r.prehash)}function IS(r){let e=_a(r);_r(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:o}=e;if(t){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:_S,hexToBytes:TS}=zl,Gn={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode:(r,e)=>{let{Err:t}=Gn;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,o=ai(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let i=n>127?ai(o.length/2|128):"";return`${ai(r)}${i}${o}${e}`},decode(r,e){let{Err:t}=Gn,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 o=e[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&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 d of l)s=s<<8|d;if(n+=c,s<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+s);if(a.length!==s)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+s)}}},_int:{encode(r){let{Err:e}=Gn;if(r<Qn)throw new e("integer: negative integers are not allowed");let t=ai(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected assertion");return t},decode(r){let{Err:e}=Gn;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 _S(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Gn,o=typeof r=="string"?TS(r):r;os(o);let{v:i,l:s}=n.decode(48,o);if(s.length)throw new e("Invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{v:l,l:d}=n.decode(2,c);if(d.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}=Gn,n=`${e.encode(2,t.encode(r.r))}${e.encode(2,t.encode(r.s))}`;return e.encode(48,n)}},Qn=BigInt(0),pt=BigInt(1),NB=BigInt(2),m8=BigInt(3),BB=BigInt(4);function kS(r){let e=IS(r),{Fp:t}=e,n=Eo(e.n,e.nBitLength),o=e.toBytes||((m,g,y)=>{let b=g.toAffine();return Fn(Uint8Array.from([4]),t.toBytes(b.x),t.toBytes(b.y))}),i=e.fromBytes||(m=>{let g=m.subarray(1),y=t.fromBytes(g.subarray(0,t.BYTES)),b=t.fromBytes(g.subarray(t.BYTES,2*t.BYTES));return{x:y,y:b}});function s(m){let{a:g,b:y}=e,b=t.sqr(m),w=t.mul(b,m);return t.add(t.add(w,t.mul(m,g)),y)}if(!t.eql(t.sqr(e.Gy),s(e.Gx)))throw new Error("bad generator point: equation left != right");function a(m){return Aa(m,pt,e.n)}function c(m){let{allowedPrivateKeyLengths:g,nByteLength:y,wrapPrivateKey:b,n:w}=e;if(g&&typeof m!="bigint"){if(bo(m)&&(m=On(m)),typeof m!="string"||!g.includes(m.length))throw new Error("Invalid key");m=m.padStart(y*2,"0")}let x;try{x=typeof m=="bigint"?m:Mn(Ue("private key",m,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof m}`)}return b&&(x=_e(x,w)),bt("private key",x,pt,w),x}function l(m){if(!(m instanceof f))throw new Error("ProjectivePoint expected")}let d=li((m,g)=>{let{px:y,py:b,pz:w}=m;if(t.eql(w,t.ONE))return{x:y,y:b};let x=m.is0();g==null&&(g=x?t.ONE:t.inv(w));let T=t.mul(y,g),k=t.mul(b,g),v=t.mul(w,g);if(x)return{x:t.ZERO,y:t.ZERO};if(!t.eql(v,t.ONE))throw new Error("invZ was invalid");return{x:T,y:k}}),u=li(m=>{if(m.is0()){if(e.allowInfinityPoint&&!t.is0(m.py))return;throw new Error("bad point: ZERO")}let{x:g,y}=m.toAffine();if(!t.isValid(g)||!t.isValid(y))throw new Error("bad point: x or y not FE");let b=t.sqr(y),w=s(g);if(!t.eql(b,w))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class f{constructor(g,y,b){if(this.px=g,this.py=y,this.pz=b,g==null||!t.isValid(g))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(b==null||!t.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(g){let{x:y,y:b}=g||{};if(!g||!t.isValid(y)||!t.isValid(b))throw new Error("invalid affine point");if(g instanceof f)throw new Error("projective point not allowed");let w=x=>t.eql(x,t.ZERO);return w(y)&&w(b)?f.ZERO:new f(y,b,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(g){let y=t.invertBatch(g.map(b=>b.pz));return g.map((b,w)=>b.toAffine(y[w])).map(f.fromAffine)}static fromHex(g){let y=f.fromAffine(i(Ue("pointHex",g)));return y.assertValidity(),y}static fromPrivateKey(g){return f.BASE.multiply(c(g))}static msm(g,y){return Yl(f,n,g,y)}_setWindowSize(g){p.setWindowSize(this,g)}assertValidity(){u(this)}hasEvenY(){let{y:g}=this.toAffine();if(t.isOdd)return!t.isOdd(g);throw new Error("Field doesn't support isOdd")}equals(g){l(g);let{px:y,py:b,pz:w}=this,{px:x,py:T,pz:k}=g,v=t.eql(t.mul(y,k),t.mul(x,w)),S=t.eql(t.mul(b,k),t.mul(T,w));return v&&S}negate(){return new f(this.px,t.neg(this.py),this.pz)}double(){let{a:g,b:y}=e,b=t.mul(y,m8),{px:w,py:x,pz:T}=this,k=t.ZERO,v=t.ZERO,S=t.ZERO,_=t.mul(w,w),F=t.mul(x,x),N=t.mul(T,T),O=t.mul(w,x);return O=t.add(O,O),S=t.mul(w,T),S=t.add(S,S),k=t.mul(g,S),v=t.mul(b,N),v=t.add(k,v),k=t.sub(F,v),v=t.add(F,v),v=t.mul(k,v),k=t.mul(O,k),S=t.mul(b,S),N=t.mul(g,N),O=t.sub(_,N),O=t.mul(g,O),O=t.add(O,S),S=t.add(_,_),_=t.add(S,_),_=t.add(_,N),_=t.mul(_,O),v=t.add(v,_),N=t.mul(x,T),N=t.add(N,N),_=t.mul(N,O),k=t.sub(k,_),S=t.mul(N,F),S=t.add(S,S),S=t.add(S,S),new f(k,v,S)}add(g){l(g);let{px:y,py:b,pz:w}=this,{px:x,py:T,pz:k}=g,v=t.ZERO,S=t.ZERO,_=t.ZERO,F=e.a,N=t.mul(e.b,m8),O=t.mul(y,x),B=t.mul(b,T),L=t.mul(w,k),D=t.add(y,b),I=t.add(x,T);D=t.mul(D,I),I=t.add(O,B),D=t.sub(D,I),I=t.add(y,w);let A=t.add(x,k);return I=t.mul(I,A),A=t.add(O,L),I=t.sub(I,A),A=t.add(b,w),v=t.add(T,k),A=t.mul(A,v),v=t.add(B,L),A=t.sub(A,v),_=t.mul(F,I),v=t.mul(N,L),_=t.add(v,_),v=t.sub(B,_),_=t.add(B,_),S=t.mul(v,_),B=t.add(O,O),B=t.add(B,O),L=t.mul(F,L),I=t.mul(N,I),B=t.add(B,L),L=t.sub(O,L),L=t.mul(F,L),I=t.add(I,L),O=t.mul(B,I),S=t.add(S,O),O=t.mul(A,I),v=t.mul(D,v),v=t.sub(v,O),O=t.mul(D,B),_=t.mul(A,_),_=t.add(_,O),new f(v,S,_)}subtract(g){return this.add(g.negate())}is0(){return this.equals(f.ZERO)}wNAF(g){return p.wNAFCached(this,g,f.normalizeZ)}multiplyUnsafe(g){bt("scalar",g,Qn,e.n);let y=f.ZERO;if(g===Qn)return y;if(g===pt)return this;let{endo:b}=e;if(!b)return p.unsafeLadder(this,g);let{k1neg:w,k1:x,k2neg:T,k2:k}=b.splitScalar(g),v=y,S=y,_=this;for(;x>Qn||k>Qn;)x&pt&&(v=v.add(_)),k&pt&&(S=S.add(_)),_=_.double(),x>>=pt,k>>=pt;return w&&(v=v.negate()),T&&(S=S.negate()),S=new f(t.mul(S.px,b.beta),S.py,S.pz),v.add(S)}multiply(g){let{endo:y,n:b}=e;bt("scalar",g,pt,b);let w,x;if(y){let{k1neg:T,k1:k,k2neg:v,k2:S}=y.splitScalar(g),{p:_,f:F}=this.wNAF(k),{p:N,f:O}=this.wNAF(S);_=p.constTimeNegate(T,_),N=p.constTimeNegate(v,N),N=new f(t.mul(N.px,y.beta),N.py,N.pz),w=_.add(N),x=F.add(O)}else{let{p:T,f:k}=this.wNAF(g);w=T,x=k}return f.normalizeZ([w,x])[0]}multiplyAndAddUnsafe(g,y,b){let w=f.BASE,x=(k,v)=>v===Qn||v===pt||!k.equals(w)?k.multiplyUnsafe(v):k.multiply(v),T=x(this,y).add(x(g,b));return T.is0()?void 0:T}toAffine(g){return d(this,g)}isTorsionFree(){let{h:g,isTorsionFree:y}=e;if(g===pt)return!0;if(y)return y(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:g,clearCofactor:y}=e;return g===pt?this:y?y(f,this):this.multiplyUnsafe(e.h)}toRawBytes(g=!0){return zr("isCompressed",g),this.assertValidity(),o(f,this,g)}toHex(g=!0){return zr("isCompressed",g),On(this.toRawBytes(g))}}f.BASE=new f(e.Gx,e.Gy,t.ONE),f.ZERO=new f(t.ZERO,t.ONE,t.ZERO);let h=e.nBitLength,p=Ql(f,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:f,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:a}}function CS(r){let e=_a(r);return _r(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function g8(r){let e=CS(r),{Fp:t,n}=e,o=t.BYTES+1,i=2*t.BYTES+1;function s(L){return _e(L,n)}function a(L){return Gl(L,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:d,isWithinCurveOrder:u}=kS({...e,toBytes(L,D,I){let A=D.toAffine(),R=t.toBytes(A.x),P=Fn;return zr("isCompressed",I),I?P(Uint8Array.from([D.hasEvenY()?2:3]),R):P(Uint8Array.from([4]),R,t.toBytes(A.y))},fromBytes(L){let D=L.length,I=L[0],A=L.subarray(1);if(D===o&&(I===2||I===3)){let R=Mn(A);if(!Aa(R,pt,t.ORDER))throw new Error("Point is not on curve");let P=d(R),q;try{q=t.sqrt(P)}catch(ae){let ce=ae instanceof Error?": "+ae.message:"";throw new Error("Point is not on curve"+ce)}let z=(q&pt)===pt;return(I&1)===1!==z&&(q=t.neg(q)),{x:R,y:q}}else if(D===i&&I===4){let R=t.fromBytes(A.subarray(0,t.BYTES)),P=t.fromBytes(A.subarray(t.BYTES,2*t.BYTES));return{x:R,y:P}}else throw new Error(`Point of length ${D} was invalid. Expected ${o} compressed bytes or ${i} uncompressed bytes`)}}),f=L=>On(xo(L,e.nByteLength));function h(L){let D=n>>pt;return L>D}function p(L){return h(L)?s(-L):L}let m=(L,D,I)=>Mn(L.slice(D,I));class g{constructor(D,I,A){this.r=D,this.s=I,this.recovery=A,this.assertValidity()}static fromCompact(D){let I=e.nByteLength;return D=Ue("compactSignature",D,I*2),new g(m(D,0,I),m(D,I,2*I))}static fromDER(D){let{r:I,s:A}=Gn.toSig(Ue("DER",D));return new g(I,A)}assertValidity(){bt("r",this.r,pt,n),bt("s",this.s,pt,n)}addRecoveryBit(D){return new g(this.r,this.s,D)}recoverPublicKey(D){let{r:I,s:A,recovery:R}=this,P=k(Ue("msgHash",D));if(R==null||![0,1,2,3].includes(R))throw new Error("recovery id invalid");let q=R===2||R===3?I+e.n:I;if(q>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let z=R&1?"03":"02",Z=c.fromHex(z+f(q)),ae=a(q),ce=s(-P*ae),fe=s(A*ae),ve=c.BASE.multiplyAndAddUnsafe(Z,ce,fe);if(!ve)throw new Error("point at infinify");return ve.assertValidity(),ve}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,s(-this.s),this.recovery):this}toDERRawBytes(){return ci(this.toDERHex())}toDERHex(){return Gn.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return ci(this.toCompactHex())}toCompactHex(){return f(this.r)+f(this.s)}}let y={isValidPrivateKey(L){try{return l(L),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let L=o2(e.n);return i6(e.randomBytes(L),e.n)},precompute(L=8,D=c.BASE){return D._setWindowSize(L),D.multiply(BigInt(3)),D}};function b(L,D=!0){return c.fromPrivateKey(L).toRawBytes(D)}function w(L){let D=bo(L),I=typeof L=="string",A=(D||I)&&L.length;return D?A===o||A===i:I?A===2*o||A===2*i:L instanceof c}function x(L,D,I=!0){if(w(L))throw new Error("first arg must be private key");if(!w(D))throw new Error("second arg must be public key");return c.fromHex(D).multiply(l(L)).toRawBytes(I)}let T=e.bits2int||function(L){let D=Mn(L),I=L.length*8-e.nBitLength;return I>0?D>>BigInt(I):D},k=e.bits2int_modN||function(L){return s(T(L))},v=Ia(e.nBitLength);function S(L){return bt(`num < 2^${e.nBitLength}`,L,Qn,v),xo(L,e.nByteLength)}function _(L,D,I=F){if(["recovered","canonical"].some(Be=>Be in I))throw new Error("sign() legacy options not supported");let{hash:A,randomBytes:R}=e,{lowS:P,prehash:q,extraEntropy:z}=I;P==null&&(P=!0),L=Ue("msgHash",L),p8(I),q&&(L=Ue("prehashed msgHash",A(L)));let Z=k(L),ae=l(D),ce=[S(ae),S(Z)];if(z!=null&&z!==!1){let Be=z===!0?R(t.BYTES):z;ce.push(Ue("extraEntropy",Be))}let fe=Fn(...ce),ve=Z;function Ne(Be){let Ve=T(Be);if(!u(Ve))return;let Ot=a(Ve),at=c.BASE.multiply(Ve).toAffine(),Qt=s(at.x);if(Qt===Qn)return;let Pn=s(Ot*s(ve+Qt*ae));if(Pn===Qn)return;let ha=(at.x===Qt?0:2)|Number(at.y&pt),pa=Pn;return P&&h(Pn)&&(pa=p(Pn),ha^=1),new g(Qt,pa,ha)}return{seed:fe,k2sig:Ne}}let F={lowS:e.lowS,prehash:!1},N={lowS:e.lowS,prehash:!1};function O(L,D,I=F){let{seed:A,k2sig:R}=_(L,D,I),P=e;return J0(P.hash.outputLen,P.nByteLength,P.hmac)(A,R)}c.BASE._setWindowSize(8);function B(L,D,I,A=N){let R=L;if(D=Ue("msgHash",D),I=Ue("publicKey",I),"strict"in A)throw new Error("options.strict was renamed to lowS");p8(A);let{lowS:P,prehash:q}=A,z,Z;try{if(typeof R=="string"||bo(R))try{z=g.fromDER(R)}catch(at){if(!(at instanceof Gn.Err))throw at;z=g.fromCompact(R)}else if(typeof R=="object"&&typeof R.r=="bigint"&&typeof R.s=="bigint"){let{r:at,s:Qt}=R;z=new g(at,Qt)}else throw new Error("PARSE");Z=c.fromHex(I)}catch(at){if(at.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(P&&z.hasHighS())return!1;q&&(D=e.hash(D));let{r:ae,s:ce}=z,fe=k(D),ve=a(ce),Ne=s(fe*ve),Be=s(ae*ve),Ve=c.BASE.multiplyAndAddUnsafe(Z,Ne,Be)?.toAffine();return Ve?s(Ve.x)===ae:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:x,sign:O,verify:B,ProjectivePoint:c,Signature:g,utils:y}}function PS(r){return{hash:r,hmac:(e,...t)=>_o(r,e,W0(...t)),randomBytes:si}}function y8(r,e){let t=n=>g8({...r,...PS(n)});return Object.freeze({...t(e),create:t})}var x8=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),w8=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),RS=BigInt(1),S2=BigInt(2),b8=(r,e)=>(r+e/S2)/e;function LS(r){let e=x8,t=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,d=l*l*r%e,u=Fe(d,t,e)*d%e,f=Fe(u,t,e)*d%e,h=Fe(f,S2,e)*l%e,p=Fe(h,o,e)*h%e,m=Fe(p,i,e)*p%e,g=Fe(m,a,e)*m%e,y=Fe(g,c,e)*g%e,b=Fe(y,a,e)*m%e,w=Fe(b,t,e)*d%e,x=Fe(w,s,e)*p%e,T=Fe(x,n,e)*l%e,k=Fe(T,S2,e);if(!A2.eql(A2.sqr(k),r))throw new Error("Cannot find square root");return k}var A2=Eo(x8,void 0,void 0,{sqrt:LS}),Pr=y8({a:BigInt(0),b:BigInt(7),Fp:A2,n:w8,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=w8,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-RS*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=t,s=BigInt("0x100000000000000000000000000000000"),a=b8(i*r,e),c=b8(-n*r,e),l=_e(r-a*t-c*o,e),d=_e(-a*n-c*i,e),u=l>s,f=d>s;if(u&&(l=e-l),f&&(d=e-d),l>s||d>s)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:u,k1:l,k2neg:f,k2:d}}}},Tr),qB=BigInt(0);var WB=Pr.ProjectivePoint;function I2(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function E8(r,e){let t=ut.digest(e instanceof Uint8Array?e:e.subarray());if(I2(t))return t.then(({digest:n})=>Pr.sign(n,r).toDERRawBytes()).catch(n=>{throw new $a(String(n))});try{return Pr.sign(t.digest,r).toDERRawBytes()}catch(n){throw new $a(String(n))}}function v8(r,e,t){let n=ut.digest(t instanceof Uint8Array?t:t.subarray());if(I2(n))return n.then(({digest:o})=>Pr.verify(e,o,r)).catch(o=>{throw new Va(String(o))});try{return Pr.verify(e,n.digest,r)}catch(o){throw new Va(String(o))}}var qa=class{type="secp256k1";raw;_key;constructor(e){this._key=I8(e),this.raw=S8(this._key)}toMultihash(){return Jt.digest(Lt(this))}toCID(){return X.createV1(114,this.toMultihash())}toString(){return Se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}verify(e,t){return v8(this._key,t,e)}},Wa=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=A8(e),this.publicKey=new qa(t??_8(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}sign(e){return E8(this.raw,e)}};function _2(r){return new Wa(r)}function T2(r){return new qa(r)}async function T8(){let r=DS();return new Wa(r)}function S8(r){return Pr.ProjectivePoint.fromHex(r).toRawBytes(!0)}function A8(r){try{return Pr.getPublicKey(r,!0),r}catch(e){throw new ma(String(e))}}function I8(r){try{return Pr.ProjectivePoint.fromHex(r),r}catch(e){throw new Rn(String(e))}}function _8(r){try{return Pr.getPublicKey(r,!0)}catch(e){throw new ma(String(e))}}function DS(){return Pr.utils.randomPrivateKey()}async function Hu(r,e){if(r==="Ed25519")return y6();if(r==="secp256k1")return T8();if(r==="RSA")return v2(e??2048);throw new $r}function rt(r){let{Type:e,Data:t}=yn.decode(r),n=t??new Uint8Array;switch(e){case Ye.RSA:return E2(n);case Ye.Ed25519:return u2(n);case Ye.secp256k1:return T2(n);default:throw new $r}}function qu(r){let{Type:e,Data:t}=yn.decode(r.digest),n=t??new Uint8Array;switch(e){case Ye.Ed25519:return u2(n);case Ye.secp256k1:return T2(n);default:throw new $r}}function Lt(r){return yn.encode({Type:Ye[r.type],Data:r.raw})}function k8(r){let e=Ra.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Ye.RSA:return Vu(t);case Ye.Ed25519:return l2(t);case Ye.secp256k1:return _2(t);default:throw new $r}}function C8(r){return r.byteLength===64?l2(r):r.byteLength===32?_2(r):Vu(r)}function hs(r){return Ra.encode({Type:Ye[r.type],Data:r.raw})}var P8=Symbol.for("nodejs.util.inspect.custom"),NS=114,za=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()})`}[al]=!0;toString(){return this.string==null&&(this.string=Se.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return X.createV1(NS,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return te(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return te(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[P8](){return`PeerId(${this.toString()})`}},Ga=class extends za{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Qa=class extends za{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Ya=class extends za{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},BS=2336,Xa=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Jt.digest(M(this.url))}[P8](){return`PeerId(${this.url})`}[al]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return X.createV1(BS,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=V(e)),e.toString()===this.toString())}};var OS=114,R8=2336;function Re(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=ke(Se.decode(`z${r}`));else{if(e==null)throw new C('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=ke(e.decode(r))}return mt(t)}function En(r){if(r.type==="Ed25519")return new Qa({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Ya({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Ga({multihash:r.toCID().multihash,publicKey:r});throw new $r}function L8(r){return En(r.publicKey)}function mt(r){if(US(r))return new Ga({multihash:r});if(MS(r))try{let e=qu(r);if(e.type==="Ed25519")return new Qa({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Ya({multihash:r,publicKey:e})}catch{let t=V(r.digest);return new Xa(new URL(t))}throw new co("Supplied PeerID Multihash is invalid")}function vn(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==OS&&r.code!==R8)throw new hl("Supplied PeerID CID is invalid");if(r.code===R8){let e=V(r.multihash.digest);return new Xa(new URL(e))}return mt(r.multihash)}function MS(r){return r.code===Jt.code}function US(r){return r.code===ut.code}function hi(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function Wu(r){let e=ke(Se.decode(`z${r}`));return mt(e)}var gt=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 hi(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 hi(this.map.values(),e=>e.key)}values(){return hi(this.map.values(),e=>e.value)}get size(){return this.map.size}};var nr=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 hi(this.set.entries(),e=>{let t=Wu(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Wu(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return hi(this.set.values(),e=>Wu(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}};function D8(r,e,t,n){ni(r);let o=j4({dkLen:32,asyncTick:10},n),{c:i,dkLen:s,asyncTick:a}=o;if(po(i),po(s),po(a),i<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=Wr(e),l=Wr(t),d=new Uint8Array(s),u=_o.create(r,c),f=u._cloneInto().update(l);return{c:i,dkLen:s,asyncTick:a,DK:d,PRF:u,PRFSalt:f}}function N8(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}function B8(r,e,t,n){let{c:o,dkLen:i,DK:s,PRF:a,PRFSalt:c}=D8(r,e,t,n),l,d=new Uint8Array(4),u=ii(d),f=new Uint8Array(a.outputLen);for(let h=1,p=0;p<i;h++,p+=a.outputLen){let m=s.subarray(p,p+a.outputLen);u.setInt32(0,h,!1),(l=c._cloneInto(l)).update(d).digestInto(f),m.set(f.subarray(0,m.length));for(let g=1;g<o;g++){a._cloneInto(l).update(f).digestInto(f);for(let y=0;y<m.length;y++)m[y]^=f[y]}}return N8(a,c,s,l,f)}async function zu(r,e,t,n){let{c:o,dkLen:i,asyncTick:s,DK:a,PRF:c,PRFSalt:l}=D8(r,e,t,n),d,u=new Uint8Array(4),f=ii(u),h=new Uint8Array(c.outputLen);for(let p=1,m=0;m<i;p++,m+=c.outputLen){let g=a.subarray(m,m+c.outputLen);f.setInt32(0,p,!1),(d=l._cloneInto(d)).update(u).digestInto(h),g.set(h.subarray(0,g.length)),await Y4(o-1,s,()=>{c._cloneInto(d).update(h).digestInto(h);for(let y=0;y<g.length;y++)g[y]^=h[y]})}return N8(c,l,a,d,h)}var ja=new Uint32Array([1732584193,4023233417,2562383102,271733878,3285377520]),To=new Uint32Array(80),k2=class extends mo{constructor(){super(64,20,8,!1),this.A=ja[0]|0,this.B=ja[1]|0,this.C=ja[2]|0,this.D=ja[3]|0,this.E=ja[4]|0}get(){let{A:e,B:t,C:n,D:o,E:i}=this;return[e,t,n,o,i]}set(e,t,n,o,i){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=i|0}process(e,t){for(let c=0;c<16;c++,t+=4)To[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)To[c]=Vl(To[c-3]^To[c-8]^To[c-14]^To[c-16],1);let{A:n,B:o,C:i,D:s,E:a}=this;for(let c=0;c<80;c++){let l,d;c<20?(l=Kl(o,i,s),d=1518500249):c<40?(l=o^i^s,d=1859775393):c<60?(l=Hl(o,i,s),d=2400959708):(l=o^i^s,d=3395469782);let u=Vl(n,5)+l+a+d+To[c]|0;a=s,s=i,i=Vl(o,30),o=n,n=u}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,this.set(n,o,i,s,a)}roundClean(){To.fill(0)}destroy(){this.set(0,0,0,0,0),this.buffer.fill(0)}},O8=ns(()=>new k2);var M8={sha1:O8,"sha2-256":Tr,"sha2-512":wo};function Za(r,e,t,n,o){if(o!=="sha1"&&o!=="sha2-256"&&o!=="sha2-512"){let a=Object.keys(M8).join(" / ");throw new C(`Hash '${o}' is unknown or not supported. Must be ${a}`)}let i=M8[o],s=B8(i,r,e,{c:t,dkLen:n});return it.encode(s).substring(1)}var C2=64,Xr=class{fp;h;seed;constructor(e,t,n,o=2){if(o>C2)throw new TypeError("Invalid Fingerprint Size");let i=t.hashV(e,n),s=se(o);for(let a=0;a<s.length;a++)s[a]=i[a];s.length===0&&(s[0]=7),this.fp=s,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?te(this.fp,e.fp):!1}};function pi(r,e){return Math.floor(Math.random()*(e-r))+r}var mi=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Xr))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof Xr))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 Xr))throw new TypeError("Invalid Fingerprint");let t=pi(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof Xr))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var P2={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},V8={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},K8=new globalThis.TextEncoder;function $S(r,e){let t=P2[e],n=V8[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function VS(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=P2[e],o=V8[e],i=r;for(;i.length>0;){let s=K8.encodeInto(i,t);i=i.slice(s.read);for(let a=0;a<s.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function R2(r,{size:e=32,utf8Buffer:t}={}){if(!P2[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 VS(r,e,t);r=K8.encode(r)}return $S(r,e)}var KS=fr($8(),1);var ec={hash:r=>Number(R2(r,{size:32})),hashV:(r,e)=>HS(ec.hash(r,e))};function HS(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),M(e,"base16")}var qS=500,tc=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??ec,this.seed=e.seed??pi(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=M(e));let t=new Xr(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new mi(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new mi(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let i=[n,o],s=i[pi(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new mi(this.bucketSize));for(let a=0;a<qS;a++){let c=this.buckets[s].swap(t);if(c!=null&&(s=(s^c.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new mi(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=M(e));let t=new Xr(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let i=(n^t.hash())%this.filterSize;return this.buckets[i]?.has(t)??!1}remove(e){typeof e=="string"&&(e=M(e));let t=new Xr(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let i=(n^t.hash())%this.filterSize,s=this.buckets[i]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},WS={1:.5,2:.84,4:.95,8:.98};function zS(r=.001){return r>.002?2:r>1e-5?4:8}function H8(r,e=.001){let t=zS(e),n=WS[t],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),C2);return{filterSize:o,bucketSize:t,fingerprintSize:i}}var Qu=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??ec,this.seed=e.seed??pi(0,Math.pow(2,10)),this.filterSeries=[new tc({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=M(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 tc({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=M(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=M(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 Sn(r,e=.001,t){return new Qu({...H8(r,e),...t??{}})}var Yu=class{filter;constructor(e,t){this.filter=Sn(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 L2(r,e=.001){return new Yu(r,e)}var D2=class extends gt{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 rc(r){let{name:e,metrics:t}=r,n;return t!=null?n=new D2({name:e,metrics:t}):n=new gt,n}var Yn=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(e=!1,t=0){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){let n=it.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=it.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=it.encode(e.multihash.bytes);this.blocks.set(n,t)}};function GS(r){let e=new Uint8Array(r.reduce((n,o)=>n+pe(o),0)),t=0;for(let n of r)e=Ke(n,e,t),t+=pe(n);return e}var q8=GS;function N2(r){return q8([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var Xu=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}async sendBlocksToPeer(e){let t=new Yn,n=new Set;for(let[o,i]of this.wants.entries())try{let s=await this.blockstore.get(i.cid,e);i.wantType===et.WantHave?s.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(o),t.addBlock(i.cid,{data:s,prefix:N2(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Ir.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(o),t.addBlock(i.cid,{data:s,prefix:N2(i.cid)}))}catch(s){if(s.name!=="NotFoundError")throw s;if(this.log("do not have block for %c",i.cid),!i.sendDontHave||i.sentDontHave===!0)continue;i.sentDontHave=!0,t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Ir.DontHaveBlock})}if(t.blocks.size>0||t.blockPresences.size>0){this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((o,i)=>o+i.data.byteLength,0));for(let o of n)this.wants.delete(o)}}};var ju=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=rc({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return[...t.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);if(n==null&&(n=new Xu({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((o,i)=>o+i.data.byteLength,0)??0),t.wantlist!=null){t.wantlist.full===!0&&n.wants.clear();for(let o of t.wantlist.entries){let i=X.decode(o.cid),s=V(i.multihash.bytes,"base64");o.cancel===!0?(this.log("peer %p cancelled want of block for %c",e,i),n.wants.delete(s)):(o.wantType===et.WantHave?this.log("peer %p wanted block presence for %c",e,i):this.log("peer %p wanted block for %c",e,i),n.wants.set(s,{cid:i,priority:o.priority,wantType:o.wantType??et.WantBlock,sendDontHave:o.sendDontHave??!1}))}}this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=V(e.multihash.bytes,"base64"),o=[];for(let i of this.ledgerMap.values())i.wants.has(n)&&o.push(i);await Promise.all(o.map(async i=>i.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};function QS(r,e){try{if(typeof r=="string"&&r.length>0)return YS(r);if(typeof r=="number"&&isFinite(r))return e?.long?jS(r):XS(r);throw new Error("Value is not a string or number.")}catch(t){let n=ZS(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function YS(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let 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)return NaN;let t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*315576e5;case"weeks":case"week":case"w":return t*6048e5;case"days":case"day":case"d":return t*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return t*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return t*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return t*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var Ju=QS;function XS(r){let e=Math.abs(r);return 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 jS(r){let e=Math.abs(r);return e>=864e5?Zu(r,e,864e5,"day"):e>=36e5?Zu(r,e,36e5,"hour"):e>=6e4?Zu(r,e,6e4,"minute"):e>=1e3?Zu(r,e,1e3,"second"):`${r} ms`}function Zu(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function ZS(r){return typeof r=="object"&&r!==null&&"message"in r}function B2(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=o,t.enabled=s,t.humanize=Ju,t.destroy=l,Object.keys(r).forEach(d=>{t[d]=r[d]}),t.names=[],t.skips=[],t.formatters={};function e(d){let u=0;for(let f=0;f<d.length;f++)u=(u<<5)-u+d.charCodeAt(f),u|=0;return t.colors[Math.abs(u)%t.colors.length]}t.selectColor=e;function t(d){let u,f=null,h,p;function m(...g){if(!m.enabled)return;let y=m,b=Number(new Date),w=b-(u||b);y.diff=w,y.prev=u,y.curr=b,u=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,(k,v)=>{if(k==="%%")return"%";x++;let S=t.formatters[v];if(typeof S=="function"){let _=g[x];k=S.call(y,_),g.splice(x,1),x--}return k}),t.formatArgs.call(y,g),(y.log||t.log).apply(y,g)}return m.namespace=d,m.useColors=t.useColors(),m.color=t.selectColor(d),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(h!==t.namespaces&&(h=t.namespaces,p=t.enabled(d)),p),set:g=>{f=g}}),typeof t.init=="function"&&t.init(m),m}function n(d,u){let f=t(this.namespace+(typeof u>"u"?":":u)+d);return f.log=this.log,f}function o(d){t.save(d),t.namespaces=d,t.names=[],t.skips=[];let u,f=(typeof d=="string"?d:"").split(/[\s,]+/),h=f.length;for(u=0;u<h;u++)f[u]&&(d=f[u].replace(/\*/g,".*?"),d[0]==="-"?t.skips.push(new RegExp("^"+d.substr(1)+"$")):t.names.push(new RegExp("^"+d+"$")))}function i(){let d=[...t.names.map(a),...t.skips.map(a).map(u=>"-"+u)].join(",");return t.enable(""),d}function s(d){if(d[d.length-1]==="*")return!0;let u,f;for(u=0,f=t.skips.length;u<f;u++)if(t.skips[u].test(d))return!1;for(u=0,f=t.names.length;u<f;u++)if(t.names[u].test(d))return!0;return!1}function a(d){return d.toString().substring(2,d.toString().length-2).replace(/\.\*\?$/,"*")}function c(d){return d instanceof Error?d.stack??d.message:d}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 e1=iA(),JS=["#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 eA(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function tA(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ju(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,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var rA=console.debug??console.log??(()=>{});function nA(r){try{r?e1?.setItem("debug",r):e1?.removeItem("debug")}catch{}}function oA(){let r;try{r=e1?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function iA(){try{return localStorage}catch{}}function sA(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var W8=B2({formatArgs:tA,save:nA,load:oA,useColors:eA,setupFormatters:sA,colors:JS,storage:e1,log:rA});var or=W8;or.formatters.b=r=>r==null?"undefined":Se.baseEncode(r);or.formatters.t=r=>r==null?"undefined":lt.baseEncode(r);or.formatters.m=r=>r==null?"undefined":it.baseEncode(r);or.formatters.p=r=>r==null?"undefined":r.toString();or.formatters.c=r=>r==null?"undefined":r.toString();or.formatters.k=r=>r==null?"undefined":r.toString();or.formatters.a=r=>r==null?"undefined":r.toString();or.formatters.e=r=>r==null?"undefined":z8(r.stack)??z8(r.message)??r.toString();function aA(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 ko(){return{forComponent(r){return mr(r)}}}function mr(r){let e=aA(`${r}:trace`);return or.enabled(`${r}:trace`)&&or.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=or(`${r}:trace`)),Object.assign(or(r),{error:or(`${r}:error`),trace:e})}function z8(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var M2=fr(Q8(),1);var oc=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},U2=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Y8=r=>globalThis.DOMException===void 0?new U2(r):new DOMException(r),X8=r=>{let e=r.reason===void 0?Y8("This operation was aborted."):r.reason;return e instanceof Error?e:Y8(e)};function jr(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,s,c=new Promise((l,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:f}=e;f.aborted&&d(X8(f));let h=()=>{d(X8(f))};f.addEventListener("abort",h,{once:!0}),r.finally(()=>{f.removeEventListener("abort",h)})}if(t===Number.POSITIVE_INFINITY){r.then(l,d);return}let u=new oc;s=i.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(f){d(f)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?d(o):(u.message=o??`Promise timed out after ${t} milliseconds`,d(u))},t),(async()=>{try{l(await r)}catch(f){d(f)}})()}).finally(()=>{c.clear()});return c.clear=()=>{i.clearTimeout.call(void 0,s),s=void 0},c}function F2(r,e,t){let n=0,o=r.length;for(;o>0;){let i=Math.trunc(o/2),s=n+i;t(r[s],e)<=0?(n=++s,o-=i+1):o=i}return n}var ic=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=F2(this.#e,n,(i,s)=>s.priority-i.priority);this.#e.splice(o,0,n)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var An=class extends M2.default{#e;#t;#r=0;#o;#a;#l=0;#i;#u;#n;#m;#s=0;#d;#c;#g;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:ic,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#o=e.intervalCap,this.#a=e.interval,this.#n=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#c=e.autoStart===!1}get#b(){return this.#t||this.#r<this.#o}get#x(){return this.#s<this.#d}#E(){this.#s--,this.#f(),this.emit("next")}#v(){this.#w(),this.#y(),this.#u=void 0}get#S(){let e=Date.now();if(this.#i===void 0){let t=this.#l-e;if(t<0)this.#r=this.#e?this.#s:0;else return this.#u===void 0&&(this.#u=setTimeout(()=>{this.#v()},t)),!0}return!1}#f(){if(this.#n.size===0)return this.#i&&clearInterval(this.#i),this.#i=void 0,this.emit("empty"),this.#s===0&&this.emit("idle"),!1;if(!this.#c){let e=!this.#S;if(this.#b&&this.#x){let t=this.#n.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#i!==void 0||(this.#i=setInterval(()=>{this.#w()},this.#a),this.#l=Date.now()+this.#a)}#w(){this.#r===0&&this.#s===0&&this.#i&&(clearInterval(this.#i),this.#i=void 0),this.#r=this.#e?this.#s:0,this.#h()}#h(){for(;this.#f(););}get concurrency(){return this.#d}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#d=e,this.#h()}async#A(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#n.enqueue(async()=>{this.#s++,this.#r++;try{t.signal?.throwIfAborted();let i=e({signal:t.signal});t.timeout&&(i=jr(Promise.resolve(i),{milliseconds:t.timeout})),t.signal&&(i=Promise.race([i,this.#A(t.signal)]));let s=await i;n(s),this.emit("completed",s)}catch(i){if(i instanceof oc&&!t.throwOnTimeout){n();return}o(i),this.emit("error",i)}finally{this.#E()}},t),this.emit("add"),this.#f()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#c?(this.#c=!1,this.#h(),this):this}pause(){this.#c=!0}clear(){this.#n=new this.#m}async onEmpty(){this.#n.size!==0&&await this.#p("empty")}async onSizeLessThan(e){this.#n.size<e||await this.#p("next",()=>this.#n.size<e)}async onIdle(){this.#s===0&&this.#n.size===0||await this.#p("idle")}async#p(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#n.size}sizeBy(e){return this.#n.filter(e).length}get pending(){return this.#s}get isPaused(){return this.#c}};function r1(r){let e=[gr.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var $2=60;function n1(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:gr[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:gr[e.type],TTL:e.TTL??e.ttl??$2,data:e.data instanceof Uint8Array?V(e.data):e.data}))}}var uA=4;function V2(r,e={}){let t=new An({concurrency:e.queryConcurrency??uA});return async(n,o={})=>{let i=new URLSearchParams;i.set("name",n),r1(o.types).forEach(a=>{i.append("type",gr[a])}),o.onProgress?.(new H("dns:query",{detail:n}));let s=await t.add(async()=>{let a=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=n1(await a.json());return o.onProgress?.(new H("dns:response",{detail:c})),c},{signal:o.signal});if(s==null)throw new Error("No DNS response received");return s}}function j8(){return[V2("https://cloudflare-dns.com/dns-query"),V2("https://dns.google/resolve")]}var e5=fr(J8(),1);var K2=class{lru;constructor(e){this.lru=(0,e5.default)(e)}get(e,t){let n=!0,o=[];for(let i of t){let s=this.getAnswers(e,i);if(s.length===0){n=!1;break}o.push(...s)}if(n)return n1({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let i=o.filter(s=>s.expires>Date.now()).map(({expires:s,value:a})=>({...a,TTL:Math.round((s-Date.now())/1e3),type:gr[a.type]}));return i.length===0&&this.lru.remove(n),i}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??$2)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function t5(r){return new K2(r)}var dA=1e3,o1=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=t5(e.cacheSize??dA),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["."]=j8())}async query(e,t={}){let n=r1(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new H("dns:cache",{detail:o})),o;let i=`${e.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of s){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let d of l.Answer)this.cache.add(e,d);return l}catch(l){a.push(l),t.onProgress?.(new H("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var gr;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(gr||(gr={}));function i1(r={}){return new o1(r)}var fA=["string","number","bigint","symbol"],hA=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function r5(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(fA.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(pA(r))return"Buffer";let t=mA(r);return t||"Object"}function pA(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function mA(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(hA.includes(e))return e}var E=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};E.uint=new E(0,"uint",!0);E.negint=new E(1,"negint",!0);E.bytes=new E(2,"bytes",!0);E.string=new E(3,"string",!0);E.array=new E(4,"array",!1);E.map=new E(5,"map",!1);E.tag=new E(6,"tag",!1);E.float=new E(7,"float",!0);E.false=new E(7,"false",!0);E.true=new E(7,"true",!0);E.null=new E(7,"null",!0);E.undefined=new E(7,"undefined",!0);E.break=new E(7,"break",!0);var U=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var ps=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",gA=new TextDecoder,yA=new TextEncoder;function s1(r){return ps&&globalThis.Buffer.isBuffer(r)}function sc(r){return r instanceof Uint8Array?s1(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var s5=ps?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):o5(r,e,t):(r,e,t)=>t-e>64?gA.decode(r.subarray(e,t)):o5(r,e,t),a1=ps?r=>r.length>64?globalThis.Buffer.from(r):n5(r):r=>r.length>64?yA.encode(r):n5(r),In=r=>Uint8Array.from(r),ms=ps?(r,e,t)=>s1(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),a5=ps?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),sc(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let o of r)n+o.length>t.length&&(o=o.subarray(0,t.length-n)),t.set(o,n),n+=o.length;return t},c5=ps?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function l5(r,e){if(s1(r)&&s1(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function n5(r){let e=[],t=0;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(o=65536+((o&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128)}return e}function o5(r,e,t){let n=[];for(;e<t;){let o=r[e],i=null,s=o>239?4:o>223?3:o>191?2:1;if(e+s<=t){let a,c,l,d;switch(s){case 1:o<128&&(i=o);break;case 2:a=r[e+1],(a&192)===128&&(d=(o&31)<<6|a&63,d>127&&(i=d));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(d=(o&15)<<12|(a&63)<<6|c&63,d>2047&&(d<55296||d>57343)&&(i=d));break;case 4:a=r[e+1],c=r[e+2],l=r[e+3],(a&192)===128&&(c&192)===128&&(l&192)===128&&(d=(o&15)<<18|(a&63)<<12|(c&63)<<6|l&63,d>65535&&d<1114112&&(i=d))}}i===null?(i=65533,s=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|i&1023),n.push(i),e+=s}return H2(n)}var i5=4096;function H2(r){let e=r.length;if(e<=i5)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=i5));return t}var wA=256,ac=class{constructor(e=wA){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=t.length-(this.maxCursor-this.cursor)-1;t.set(e,o)}else{if(t){let o=t.length-(this.maxCursor-this.cursor)-1;o<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=c5(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=ms(n,0,this.cursor)}else t=a5(this.chunks,this.cursor);return e&&this.reset(),t}};var j="CBOR decode error:",Xn="CBOR encode error:",cc=[];cc[23]=1;cc[24]=2;cc[25]=3;cc[26]=5;cc[27]=9;function jn(r,e,t){if(r.length-e<t)throw new Error(`${j} not enough data for type`)}var yt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function yr(r,e,t){jn(r,e,1);let n=r[e];if(t.strict===!0&&n<yt[0])throw new Error(`${j} integer encoded in more bytes than necessary (strict decode)`);return n}function wr(r,e,t){jn(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<yt[1])throw new Error(`${j} integer encoded in more bytes than necessary (strict decode)`);return n}function br(r,e,t){jn(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<yt[2])throw new Error(`${j} integer encoded in more bytes than necessary (strict decode)`);return n}function xr(r,e,t){jn(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],o=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&i<yt[3])throw new Error(`${j} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(t.allowBigInt===!0)return i;throw new Error(`${j} integers outside of the safe integer range are not supported`)}function u5(r,e,t,n){return new U(E.uint,yr(r,e+1,n),2)}function d5(r,e,t,n){return new U(E.uint,wr(r,e+1,n),3)}function f5(r,e,t,n){return new U(E.uint,br(r,e+1,n),5)}function h5(r,e,t,n){return new U(E.uint,xr(r,e+1,n),9)}function Rr(r,e){return Et(r,0,e.value)}function Et(r,e,t){if(t<yt[0]){let n=Number(t);r.push([e|n])}else if(t<yt[1]){let n=Number(t);r.push([e|24,n])}else if(t<yt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<yt[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<yt[4]){let o=[e|27,0,0,0,0,0,0,0],i=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=s&255,s=s>>8,o[3]=s&255,s=s>>8,o[2]=s&255,s=s>>8,o[1]=s&255,r.push(o)}else throw new Error(`${j} encountered BigInt larger than allowable range`)}}Rr.encodedSize=function(e){return Et.encodedSize(e.value)};Et.encodedSize=function(e){return e<yt[0]?1:e<yt[1]?2:e<yt[2]?3:e<yt[3]?5:9};Rr.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function p5(r,e,t,n){return new U(E.negint,-1-yr(r,e+1,n),2)}function m5(r,e,t,n){return new U(E.negint,-1-wr(r,e+1,n),3)}function g5(r,e,t,n){return new U(E.negint,-1-br(r,e+1,n),5)}var q2=BigInt(-1),y5=BigInt(1);function w5(r,e,t,n){let o=xr(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new U(E.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${j} integers outside of the safe integer range are not supported`);return new U(E.negint,q2-BigInt(o),9)}function c1(r,e){let t=e.value,n=typeof t=="bigint"?t*q2-y5:t*-1-1;Et(r,e.type.majorEncoded,n)}c1.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*q2-y5:t*-1-1;return n<yt[0]?1:n<yt[1]?2:n<yt[2]?3:n<yt[3]?5:9};c1.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function lc(r,e,t,n){jn(r,e,t+n);let o=ms(r,e+t,e+t+n);return new U(E.bytes,o,t+n)}function b5(r,e,t,n){return lc(r,e,1,t)}function x5(r,e,t,n){return lc(r,e,2,yr(r,e+1,n))}function E5(r,e,t,n){return lc(r,e,3,wr(r,e+1,n))}function v5(r,e,t,n){return lc(r,e,5,br(r,e+1,n))}function S5(r,e,t,n){let o=xr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${j} 64-bit integer bytes lengths not supported`);return lc(r,e,9,o)}function l1(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===E.string?a1(r.value):r.value),r.encodedBytes}function gs(r,e){let t=l1(e);Et(r,e.type.majorEncoded,t.length),r.push(t)}gs.encodedSize=function(e){let t=l1(e);return Et.encodedSize(t.length)+t.length};gs.compareTokens=function(e,t){return xA(l1(e),l1(t))};function xA(r,e){return r.length<e.length?-1:r.length>e.length?1:l5(r,e)}function uc(r,e,t,n,o){let i=t+n;jn(r,e,i);let s=new U(E.string,s5(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=ms(r,e+t,e+i)),s}function A5(r,e,t,n){return uc(r,e,1,t,n)}function I5(r,e,t,n){return uc(r,e,2,yr(r,e+1,n),n)}function _5(r,e,t,n){return uc(r,e,3,wr(r,e+1,n),n)}function T5(r,e,t,n){return uc(r,e,5,br(r,e+1,n),n)}function k5(r,e,t,n){let o=xr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${j} 64-bit integer string lengths not supported`);return uc(r,e,9,o,n)}var C5=gs;function ys(r,e,t,n){return new U(E.array,n,t)}function P5(r,e,t,n){return ys(r,e,1,t)}function R5(r,e,t,n){return ys(r,e,2,yr(r,e+1,n))}function L5(r,e,t,n){return ys(r,e,3,wr(r,e+1,n))}function D5(r,e,t,n){return ys(r,e,5,br(r,e+1,n))}function N5(r,e,t,n){let o=xr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${j} 64-bit integer array lengths not supported`);return ys(r,e,9,o)}function B5(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${j} indefinite length items not allowed`);return ys(r,e,1,1/0)}function u1(r,e){Et(r,E.array.majorEncoded,e.value)}u1.compareTokens=Rr.compareTokens;u1.encodedSize=function(e){return Et.encodedSize(e.value)};function ws(r,e,t,n){return new U(E.map,n,t)}function O5(r,e,t,n){return ws(r,e,1,t)}function M5(r,e,t,n){return ws(r,e,2,yr(r,e+1,n))}function U5(r,e,t,n){return ws(r,e,3,wr(r,e+1,n))}function F5(r,e,t,n){return ws(r,e,5,br(r,e+1,n))}function $5(r,e,t,n){let o=xr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${j} 64-bit integer map lengths not supported`);return ws(r,e,9,o)}function V5(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${j} indefinite length items not allowed`);return ws(r,e,1,1/0)}function d1(r,e){Et(r,E.map.majorEncoded,e.value)}d1.compareTokens=Rr.compareTokens;d1.encodedSize=function(e){return Et.encodedSize(e.value)};function K5(r,e,t,n){return new U(E.tag,t,1)}function H5(r,e,t,n){return new U(E.tag,yr(r,e+1,n),2)}function q5(r,e,t,n){return new U(E.tag,wr(r,e+1,n),3)}function W5(r,e,t,n){return new U(E.tag,br(r,e+1,n),5)}function z5(r,e,t,n){return new U(E.tag,xr(r,e+1,n),9)}function f1(r,e){Et(r,E.tag.majorEncoded,e.value)}f1.compareTokens=Rr.compareTokens;f1.encodedSize=function(e){return Et.encodedSize(e.value)};var _A=20,TA=21,kA=22,CA=23;function G5(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${j} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new U(E.null,null,1):new U(E.undefined,void 0,1)}function Q5(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${j} indefinite length items not allowed`);return new U(E.break,void 0,1)}function W2(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${j} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${j} Infinity values are not supported`)}return new U(E.float,r,e)}function Y5(r,e,t,n){return W2(z2(r,e+1),3,n)}function X5(r,e,t,n){return W2(G2(r,e+1),5,n)}function j5(r,e,t,n){return W2(tg(r,e+1),9,n)}function h1(r,e,t){let n=e.value;if(n===!1)r.push([E.float.majorEncoded|_A]);else if(n===!0)r.push([E.float.majorEncoded|TA]);else if(n===null)r.push([E.float.majorEncoded|kA]);else if(n===void 0)r.push([E.float.majorEncoded|CA]);else{let o,i=!1;(!t||t.float64!==!0)&&(J5(n),o=z2(Zr,1),n===o||Number.isNaN(n)?(Zr[0]=249,r.push(Zr.slice(0,3)),i=!0):(eg(n),o=G2(Zr,1),n===o&&(Zr[0]=250,r.push(Zr.slice(0,5)),i=!0))),i||(PA(n),o=tg(Zr,1),Zr[0]=251,r.push(Zr.slice(0,9)))}}h1.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){J5(n);let o=z2(Zr,1);if(n===o||Number.isNaN(n))return 3;if(eg(n),o=G2(Zr,1),n===o)return 5}return 9};var Z5=new ArrayBuffer(9),Lr=new DataView(Z5,1),Zr=new Uint8Array(Z5,0);function J5(r){if(r===1/0)Lr.setUint16(0,31744,!1);else if(r===-1/0)Lr.setUint16(0,64512,!1);else if(Number.isNaN(r))Lr.setUint16(0,32256,!1);else{Lr.setFloat32(0,r);let e=Lr.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Lr.setUint16(0,31744,!1);else if(t===0)Lr.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?Lr.setUint16(0,0):o<-14?Lr.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Lr.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function z2(r,e){if(r.length-e<2)throw new Error(`${j} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,t&32768?-i:i}function eg(r){Lr.setFloat32(0,r,!1)}function G2(r,e){if(r.length-e<4)throw new Error(`${j} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function PA(r){Lr.setFloat64(0,r,!1)}function tg(r,e){if(r.length-e<8)throw new Error(`${j} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}h1.compareTokens=Rr.compareTokens;function Ae(r,e,t){throw new Error(`${j} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function p1(r){return()=>{throw new Error(`${j} ${r}`)}}var K=[];for(let r=0;r<=23;r++)K[r]=Ae;K[24]=u5;K[25]=d5;K[26]=f5;K[27]=h5;K[28]=Ae;K[29]=Ae;K[30]=Ae;K[31]=Ae;for(let r=32;r<=55;r++)K[r]=Ae;K[56]=p5;K[57]=m5;K[58]=g5;K[59]=w5;K[60]=Ae;K[61]=Ae;K[62]=Ae;K[63]=Ae;for(let r=64;r<=87;r++)K[r]=b5;K[88]=x5;K[89]=E5;K[90]=v5;K[91]=S5;K[92]=Ae;K[93]=Ae;K[94]=Ae;K[95]=p1("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)K[r]=A5;K[120]=I5;K[121]=_5;K[122]=T5;K[123]=k5;K[124]=Ae;K[125]=Ae;K[126]=Ae;K[127]=p1("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)K[r]=P5;K[152]=R5;K[153]=L5;K[154]=D5;K[155]=N5;K[156]=Ae;K[157]=Ae;K[158]=Ae;K[159]=B5;for(let r=160;r<=183;r++)K[r]=O5;K[184]=M5;K[185]=U5;K[186]=F5;K[187]=$5;K[188]=Ae;K[189]=Ae;K[190]=Ae;K[191]=V5;for(let r=192;r<=215;r++)K[r]=K5;K[216]=H5;K[217]=q5;K[218]=W5;K[219]=z5;K[220]=Ae;K[221]=Ae;K[222]=Ae;K[223]=Ae;for(let r=224;r<=243;r++)K[r]=p1("simple values are not supported");K[244]=Ae;K[245]=Ae;K[246]=Ae;K[247]=G5;K[248]=p1("simple values are not supported");K[249]=Y5;K[250]=X5;K[251]=j5;K[252]=Ae;K[253]=Ae;K[254]=Ae;K[255]=Q5;var Jr=[];for(let r=0;r<24;r++)Jr[r]=new U(E.uint,r,1);for(let r=-1;r>=-24;r--)Jr[31-r]=new U(E.negint,r,1);Jr[64]=new U(E.bytes,new Uint8Array(0),1);Jr[96]=new U(E.string,"",1);Jr[128]=new U(E.array,0,1);Jr[160]=new U(E.map,0,1);Jr[244]=new U(E.false,!1,1);Jr[245]=new U(E.true,!0,1);Jr[246]=new U(E.null,null,1);function rg(r){switch(r.type){case E.false:return In([244]);case E.true:return In([245]);case E.null:return In([246]);case E.bytes:return r.value.length?void 0:In([64]);case E.string:return r.value===""?In([96]):void 0;case E.array:return r.value===0?In([128]):void 0;case E.map:return r.value===0?In([160]):void 0;case E.uint:return r.value<24?In([Number(r.value)]):void 0;case E.negint:if(r.value>=-24)return In([31-Number(r.value)])}}var LA={float64:!1,mapSorter:BA,quickEncodeToken:rg};function DA(){let r=[];return r[E.uint.major]=Rr,r[E.negint.major]=c1,r[E.bytes.major]=gs,r[E.string.major]=C5,r[E.array.major]=u1,r[E.map.major]=d1,r[E.tag.major]=f1,r[E.float.major]=h1,r}var ng=DA(),Q2=new ac,g1=class r{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${Xn} object contains circular references`);return new r(t,e)}},Co={null:new U(E.null,null),undefined:new U(E.undefined,void 0),true:new U(E.true,!0),false:new U(E.false,!1),emptyArray:new U(E.array,0),emptyMap:new U(E.map,0)},Po={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new U(E.float,r):r>=0?new U(E.uint,r):new U(E.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new U(E.uint,r):new U(E.negint,r)},Uint8Array(r,e,t,n){return new U(E.bytes,r)},string(r,e,t,n){return new U(E.string,r)},boolean(r,e,t,n){return r?Co.true:Co.false},null(r,e,t,n){return Co.null},undefined(r,e,t,n){return Co.undefined},ArrayBuffer(r,e,t,n){return new U(E.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new U(E.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[Co.emptyArray,new U(E.break)]:Co.emptyArray;n=g1.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=m1(s,t,n);return t.addBreakTokens?[new U(E.array,r.length),o,new U(E.break)]:[new U(E.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",i=o?r.keys():Object.keys(r),s=o?r.size:i.length;if(!s)return t.addBreakTokens===!0?[Co.emptyMap,new U(E.break)]:Co.emptyMap;n=g1.createCheck(n,r);let a=[],c=0;for(let l of i)a[c++]=[m1(l,t,n),m1(o?r.get(l):r[l],t,n)];return NA(a,t),t.addBreakTokens?[new U(E.map,s),a,new U(E.break)]:[new U(E.map,s),a]}};Po.Map=Po.Object;Po.Buffer=Po.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Po[`${r}Array`]=Po.DataView;function m1(r,e={},t){let n=r5(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||Po[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=Po[n];if(!i)throw new Error(`${Xn} unsupported type: ${n}`);return i(r,n,e,t)}function NA(r,e){e.mapSorter&&r.sort(e.mapSorter)}function BA(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let o=t.type.major,i=ng[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function og(r,e,t,n){if(Array.isArray(e))for(let o of e)og(r,o,t,n);else t[e.type.major](r,e,n)}function Y2(r,e,t){let n=m1(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let o=t.quickEncodeToken(n);if(o)return o;let i=e[n.type.major];if(i.encodedSize){let s=i.encodedSize(n,t),a=new ac(s);if(i(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return sc(a.chunks[0])}}return Q2.reset(),og(Q2,n,e,t),Q2.toBytes(!0)}function Ro(r,e){return e=Object.assign({},LA,e),Y2(r,ng,e)}var OA={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},y1=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],t=Jr[e];if(t===void 0){let n=K[e];if(!n)throw new Error(`${j} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;t=n(this.data,this._pos,o,this.options)}return this._pos+=t.encodedLength,t}},dc=Symbol.for("DONE"),w1=Symbol.for("BREAK");function MA(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=bs(e,t);if(i===w1){if(r.value===1/0)break;throw new Error(`${j} got unexpected break to lengthed array`)}if(i===dc)throw new Error(`${j} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function UA(r,e,t){let n=t.useMaps===!0,o=n?void 0:{},i=n?new Map:void 0;for(let s=0;s<r.value;s++){let a=bs(e,t);if(a===w1){if(r.value===1/0)break;throw new Error(`${j} got unexpected break to lengthed map`)}if(a===dc)throw new Error(`${j} found map but not enough entries (got ${s} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${j} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&i.has(a)||!n&&a in o))throw new Error(`${j} found repeat map key "${a}"`);let c=bs(e,t);if(c===dc)throw new Error(`${j} found map but not enough entries (got ${s} [no value], expected ${r.value})`);n?i.set(a,c):o[a]=c}return n?i:o}function bs(r,e){if(r.done())return dc;let t=r.next();if(t.type===E.break)return w1;if(t.type.terminal)return t.value;if(t.type===E.array)return MA(t,r,e);if(t.type===E.map)return UA(t,r,e);if(t.type===E.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=bs(r,e);return e.tags[t.value](n)}throw new Error(`${j} tag not supported (${t.value})`)}throw new Error("unsupported")}function X2(r,e){if(!(r instanceof Uint8Array))throw new Error(`${j} data to decode must be a Uint8Array`);e=Object.assign({},OA,e);let t=e.tokenizer||new y1(r,e),n=bs(t,e);if(n===dc)throw new Error(`${j} did not find any content to decode`);if(n===w1)throw new Error(`${j} got unexpected break`);return[n,r.subarray(t.pos())]}function Er(r,e){let[t,n]=X2(r,e);if(n.length>0)throw new Error(`${j} too many terminals, data makes no sense`);return t}var Zn="/",ig=new TextEncoder().encode(Zn),b1=ig[0],De=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=M(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]!==b1)throw new Error("Invalid key")}toString(e="utf8"){return V(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Zn))}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=ig),this._buf[0]!==b1){let e=new Uint8Array(this._buf.byteLength+1);e.fill(b1,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===b1;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let i=t[o],s=n[o];if(i<s)return!0;if(i>s)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(Zn).slice(1)}type(){return FA(this.baseNamespace())}name(){return $A(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Zn)||(e+=Zn),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Zn):new r(e.slice(0,-1).join(Zn))}child(e){return this.toString()===Zn?e:e.toString()===Zn?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(),...VA(e.map(t=>t.namespaces()))])}};function FA(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function $A(r){let e=r.split(":");return e[e.length-1]}function VA(r){return[].concat(...r)}function x1({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*KA(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t],i=X.asCID(n);i!=null?yield[o.join("/"),i]:typeof n=="object"&&(yield*Z2(n,o))}else{let t=X.asCID(e);t!=null?yield[r.join("/"),t]:yield*Z2(e,r)}}function*Z2(r,e){if(r==null||r instanceof Uint8Array)return;let t=X.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,o]of Object.entries(r)){let i=[...e,n];yield*KA(i,o)}}function*HA(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t];yield o.join("/"),typeof n=="object"&&X.asCID(n)==null&&(yield*J2(n,o))}else yield*J2(e,r)}function*J2(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let o=[...e,t];yield o.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&X.asCID(n)==null&&(yield*HA(o,n))}}function qA(r,e){let t=r;for(let[n,o]of e.entries()){if(t=t[o],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let i=X.asCID(t);if(i!=null)return{value:i,remaining:e.slice(n+1).join("/")}}return{value:t}}var ep=class{cid;bytes;value;asBlock;constructor({cid:e,bytes:t,value:n}){if(e==null||t==null||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=t,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:x1(),bytes:x1(),value:x1(),asBlock:x1()})}links(){return Z2(this.value,[])}tree(){return J2(this.value,[])}get(e="/"){return qA(this.value,e.split("/").filter(Boolean))}};function sg({bytes:r,cid:e,value:t,codec:n}){let o=t!==void 0?t:n?.decode(r);if(o===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new ep({cid:e,bytes:r,value:o})}var lg="/pin/",ag="/pinned-block/",tp=mn,cg=1;function E1(r){return r.version===0&&(r=r.toV1()),new De(`${lg}${r.toString(tp)}`)}var v1=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=E1(e);if(await this.datastore.has(n))throw new Error("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new Error("Depth must be greater than or equal to 0");let i=new Mt({concurrency:cg});for await(let a of this.#e(e,i,{...t,depth:o}))await this.#t(a,c=>c.pinnedBy.find(l=>te(l,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),t),yield a;let s={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,Ro(s),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=await this.getCodec(e.code),i=await this.blockstore.get(e,n),s=sg({bytes:i,cid:e,codec:o});yield e;for await(let[,a]of s.links())yield*await t.add(async()=>this.#e(a,t,{...n,depth:n.depth-1}))}async#t(e,t,n){let o=new De(`${ag}${tp.encode(e.multihash.bytes)}`),i={pinCount:0,pinnedBy:[]};try{i=Er(await this.datastore.get(o,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(i)){if(i.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,Ro(i),n),n.onProgress?.(new H("helia:pin:add",e))}}async*rm(e,t={}){let n=E1(e),o=await this.datastore.get(n,t),i=Er(o);await this.datastore.delete(n,t);let s=new Mt({concurrency:cg});for await(let a of this.#e(e,s,{...t,depth:i.depth}))await this.#t(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>te(l,e.bytes)),!0),{...t,depth:i.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:lg+(e.cid!=null?`${e.cid.toString(mn)}`:"")},e)){let o=X.parse(t.toString().substring(5),mn),i=Er(n);yield{cid:o,...i}}}async isPinned(e,t={}){let n=new De(`${ag}${tp.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=E1(e),o=await this.datastore.get(n,t);return Er(o)}async setMetadata(e,t,n){let o=E1(e),i=await this.datastore.get(o,n),s=Er(i);s.metadata=t??{},await this.datastore.put(o,Ro(s),n)}};var rp=1,np=5;var fc=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},Lo=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},hc=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},pc=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}};var WA=5,S1=class{log;routers;providerLookupConcurrency;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??WA}async start(){await wt(...this.routers)}async stop(){await Tt(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new Lo("No content routers available");let n=new Ut({concurrency:this.providerLookupConcurrency});n.addEventListener("error",()=>{});for await(let o of $t(n.toGenerator(),...xs(this.routers,"findProviders").map(i=>i.findProviders(e,t))))if(o!=null){if(o.multiaddrs.length===0){if(n.find(o.id)!=null)continue;n.add(async()=>{try{let i=await this.findPeer(o.id,t);return i.multiaddrs.length===0?null:i}catch(i){return this.log.error("could not load multiaddrs for peer %p",o.id,i),null}},{peerId:o.id,signal:t.signal}).catch(i=>{this.log.error("could not load multiaddrs for peer %p",o.id,i)})}yield o}}async provide(e,t={}){if(this.routers.length===0)throw new Lo("No content routers available");await Promise.all(xs(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async put(e,t,n){await Promise.all(xs(this.routers,"put").map(async o=>{await o.put(e,t,n)}))}async get(e,t){return Promise.any(xs(this.routers,"get").map(async n=>n.get(e,t)))}async findPeer(e,t){if(this.routers.length===0)throw new Lo("No peer routers available");let n=this,o=$t(...xs(this.routers,"findPeer").map(i=>async function*(){try{yield await i.findPeer(e,t)}catch(s){n.log.error(s)}}()));for await(let i of o)if(i!=null)return i;throw new Oe("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Lo("No peer routers available");for await(let n of $t(...xs(this.routers,"getClosestPeers").map(o=>o.getClosestPeers(e,t))))n!=null&&(yield n)}};function xs(r,e){return r.filter(t=>t[e]!=null)}var Do={},Es=r=>{r.addEventListener("message",e=>{Es.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{Es.dispatchEvent("message",r,e)})};Es.addEventListener=(r,e)=>{Do[r]==null&&(Do[r]=[]),Do[r].push(e)};Es.removeEventListener=(r,e)=>{Do[r]!=null&&(Do[r]=Do[r].filter(t=>t===e))};Es.dispatchEvent=function(r,e,t){Do[r]!=null&&Do[r].forEach(n=>n(e,t))};var op=Es;var ip="lock:worker:request-read",sp="lock:worker:release-read",ap="lock:master:grant-read",cp="lock:worker:request-write",lp="lock:worker:release-write",up="lock:master:grant-write";var ug=(r=21)=>Math.random().toString().substring(2);var dg=(r,e,t,n,o)=>(i,s)=>{if(s.data.type!==t)return;let a={type:s.data.type,name:s.data.name,identifier:s.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{i.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let l=d=>{if(d?.data==null)return;let u={type:d.data.type,name:d.data.name,identifier:d.data.identifier};u.type===n&&u.identifier===a.identifier&&(i.removeEventListener("message",l),c())};i.addEventListener("message",l)})}}}))},fg=(r,e,t,n)=>async()=>{let o=ug();return globalThis.postMessage({type:e,identifier:o,name:r}),new Promise(i=>{let s=a=>{if(a?.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===o&&(globalThis.removeEventListener("message",s),i(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",s)})},zA={singleProcess:!1},hg=r=>{if(r=Object.assign({},zA,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return op.addEventListener("message",dg(t,"requestReadLock",ip,sp,ap)),op.addEventListener("message",dg(t,"requestWriteLock",cp,lp,up)),t}return{isWorker:!0,readLock:t=>fg(t,ip,ap,sp),writeLock:t=>fg(t,cp,up,lp)}};var yi={},No;async function dp(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>jr((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var GA=(r,e)=>{if(No.isWorker===!0)return{readLock:No.readLock(r,e),writeLock:No.writeLock(r,e)};let t=new An({concurrency:1}),n;return{async readLock(){if(n!=null)return dp(n,e);n=new An({concurrency:e.concurrency,autoStart:!1});let o=n,i=dp(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),i},async writeLock(){return n=null,dp(t,e)}}},QA={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function wi(r){let e=Object.assign({},QA,r);return No==null&&(No=hg(e),No.isWorker!==!0&&(No.addEventListener("requestReadLock",t=>{yi[t.data.name]!=null&&yi[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),No.addEventListener("requestWriteLock",async t=>{yi[t.data.name]!=null&&yi[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),yi[e.name]==null&&(yi[e.name]=GA(e.name,e)),yi[e.name]}var A1=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=wi({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await wt(this.child),this.started=!0}async stop(){await Tt(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{o()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new Error("CID was pinned");await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let o=this;yield*this.child.deleteMany(async function*(){for await(let i of e){if(await o.pins.isPinned(i))throw new Error("CID was pinned");yield i}}(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var fp=new De("/version"),pg=1;async function mg(r){if(!await r.has(fp)){await r.put(fp,M(`${pg}`));return}let e=await r.get(fp),t=V(e);if(parseInt(t,10)!==pg)throw new Error("Unknown datastore version, a datastore migration may be required")}var mp={};Xe(mp,{code:()=>pp,decode:()=>nI,decodeOptions:()=>eI,encode:()=>rI,encodeOptions:()=>ZA,name:()=>tI,toByteView:()=>yg});var gg=42;function yg(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function YA(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=X.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new U(E.tag,gg),new U(E.bytes,t)]}function XA(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function jA(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var hp={float64:!0,typeEncoders:{Object:YA,undefined:XA,number:jA}},ZA={...hp,typeEncoders:{...hp.typeEncoders}};function JA(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return X.decode(r.subarray(1))}var I1={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};I1.tags[gg]=JA;var eI={...I1,tags:I1.tags.slice()},tI="dag-cbor",pp=113,rI=r=>Ro(r,hp),nI=r=>Er(yg(r),I1);var vp={};Xe(vp,{code:()=>Ep,decode:()=>bg,encode:()=>wg,format:()=>pI,name:()=>hI,parse:()=>gI,stringify:()=>pI});var gp=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===E.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===E.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[E.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i);e.push(o)}[E.negint.major](e,t){this[E.uint.major](e,t)}[E.bytes.major](e,t){throw new Error(`${Xn} unsupported type: Uint8Array`)}[E.string.major](e,t){this.prefix(e);let n=a1(JSON.stringify(t.value));e.push(n.length>32?sc(n):n)}[E.array.major](e,t){this.prefix(e),this.inRecursive.push({type:E.array,elements:0}),e.push([91])}[E.map.major](e,t){this.prefix(e),this.inRecursive.push({type:E.map,elements:0}),e.push([123])}[E.tag.major](e,t){}[E.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===E.array)e.push([93]);else if(s.type===E.map)e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(t.value===void 0)throw new Error(`${Xn} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),o=[],i=!1;for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s),!i&&(o[s]===46||o[s]===101||o[s]===69)&&(i=!0);i||(o.push(46),o.push(48)),e.push(o)}};function oI(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${Xn} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==E.string||n.type!==E.string)throw new Error(`${Xn} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${Xn} unexpected duplicate map keys, this is not supported`)}var iI={addBreakTokens:!0,mapSorter:oI};function yp(r,e){return e=Object.assign({},iI,e),Y2(r,new gp,e)}var vs=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos<e.length)throw new Error(`${j} unexpected end of input at position ${this._pos}`);for(let t=0;t<e.length;t++)if(this.data[this._pos++]!==e[t])throw new Error(`${j} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,o=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new U(E.uint,0,this._pos-e);if(o([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${j} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${j} unexpected token at position ${this._pos}`);n=!0,this._pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,o([48,49,50,51,52,53,54,55,56,57]));let i=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),s=parseFloat(i);return n?new U(E.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new U(s>=0?E.uint:E.negint,s,this._pos-e):new U(s>=0?E.uint:E.negint,BigInt(i),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${j} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let i=this._pos,s=0;i<this.data.length&&s<65536;i++,s++){let a=this.data[i];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,i));return this._pos=i+1,new U(E.string,c,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${j} unexpected end of unicode escape sequence at position ${this._pos}`);let i=0;for(let s=0;s<4;s++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${j} unexpected unicode escape character at position ${this._pos}`);i=i*16+a,this._pos++}return i},o=()=>{let i=this.ch(),s=null,a=i>239?4:i>223?3:i>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${j} unexpected unicode sequence at position ${this._pos}`);let c,l,d,u;switch(a){case 1:i<128&&(s=i);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(u=(i&31)<<6|c&63,u>127&&(s=u));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(u=(i&15)<<12|(c&63)<<6|l&63,u>2047&&(u<55296||u>57343)&&(s=u));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],d=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(d&192)===128&&(u=(i&15)<<18|(c&63)<<12|(l&63)<<6|d&63,u>65535&&u<1114112&&(s=u))}s===null?(s=65533,a=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.push(s),this._pos+=a};for(;!this.done();){let i=this.ch(),s;switch(i){case 92:if(this._pos++,this.done())throw new Error(`${j} unexpected string termination at position ${this._pos}`);switch(s=this.ch(),this._pos++,s){case 34:case 39:case 92:case 47:t.push(s);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${j} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new U(E.string,H2(t),this._pos-e);default:if(i<32)throw new Error(`${j} invalid control character at position ${this._pos}`);i<128?(t.push(i),this._pos++):o()}}throw new Error(`${j} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new U(E.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new U(E.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new U(E.null,null,4);case 102:return this.expect([102,97,108,115,101]),new U(E.false,!1,5);case 116:return this.expect([116,114,117,101]),new U(E.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${j} unexpected character at position ${this._pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this._pos++,this.skipWhitespace(),new U(E.break,void 0,1);if(this.ch()!==44)throw new Error(`${j} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this._pos++,this.skipWhitespace(),new U(E.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new U(E.break,void 0,1);if(this.ch()!==44)throw new Error(`${j} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this._pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this._pos++,this.skipWhitespace(),new U(E.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${j} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${j} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function wp(r,e){return e=Object.assign({tokenizer:new vs(r,e)},e),Er(r,e)}function aI(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function cI(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=X.asCID(r);if(!e)return null;let t=e.toString();return[new U(E.map,1/0,1),new U(E.string,"/",1),new U(E.string,t,t.length),new U(E.break,void 0,1)]}function _1(r){let e=it.encode(r).slice(1);return[new U(E.map,1/0,1),new U(E.string,"/",1),new U(E.map,1/0,1),new U(E.string,"bytes",5),new U(E.string,e,e.length),new U(E.break,void 0,1),new U(E.break,void 0,1)]}function en(r){return _1(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function lI(r){return _1(new Uint8Array(r))}function uI(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function dI(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var fI={typeEncoders:{Object:cI,Buffer:_1,Uint8Array:_1,Int8Array:en,Uint16Array:en,Int16Array:en,Uint32Array:en,Int32Array:en,Float32Array:en,Float64Array:en,Uint8ClampedArray:en,BigInt64Array:en,BigUint64Array:en,DataView:en,ArrayBuffer:lI,undefined:uI,number:dI}},bp=class extends vs{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===E.map){let t=this._next();if(t.type===E.string&&t.value==="/"){let n=this._next();if(n.type===E.string){if(this._next().type!==E.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new U(E.tag,42,0)}if(n.type===E.map){let o=this._next();if(o.type===E.string&&o.value==="bytes"){let i=this._next();if(i.type===E.string){for(let a=0;a<2;a++)if(this._next().type!==E.break)throw new Error("Invalid encoded Bytes form");let s=it.decode(`m${i.value}`);return new U(E.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},xp={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};xp.tags[42]=X.parse;var hI="dag-json",Ep=297,wg=r=>yp(r,fI),bg=r=>{let e=aI(r),t=Object.assign(xp,{tokenizer:new bp(e,xp)});return wp(e,t)},pI=r=>mI.decode(wg(r));var mI=new TextDecoder,gI=r=>bg(yI.encode(r)),yI=new TextEncoder;var kp={};Xe(kp,{code:()=>Tp,createLink:()=>Cg,createNode:()=>kg,decode:()=>PI,encode:()=>CI,name:()=>kI,prepare:()=>Ip,validate:()=>_p});var wI=new TextDecoder;function Sp(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let o=r[e++];if(t+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[t,e]}function T1(r,e){let t;[t,e]=Sp(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function xg(r,e){let t;return[t,e]=Sp(r,e),[t&7,t>>3,e]}function bI(r){let e={},t=r.length,n=0;for(;n<t;){let o,i;if([o,i,n]=xg(r,n),i===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=T1(r,n)}else if(i===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=T1(r,n),e.Name=wI.decode(s)}else if(i===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=Sp(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${i}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function Eg(r){let e=r.length,t=0,n,o=!1,i;for(;t<e;){let a,c;if([a,c,t]=xg(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(i)throw new Error("protobuf: (PBNode) duplicate Data section");[i,t]=T1(r,t),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=T1(r,t),n.push(bI(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return i&&(s.Data=i),s.Links=n||[],s}var Sg=new TextEncoder,vg=2**32,xI=2**31;function EI(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=mc(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=Sg.encode(r.Name);t-=n.length,e.set(n,t),t=mc(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=mc(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function Ag(r){let e=SI(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=mc(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let i=EI(r.Links[o],t.subarray(0,n));n-=i,n=mc(t,n,i)-1,t[n]=18}return t}function vI(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+Ss(t)}if(typeof r.Name=="string"){let t=Sg.encode(r.Name).length;e+=1+t+Ss(t)}return typeof r.Tsize=="number"&&(e+=1+Ss(r.Tsize)),e}function SI(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+Ss(t)}if(r.Links)for(let t of r.Links){let n=vI(t);e+=1+n+Ss(n)}return e}function mc(r,e,t){e-=Ss(t);let n=e;for(;t>=xI;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function Ss(r){return r%2===0&&r++,Math.floor((AI(r)+6)/7)}function AI(r){let e=0;return r>=vg&&(r=Math.floor(r/vg),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+II[r]}var II=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var _I=["Data","Links"],TI=["Hash","Name","Tsize"],Ap=new TextEncoder;function _g(r,e){if(r===e)return 0;let t=r.Name?Ap.encode(r.Name):[],n=e.Name?Ap.encode(e.Name):[],o=t.length,i=n.length;for(let s=0,a=Math.min(o,i);s<a;++s)if(t[s]!==n[s]){o=t[s],i=n[s];break}return o<i?-1:i<o?1:0}function Ig(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function Tg(r){if(typeof r.asCID=="object"){let t=X.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=X.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=X.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=X.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function Ip(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=Ap.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(Tg),e.Links.sort(_g);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function _p(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!Ig(r,_I))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<r.Links.length;e++){let t=r.Links[e];if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!Ig(t,TI))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(t.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(t.Hash==null||!t.Hash["/"]||t.Hash["/"]!==t.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(t.Name!==void 0&&typeof t.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(t.Tsize!==void 0){if(typeof t.Tsize!="number"||t.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(t.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&_g(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function kg(r,e=[]){return Ip({Data:r,Links:e})}function Cg(r,e,t){return Tg({Hash:t,Name:r,Tsize:e})}function Pg(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var kI="dag-pb",Tp=112;function CI(r){_p(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),Ag(e)}function PI(r){let e=Pg(r),t=Eg(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let i={};try{i.Hash=X.decode(o.Hash)}catch{}if(!i.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(i.Name=o.Name),o.Tsize!==void 0&&(i.Tsize=o.Tsize),i})),n}function As(r){return r?.then!=null}function Rg(r=[],e){let t={[Tp]:kp,[Jo]:Gi,[pp]:mp,[Ep]:vp,[T0]:Rl};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);As(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new pc(`Could not load codec for ${n}`)}}function Lg(r=[],e){let t={[ut.code]:ut,[Dl.code]:Dl,[Jt.code]:Jt};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);As(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new hc(`No hasher configured for multihash code 0x${n.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`)}}var Dr=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};var Jn=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,block:o}of e)await this.put(n,o,t),yield n}get(e,t){return Promise.reject(new Error(".get is not implemented"))}async*getMany(e,t){for await(let n of e)yield{cid:n,block:await this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var k1=0,C1=class extends Jn{child;constructor(e){super(),this.child=e}put(e,t){return e.multihash.code===k1||this.child==null?e:this.child.put(e,t)}get(e){if(e.multihash.code===k1)return e.multihash.digest;if(this.child==null)throw new Dr;return this.child.get(e)}has(e){return e.multihash.code===k1?!0:this.child==null?!1:this.child.has(e)}delete(e){if(e.code!==k1&&this.child!=null)return this.child.delete(e)}getAll(e){return this.child!=null?this.child.getAll(e):[]}};function RI(r){return r[Symbol.asyncIterator]!=null}function LI(r,e){let t=0;if(RI(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=Wi(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();let s=e(o,t++);if(typeof s.then=="function")return async function*(){await s&&(yield o);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){s===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)}()}var tn=LI;function DI(r){return r[Symbol.asyncIterator]!=null}function Dg(r){return r?.then!=null}function NI(r,e){let t=0;if(DI(r))return async function*(){for await(let c of r){let l=e(c,t++);Dg(l)&&await l,yield c}}();let n=Wi(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();if(typeof e(o,t++)?.then=="function")return async function*(){yield o;for await(let c of n){let l=e(c,t++);Dg(l)&&await l,yield c}}();let a=e;return function*(){yield o;for(let c of n)a(c,t++),yield c}()}var bi=NI;var P1=class{child;getHasher;log;logger;components;constructor(e){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.components=e,this.child=new C1(e.blockstore),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new H("blocks:put:duplicate",e)),e):(n.onProgress?.(new H("blocks:put:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,t,n))),n.onProgress?.(new H("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=tn(e,async({cid:i})=>{let s=await this.child.has(i,t);return s&&t.onProgress?.(new H("blocks:put-many:duplicate",i)),!s}),o=bi(n,async({cid:i,block:s})=>{t.onProgress?.(new H("blocks:put-many:providers:notify",i)),await Promise.all(this.components.blockBrokers.map(async a=>a.announce?.(i,s,t)))});t.onProgress?.(new H("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async get(e,t={}){if(t.offline!==!0&&!await this.child.has(e,t)){let n=await this.getHasher(e.multihash.code);t.onProgress?.(new H("blocks:get:providers:get",e));let o=await Ng(e,this.components.blockBrokers,n,{...t,log:this.log});return t.onProgress?.(new H("blocks:get:blockstore:put",e)),await this.child.put(e,o,t),t.onProgress?.(new H("blocks:get:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async i=>i.announce?.(e,o,t))),o}return t.onProgress?.(new H("blocks:get:blockstore:get",e)),this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new H("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(bi(e,async n=>{if(t.offline!==!0&&!await this.child.has(n,t)){let o=await this.getHasher(n.multihash.code);t.onProgress?.(new H("blocks:get-many:providers:get",n));let i=await Ng(n,this.components.blockBrokers,o,{...t,log:this.log});t.onProgress?.(new H("blocks:get-many:blockstore:put",n)),await this.child.put(n,i,t),t.onProgress?.(new H("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(n,i,t)))}}))}async delete(e,t={}){t.onProgress?.(new H("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new H("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany(async function*(){for await(let n of e)yield n}(),t)}async has(e,t={}){return this.child.has(e,t)}async*getAll(e={}){e.onProgress?.(new H("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}},R1=class extends P1{started;constructor(e){super(e),this.started=!1}isStarted(){return this.started}async start(){await wt(this.child,...this.components.blockBrokers),this.started=!0}async stop(){await Tt(this.child,...this.components.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){let n=this.components.blockBrokers.map(o=>o.createSession==null?o:o.createSession(t));return new Cp({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}},Cp=class extends P1{closeController;constructor(e,t){super(e),this.closeController=new AbortController,$(1/0,this.closeController.signal),this.log=e.logger.forComponent(`helia:session-storage:${t.root}`)}close(){this.closeController.abort()}async put(e,t,n={}){let o=he([this.closeController.signal,n.signal]);$(1/0,o);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=he([this.closeController.signal,t.signal]);$(1/0,n);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async get(e,t={}){let n=he([this.closeController.signal,t.signal]);$(1/0,n);try{return await super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=he([this.closeController.signal,t.signal]);$(1/0,n);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=he([this.closeController.signal,t.signal]);$(1/0,n);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=he([this.closeController.signal,t.signal]);$(1/0,n);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=he([this.closeController.signal,t.signal]);$(1/0,n);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=he([this.closeController.signal,e.signal]);$(1/0,t);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};function BI(r){return typeof r.retrieve=="function"}var OI=(r,e)=>{if(e==null)throw new C(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`);return async t=>{let n,o=e.digest(t);if(As(o)?n=await o:n=o,!te(n.digest,r.multihash.digest))throw new co("Hash of downloaded block did not match multihash from passed CID")}};async function Ng(r,e,t,n){let o=OI(r,t),i=new AbortController,s=he([i.signal,n.signal]);$(1/0,i.signal,s);let a=[];for(let c of e)BI(c)&&a.push(c);try{return await Promise.any(a.map(async c=>{try{let l=!1,d=await c.retrieve(r,{...n,signal:s,validateFn:async u=>{await o(u),l=!0}});return l||await o(d),d}catch(l){throw n.log.error("could not retrieve verified block for %c",r,l),l}}))}finally{i.abort(),s.clear()}}var xi=class extends ge{intialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;constructor(e,t){super(),$(1/0,this),this.name=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.name),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.providers=[],this.evictionFilter=Sn(this.maxProviders)}async retrieve(e,t={}){let n=it.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o;let i=J();if(this.requests.set(n,i.promise),this.providers.length===0){let l=!1;this.intialPeerSearchComplete==null&&(l=!0,this.log=this.logger.forComponent(`${this.name}:${e}`),this.intialPeerSearchComplete=this.findProviders(e,this.minProviders,t)),await this.intialPeerSearchComplete,l&&this.log("found initial session peers for %c",e)}let s=!1,a=new Mt({concurrency:this.maxProviders});a.addEventListener("error",()=>{}),a.addEventListener("failure",l=>{this.log.error("error querying provider %o, evicting from session",l.detail.job.options.provider,l.detail.error),this.evict(l.detail.job.options.provider)}),a.addEventListener("success",l=>{s=!0,i.resolve(l.detail.result)}),a.addEventListener("idle",()=>{s||t.signal?.aborted===!0||Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let l=0;l<this.minProviders&&this.providers.length!==0;l++){let d=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(d)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),i.resolve(await this.retrieve(e,t))}).catch(l=>{this.log.error("could not find new providers for %c",e,l),i.reject(l)})});let c=l=>{a.add(async()=>this.queryProvider(e,l.detail,t),{provider:l.detail}).catch(d=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,d)})};this.addEventListener("provider",c),Promise.all([...this.providers].map(async l=>a.add(async()=>this.queryProvider(e,l,t),{provider:l}))).catch(l=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,l)});try{return await i.promise}finally{this.removeEventListener("provider",c),a.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toEvictionKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toEvictionKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async findProviders(e,t,n){let o=J(),i=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c",t,this.maxProviders,e);for await(let s of this.findNewProviders(e,n)){if(i===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(s)&&(this.log("found %d/%d new providers",i,this.maxProviders),this.providers.push(s),this.safeDispatchEvent("provider",{detail:s}),i++,i===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",i);break}}if(this.log("found %d/%d new session peers",i,this.maxProviders),i<t)throw new fc(`Found ${i} of ${t} ${this.name} providers for ${e}`)}).catch(s=>{this.log.error("error searching routing for potential session peers for %c",e,s.errors??s),o.reject(s)}),o.promise}};var L1=class{blockstore;datastore;pins;logger;routing;getCodec;getHasher;dns;metrics;log;constructor(e){this.logger=e.logger??ko(),this.log=this.logger.forComponent("helia"),this.getHasher=Lg(e.hashers,e.loadHasher),this.getCodec=Rg(e.codecs,e.loadCodec),this.dns=e.dns??i1(),this.metrics=e.metrics;let t={blockstore:e.blockstore,datastore:e.datastore,logger:this.logger,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,dns:this.dns,metrics:this.metrics,...e.components??{}};this.routing=t.routing=new S1(t,{routers:(e.routers??[]).flatMap(o=>{let i=[o];return o[ln]!=null&&i.push(o[ln]),o[un]!=null&&i.push(o[un]),i}),providerLookupConcurrency:e.providerLookupConcurrency});let n=new R1(t);this.pins=new v1(e.datastore,n,this.getCodec),this.blockstore=new A1(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,t.blockBrokers=e.blockBrokers.map(o=>o(t))}async start(){await mg(this.datastore),await wt(this.blockstore,this.datastore,this.routing)}async stop(){await Tt(this.blockstore,this.datastore,this.routing)}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,o=this.blockstore.unwrap();this.log("gc start"),await Ct(o.deleteMany(async function*(){for await(let{cid:i}of o.getAll())try{if(await n.pins.isPinned(i,e))continue;yield i,e.onProgress?.(new H("helia:gc:deleted",i))}catch(s){n.log.error("Error during gc",s),e.onProgress?.(new H("helia:gc:error",s))}}()))}finally{t()}this.log("gc finished")}};var Pp=class extends xi{wantList;network;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network}async queryProvider(e,t,n){this.log("sending WANT-BLOCK for %c to %p",e,t);let o=await this.wantList.wantSessionBlock(e,t,n);if(this.log("%p %s %c",t,o.has?"has":"does not have",e),o.has&&o.block!=null)return o.block;throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield n.id}toEvictionKey(e){return e.toMultihash().bytes}equals(e,t){return e.equals(t)}};function Bg(r,e){return new Pp(r,e)}var D1=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=e.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};var Rp=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 N1(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Rp({name:e,metrics:t}):n=new Map,n}function MI(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=Ft(r);e.push(t),r=r.slice(pe(t))}return e}var Og=MI;var B1=class extends ge{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(e,t={}){super(),$(1/0,this),this.peers=rc({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=N1({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendMessagesDelay=t.sendMessagesDelay??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=t.hashLoader,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,o)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(o=>{this.log.error("error processing newly connected bitswap peer %p",n.detail,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=V(e.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:e,priority:t.priority??1,wantType:t.wantType??et.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,o)),o.wantType===et.WantHave&&t.wantType===et.WantBlock&&(o.wantType=et.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===et.WantBlock?(await hr(this,"block",t?.signal,{filter:a=>te(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await hr(this,"presence",t?.signal,{filter:s=>te(e.multihash.digest,s.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),o.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers",e)})},this.sendMessagesDelay)}async sendMessages(){this.sendingMessages=J(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,o=new Yn;for(let[i,s]of this.wants.entries())t.has(i)||s.cancel||(n.add(i),o.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:s.priority,wantType:s.wantType,cancel:s.cancel,sendDontHave:s.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(e,o);for(let i of n)t.add(i)}catch(i){this.log.error("error sending full wantlist to new peer",i)}})).catch(e=>{this.log.error("error sending messages",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=V(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let o=new Yn;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:et.WantHave,priority:1}),await this.network.sendMessage(t,o),(await hr(this,"presence",n.signal,{filter:s=>t.equals(s.detail.sender)&&te(e.multihash.digest,s.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:et.WantBlock})}async wantSessionBlock(e,t,n={}){let o=new Yn;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:et.WantBlock,priority:1}),await this.network.sendMessage(t,o),(await hr(this,"presence",n.signal,{filter:s=>t.equals(s.detail.sender)&&te(e.multihash.digest,s.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=V(e.multihash.bytes,"base64"),o=this.wants.get(n);o!=null&&(o.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e,t.blocks.length);let n=!1;for(let o of t.blocks){if(o.prefix==null||o.data==null)continue;let i=Og(o.prefix),s=i[0],a=i[1],c=i[2],l=c===ut.code?ut:await this.hashLoader?.getHasher(c);if(l==null){this.log.error("unknown hash algorithm",c);continue}let d=l.digest(o.data);d.then!=null&&(d=await d);let u=X.create(s===0?0:1,a,d);this.log("received block from %p for %c",e,u),this.safeDispatchEvent("block",{detail:{sender:e,cid:u,block:o.data}}),this.safeDispatchEvent("presence",{detail:{sender:e,cid:u,has:!0,block:o.data}});let f=V(u.multihash.bytes,"base64"),h=this.wants.get(f);h!=null&&(h.cancel=!0,n=!0)}for(let{cid:o,type:i}of t.blockPresences){let s=X.decode(o);this.log("received %s from %p for %c",i,e,s),this.safeDispatchEvent("presence",{detail:{sender:e,cid:s,has:i===Ir.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new Yn(!0);for(let[o,i]of this.wants.entries())i.cancel||(t.add(o),n.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:1,wantType:et.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n),this.peers.set(e,t)}catch(o){this.log.error("error sending full wantlist to new peer %p",e,o)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var O1=class{log;logger;stats;network;blockstore;peerWantLists;wantList;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.stats=new D1(e),this.network=new $l(e,t),this.peerWantLists=new ju({...e,network:this.network},t),this.wantList=new B1({...e,network:this.network},t)}createSession(e={}){return Bg({wantList:this.wantList,network:this.network,logger:this.logger},e)}async want(e,t={}){let n=new AbortController,o=he([n.signal,t.signal]);$(1/0,n.signal,o),this.network.findAndConnect(e,{...t,signal:o}).catch(i=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c",e,i)});try{return(await this.wantList.wantBlock(e,{...t,signal:o})).block}finally{n.abort(),o.clear()}}async notify(e,t,n={}){await Promise.all([this.peerWantLists.receivedBlock(e,n),this.wantList.receivedBlock(e,n)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var Mg=(r,e={})=>new O1(r,e);var Lp=class{bitswap;started;constructor(e,t={}){let{getHasher:n}=e;this.bitswap=Mg(e,{hashLoader:{getHasher:async o=>n(o)},...t}),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(e,t,n){await this.bitswap.notify(e,t,n)}async retrieve(e,t={}){return this.bitswap.want(e,t)}createSession(e){let t=this.bitswap.createSession(e);return{announce:async(n,o,i)=>{await this.bitswap.notify(n,o,i)},retrieve:async(n,o)=>t.retrieve(n,o)}}};function Dp(r={}){return e=>new Lp(e,r)}var M1=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,o){return this.readAtomically(()=>{let i=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let d=this.readAtomically(()=>{let u=this.readChar();if(u===void 0)return;let f=Number.parseInt(u,e);if(!Number.isNaN(f))return f});if(d===void 0)break;if(i*=e,i+=d,i>l||(s+=1,t!==void 0&&s>t))return}if(s!==0)return!n&&c&&s>1?void 0:i})}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 o=n*2;if(n<t.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return t[o]=s[0],t[o+1]=s[1],t[o+2]=s[2],t[o+3]=s[3],[o+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[o,!1];t[o]=i>>8,t[o+1]=i&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),s=16-(n+2),[a]=e(i.subarray(0,s));return t.set(i.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Ug=45,UI=15,Is=new M1;function Np(r){if(!(r.length>UI))return Is.new(r).parseWith(()=>Is.readIPv4Addr())}function Bp(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ug))return Is.new(r).parseWith(()=>Is.readIPv6Addr())}function U1(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ug))return Is.new(r).parseWith(()=>Is.readIPAddr())}function _s(r){return!!Np(r)}function Ts(r){return!!Bp(r)}function F1(r){return!!U1(r)}var $g=fr(Fg(),1),FI=["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"],$I=FI.map(r=>new $g.Netmask(r));function Op(r){for(let e of $I)if(e.contains(r))return!0;return!1}function VI(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function KI(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"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return Op(o)}function HI(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function qI(r){let e=r.split(":"),t=e[e.length-1];return Op(t)}function WI(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 Bt(r){return _s(r)?Op(r):VI(r)?KI(r):HI(r)?qI(r):Ts(r)?WI(r):void 0}var zI=r=>r.toString().split("/").slice(1),ks=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),me=r=>({match:e=>ks(t=>t===r).match(e),pattern:r}),Cs=()=>({match:r=>ks(e=>typeof e=="string").match(r),pattern:"{string}"}),yc=()=>({match:r=>ks(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),We=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{Se.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),wc=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{S0.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),Le=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),qt=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),be=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function $e(...r){function e(o){let i=zI(o);for(let s of r){let a=s.match(i);if(a===!1)return!1;i=a}return i}function t(o){return e(o)!==!1}function n(o){let i=e(o);return i===!1?!1:i.length===0}return{matchers:r,matches:t,exactMatch:n}}var V1=be(me("dns4"),Cs()),K1=be(me("dns6"),Cs()),H1=be(me("dnsaddr"),Cs()),Up=be(me("dns"),Cs()),zK=$e(V1,Le(We())),GK=$e(K1,Le(We())),QK=$e(H1,Le(We())),bc=$e(qt(Up,H1,V1,K1),Le(We())),Vg=be(me("ip4"),ks(_s)),Kg=be(me("ip6"),ks(Ts)),Fp=qt(Vg,Kg),eo=qt(Fp,Up,V1,K1,H1),Hg=$e(qt(Fp,be(qt(Up,H1,V1,K1),Le(We())))),YK=$e(Vg),XK=$e(Kg),qg=$e(Fp),$p=be(eo,me("tcp"),yc()),xc=be(eo,me("udp"),yc()),Vp=$e(be($p,Le(We()))),jK=$e(xc),Kp=be(xc,me("quic")),q1=be(xc,me("quic-v1")),GI=qt(Kp,q1),ZK=$e(Kp),JK=$e(q1),Mp=qt(eo,$p,xc,Kp,q1),Wg=qt(be(Mp,me("ws"),Le(We()))),Ec=$e(Wg),zg=qt(be(Mp,me("wss"),Le(We())),be(Mp,me("tls"),Le(be(me("sni"),Cs())),me("ws"),Le(We()))),Ps=$e(zg),Gg=be(xc,me("webrtc-direct"),Le(wc()),Le(wc()),Le(We())),vc=$e(Gg),Qg=be(q1,me("webtransport"),Le(wc()),Le(wc()),Le(We())),Ei=$e(Qg),$1=qt(Wg,zg,be($p,Le(We())),be(GI,Le(We())),be(eo,Le(We())),Gg,Qg,We()),Yg=$e($1),QI=be($1,me("p2p-circuit"),We()),ir=$e(QI),YI=qt(be($1,me("p2p-circuit"),me("webrtc"),Le(We())),be($1,me("webrtc"),Le(We())),me("webrtc")),Sc=$e(YI),XI=qt(be(eo,me("tcp"),yc(),me("http"),Le(We())),be(eo,me("http"),Le(We()))),Xg=$e(XI),jI=qt(be(eo,me("tcp"),qt(be(me("443"),me("http")),be(yc(),me("https"))),Le(We())),be(eo,me("tls"),me("http"),Le(We())),be(eo,me("https"),Le(We()))),jg=$e(jI);var aH=parseInt("0xFFFF",16),cH=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var e7=_s,r_=Ts,Hp=function(r){let e=0;if(r=r.toString().trim(),e7(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(r_(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let i=e7(t[n]),s;i&&(s=Hp(t[n]),t[n]=V(s.slice(0,2),"base16")),s!=null&&++n<8&&t.splice(n,0,V(s.slice(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 i=[n,1];for(n=9-t.length;n>0;n--)i.push("0");t.splice.apply(t,i)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let i=parseInt(t[n],16);o[e++]=i>>8&255,o[e++]=i&255}return o}throw new Error("invalid ip address")},t7=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let i=0;i<t;i++)o.push(r[e+i]);return o.join(".")}if(t===16){let o=[];for(let i=0;i<t;i+=2)o.push(n.getUint16(e+i).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Rs={},qp={},o_=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];o_.forEach(r=>{let e=i_(...r);qp[e.code]=e,Rs[e.name]=e});function i_(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function ee(r){if(typeof r=="number"){if(qp[r]!=null)return qp[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Rs[r]!=null)return Rs[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var HH=ee("ip4"),qH=ee("ip6"),WH=ee("ipcidr");function Qp(r,e){switch(ee(r).code){case 4:case 41:return a_(e);case 42:return Gp(e);case 6:case 273:case 33:case 132:return o7(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Gp(e);case 421:return d_(e);case 444:return n7(e);case 445:return n7(e);case 466:return u_(e);case 481:return globalThis.encodeURIComponent(Gp(e));default:return V(e,"base16")}}function Yp(r,e){switch(ee(r).code){case 4:return r7(e);case 41:return r7(e);case 42:return zp(e);case 6:case 273:case 33:case 132:return Xp(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return zp(e);case 421:return c_(e);case 444:return f_(e);case 445:return h_(e);case 466:return l_(e);case 481:return zp(globalThis.decodeURIComponent(e));default:return M(e,"base16")}}var Wp=Object.values(Nn).map(r=>r.decoder),s_=function(){let r=Wp[0].or(Wp[1]);return Wp.slice(2).forEach(e=>r=r.or(e)),r}();function r7(r){if(!F1(r))throw new Error("invalid ip address");return Hp(r)}function a_(r){let e=t7(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!F1(e))throw new Error("invalid ip address");return e}function Xp(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function o7(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function zp(r){let e=M(r),t=Uint8Array.from(Ke(e.length));return Pe([t,e],t.length+e.length)}function Gp(r){let e=Ft(r);if(r=r.slice(pe(e)),r.length!==e)throw new Error("inconsistent lengths");return V(r)}function c_(r){let e;r[0]==="Q"||r[0]==="1"?e=ke(Se.decode(`z${r}`)).bytes:e=X.parse(r).multihash.bytes;let t=Uint8Array.from(Ke(e.length));return Pe([t,e],t.length+e.length)}function l_(r){let e=s_.decode(r),t=Uint8Array.from(Ke(e.length));return Pe([t,e],t.length+e.length)}function u_(r){let e=Ft(r),t=r.slice(pe(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+V(t,"base64url")}function d_(r){let e=Ft(r),t=r.slice(pe(e));if(t.length!==e)throw new Error("inconsistent lengths");return V(t,"base58btc")}function f_(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=lt.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 o=Xp(n);return Pe([t,o],t.length+o.length)}function h_(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=lt.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 o=Xp(n);return Pe([t,o],t.length+o.length)}function n7(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=V(e,"base32"),o=o7(t);return`${n}:${o}`}function i7(r){r=jp(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let i=0;i<o.length;i++){let s=o[i],a=ee(s);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(i++,i>=o.length)throw a7("invalid address: "+r);if(a.path===!0){n=jp(o.slice(i).join("/")),e.push([a.code,Yp(a.code,n)]),t.push([a.code,n]);break}let c=Yp(a.code,o[i]);e.push([a.code,c]),t.push([a.code,Qp(a.code,c)])}return{string:s7(t),bytes:Jp(e),tuples:e,stringTuples:t,path:n}}function Zp(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let i=Ft(r,o),s=pe(i),a=ee(i),c=p_(a,r.slice(o+s));if(c===0){e.push([i]),t.push([i]),o+=s;continue}let l=r.slice(o+s,o+s+c);if(o+=c+s,o>r.length)throw a7("Invalid address Uint8Array: "+V(r,"base16"));e.push([i,l]);let d=Qp(i,l);if(t.push([i,d]),a.path===!0){n=d;break}}return{bytes:Uint8Array.from(r),string:s7(t),tuples:e,stringTuples:t,path:n}}function s7(r){let e=[];return r.map(t=>{let n=ee(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),jp(e.join("/"))}function Jp(r){return Pe(r.map(e=>{let t=ee(e[0]),n=Uint8Array.from(Ke(t.code));return e.length>1&&e[1]!=null&&(n=Pe([n,e[1]])),n}))}function p_(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=Ft(e instanceof Uint8Array?e:Uint8Array.from(e));return t+pe(t)}}function jp(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function a7(r){return new Error("Error parsing address: "+r)}var m_=Symbol.for("nodejs.util.inspect.custom"),tm=Symbol.for("@multiformats/js-multiaddr/multiaddr"),g_=[ee("dns").code,ee("dns4").code,ee("dns6").code,ee("dnsaddr").code],em=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}},W1=class r{bytes;#e;#t;#r;#o;[tm]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=Zp(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=i7(e)}else if(Bo(e))t=Zp(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#r=t.stringTuples,this.#o=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,i="",s=ee("tcp"),a=ee("udp"),c=ee("ip4"),l=ee("ip6"),d=ee("dns6"),u=ee("ip6zone");for(let[h,p]of this.stringTuples())h===u.code&&(i=`%${p??""}`),g_.includes(h)&&(t=s.name,o=443,n=`${p??""}${i}`,e=h===d.code?6:4),(h===s.code||h===a.code)&&(t=ee(h).name,o=parseInt(p??"")),(h===c.code||h===l.code)&&(t=ee(h).name,n=`${p??""}${i}`,e=h===l.code?6:4);if(e==null||t==null||n==null||o==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:o}}protos(){return this.#t.map(([e])=>Object.assign({},ee(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>ee(e).name)}tuples(){return this.#t}stringTuples(){return this.#r}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(Jp(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===Rs.p2p.code&&e.push([n,o]),n===Rs["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?V(Se.decode(`z${n}`),"base58btc"):V(X.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#o}equals(e){return te(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(i=>i.resolvable);if(t==null)return[this];let n=Ls.get(t.name);if(n==null)throw new em(`no available resolver for ${t.name}`);return(await n(this,e)).map(i=>Q(i))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[m_](){return`Multiaddr(${this.#e})`}};var Ls=new Map;function Bo(r){return!!r?.[tm]}function Q(r){return new W1(r)}var y_=[ee("tcp").code,ee("dns").code,ee("dnsaddr").code,ee("dns4").code,ee("dns6").code];function c7(r){return d7("sni",r)?.[1]}function l7(r){let e=d7("tcp",r)?.[1];return e==null?"":`:${e}`}function d7(r,e){let t;try{t=ee(r).code}catch{return}for(let[n,o]of e)if(n===t&&o!=null)return[n,o]}function u7(r){return r.some(([e,t])=>e===ee("tls").code)}function sr(r,e,t){let n=f7[ee(r).name];if(n==null)throw new Error(`Can't interpret protocol ${ee(r).name}`);let o=n(e,t);return r===ee("ip6").code?`[${o}]`:o}var f7={ip4:(r,e)=>r,ip6:(r,e)=>e.length===0?r:`[${r}]`,tcp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`tcp://${sr(t[0],t[1]??"",e)}:${r}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${sr(t[0],t[1]??"",e)}:${r}`},dnsaddr:(r,e)=>r,dns4:(r,e)=>r,dns6:(r,e)=>r,dns:(r,e)=>r,ipfs:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${sr(t[0],t[1]??"",e)}/ipfs/${r}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${sr(t[0],t[1]??"",e)}/p2p/${r}`},http:(r,e)=>{let t=u7(e),n=c7(e),o=l7(e);if(t&&n!=null)return`https://${n}${o}`;let i=t?"https://":"http://",s=e.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let a=sr(s[0],s[1]??"",e);return a=a.replace("tcp://",""),`${i}${a}`},"http-path":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=sr(t[0],t[1]??"",e),o=decodeURIComponent(r);return`${n}/${o}`},tls:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return sr(t[0],t[1]??"",e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return sr(t[0],t[1]??"",e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=sr(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=u7(e),n=c7(e),o=l7(e);if(t&&n!=null)return`wss://${n}${o}`;let i=t?"wss://":"ws://",s=e.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let a=sr(s[0],s[1]??"",e);return a=a.replace("tcp://",""),`${i}${a}`},wss:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=sr(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${sr(t[0],t[1]??"",e)}/p2p-websocket-star`},"p2p-webrtc-star":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${sr(t[0],t[1]??"",e)}/p2p-webrtc-star`},"p2p-webrtc-direct":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${sr(t[0],t[1]??"",e)}/p2p-webrtc-direct`}};function z1(r,e){let n=Q(r).stringTuples(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let i=ee(o[0]),s=f7[i.name];if(s==null)throw new Error(`No interpreter found for ${i.name}`);let a=s(o[1]??"",n);return e?.assumeHttp!==!1&&y_.includes(o[0])&&(a=a.replace(/^.*:\/\//,""),o[1]==="443"?a=`https://${a}`:a=`http://${a}`),(a.startsWith("http://")||a.startsWith("https://")||a.startsWith("ws://")||a.startsWith("wss://"))&&(a=new URL(a).toString(),a.endsWith("/")&&(a=a.substring(0,a.length-1))),a}var G1=class{url;#e=0;#t=0;#r=0;#o=0;#a=new Map;log;constructor(e,t){this.url=e instanceof URL?e:new URL(e),this.log=t.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#l(e){let t=e.multihash.bytes;return it.encode(t)}async getRawBlock(e,t){let n=new URL(this.url.toString());if(n.pathname=`/ipfs/${e.toString()}`,n.search="?format=raw",t?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${e} from gateway ${this.url} was aborted prior to fetch`);let o=this.#l(e),i=new AbortController,s=()=>{i.abort()};t?.addEventListener("abort",s);try{let a=this.#a.get(o);return a==null&&(this.#e++,a=fetch(n.toString(),{signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"}).then(async c=>{if(this.log("GET %s %d",n,c.status),!c.ok)throw this.#t++,new Error(`unable to fetch raw block for CID ${e} from gateway ${this.url}`);return this.#o++,new Uint8Array(await c.arrayBuffer())}),this.#a.set(o,a)),await a}catch{throw t?.aborted===!0?new Error(`fetching raw block for CID ${e} from gateway ${this.url} was aborted`):(this.#t++,new Error(`unable to fetch raw block for CID ${e}`))}finally{t?.removeEventListener("abort",s),this.#a.delete(o)}}reliability(){return this.#e===0?1:this.#r>0?-1/0:this.#o/(this.#e+this.#t*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#e,errors:this.#t,invalidBlocks:this.#r,successes:this.#o,pendingResponses:this.#a.size}}};function w_(r,e,t){return r.filter(n=>{if(jg.matches(n)||e&&Xg.matches(n))return t||bc.matches(n)?!0:Bt(n.toOptions().host)===!1;if(!e&&t){let{host:o}=n.toOptions();if(o==="127.0.0.1"||o==="localhost"||o.endsWith(".localhost"))return!0}return!1})}async function*Q1(r,e,t,n,o,i){for await(let s of e.findProviders(r,i)){let a=w_(s.multiaddrs,n,o);if(a.length===0)continue;let c=z1(a[0]);yield new G1(c,t)}}var rm=class extends xi{routing;allowInsecure;allowLocal;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??Y1,this.allowLocal=t.allowLocal??X1}async queryProvider(e,t,n){this.log("fetching BLOCK for %c from %s",e,t.url);let o=await t.getRawBlock(e,n.signal);return this.log.trace("got block for %c from %s",e,t.url),await n.validateFn?.(o),o}async*findNewProviders(e,t={}){yield*Q1(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,t)}toEvictionKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}};function h7(r,e){return new rm(r,e)}var j1=class{allowInsecure;allowLocal;routing;log;logger;constructor(e,t={}){this.log=e.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=e.logger,this.routing=e.routing,this.allowInsecure=t.allowInsecure??Y1,this.allowLocal=t.allowLocal??X1}async retrieve(e,t={}){let n=[];for await(let o of Q1(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,t)){this.log("getting block for %c from %s",e,o.url);try{let i=await o.getRawBlock(e,t.signal);this.log.trace("got block for %c from %s",e,o.url);try{await t.validateFn?.(i)}catch(s){this.log.error("failed to validate block for %c from %s",e,o.url,s);continue}return i}catch(i){if(this.log.error("failed to get block for %c from %s",e,o.url,i),i instanceof Error?n.push(i):n.push(new Error(`Unable to fetch raw block for CID ${e} from gateway ${o.url}`)),t.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${e} from any gateway`):new Error(`Unable to fetch raw block for CID ${e} from any gateway`)}createSession(e={}){return h7({logger:this.logger,routing:this.routing},{...e,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure})}};var Y1=!1,X1=!1;function nm(r={}){return e=>new j1(e,r)}async function*Z1(r,e={}){let t=r.getReader();try{for(;;){let n=await t.read();if(n.done)return;yield n.value}}finally{e.preventCancel!==!0&&await t.cancel(),t.releaseLock()}}var A_=fr(J1(),1);var rn=class extends Error{static name="SignatureVerificationError";constructor(e="Record signature verification failed"){super(e),this.name="SignatureVerificationError"}},ed=class extends Error{static name="RecordExpiredError";constructor(e="Record has expired"){super(e),this.name="RecordExpiredError"}},Ds=class extends Error{static name="UnsupportedValidityError";constructor(e="The validity type is unsupported"){super(e),this.name="UnsupportedValidityError"}},td=class extends Error{static name="RecordTooLargeError";constructor(e="The record is too large"){super(e),this.name="RecordTooLargeError"}},rd=class extends Error{static name="InvalidValueError";constructor(e="Value must be a valid content path starting with /"){super(e),this.name="InvalidValueError"}},nd=class extends Error{static name="InvalidRecordDataError";constructor(e="Invalid record data"){super(e),this.name="InvalidRecordDataError"}},Ac=class extends Error{static name="InvalidEmbeddedPublicKeyError";constructor(e="Invalid embedded public key"){super(e),this.name="InvalidEmbeddedPublicKeyError"}};var ar;(function(r){let e;(function(o){o.EOL="EOL"})(e=r.ValidityType||(r.ValidityType={}));let t;(function(o){o[o.EOL=0]="EOL"})(t||(t={})),function(o){o.codec=()=>He(t)}(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=oe((o,i,s={})=>{s.lengthDelimited!==!1&&i.fork(),o.value!=null&&(i.uint32(10),i.bytes(o.value)),o.signatureV1!=null&&(i.uint32(18),i.bytes(o.signatureV1)),o.validityType!=null&&(i.uint32(24),r.ValidityType.codec().encode(o.validityType,i)),o.validity!=null&&(i.uint32(34),i.bytes(o.validity)),o.sequence!=null&&(i.uint32(40),i.uint64(o.sequence)),o.ttl!=null&&(i.uint32(48),i.uint64(o.ttl)),o.pubKey!=null&&(i.uint32(58),i.bytes(o.pubKey)),o.signatureV2!=null&&(i.uint32(66),i.bytes(o.signatureV2)),o.data!=null&&(i.uint32(74),i.bytes(o.data)),s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.value=o.bytes();break}case 2:{a.signatureV1=o.bytes();break}case 3:{a.validityType=r.ValidityType.codec().decode(o);break}case 4:{a.validity=o.bytes();break}case 5:{a.sequence=o.uint64();break}case 6:{a.ttl=o.uint64();break}case 7:{a.pubKey=o.bytes();break}case 8:{a.signatureV2=o.bytes();break}case 9:{a.data=o.bytes();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>ne(o,r.codec()),r.decode=(o,i)=>re(o,r.codec(),i)})(ar||(ar={}));var b_=mr("ipns:utils"),p7=M("/ipns/");var x_=0,E_=18;function m7(r){let e;if(r.pubKey!=null)try{e=rt(r.pubKey)}catch(t){throw b_.error(t),t}if(e!=null)return e}function g7(r){let e=M("ipns-signature:");return Pe([e,r])}function Ic(r){return"signatureV1"in r?ar.encode({value:M(r.value),signatureV1:r.signatureV1,validityType:r.validityType,validity:M(r.validity),sequence:r.sequence,ttl:r.ttl,pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data}):ar.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data})}function _n(r){let e=ar.decode(r);if(e.sequence!=null&&(e.sequence=BigInt(e.sequence)),e.ttl!=null&&(e.ttl=BigInt(e.ttl)),e.signatureV2==null||e.data==null)throw new rn("Missing data or signatureV2");let t=y7(e.data),n=v_(t.Value),o=V(t.Validity);if(e.value!=null&&e.signatureV1!=null)return S_(e),{value:n,validityType:ar.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV1:e.signatureV1,signatureV2:e.signatureV2,data:e.data};if(e.signatureV2!=null)return{value:n,validityType:ar.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV2:e.signatureV2,data:e.data};throw new Error("invalid record: does not include signatureV1 or signatureV2")}function _c(r){return Pe([p7,r.bytes])}function Ns(r){let e=ke(r.slice(p7.length));if(!od(e,x_)&&!od(e,E_))throw new co("Multihash in IPNS key was not identity or sha2-256");return e}function y7(r){let e=Er(r);if(e.ValidityType===0)e.ValidityType=ar.ValidityType.EOL;else throw new Ds("The validity type is unsupported");return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e}function v_(r){let e=V(r).trim();if(e.startsWith("/"))return e;try{return`/ipfs/${X.decode(r).toV1().toString()}`}catch{}try{return`/ipfs/${X.parse(e).toV1().toString()}`}catch{}throw new rd("Value must be a valid content path starting with /")}function S_(r){if(r.data==null)throw new nd("Record data is missing");let e=y7(r.data);if(!te(e.Value,r.value??new Uint8Array(0)))throw new rn('Field "value" did not match between protobuf and CBOR');if(!te(e.Validity,r.validity??new Uint8Array(0)))throw new rn('Field "validity" did not match between protobuf and CBOR');if(e.ValidityType!==r.validityType)throw new rn('Field "validityType" did not match between protobuf and CBOR');if(e.Sequence!==r.sequence)throw new rn('Field "sequence" did not match between protobuf and CBOR');if(e.TTL!==r.ttl)throw new rn('Field "ttl" did not match between protobuf and CBOR')}function od(r,e){return r.code===e}var oW=mr("ipns"),iW=60*60*1e9,I_="/ipns/",sW=I_.length;var w7=fr(J1(),1);var id=mr("ipns:validator"),__=1024*10,T_=async(r,e)=>{let t=_n(e),n;try{let o=g7(t.data);n=await r.verify(o,t.signatureV2)}catch{n=!1}if(!n)throw id.error("record signature verification failed"),new rn("Record signature verification failed");if(t.validityType===ar.ValidityType.EOL){if(w7.default.fromString(t.validity).toDate().getTime()<Date.now())throw id.error("record has expired"),new ed("record has expired")}else if(t.validityType!=null)throw id.error("the validity type is unsupported"),new Ds("The validity type is unsupported");id("ipns record for %s is valid",t.value)};async function sd(r,e){if(e.byteLength>__)throw new td("The record is too large");let t=Ns(r),n;od(t,0)&&(n=qu(t));let o=_n(e),i=m7(o)??n;if(i==null)throw new Ac("Could not extract public key from IPNS record or routing key");let s=_c(i.toMultihash());if(!te(r,s))throw new Ac("Embedded public key did not match routing key");await T_(i,e)}async function*Tc(r){let e=/\r?\n/,t=new TextDecoder("utf8"),n="";for await(let o of r){typeof o=="string"&&(o=new TextEncoder().encode(o)),n+=t.decode(o,{stream:!0});let i=n.split(e);n=i.pop()??"";for(let s=0;s<i.length;s++)yield JSON.parse(i[s])}n+=t.decode(),n!==""&&(yield JSON.parse(n))}var Bs=class extends Error{static name="InvalidRequestError";constructor(e="Invalid request"){super(e),this.name="InvalidRequestError"}},vi=class extends Error{static name="BadResponseError";constructor(e="Bad response"){super(e),this.name="BadResponseError"}};function k_(r){return r[Symbol.asyncIterator]!=null}function C_(r){if(k_(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var kc=C_;var b7=M("/ipns/");function x7(r){return te(r.subarray(0,b7.byteLength),b7)}var ad=class{client;constructor(e){this.client=e}async*findProviders(e,t={}){yield*jt(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs??[]}))}async provide(){}async put(e,t,n){if(!x7(e))return;let o=Ns(e),i=X.createV1(114,o),s=_n(t);await this.client.putIPNS(i,s,n)}async get(e,t){if(!x7(e))throw new Oe("Not found");let n=Ns(e),o=X.createV1(114,n);try{let i=await this.client.getIPNS(o,t);return Ic(i)}catch(i){throw i.name==="BadResponseError"?new Oe("Not found"):i}}},cd=class{client;constructor(e){this.client=e}async findPeer(e,t={}){let n=await kc(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new Oe("Not found")}async*getClosestPeers(e,t={}){}};var Wt=mr("delegated-routing-v1-http-api-client"),E7={concurrentRequests:4,timeout:3e4},ld=class{started;httpQueue;shutDownController;clientUrl;timeout;contentRouting;peerRouting;filterAddrs;filterProtocols;constructor(e,t={}){this.started=!1,this.shutDownController=new AbortController,$(1/0,this.shutDownController.signal),this.httpQueue=new An({concurrency:t.concurrentRequests??E7.concurrentRequests}),this.clientUrl=e instanceof URL?e:new URL(e),this.timeout=t.timeout??E7.timeout,this.filterAddrs=t.filterAddrs,this.filterProtocols=t.filterProtocols,this.contentRouting=new ad(this),this.peerRouting=new cd(this)}get[ln](){return this.contentRouting}get[un](){return this.peerRouting}isStarted(){return this.started}start(){this.started=!0}stop(){this.httpQueue.clear(),this.shutDownController.abort(),this.started=!1}async*getProviders(e,t={}){Wt("getProviders starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=he([this.shutDownController.signal,n,t.signal]);$(1/0,n,o);let i=J(),s=J();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let a=new URL(`${this.clientUrl}routing/v1/providers/${e.toString()}`);this.#t(a,t.filterAddrs,t.filterProtocols);let l=await fetch(a,{headers:{Accept:"application/x-ndjson"},signal:o});if(l.status===404)throw new Oe("No matching records found");if(l.status===422)throw new Bs("Request does not conform to schema or semantic constraints");if(l.body==null)throw new vi("Routing response had no body");if(l.headers.get("Content-Type")==="application/json"){let u=await l.json();for(let f of u.Providers){let h=this.#e(f);h!=null&&(yield h)}}else for await(let u of Tc(Z1(l.body))){let f=this.#e(u);f!=null&&(yield f)}}catch(a){Wt.error("getProviders errored:",a)}finally{o.clear(),s.resolve(),Wt("getProviders finished: %c",e)}}async*getPeers(e,t={}){Wt("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=he([this.shutDownController.signal,n,t.signal]);$(1/0,n,o);let i=J(),s=J();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let a=new URL(`${this.clientUrl}routing/v1/peers/${e.toCID().toString()}`);this.#t(a,t.filterAddrs,t.filterProtocols);let l=await fetch(a,{headers:{Accept:"application/x-ndjson"},signal:o});if(l.status===404)throw new Oe("No matching records found");if(l.status===422)throw new Bs("Request does not conform to schema or semantic constraints");if(l.body==null)throw new vi("Routing response had no body");if(l.headers.get("Content-Type")==="application/json"){let u=await l.json();for(let f of u.Peers){let h=this.#e(f);h!=null&&(yield h)}}else for await(let u of Tc(Z1(l.body))){let f=this.#e(u);f!=null&&(yield f)}}catch(a){Wt.error("getPeers errored:",a)}finally{o.clear(),s.resolve(),Wt("getPeers finished: %c",e)}}async getIPNS(e,t={}){Wt("getIPNS starts: %s",e);let n=AbortSignal.timeout(this.timeout),o=he([this.shutDownController.signal,n,t.signal]);$(1/0,n,o);let i=J(),s=J();this.httpQueue.add(async()=>(i.resolve(),s.promise));let a=`${this.clientUrl}routing/v1/ipns/${e}`;try{await i.promise;let l=await fetch(a,{headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o});if(Wt("getIPNS GET %s %d",a,l.status),l.status===404)throw new Oe("No matching records found");if(l.status===422)throw new Bs("Request does not conform to schema or semantic constraints");if(l.body==null)throw new vi("GET ipns response had no body");let d=await l.arrayBuffer(),u=new Uint8Array(d,0,d.byteLength);return t.validate!==!1&&await sd(_c(e.multihash),u),_n(u)}catch(c){throw Wt.error("getIPNS GET %s error:",a,c),c}finally{o.clear(),s.resolve(),Wt("getIPNS finished: %s",e)}}async putIPNS(e,t,n={}){Wt("putIPNS starts: %c",e);let o=AbortSignal.timeout(this.timeout),i=he([this.shutDownController.signal,o,n.signal]);$(1/0,o,i);let s=J(),a=J();this.httpQueue.add(async()=>(s.resolve(),a.promise));let c=`${this.clientUrl}routing/v1/ipns/${e}`;try{await s.promise;let l=Ic(t),u=await fetch(c,{method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:l,signal:i});if(Wt("putIPNS PUT %s %d",c,u.status),u.status!==200)throw new vi("PUT ipns response had status other than 200")}catch(l){throw Wt.error("putIPNS PUT %s error:",c,l.stack),l}finally{i.clear(),a.resolve(),Wt("putIPNS finished: %c",e)}}#e(e){try{let t=[],n=e.Addrs?.map(Q)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:Re(e.ID),Addrs:n,Protocols:t}}catch(t){Wt.error("could not conform record to peer schema",t)}}#t(e,t,n){if(t!=null||this.filterAddrs!=null){let o=t?.join(",")??this.filterAddrs?.join(",")??"";o!==""&&e.searchParams.set("filter-addrs",o)}if(n!=null||this.filterProtocols!=null){let o=n?.join(",")??this.filterProtocols?.join(",")??"";o!==""&&e.searchParams.set("filter-protocols",o)}}};function v7(r,e={}){return new ld(new URL(r),e)}var S7="[a-fA-F\\d:]",Oo=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${S7})|(?<=${S7})(?=\\s|$))`:"",nn="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",st="[a-fA-F\\d]{1,4}",ud=`
|
|
7
|
+
`)}`:`${t} :`}};k6=Io;G.Constructed=k6;Io.NAME="CONSTRUCTED";var su=class extends Dt{fromBER(e,t,n){return t}toBER(e){return Yr}};su.override="EndOfContentValueBlock";var C6,au=class extends xt{constructor(e={}){super(e,su),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};C6=au;G.EndOfContent=C6;au.NAME=Na;var P6,Kn=class extends xt{constructor(e={}){super(e,Dt),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};P6=Kn;G.Null=P6;Kn.NAME="NULL";var cu=class extends zn(Dt){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=ye.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,n){let o=ye.BufferSourceConverter.toUint8Array(e);return Wn(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,p2.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};cu.NAME="BooleanValueBlock";var R6,lu=class extends xt{constructor(e={}){super(e,cu),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};R6=lu;G.Boolean=R6;lu.NAME="BOOLEAN";var uu=class extends zn(wn){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=wn.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let i=0;i<this.value.length;i++){let s=this.value[i].constructor.NAME;if(s===Na){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(s!==A6)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,t,n),this.blockLength=n;return o}toBER(e,t){return this.isConstructed?wn.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};uu.NAME="OctetStringValueBlock";var L6,Hn=class r extends xt{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,i;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},uu),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let i=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(i.byteLength){let s=Uu(i,0,i.byteLength);s.offset!==-1&&s.offset===n&&(this.valueBlock.value=[s.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?Io.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${ye.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof r&&e.push(t.valueBlock.valueHexView);return ye.BufferSourceConverter.concat(e)}};L6=Hn;G.OctetString=L6;Hn.NAME=A6;var du=class extends zn(wn){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n){if(!n)return t;let o=-1;if(this.isConstructed){if(o=wn.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===Na){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==I6)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return o}let i=ye.BufferSourceConverter.toUint8Array(e);if(!Wn(this,i,t,n))return-1;let s=i.subarray(t,t+n);if(this.unusedBits=s[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=s.subarray(1);try{if(a.byteLength){let c=Uu(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=s.subarray(1),this.blockLength=s.length,t+n}toBER(e,t){if(this.isConstructed)return wn.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return Yr;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};du.NAME="BitStringValueBlock";var D6,us=class extends xt{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,i;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},du),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Io.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let o of t)e.push(o.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};D6=us;G.BitString=D6;us.NAME=I6;var N6;function ES(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,l=0,d=c<s?s:c,u=0;for(let f=d;f>=0;f--,u++){switch(!0){case u<a.length:l=i[s-u]+a[c-u]+t[0];break;default:l=i[s-u]+t[0]}switch(t[0]=l/10,!0){case u>=i.length:i=Jl(new Uint8Array([l%10]),i);break;default:i[s-u]=l%10}}return t[0]>0&&(i=Jl(t,i)),i}function S6(r){if(r>=La.length)for(let e=La.length;e<=r;e++){let t=new Uint8Array([0]),n=La[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let i=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=i[0]/10,n[o]=i[0]%10}t[0]>0&&(n=Jl(t,n)),La.push(n)}return La[r]}function vS(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,l,d=0;for(let u=c;u>=0;u--,d++)switch(l=i[s-d]-a[c-d]-t,!0){case l<0:t=1,i[s-d]=l+10;break;default:t=0,i[s-d]=l}if(t>0)for(let u=s-c+1;u>=0;u--,d++)if(l=i[s-d]-t,l<0)t=1,i[s-d]=l+10;else{t=0,i[s-d]=l;break}return i.slice()}var Ba=class extends zn(Dt){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=p2.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(x6(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let i=this.fromBER(e,t,n);if(i===-1)return i;let s=this.valueHexView;return s[0]===0&&s[1]&128?this.valueHexView=s.subarray(1):o!==0&&s.length<o&&(o-s.length>1&&(o=s.length+1),this.valueHexView=s.subarray(o-s.length)),i}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,o,i=this.valueHexView,s="",a=!1;for(let c=i.byteLength-1;c>=0;c--){o=i[c];for(let l=0;l<8;l++){if((o&1)===1)switch(n){case e:t=vS(S6(n),t),s="-";break;default:t=ES(t,S6(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(s+=v6.charAt(t[c]));return a===!1&&(s+=v6.charAt(0)),s}};N6=Ba;Ba.NAME="IntegerValueBlock";Object.defineProperty(N6.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var B6,tt=class r extends xt{constructor(e={}){super(e,Ba),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return eu(),BigInt(this.valueBlock.toString())}static fromBigInt(e){eu();let t=BigInt(e),n=new Da,o=t.toString(16).replace(/^-/,""),i=new Uint8Array(ye.Convert.FromHex(o));if(t<0){let a=new Uint8Array(i.length+(i[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${ye.Convert.ToHex(a)}`)+t,d=ye.BufferSourceConverter.toUint8Array(ye.Convert.FromHex(l.toString(16)));d[0]|=128,n.write(d)}else i[0]&128&&n.write(new Uint8Array([0])),n.write(i);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};B6=tt;G.Integer=B6;tt.NAME="INTEGER";var O6,fu=class extends tt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};O6=fu;G.Enumerated=O6;fu.NAME="ENUMERATED";var Oa=class extends zn(Dt){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=ye.BufferSourceConverter.toUint8Array(e);if(!Wn(this,o,t,n))return-1;let i=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=i[a]&127,this.blockLength++,!!(i[a]&128));a++);let s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)s[a]=this.valueHexView[a];return this.valueHexView=s,i[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=di(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){eu();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,i=new Uint8Array(this.blockLength);for(let s=0;s<this.blockLength-1;s++)i[s]=o[s]|128;return i[this.blockLength-1]=o[this.blockLength-1],i.buffer}let t=Ao(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Yr;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),i=t.byteLength-1;for(let s=0;s<i;s++)n[s]=o[s]|128;n[i]=o[i]}return n}toString(){let e="";if(this.isHexOnly)e=ye.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Oa.NAME="sidBlock";var hu=class extends Dt{constructor({value:e=ds,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let i=new Oa;if(o=i.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=i.error,o;this.value.length===0&&(i.isFirstSid=!0),this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,Yr;t.push(o)}return m2(t)}fromString(e){this.value=[];let t=0,n=0,o="",i=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,i){let s=this.value[0],a=0;switch(s.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;s.valueDec=c+a,i=!1}else{let s=new Oa;if(o>Number.MAX_SAFE_INTEGER){eu();let a=BigInt(o);s.valueBigInt=a}else if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return;this.value.length||(s.isFirstSid=!0,i=!0),this.value.push(s)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};hu.NAME="ObjectIdentifierValueBlock";var M6,Cr=class extends xt{constructor(e={}){super(e,hu),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};M6=Cr;G.ObjectIdentifier=M6;Cr.NAME="OBJECT IDENTIFIER";var Ma=class extends zn(Vn){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=ye.BufferSourceConverter.toUint8Array(e);if(!Wn(this,o,t,n))return-1;let i=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=i[a]&127,this.blockLength++,!!(i[a]&128));a++);let s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)s[a]=this.valueHexView[a];return this.valueHexView=s,i[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=di(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,i=new Uint8Array(this.blockLength);for(let s=0;s<this.blockLength-1;s++)i[s]=o[s]|128;return i[this.blockLength-1]=o[this.blockLength-1],i.buffer}let t=Ao(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Yr;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),i=t.byteLength-1;for(let s=0;s<i;s++)n[s]=o[s]|128;n[i]=o[i]}return n.buffer}toString(){let e="";return this.isHexOnly?e=ye.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Ma.NAME="relativeSidBlock";var pu=class extends Dt{constructor({value:e=ds,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let i=new Ma;if(o=i.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=i.error,o;this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let i=this.value[o].toBER(e);if(i.byteLength===0)return this.error=this.value[o].error,Yr;n.push(i)}return m2(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let i=new Ma;if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};pu.NAME="RelativeObjectIdentifierValueBlock";var U6,mu=class extends xt{constructor(e={}){super(e,pu),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};U6=mu;G.RelativeObjectIdentifier=U6;mu.NAME="RelativeObjectIdentifier";var F6,ft=class extends Io{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};F6=ft;G.Sequence=F6;ft.NAME="SEQUENCE";var $6,gu=class extends Io{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};$6=gu;G.Set=$6;gu.NAME="SET";var yu=class extends zn(Dt){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=ds}toJSON(){return{...super.toJSON(),value:this.value}}};yu.NAME="StringValueBlock";var wu=class extends yu{};wu.NAME="SimpleStringValueBlock";var Vt=class extends nu{constructor({...e}={}){super(e,wu)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,ye.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};Vt.NAME="SIMPLE STRING";var bu=class extends Vt{fromBuffer(e){this.valueBlock.valueHexView=ye.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=ye.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=ye.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(ye.Convert.FromUtf8String(e)),this.valueBlock.value=e}};bu.NAME="Utf8StringValueBlock";var V6,qn=class extends bu{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};V6=qn;G.Utf8String=V6;qn.NAME="UTF8String";var xu=class extends Vt{fromBuffer(e){this.valueBlock.value=ye.Convert.ToUtf16String(e),this.valueBlock.valueHexView=ye.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(ye.Convert.FromUtf16String(e))}};xu.NAME="BmpStringValueBlock";var K6,Eu=class extends xu{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};K6=Eu;G.BmpString=K6;Eu.NAME="BMPString";var vu=class extends Vt{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let i=Ao(e.charCodeAt(o),8),s=new Uint8Array(i);if(s.length>4)continue;let a=4-s.length;for(let c=s.length-1;c>=0;c--)n[o*4+c+a]=s[c]}this.valueBlock.value=e}};vu.NAME="UniversalStringValueBlock";var H6,Su=class extends vu{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};H6=Su;G.UniversalString=H6;Su.NAME="UniversalString";var q6,Au=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};q6=Au;G.NumericString=q6;Au.NAME="NumericString";var W6,Iu=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};W6=Iu;G.PrintableString=W6;Iu.NAME="PrintableString";var z6,_u=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};z6=_u;G.TeletexString=z6;_u.NAME="TeletexString";var G6,Tu=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};G6=Tu;G.VideotexString=G6;Tu.NAME="VideotexString";var Q6,ku=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Q6=ku;G.IA5String=Q6;ku.NAME="IA5String";var Y6,Cu=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Y6=Cu;G.GraphicString=Y6;Cu.NAME="GraphicString";var X6,Ua=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};X6=Ua;G.VisibleString=X6;Ua.NAME="VisibleString";var j6,Pu=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};j6=Pu;G.GeneralString=j6;Pu.NAME="GeneralString";var Z6,Ru=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Z6=Ru;G.CharacterString=Z6;Ru.NAME="CharacterString";var J6,Fa=class extends Ua{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,ye.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=tr(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=tr(this.month,2),t[2]=tr(this.day,2),t[3]=tr(this.hour,2),t[4]=tr(this.minute,2),t[5]=tr(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};J6=Fa;G.UTCTime=J6;Fa.NAME="UTCTime";var e8,Lu=class extends Fa{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t=!1,n="",o="",i=0,s,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let u=new Number(e[e.length-1]);if(isNaN(u.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let u=1,f=n.indexOf("+"),h="";if(f===-1&&(f=n.indexOf("-"),u=-1),f!==-1){if(h=n.substring(f+1),n=n.substring(0,f),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(h.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=u*p,h.length===4){if(p=parseInt(h.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=u*p}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let u=new Number(`0${n.substring(l)}`);if(isNaN(u.valueOf()))throw new Error("Wrong input string for conversion");i=u.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(s=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let u=60*i;this.minute=Math.floor(u),u=60*(u-this.minute),this.second=Math.floor(u),u=1e3*(u-this.second),this.millisecond=Math.floor(u)}break;case o.length===12:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let u=60*i;this.second=Math.floor(u),u=1e3*(u-this.second),this.millisecond=Math.floor(u)}break;case o.length===14:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let u=1e3*i;this.millisecond=Math.floor(u)}break;default:throw new Error("Wrong input string for conversion")}let d=s.exec(o);if(d===null)throw new Error("Wrong input string for conversion");for(let u=1;u<d.length;u++)switch(u){case 1:this.year=parseInt(d[u],10);break;case 2:this.month=parseInt(d[u],10);break;case 3:this.day=parseInt(d[u],10);break;case 4:this.hour=parseInt(d[u],10)+a;break;case 5:this.minute=parseInt(d[u],10)+c;break;case 6:this.second=parseInt(d[u],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let u=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=u.getUTCFullYear(),this.month=u.getUTCMonth(),this.day=u.getUTCDay(),this.hour=u.getUTCHours(),this.minute=u.getUTCMinutes(),this.second=u.getUTCSeconds(),this.millisecond=u.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(tr(this.year,4)),t.push(tr(this.month,2)),t.push(tr(this.day,2)),t.push(tr(this.hour,2)),t.push(tr(this.minute,2)),t.push(tr(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(tr(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};e8=Lu;G.GeneralizedTime=e8;Lu.NAME="GeneralizedTime";var t8,Du=class extends qn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};t8=Du;G.DATE=t8;Du.NAME="DATE";var r8,Nu=class extends qn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};r8=Nu;G.TimeOfDay=r8;Nu.NAME="TimeOfDay";var n8,Bu=class extends qn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};n8=Bu;G.DateTime=n8;Bu.NAME="DateTime";var o8,Ou=class extends qn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};o8=Ou;G.Duration=o8;Ou.NAME="Duration";var i8,Mu=class extends qn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};i8=Mu;G.TIME=i8;Mu.NAME="TIME";function V(r,e="utf8"){let t=Nl[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function Kt(r){if(isNaN(r)||r<=0)throw new C("random bytes length must be a Number bigger than 0");return si(r)}var $a=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},Va=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Fu=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var s8={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new Fu("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var rr=s8;async function a8(r){let e=await rr.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await SS(e);return{privateKey:t[0],publicKey:t[1]}}async function c8(r,e){let t=await rr.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await rr.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function l8(r,e,t){let n=await rr.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return rr.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function SS(r){if(r.privateKey==null||r.publicKey==null)throw new C("Private and public key are required");return Promise.all([rr.get().subtle.exportKey("jwk",r.privateKey),rr.get().subtle.exportKey("jwk",r.publicKey)])}function w2(r){if(r.kty!=="RSA")throw new C("invalid key type");if(r.n==null)throw new C("invalid key modulus");return M(r.n,"base64url").length*8}var fs=class{type="RSA";_key;_raw;_multihash;constructor(e,t){this._key=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Ka.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return X.createV1(114,this._multihash)}toString(){return Se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}verify(e,t){return l8(this._key,t,e)}},Ha=class{type="RSA";_key;_raw;publicKey;constructor(e,t){this._key=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Ka.jwkToPkcs1(this._key)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}sign(e){return c8(this._key,e)}};var $u=8192,b2=18;function u8(r){let{result:e}=fi(r),t=e.valueBlock.value;return{n:bn(t[1]),e:bn(t[2]),d:bn(t[3]),p:bn(t[4]),q:bn(t[5]),dp:bn(t[6]),dq:bn(t[7]),qi:bn(t[8]),kty:"RSA",alg:"RS256"}}function AS(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 C("JWK was missing components");let t=new ft({value:[new tt({value:0}),tt.fromBigInt(xn(M(r.n,"base64url"))),tt.fromBigInt(xn(M(r.e,"base64url"))),tt.fromBigInt(xn(M(r.d,"base64url"))),tt.fromBigInt(xn(M(r.p,"base64url"))),tt.fromBigInt(xn(M(r.q,"base64url"))),tt.fromBigInt(xn(M(r.dp,"base64url"))),tt.fromBigInt(xn(M(r.dq,"base64url"))),tt.fromBigInt(xn(M(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function d8(r){let{result:e}=fi(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:bn(t[0]),e:bn(t[1])}}function x2(r){if(r.n==null||r.e==null)throw new C("JWK was missing components");let t=new ft({value:[new ft({value:[new Cr({value:"1.2.840.113549.1.1.1"}),new Kn]}),new us({valueHex:new ft({value:[tt.fromBigInt(xn(M(r.n,"base64url"))),tt.fromBigInt(xn(M(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function bn(r){let e=r.valueBlock.valueHexView;for(;e[0]===0;)e=e.subarray(1);return V(e,"base64url")}function xn(r){let e=[];return r.forEach(function(t){let n=t.toString(16);n.length%2>0&&(n=`0${n}`),e.push(n)}),BigInt("0x"+e.join(""))}function Vu(r){let e=u8(r);return f8(e)}function E2(r){let e=d8(r);if(w2(e)>$u)throw new Rn("Key size is too large");let t=Tr(yn.encode({Type:Ye.RSA,Data:r})),n=Zt(b2,t);return new fs(e,n)}function f8(r){if(w2(r)>$u)throw new C("Key size is too large");let e=h8(r),t=Tr(yn.encode({Type:Ye.RSA,Data:x2(e.publicKey)})),n=Zt(b2,t);return new Ha(e.privateKey,new fs(e.publicKey,n))}async function v2(r){if(r>$u)throw new C("Key size is too large");let e=await a8(r),t=Tr(yn.encode({Type:Ye.RSA,Data:x2(e.publicKey)})),n=Zt(b2,t);return new Ha(e.privateKey,new fs(e.publicKey,n))}function h8(r){if(r==null)throw new C("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var Ku=class extends rs{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ni(e);let n=Wr(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,i=new Uint8Array(o);i.set(n.length>o?e.create().update(n).digest():n);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=e.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),i.fill(0)}update(e){return ts(this),this.iHash.update(e),this}digestInto(e){ts(this),es(e,this.outputLen),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||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},_o=(r,e,t)=>new Ku(r,e).update(t).digest();_o.create=(r,e)=>new Ku(r,e);function p8(r){r.lowS!==void 0&&zr("lowS",r.lowS),r.prehash!==void 0&&zr("prehash",r.prehash)}function IS(r){let e=_a(r);_r(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:o}=e;if(t){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:_S,hexToBytes:TS}=zl,Gn={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode:(r,e)=>{let{Err:t}=Gn;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,o=ai(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let i=n>127?ai(o.length/2|128):"";return`${ai(r)}${i}${o}${e}`},decode(r,e){let{Err:t}=Gn,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 o=e[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&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 d of l)s=s<<8|d;if(n+=c,s<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+s);if(a.length!==s)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+s)}}},_int:{encode(r){let{Err:e}=Gn;if(r<Qn)throw new e("integer: negative integers are not allowed");let t=ai(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected assertion");return t},decode(r){let{Err:e}=Gn;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 _S(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Gn,o=typeof r=="string"?TS(r):r;os(o);let{v:i,l:s}=n.decode(48,o);if(s.length)throw new e("Invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{v:l,l:d}=n.decode(2,c);if(d.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}=Gn,n=`${e.encode(2,t.encode(r.r))}${e.encode(2,t.encode(r.s))}`;return e.encode(48,n)}},Qn=BigInt(0),pt=BigInt(1),NB=BigInt(2),m8=BigInt(3),BB=BigInt(4);function kS(r){let e=IS(r),{Fp:t}=e,n=Eo(e.n,e.nBitLength),o=e.toBytes||((m,g,y)=>{let b=g.toAffine();return Fn(Uint8Array.from([4]),t.toBytes(b.x),t.toBytes(b.y))}),i=e.fromBytes||(m=>{let g=m.subarray(1),y=t.fromBytes(g.subarray(0,t.BYTES)),b=t.fromBytes(g.subarray(t.BYTES,2*t.BYTES));return{x:y,y:b}});function s(m){let{a:g,b:y}=e,b=t.sqr(m),w=t.mul(b,m);return t.add(t.add(w,t.mul(m,g)),y)}if(!t.eql(t.sqr(e.Gy),s(e.Gx)))throw new Error("bad generator point: equation left != right");function a(m){return Aa(m,pt,e.n)}function c(m){let{allowedPrivateKeyLengths:g,nByteLength:y,wrapPrivateKey:b,n:w}=e;if(g&&typeof m!="bigint"){if(bo(m)&&(m=On(m)),typeof m!="string"||!g.includes(m.length))throw new Error("Invalid key");m=m.padStart(y*2,"0")}let x;try{x=typeof m=="bigint"?m:Mn(Ue("private key",m,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof m}`)}return b&&(x=_e(x,w)),bt("private key",x,pt,w),x}function l(m){if(!(m instanceof f))throw new Error("ProjectivePoint expected")}let d=li((m,g)=>{let{px:y,py:b,pz:w}=m;if(t.eql(w,t.ONE))return{x:y,y:b};let x=m.is0();g==null&&(g=x?t.ONE:t.inv(w));let T=t.mul(y,g),k=t.mul(b,g),v=t.mul(w,g);if(x)return{x:t.ZERO,y:t.ZERO};if(!t.eql(v,t.ONE))throw new Error("invZ was invalid");return{x:T,y:k}}),u=li(m=>{if(m.is0()){if(e.allowInfinityPoint&&!t.is0(m.py))return;throw new Error("bad point: ZERO")}let{x:g,y}=m.toAffine();if(!t.isValid(g)||!t.isValid(y))throw new Error("bad point: x or y not FE");let b=t.sqr(y),w=s(g);if(!t.eql(b,w))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class f{constructor(g,y,b){if(this.px=g,this.py=y,this.pz=b,g==null||!t.isValid(g))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(b==null||!t.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(g){let{x:y,y:b}=g||{};if(!g||!t.isValid(y)||!t.isValid(b))throw new Error("invalid affine point");if(g instanceof f)throw new Error("projective point not allowed");let w=x=>t.eql(x,t.ZERO);return w(y)&&w(b)?f.ZERO:new f(y,b,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(g){let y=t.invertBatch(g.map(b=>b.pz));return g.map((b,w)=>b.toAffine(y[w])).map(f.fromAffine)}static fromHex(g){let y=f.fromAffine(i(Ue("pointHex",g)));return y.assertValidity(),y}static fromPrivateKey(g){return f.BASE.multiply(c(g))}static msm(g,y){return Yl(f,n,g,y)}_setWindowSize(g){p.setWindowSize(this,g)}assertValidity(){u(this)}hasEvenY(){let{y:g}=this.toAffine();if(t.isOdd)return!t.isOdd(g);throw new Error("Field doesn't support isOdd")}equals(g){l(g);let{px:y,py:b,pz:w}=this,{px:x,py:T,pz:k}=g,v=t.eql(t.mul(y,k),t.mul(x,w)),S=t.eql(t.mul(b,k),t.mul(T,w));return v&&S}negate(){return new f(this.px,t.neg(this.py),this.pz)}double(){let{a:g,b:y}=e,b=t.mul(y,m8),{px:w,py:x,pz:T}=this,k=t.ZERO,v=t.ZERO,S=t.ZERO,_=t.mul(w,w),F=t.mul(x,x),N=t.mul(T,T),O=t.mul(w,x);return O=t.add(O,O),S=t.mul(w,T),S=t.add(S,S),k=t.mul(g,S),v=t.mul(b,N),v=t.add(k,v),k=t.sub(F,v),v=t.add(F,v),v=t.mul(k,v),k=t.mul(O,k),S=t.mul(b,S),N=t.mul(g,N),O=t.sub(_,N),O=t.mul(g,O),O=t.add(O,S),S=t.add(_,_),_=t.add(S,_),_=t.add(_,N),_=t.mul(_,O),v=t.add(v,_),N=t.mul(x,T),N=t.add(N,N),_=t.mul(N,O),k=t.sub(k,_),S=t.mul(N,F),S=t.add(S,S),S=t.add(S,S),new f(k,v,S)}add(g){l(g);let{px:y,py:b,pz:w}=this,{px:x,py:T,pz:k}=g,v=t.ZERO,S=t.ZERO,_=t.ZERO,F=e.a,N=t.mul(e.b,m8),O=t.mul(y,x),B=t.mul(b,T),L=t.mul(w,k),D=t.add(y,b),I=t.add(x,T);D=t.mul(D,I),I=t.add(O,B),D=t.sub(D,I),I=t.add(y,w);let A=t.add(x,k);return I=t.mul(I,A),A=t.add(O,L),I=t.sub(I,A),A=t.add(b,w),v=t.add(T,k),A=t.mul(A,v),v=t.add(B,L),A=t.sub(A,v),_=t.mul(F,I),v=t.mul(N,L),_=t.add(v,_),v=t.sub(B,_),_=t.add(B,_),S=t.mul(v,_),B=t.add(O,O),B=t.add(B,O),L=t.mul(F,L),I=t.mul(N,I),B=t.add(B,L),L=t.sub(O,L),L=t.mul(F,L),I=t.add(I,L),O=t.mul(B,I),S=t.add(S,O),O=t.mul(A,I),v=t.mul(D,v),v=t.sub(v,O),O=t.mul(D,B),_=t.mul(A,_),_=t.add(_,O),new f(v,S,_)}subtract(g){return this.add(g.negate())}is0(){return this.equals(f.ZERO)}wNAF(g){return p.wNAFCached(this,g,f.normalizeZ)}multiplyUnsafe(g){bt("scalar",g,Qn,e.n);let y=f.ZERO;if(g===Qn)return y;if(g===pt)return this;let{endo:b}=e;if(!b)return p.unsafeLadder(this,g);let{k1neg:w,k1:x,k2neg:T,k2:k}=b.splitScalar(g),v=y,S=y,_=this;for(;x>Qn||k>Qn;)x&pt&&(v=v.add(_)),k&pt&&(S=S.add(_)),_=_.double(),x>>=pt,k>>=pt;return w&&(v=v.negate()),T&&(S=S.negate()),S=new f(t.mul(S.px,b.beta),S.py,S.pz),v.add(S)}multiply(g){let{endo:y,n:b}=e;bt("scalar",g,pt,b);let w,x;if(y){let{k1neg:T,k1:k,k2neg:v,k2:S}=y.splitScalar(g),{p:_,f:F}=this.wNAF(k),{p:N,f:O}=this.wNAF(S);_=p.constTimeNegate(T,_),N=p.constTimeNegate(v,N),N=new f(t.mul(N.px,y.beta),N.py,N.pz),w=_.add(N),x=F.add(O)}else{let{p:T,f:k}=this.wNAF(g);w=T,x=k}return f.normalizeZ([w,x])[0]}multiplyAndAddUnsafe(g,y,b){let w=f.BASE,x=(k,v)=>v===Qn||v===pt||!k.equals(w)?k.multiplyUnsafe(v):k.multiply(v),T=x(this,y).add(x(g,b));return T.is0()?void 0:T}toAffine(g){return d(this,g)}isTorsionFree(){let{h:g,isTorsionFree:y}=e;if(g===pt)return!0;if(y)return y(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:g,clearCofactor:y}=e;return g===pt?this:y?y(f,this):this.multiplyUnsafe(e.h)}toRawBytes(g=!0){return zr("isCompressed",g),this.assertValidity(),o(f,this,g)}toHex(g=!0){return zr("isCompressed",g),On(this.toRawBytes(g))}}f.BASE=new f(e.Gx,e.Gy,t.ONE),f.ZERO=new f(t.ZERO,t.ONE,t.ZERO);let h=e.nBitLength,p=Ql(f,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:f,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:a}}function CS(r){let e=_a(r);return _r(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function g8(r){let e=CS(r),{Fp:t,n}=e,o=t.BYTES+1,i=2*t.BYTES+1;function s(L){return _e(L,n)}function a(L){return Gl(L,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:d,isWithinCurveOrder:u}=kS({...e,toBytes(L,D,I){let A=D.toAffine(),R=t.toBytes(A.x),P=Fn;return zr("isCompressed",I),I?P(Uint8Array.from([D.hasEvenY()?2:3]),R):P(Uint8Array.from([4]),R,t.toBytes(A.y))},fromBytes(L){let D=L.length,I=L[0],A=L.subarray(1);if(D===o&&(I===2||I===3)){let R=Mn(A);if(!Aa(R,pt,t.ORDER))throw new Error("Point is not on curve");let P=d(R),q;try{q=t.sqrt(P)}catch(ae){let ce=ae instanceof Error?": "+ae.message:"";throw new Error("Point is not on curve"+ce)}let z=(q&pt)===pt;return(I&1)===1!==z&&(q=t.neg(q)),{x:R,y:q}}else if(D===i&&I===4){let R=t.fromBytes(A.subarray(0,t.BYTES)),P=t.fromBytes(A.subarray(t.BYTES,2*t.BYTES));return{x:R,y:P}}else throw new Error(`Point of length ${D} was invalid. Expected ${o} compressed bytes or ${i} uncompressed bytes`)}}),f=L=>On(xo(L,e.nByteLength));function h(L){let D=n>>pt;return L>D}function p(L){return h(L)?s(-L):L}let m=(L,D,I)=>Mn(L.slice(D,I));class g{constructor(D,I,A){this.r=D,this.s=I,this.recovery=A,this.assertValidity()}static fromCompact(D){let I=e.nByteLength;return D=Ue("compactSignature",D,I*2),new g(m(D,0,I),m(D,I,2*I))}static fromDER(D){let{r:I,s:A}=Gn.toSig(Ue("DER",D));return new g(I,A)}assertValidity(){bt("r",this.r,pt,n),bt("s",this.s,pt,n)}addRecoveryBit(D){return new g(this.r,this.s,D)}recoverPublicKey(D){let{r:I,s:A,recovery:R}=this,P=k(Ue("msgHash",D));if(R==null||![0,1,2,3].includes(R))throw new Error("recovery id invalid");let q=R===2||R===3?I+e.n:I;if(q>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let z=R&1?"03":"02",Z=c.fromHex(z+f(q)),ae=a(q),ce=s(-P*ae),fe=s(A*ae),ve=c.BASE.multiplyAndAddUnsafe(Z,ce,fe);if(!ve)throw new Error("point at infinify");return ve.assertValidity(),ve}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,s(-this.s),this.recovery):this}toDERRawBytes(){return ci(this.toDERHex())}toDERHex(){return Gn.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return ci(this.toCompactHex())}toCompactHex(){return f(this.r)+f(this.s)}}let y={isValidPrivateKey(L){try{return l(L),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let L=o2(e.n);return i6(e.randomBytes(L),e.n)},precompute(L=8,D=c.BASE){return D._setWindowSize(L),D.multiply(BigInt(3)),D}};function b(L,D=!0){return c.fromPrivateKey(L).toRawBytes(D)}function w(L){let D=bo(L),I=typeof L=="string",A=(D||I)&&L.length;return D?A===o||A===i:I?A===2*o||A===2*i:L instanceof c}function x(L,D,I=!0){if(w(L))throw new Error("first arg must be private key");if(!w(D))throw new Error("second arg must be public key");return c.fromHex(D).multiply(l(L)).toRawBytes(I)}let T=e.bits2int||function(L){let D=Mn(L),I=L.length*8-e.nBitLength;return I>0?D>>BigInt(I):D},k=e.bits2int_modN||function(L){return s(T(L))},v=Ia(e.nBitLength);function S(L){return bt(`num < 2^${e.nBitLength}`,L,Qn,v),xo(L,e.nByteLength)}function _(L,D,I=F){if(["recovered","canonical"].some(Be=>Be in I))throw new Error("sign() legacy options not supported");let{hash:A,randomBytes:R}=e,{lowS:P,prehash:q,extraEntropy:z}=I;P==null&&(P=!0),L=Ue("msgHash",L),p8(I),q&&(L=Ue("prehashed msgHash",A(L)));let Z=k(L),ae=l(D),ce=[S(ae),S(Z)];if(z!=null&&z!==!1){let Be=z===!0?R(t.BYTES):z;ce.push(Ue("extraEntropy",Be))}let fe=Fn(...ce),ve=Z;function Ne(Be){let Ve=T(Be);if(!u(Ve))return;let Ot=a(Ve),at=c.BASE.multiply(Ve).toAffine(),Qt=s(at.x);if(Qt===Qn)return;let Pn=s(Ot*s(ve+Qt*ae));if(Pn===Qn)return;let ha=(at.x===Qt?0:2)|Number(at.y&pt),pa=Pn;return P&&h(Pn)&&(pa=p(Pn),ha^=1),new g(Qt,pa,ha)}return{seed:fe,k2sig:Ne}}let F={lowS:e.lowS,prehash:!1},N={lowS:e.lowS,prehash:!1};function O(L,D,I=F){let{seed:A,k2sig:R}=_(L,D,I),P=e;return J0(P.hash.outputLen,P.nByteLength,P.hmac)(A,R)}c.BASE._setWindowSize(8);function B(L,D,I,A=N){let R=L;if(D=Ue("msgHash",D),I=Ue("publicKey",I),"strict"in A)throw new Error("options.strict was renamed to lowS");p8(A);let{lowS:P,prehash:q}=A,z,Z;try{if(typeof R=="string"||bo(R))try{z=g.fromDER(R)}catch(at){if(!(at instanceof Gn.Err))throw at;z=g.fromCompact(R)}else if(typeof R=="object"&&typeof R.r=="bigint"&&typeof R.s=="bigint"){let{r:at,s:Qt}=R;z=new g(at,Qt)}else throw new Error("PARSE");Z=c.fromHex(I)}catch(at){if(at.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(P&&z.hasHighS())return!1;q&&(D=e.hash(D));let{r:ae,s:ce}=z,fe=k(D),ve=a(ce),Ne=s(fe*ve),Be=s(ae*ve),Ve=c.BASE.multiplyAndAddUnsafe(Z,Ne,Be)?.toAffine();return Ve?s(Ve.x)===ae:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:x,sign:O,verify:B,ProjectivePoint:c,Signature:g,utils:y}}function PS(r){return{hash:r,hmac:(e,...t)=>_o(r,e,W0(...t)),randomBytes:si}}function y8(r,e){let t=n=>g8({...r,...PS(n)});return Object.freeze({...t(e),create:t})}var x8=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),w8=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),RS=BigInt(1),S2=BigInt(2),b8=(r,e)=>(r+e/S2)/e;function LS(r){let e=x8,t=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,d=l*l*r%e,u=Fe(d,t,e)*d%e,f=Fe(u,t,e)*d%e,h=Fe(f,S2,e)*l%e,p=Fe(h,o,e)*h%e,m=Fe(p,i,e)*p%e,g=Fe(m,a,e)*m%e,y=Fe(g,c,e)*g%e,b=Fe(y,a,e)*m%e,w=Fe(b,t,e)*d%e,x=Fe(w,s,e)*p%e,T=Fe(x,n,e)*l%e,k=Fe(T,S2,e);if(!A2.eql(A2.sqr(k),r))throw new Error("Cannot find square root");return k}var A2=Eo(x8,void 0,void 0,{sqrt:LS}),Pr=y8({a:BigInt(0),b:BigInt(7),Fp:A2,n:w8,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=w8,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-RS*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=t,s=BigInt("0x100000000000000000000000000000000"),a=b8(i*r,e),c=b8(-n*r,e),l=_e(r-a*t-c*o,e),d=_e(-a*n-c*i,e),u=l>s,f=d>s;if(u&&(l=e-l),f&&(d=e-d),l>s||d>s)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:u,k1:l,k2neg:f,k2:d}}}},Tr),qB=BigInt(0);var WB=Pr.ProjectivePoint;function I2(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function E8(r,e){let t=ut.digest(e instanceof Uint8Array?e:e.subarray());if(I2(t))return t.then(({digest:n})=>Pr.sign(n,r).toDERRawBytes()).catch(n=>{throw new $a(String(n))});try{return Pr.sign(t.digest,r).toDERRawBytes()}catch(n){throw new $a(String(n))}}function v8(r,e,t){let n=ut.digest(t instanceof Uint8Array?t:t.subarray());if(I2(n))return n.then(({digest:o})=>Pr.verify(e,o,r)).catch(o=>{throw new Va(String(o))});try{return Pr.verify(e,n.digest,r)}catch(o){throw new Va(String(o))}}var qa=class{type="secp256k1";raw;_key;constructor(e){this._key=I8(e),this.raw=S8(this._key)}toMultihash(){return Jt.digest(Lt(this))}toCID(){return X.createV1(114,this.toMultihash())}toString(){return Se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}verify(e,t){return v8(this._key,t,e)}},Wa=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=A8(e),this.publicKey=new qa(t??_8(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}sign(e){return E8(this.raw,e)}};function _2(r){return new Wa(r)}function T2(r){return new qa(r)}async function T8(){let r=DS();return new Wa(r)}function S8(r){return Pr.ProjectivePoint.fromHex(r).toRawBytes(!0)}function A8(r){try{return Pr.getPublicKey(r,!0),r}catch(e){throw new ma(String(e))}}function I8(r){try{return Pr.ProjectivePoint.fromHex(r),r}catch(e){throw new Rn(String(e))}}function _8(r){try{return Pr.getPublicKey(r,!0)}catch(e){throw new ma(String(e))}}function DS(){return Pr.utils.randomPrivateKey()}async function Hu(r,e){if(r==="Ed25519")return y6();if(r==="secp256k1")return T8();if(r==="RSA")return v2(e??2048);throw new $r}function rt(r){let{Type:e,Data:t}=yn.decode(r),n=t??new Uint8Array;switch(e){case Ye.RSA:return E2(n);case Ye.Ed25519:return u2(n);case Ye.secp256k1:return T2(n);default:throw new $r}}function qu(r){let{Type:e,Data:t}=yn.decode(r.digest),n=t??new Uint8Array;switch(e){case Ye.Ed25519:return u2(n);case Ye.secp256k1:return T2(n);default:throw new $r}}function Lt(r){return yn.encode({Type:Ye[r.type],Data:r.raw})}function k8(r){let e=Ra.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Ye.RSA:return Vu(t);case Ye.Ed25519:return l2(t);case Ye.secp256k1:return _2(t);default:throw new $r}}function C8(r){return r.byteLength===64?l2(r):r.byteLength===32?_2(r):Vu(r)}function hs(r){return Ra.encode({Type:Ye[r.type],Data:r.raw})}var P8=Symbol.for("nodejs.util.inspect.custom"),NS=114,za=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()})`}[al]=!0;toString(){return this.string==null&&(this.string=Se.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return X.createV1(NS,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return te(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return te(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[P8](){return`PeerId(${this.toString()})`}},Ga=class extends za{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Qa=class extends za{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Ya=class extends za{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},BS=2336,Xa=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Jt.digest(M(this.url))}[P8](){return`PeerId(${this.url})`}[al]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return X.createV1(BS,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=V(e)),e.toString()===this.toString())}};var OS=114,R8=2336;function Re(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=ke(Se.decode(`z${r}`));else{if(e==null)throw new C('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=ke(e.decode(r))}return mt(t)}function En(r){if(r.type==="Ed25519")return new Qa({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Ya({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Ga({multihash:r.toCID().multihash,publicKey:r});throw new $r}function L8(r){return En(r.publicKey)}function mt(r){if(US(r))return new Ga({multihash:r});if(MS(r))try{let e=qu(r);if(e.type==="Ed25519")return new Qa({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Ya({multihash:r,publicKey:e})}catch{let t=V(r.digest);return new Xa(new URL(t))}throw new co("Supplied PeerID Multihash is invalid")}function vn(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==OS&&r.code!==R8)throw new hl("Supplied PeerID CID is invalid");if(r.code===R8){let e=V(r.multihash.digest);return new Xa(new URL(e))}return mt(r.multihash)}function MS(r){return r.code===Jt.code}function US(r){return r.code===ut.code}function hi(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function Wu(r){let e=ke(Se.decode(`z${r}`));return mt(e)}var gt=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 hi(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 hi(this.map.values(),e=>e.key)}values(){return hi(this.map.values(),e=>e.value)}get size(){return this.map.size}};var nr=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 hi(this.set.entries(),e=>{let t=Wu(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Wu(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return hi(this.set.values(),e=>Wu(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}};function D8(r,e,t,n){ni(r);let o=j4({dkLen:32,asyncTick:10},n),{c:i,dkLen:s,asyncTick:a}=o;if(po(i),po(s),po(a),i<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=Wr(e),l=Wr(t),d=new Uint8Array(s),u=_o.create(r,c),f=u._cloneInto().update(l);return{c:i,dkLen:s,asyncTick:a,DK:d,PRF:u,PRFSalt:f}}function N8(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}function B8(r,e,t,n){let{c:o,dkLen:i,DK:s,PRF:a,PRFSalt:c}=D8(r,e,t,n),l,d=new Uint8Array(4),u=ii(d),f=new Uint8Array(a.outputLen);for(let h=1,p=0;p<i;h++,p+=a.outputLen){let m=s.subarray(p,p+a.outputLen);u.setInt32(0,h,!1),(l=c._cloneInto(l)).update(d).digestInto(f),m.set(f.subarray(0,m.length));for(let g=1;g<o;g++){a._cloneInto(l).update(f).digestInto(f);for(let y=0;y<m.length;y++)m[y]^=f[y]}}return N8(a,c,s,l,f)}async function zu(r,e,t,n){let{c:o,dkLen:i,asyncTick:s,DK:a,PRF:c,PRFSalt:l}=D8(r,e,t,n),d,u=new Uint8Array(4),f=ii(u),h=new Uint8Array(c.outputLen);for(let p=1,m=0;m<i;p++,m+=c.outputLen){let g=a.subarray(m,m+c.outputLen);f.setInt32(0,p,!1),(d=l._cloneInto(d)).update(u).digestInto(h),g.set(h.subarray(0,g.length)),await Y4(o-1,s,()=>{c._cloneInto(d).update(h).digestInto(h);for(let y=0;y<g.length;y++)g[y]^=h[y]})}return N8(c,l,a,d,h)}var ja=new Uint32Array([1732584193,4023233417,2562383102,271733878,3285377520]),To=new Uint32Array(80),k2=class extends mo{constructor(){super(64,20,8,!1),this.A=ja[0]|0,this.B=ja[1]|0,this.C=ja[2]|0,this.D=ja[3]|0,this.E=ja[4]|0}get(){let{A:e,B:t,C:n,D:o,E:i}=this;return[e,t,n,o,i]}set(e,t,n,o,i){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=i|0}process(e,t){for(let c=0;c<16;c++,t+=4)To[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)To[c]=Vl(To[c-3]^To[c-8]^To[c-14]^To[c-16],1);let{A:n,B:o,C:i,D:s,E:a}=this;for(let c=0;c<80;c++){let l,d;c<20?(l=Kl(o,i,s),d=1518500249):c<40?(l=o^i^s,d=1859775393):c<60?(l=Hl(o,i,s),d=2400959708):(l=o^i^s,d=3395469782);let u=Vl(n,5)+l+a+d+To[c]|0;a=s,s=i,i=Vl(o,30),o=n,n=u}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,this.set(n,o,i,s,a)}roundClean(){To.fill(0)}destroy(){this.set(0,0,0,0,0),this.buffer.fill(0)}},O8=ns(()=>new k2);var M8={sha1:O8,"sha2-256":Tr,"sha2-512":wo};function Za(r,e,t,n,o){if(o!=="sha1"&&o!=="sha2-256"&&o!=="sha2-512"){let a=Object.keys(M8).join(" / ");throw new C(`Hash '${o}' is unknown or not supported. Must be ${a}`)}let i=M8[o],s=B8(i,r,e,{c:t,dkLen:n});return it.encode(s).substring(1)}var C2=64,Xr=class{fp;h;seed;constructor(e,t,n,o=2){if(o>C2)throw new TypeError("Invalid Fingerprint Size");let i=t.hashV(e,n),s=se(o);for(let a=0;a<s.length;a++)s[a]=i[a];s.length===0&&(s[0]=7),this.fp=s,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?te(this.fp,e.fp):!1}};function pi(r,e){return Math.floor(Math.random()*(e-r))+r}var mi=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Xr))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof Xr))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 Xr))throw new TypeError("Invalid Fingerprint");let t=pi(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof Xr))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var P2={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},V8={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},K8=new globalThis.TextEncoder;function $S(r,e){let t=P2[e],n=V8[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function VS(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=P2[e],o=V8[e],i=r;for(;i.length>0;){let s=K8.encodeInto(i,t);i=i.slice(s.read);for(let a=0;a<s.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function R2(r,{size:e=32,utf8Buffer:t}={}){if(!P2[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 VS(r,e,t);r=K8.encode(r)}return $S(r,e)}var KS=fr($8(),1);var ec={hash:r=>Number(R2(r,{size:32})),hashV:(r,e)=>HS(ec.hash(r,e))};function HS(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),M(e,"base16")}var qS=500,tc=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??ec,this.seed=e.seed??pi(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=M(e));let t=new Xr(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new mi(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new mi(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let i=[n,o],s=i[pi(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new mi(this.bucketSize));for(let a=0;a<qS;a++){let c=this.buckets[s].swap(t);if(c!=null&&(s=(s^c.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new mi(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=M(e));let t=new Xr(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let i=(n^t.hash())%this.filterSize;return this.buckets[i]?.has(t)??!1}remove(e){typeof e=="string"&&(e=M(e));let t=new Xr(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let i=(n^t.hash())%this.filterSize,s=this.buckets[i]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},WS={1:.5,2:.84,4:.95,8:.98};function zS(r=.001){return r>.002?2:r>1e-5?4:8}function H8(r,e=.001){let t=zS(e),n=WS[t],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),C2);return{filterSize:o,bucketSize:t,fingerprintSize:i}}var Qu=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??ec,this.seed=e.seed??pi(0,Math.pow(2,10)),this.filterSeries=[new tc({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=M(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 tc({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=M(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=M(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 Sn(r,e=.001,t){return new Qu({...H8(r,e),...t??{}})}var Yu=class{filter;constructor(e,t){this.filter=Sn(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 L2(r,e=.001){return new Yu(r,e)}var D2=class extends gt{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 rc(r){let{name:e,metrics:t}=r,n;return t!=null?n=new D2({name:e,metrics:t}):n=new gt,n}var Yn=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(e=!1,t=0){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){let n=it.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=it.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=it.encode(e.multihash.bytes);this.blocks.set(n,t)}};function GS(r){let e=new Uint8Array(r.reduce((n,o)=>n+pe(o),0)),t=0;for(let n of r)e=Ke(n,e,t),t+=pe(n);return e}var q8=GS;function N2(r){return q8([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var Xu=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}async sendBlocksToPeer(e){let t=new Yn,n=new Set;for(let[o,i]of this.wants.entries())try{let s=await this.blockstore.get(i.cid,e);i.wantType===et.WantHave?s.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(o),t.addBlock(i.cid,{data:s,prefix:N2(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Ir.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(o),t.addBlock(i.cid,{data:s,prefix:N2(i.cid)}))}catch(s){if(s.name!=="NotFoundError")throw s;if(this.log("do not have block for %c",i.cid),!i.sendDontHave||i.sentDontHave===!0)continue;i.sentDontHave=!0,t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Ir.DontHaveBlock})}if(t.blocks.size>0||t.blockPresences.size>0){this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((o,i)=>o+i.data.byteLength,0));for(let o of n)this.wants.delete(o)}}};var ju=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=rc({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return[...t.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);if(n==null&&(n=new Xu({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((o,i)=>o+i.data.byteLength,0)??0),t.wantlist!=null){t.wantlist.full===!0&&n.wants.clear();for(let o of t.wantlist.entries){let i=X.decode(o.cid),s=V(i.multihash.bytes,"base64");o.cancel===!0?(this.log("peer %p cancelled want of block for %c",e,i),n.wants.delete(s)):(o.wantType===et.WantHave?this.log("peer %p wanted block presence for %c",e,i):this.log("peer %p wanted block for %c",e,i),n.wants.set(s,{cid:i,priority:o.priority,wantType:o.wantType??et.WantBlock,sendDontHave:o.sendDontHave??!1}))}}this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=V(e.multihash.bytes,"base64"),o=[];for(let i of this.ledgerMap.values())i.wants.has(n)&&o.push(i);await Promise.all(o.map(async i=>i.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};function QS(r,e){try{if(typeof r=="string"&&r.length>0)return YS(r);if(typeof r=="number"&&isFinite(r))return e?.long?jS(r):XS(r);throw new Error("Value is not a string or number.")}catch(t){let n=ZS(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function YS(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let 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)return NaN;let t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*315576e5;case"weeks":case"week":case"w":return t*6048e5;case"days":case"day":case"d":return t*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return t*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return t*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return t*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var Ju=QS;function XS(r){let e=Math.abs(r);return 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 jS(r){let e=Math.abs(r);return e>=864e5?Zu(r,e,864e5,"day"):e>=36e5?Zu(r,e,36e5,"hour"):e>=6e4?Zu(r,e,6e4,"minute"):e>=1e3?Zu(r,e,1e3,"second"):`${r} ms`}function Zu(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function ZS(r){return typeof r=="object"&&r!==null&&"message"in r}function B2(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=o,t.enabled=s,t.humanize=Ju,t.destroy=l,Object.keys(r).forEach(d=>{t[d]=r[d]}),t.names=[],t.skips=[],t.formatters={};function e(d){let u=0;for(let f=0;f<d.length;f++)u=(u<<5)-u+d.charCodeAt(f),u|=0;return t.colors[Math.abs(u)%t.colors.length]}t.selectColor=e;function t(d){let u,f=null,h,p;function m(...g){if(!m.enabled)return;let y=m,b=Number(new Date),w=b-(u||b);y.diff=w,y.prev=u,y.curr=b,u=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,(k,v)=>{if(k==="%%")return"%";x++;let S=t.formatters[v];if(typeof S=="function"){let _=g[x];k=S.call(y,_),g.splice(x,1),x--}return k}),t.formatArgs.call(y,g),(y.log||t.log).apply(y,g)}return m.namespace=d,m.useColors=t.useColors(),m.color=t.selectColor(d),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(h!==t.namespaces&&(h=t.namespaces,p=t.enabled(d)),p),set:g=>{f=g}}),typeof t.init=="function"&&t.init(m),m}function n(d,u){let f=t(this.namespace+(typeof u>"u"?":":u)+d);return f.log=this.log,f}function o(d){t.save(d),t.namespaces=d,t.names=[],t.skips=[];let u,f=(typeof d=="string"?d:"").split(/[\s,]+/),h=f.length;for(u=0;u<h;u++)f[u]&&(d=f[u].replace(/\*/g,".*?"),d[0]==="-"?t.skips.push(new RegExp("^"+d.substr(1)+"$")):t.names.push(new RegExp("^"+d+"$")))}function i(){let d=[...t.names.map(a),...t.skips.map(a).map(u=>"-"+u)].join(",");return t.enable(""),d}function s(d){if(d[d.length-1]==="*")return!0;let u,f;for(u=0,f=t.skips.length;u<f;u++)if(t.skips[u].test(d))return!1;for(u=0,f=t.names.length;u<f;u++)if(t.names[u].test(d))return!0;return!1}function a(d){return d.toString().substring(2,d.toString().length-2).replace(/\.\*\?$/,"*")}function c(d){return d instanceof Error?d.stack??d.message:d}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 e1=iA(),JS=["#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 eA(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function tA(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ju(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,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var rA=console.debug??console.log??(()=>{});function nA(r){try{r?e1?.setItem("debug",r):e1?.removeItem("debug")}catch{}}function oA(){let r;try{r=e1?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function iA(){try{return localStorage}catch{}}function sA(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var W8=B2({formatArgs:tA,save:nA,load:oA,useColors:eA,setupFormatters:sA,colors:JS,storage:e1,log:rA});var or=W8;or.formatters.b=r=>r==null?"undefined":Se.baseEncode(r);or.formatters.t=r=>r==null?"undefined":lt.baseEncode(r);or.formatters.m=r=>r==null?"undefined":it.baseEncode(r);or.formatters.p=r=>r==null?"undefined":r.toString();or.formatters.c=r=>r==null?"undefined":r.toString();or.formatters.k=r=>r==null?"undefined":r.toString();or.formatters.a=r=>r==null?"undefined":r.toString();or.formatters.e=r=>r==null?"undefined":z8(r.stack)??z8(r.message)??r.toString();function aA(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 ko(){return{forComponent(r){return mr(r)}}}function mr(r){let e=aA(`${r}:trace`);return or.enabled(`${r}:trace`)&&or.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=or(`${r}:trace`)),Object.assign(or(r),{error:or(`${r}:error`),trace:e})}function z8(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var M2=fr(Q8(),1);var oc=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},U2=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Y8=r=>globalThis.DOMException===void 0?new U2(r):new DOMException(r),X8=r=>{let e=r.reason===void 0?Y8("This operation was aborted."):r.reason;return e instanceof Error?e:Y8(e)};function jr(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,s,c=new Promise((l,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:f}=e;f.aborted&&d(X8(f));let h=()=>{d(X8(f))};f.addEventListener("abort",h,{once:!0}),r.finally(()=>{f.removeEventListener("abort",h)})}if(t===Number.POSITIVE_INFINITY){r.then(l,d);return}let u=new oc;s=i.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(f){d(f)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?d(o):(u.message=o??`Promise timed out after ${t} milliseconds`,d(u))},t),(async()=>{try{l(await r)}catch(f){d(f)}})()}).finally(()=>{c.clear()});return c.clear=()=>{i.clearTimeout.call(void 0,s),s=void 0},c}function F2(r,e,t){let n=0,o=r.length;for(;o>0;){let i=Math.trunc(o/2),s=n+i;t(r[s],e)<=0?(n=++s,o-=i+1):o=i}return n}var ic=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=F2(this.#e,n,(i,s)=>s.priority-i.priority);this.#e.splice(o,0,n)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var An=class extends M2.default{#e;#t;#r=0;#o;#a;#l=0;#i;#u;#n;#m;#s=0;#d;#c;#g;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:ic,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#o=e.intervalCap,this.#a=e.interval,this.#n=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#c=e.autoStart===!1}get#b(){return this.#t||this.#r<this.#o}get#x(){return this.#s<this.#d}#E(){this.#s--,this.#f(),this.emit("next")}#v(){this.#w(),this.#y(),this.#u=void 0}get#S(){let e=Date.now();if(this.#i===void 0){let t=this.#l-e;if(t<0)this.#r=this.#e?this.#s:0;else return this.#u===void 0&&(this.#u=setTimeout(()=>{this.#v()},t)),!0}return!1}#f(){if(this.#n.size===0)return this.#i&&clearInterval(this.#i),this.#i=void 0,this.emit("empty"),this.#s===0&&this.emit("idle"),!1;if(!this.#c){let e=!this.#S;if(this.#b&&this.#x){let t=this.#n.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#i!==void 0||(this.#i=setInterval(()=>{this.#w()},this.#a),this.#l=Date.now()+this.#a)}#w(){this.#r===0&&this.#s===0&&this.#i&&(clearInterval(this.#i),this.#i=void 0),this.#r=this.#e?this.#s:0,this.#h()}#h(){for(;this.#f(););}get concurrency(){return this.#d}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#d=e,this.#h()}async#A(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#n.enqueue(async()=>{this.#s++,this.#r++;try{t.signal?.throwIfAborted();let i=e({signal:t.signal});t.timeout&&(i=jr(Promise.resolve(i),{milliseconds:t.timeout})),t.signal&&(i=Promise.race([i,this.#A(t.signal)]));let s=await i;n(s),this.emit("completed",s)}catch(i){if(i instanceof oc&&!t.throwOnTimeout){n();return}o(i),this.emit("error",i)}finally{this.#E()}},t),this.emit("add"),this.#f()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#c?(this.#c=!1,this.#h(),this):this}pause(){this.#c=!0}clear(){this.#n=new this.#m}async onEmpty(){this.#n.size!==0&&await this.#p("empty")}async onSizeLessThan(e){this.#n.size<e||await this.#p("next",()=>this.#n.size<e)}async onIdle(){this.#s===0&&this.#n.size===0||await this.#p("idle")}async#p(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#n.size}sizeBy(e){return this.#n.filter(e).length}get pending(){return this.#s}get isPaused(){return this.#c}};function r1(r){let e=[gr.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var $2=60;function n1(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:gr[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:gr[e.type],TTL:e.TTL??e.ttl??$2,data:e.data instanceof Uint8Array?V(e.data):e.data}))}}var uA=4;function V2(r,e={}){let t=new An({concurrency:e.queryConcurrency??uA});return async(n,o={})=>{let i=new URLSearchParams;i.set("name",n),r1(o.types).forEach(a=>{i.append("type",gr[a])}),o.onProgress?.(new H("dns:query",{detail:n}));let s=await t.add(async()=>{let a=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=n1(await a.json());return o.onProgress?.(new H("dns:response",{detail:c})),c},{signal:o.signal});if(s==null)throw new Error("No DNS response received");return s}}function j8(){return[V2("https://cloudflare-dns.com/dns-query"),V2("https://dns.google/resolve")]}var e5=fr(J8(),1);var K2=class{lru;constructor(e){this.lru=(0,e5.default)(e)}get(e,t){let n=!0,o=[];for(let i of t){let s=this.getAnswers(e,i);if(s.length===0){n=!1;break}o.push(...s)}if(n)return n1({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let i=o.filter(s=>s.expires>Date.now()).map(({expires:s,value:a})=>({...a,TTL:Math.round((s-Date.now())/1e3),type:gr[a.type]}));return i.length===0&&this.lru.remove(n),i}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??$2)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function t5(r){return new K2(r)}var dA=1e3,o1=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=t5(e.cacheSize??dA),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["."]=j8())}async query(e,t={}){let n=r1(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new H("dns:cache",{detail:o})),o;let i=`${e.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of s){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let d of l.Answer)this.cache.add(e,d);return l}catch(l){a.push(l),t.onProgress?.(new H("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var gr;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(gr||(gr={}));function i1(r={}){return new o1(r)}var fA=["string","number","bigint","symbol"],hA=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function r5(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(fA.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(pA(r))return"Buffer";let t=mA(r);return t||"Object"}function pA(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function mA(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(hA.includes(e))return e}var E=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};E.uint=new E(0,"uint",!0);E.negint=new E(1,"negint",!0);E.bytes=new E(2,"bytes",!0);E.string=new E(3,"string",!0);E.array=new E(4,"array",!1);E.map=new E(5,"map",!1);E.tag=new E(6,"tag",!1);E.float=new E(7,"float",!0);E.false=new E(7,"false",!0);E.true=new E(7,"true",!0);E.null=new E(7,"null",!0);E.undefined=new E(7,"undefined",!0);E.break=new E(7,"break",!0);var U=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var ps=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",gA=new TextDecoder,yA=new TextEncoder;function s1(r){return ps&&globalThis.Buffer.isBuffer(r)}function sc(r){return r instanceof Uint8Array?s1(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var s5=ps?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):o5(r,e,t):(r,e,t)=>t-e>64?gA.decode(r.subarray(e,t)):o5(r,e,t),a1=ps?r=>r.length>64?globalThis.Buffer.from(r):n5(r):r=>r.length>64?yA.encode(r):n5(r),In=r=>Uint8Array.from(r),ms=ps?(r,e,t)=>s1(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),a5=ps?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),sc(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let o of r)n+o.length>t.length&&(o=o.subarray(0,t.length-n)),t.set(o,n),n+=o.length;return t},c5=ps?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function l5(r,e){if(s1(r)&&s1(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function n5(r){let e=[],t=0;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(o=65536+((o&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128)}return e}function o5(r,e,t){let n=[];for(;e<t;){let o=r[e],i=null,s=o>239?4:o>223?3:o>191?2:1;if(e+s<=t){let a,c,l,d;switch(s){case 1:o<128&&(i=o);break;case 2:a=r[e+1],(a&192)===128&&(d=(o&31)<<6|a&63,d>127&&(i=d));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(d=(o&15)<<12|(a&63)<<6|c&63,d>2047&&(d<55296||d>57343)&&(i=d));break;case 4:a=r[e+1],c=r[e+2],l=r[e+3],(a&192)===128&&(c&192)===128&&(l&192)===128&&(d=(o&15)<<18|(a&63)<<12|(c&63)<<6|l&63,d>65535&&d<1114112&&(i=d))}}i===null?(i=65533,s=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|i&1023),n.push(i),e+=s}return H2(n)}var i5=4096;function H2(r){let e=r.length;if(e<=i5)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=i5));return t}var wA=256,ac=class{constructor(e=wA){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=t.length-(this.maxCursor-this.cursor)-1;t.set(e,o)}else{if(t){let o=t.length-(this.maxCursor-this.cursor)-1;o<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=c5(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=ms(n,0,this.cursor)}else t=a5(this.chunks,this.cursor);return e&&this.reset(),t}};var j="CBOR decode error:",Xn="CBOR encode error:",cc=[];cc[23]=1;cc[24]=2;cc[25]=3;cc[26]=5;cc[27]=9;function jn(r,e,t){if(r.length-e<t)throw new Error(`${j} not enough data for type`)}var yt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function yr(r,e,t){jn(r,e,1);let n=r[e];if(t.strict===!0&&n<yt[0])throw new Error(`${j} integer encoded in more bytes than necessary (strict decode)`);return n}function wr(r,e,t){jn(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<yt[1])throw new Error(`${j} integer encoded in more bytes than necessary (strict decode)`);return n}function br(r,e,t){jn(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<yt[2])throw new Error(`${j} integer encoded in more bytes than necessary (strict decode)`);return n}function xr(r,e,t){jn(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],o=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&i<yt[3])throw new Error(`${j} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(t.allowBigInt===!0)return i;throw new Error(`${j} integers outside of the safe integer range are not supported`)}function u5(r,e,t,n){return new U(E.uint,yr(r,e+1,n),2)}function d5(r,e,t,n){return new U(E.uint,wr(r,e+1,n),3)}function f5(r,e,t,n){return new U(E.uint,br(r,e+1,n),5)}function h5(r,e,t,n){return new U(E.uint,xr(r,e+1,n),9)}function Rr(r,e){return Et(r,0,e.value)}function Et(r,e,t){if(t<yt[0]){let n=Number(t);r.push([e|n])}else if(t<yt[1]){let n=Number(t);r.push([e|24,n])}else if(t<yt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<yt[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<yt[4]){let o=[e|27,0,0,0,0,0,0,0],i=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=s&255,s=s>>8,o[3]=s&255,s=s>>8,o[2]=s&255,s=s>>8,o[1]=s&255,r.push(o)}else throw new Error(`${j} encountered BigInt larger than allowable range`)}}Rr.encodedSize=function(e){return Et.encodedSize(e.value)};Et.encodedSize=function(e){return e<yt[0]?1:e<yt[1]?2:e<yt[2]?3:e<yt[3]?5:9};Rr.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function p5(r,e,t,n){return new U(E.negint,-1-yr(r,e+1,n),2)}function m5(r,e,t,n){return new U(E.negint,-1-wr(r,e+1,n),3)}function g5(r,e,t,n){return new U(E.negint,-1-br(r,e+1,n),5)}var q2=BigInt(-1),y5=BigInt(1);function w5(r,e,t,n){let o=xr(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new U(E.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${j} integers outside of the safe integer range are not supported`);return new U(E.negint,q2-BigInt(o),9)}function c1(r,e){let t=e.value,n=typeof t=="bigint"?t*q2-y5:t*-1-1;Et(r,e.type.majorEncoded,n)}c1.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*q2-y5:t*-1-1;return n<yt[0]?1:n<yt[1]?2:n<yt[2]?3:n<yt[3]?5:9};c1.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function lc(r,e,t,n){jn(r,e,t+n);let o=ms(r,e+t,e+t+n);return new U(E.bytes,o,t+n)}function b5(r,e,t,n){return lc(r,e,1,t)}function x5(r,e,t,n){return lc(r,e,2,yr(r,e+1,n))}function E5(r,e,t,n){return lc(r,e,3,wr(r,e+1,n))}function v5(r,e,t,n){return lc(r,e,5,br(r,e+1,n))}function S5(r,e,t,n){let o=xr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${j} 64-bit integer bytes lengths not supported`);return lc(r,e,9,o)}function l1(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===E.string?a1(r.value):r.value),r.encodedBytes}function gs(r,e){let t=l1(e);Et(r,e.type.majorEncoded,t.length),r.push(t)}gs.encodedSize=function(e){let t=l1(e);return Et.encodedSize(t.length)+t.length};gs.compareTokens=function(e,t){return xA(l1(e),l1(t))};function xA(r,e){return r.length<e.length?-1:r.length>e.length?1:l5(r,e)}function uc(r,e,t,n,o){let i=t+n;jn(r,e,i);let s=new U(E.string,s5(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=ms(r,e+t,e+i)),s}function A5(r,e,t,n){return uc(r,e,1,t,n)}function I5(r,e,t,n){return uc(r,e,2,yr(r,e+1,n),n)}function _5(r,e,t,n){return uc(r,e,3,wr(r,e+1,n),n)}function T5(r,e,t,n){return uc(r,e,5,br(r,e+1,n),n)}function k5(r,e,t,n){let o=xr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${j} 64-bit integer string lengths not supported`);return uc(r,e,9,o,n)}var C5=gs;function ys(r,e,t,n){return new U(E.array,n,t)}function P5(r,e,t,n){return ys(r,e,1,t)}function R5(r,e,t,n){return ys(r,e,2,yr(r,e+1,n))}function L5(r,e,t,n){return ys(r,e,3,wr(r,e+1,n))}function D5(r,e,t,n){return ys(r,e,5,br(r,e+1,n))}function N5(r,e,t,n){let o=xr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${j} 64-bit integer array lengths not supported`);return ys(r,e,9,o)}function B5(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${j} indefinite length items not allowed`);return ys(r,e,1,1/0)}function u1(r,e){Et(r,E.array.majorEncoded,e.value)}u1.compareTokens=Rr.compareTokens;u1.encodedSize=function(e){return Et.encodedSize(e.value)};function ws(r,e,t,n){return new U(E.map,n,t)}function O5(r,e,t,n){return ws(r,e,1,t)}function M5(r,e,t,n){return ws(r,e,2,yr(r,e+1,n))}function U5(r,e,t,n){return ws(r,e,3,wr(r,e+1,n))}function F5(r,e,t,n){return ws(r,e,5,br(r,e+1,n))}function $5(r,e,t,n){let o=xr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${j} 64-bit integer map lengths not supported`);return ws(r,e,9,o)}function V5(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${j} indefinite length items not allowed`);return ws(r,e,1,1/0)}function d1(r,e){Et(r,E.map.majorEncoded,e.value)}d1.compareTokens=Rr.compareTokens;d1.encodedSize=function(e){return Et.encodedSize(e.value)};function K5(r,e,t,n){return new U(E.tag,t,1)}function H5(r,e,t,n){return new U(E.tag,yr(r,e+1,n),2)}function q5(r,e,t,n){return new U(E.tag,wr(r,e+1,n),3)}function W5(r,e,t,n){return new U(E.tag,br(r,e+1,n),5)}function z5(r,e,t,n){return new U(E.tag,xr(r,e+1,n),9)}function f1(r,e){Et(r,E.tag.majorEncoded,e.value)}f1.compareTokens=Rr.compareTokens;f1.encodedSize=function(e){return Et.encodedSize(e.value)};var _A=20,TA=21,kA=22,CA=23;function G5(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${j} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new U(E.null,null,1):new U(E.undefined,void 0,1)}function Q5(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${j} indefinite length items not allowed`);return new U(E.break,void 0,1)}function W2(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${j} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${j} Infinity values are not supported`)}return new U(E.float,r,e)}function Y5(r,e,t,n){return W2(z2(r,e+1),3,n)}function X5(r,e,t,n){return W2(G2(r,e+1),5,n)}function j5(r,e,t,n){return W2(tg(r,e+1),9,n)}function h1(r,e,t){let n=e.value;if(n===!1)r.push([E.float.majorEncoded|_A]);else if(n===!0)r.push([E.float.majorEncoded|TA]);else if(n===null)r.push([E.float.majorEncoded|kA]);else if(n===void 0)r.push([E.float.majorEncoded|CA]);else{let o,i=!1;(!t||t.float64!==!0)&&(J5(n),o=z2(Zr,1),n===o||Number.isNaN(n)?(Zr[0]=249,r.push(Zr.slice(0,3)),i=!0):(eg(n),o=G2(Zr,1),n===o&&(Zr[0]=250,r.push(Zr.slice(0,5)),i=!0))),i||(PA(n),o=tg(Zr,1),Zr[0]=251,r.push(Zr.slice(0,9)))}}h1.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){J5(n);let o=z2(Zr,1);if(n===o||Number.isNaN(n))return 3;if(eg(n),o=G2(Zr,1),n===o)return 5}return 9};var Z5=new ArrayBuffer(9),Lr=new DataView(Z5,1),Zr=new Uint8Array(Z5,0);function J5(r){if(r===1/0)Lr.setUint16(0,31744,!1);else if(r===-1/0)Lr.setUint16(0,64512,!1);else if(Number.isNaN(r))Lr.setUint16(0,32256,!1);else{Lr.setFloat32(0,r);let e=Lr.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Lr.setUint16(0,31744,!1);else if(t===0)Lr.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?Lr.setUint16(0,0):o<-14?Lr.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Lr.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function z2(r,e){if(r.length-e<2)throw new Error(`${j} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,t&32768?-i:i}function eg(r){Lr.setFloat32(0,r,!1)}function G2(r,e){if(r.length-e<4)throw new Error(`${j} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function PA(r){Lr.setFloat64(0,r,!1)}function tg(r,e){if(r.length-e<8)throw new Error(`${j} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}h1.compareTokens=Rr.compareTokens;function Ae(r,e,t){throw new Error(`${j} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function p1(r){return()=>{throw new Error(`${j} ${r}`)}}var K=[];for(let r=0;r<=23;r++)K[r]=Ae;K[24]=u5;K[25]=d5;K[26]=f5;K[27]=h5;K[28]=Ae;K[29]=Ae;K[30]=Ae;K[31]=Ae;for(let r=32;r<=55;r++)K[r]=Ae;K[56]=p5;K[57]=m5;K[58]=g5;K[59]=w5;K[60]=Ae;K[61]=Ae;K[62]=Ae;K[63]=Ae;for(let r=64;r<=87;r++)K[r]=b5;K[88]=x5;K[89]=E5;K[90]=v5;K[91]=S5;K[92]=Ae;K[93]=Ae;K[94]=Ae;K[95]=p1("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)K[r]=A5;K[120]=I5;K[121]=_5;K[122]=T5;K[123]=k5;K[124]=Ae;K[125]=Ae;K[126]=Ae;K[127]=p1("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)K[r]=P5;K[152]=R5;K[153]=L5;K[154]=D5;K[155]=N5;K[156]=Ae;K[157]=Ae;K[158]=Ae;K[159]=B5;for(let r=160;r<=183;r++)K[r]=O5;K[184]=M5;K[185]=U5;K[186]=F5;K[187]=$5;K[188]=Ae;K[189]=Ae;K[190]=Ae;K[191]=V5;for(let r=192;r<=215;r++)K[r]=K5;K[216]=H5;K[217]=q5;K[218]=W5;K[219]=z5;K[220]=Ae;K[221]=Ae;K[222]=Ae;K[223]=Ae;for(let r=224;r<=243;r++)K[r]=p1("simple values are not supported");K[244]=Ae;K[245]=Ae;K[246]=Ae;K[247]=G5;K[248]=p1("simple values are not supported");K[249]=Y5;K[250]=X5;K[251]=j5;K[252]=Ae;K[253]=Ae;K[254]=Ae;K[255]=Q5;var Jr=[];for(let r=0;r<24;r++)Jr[r]=new U(E.uint,r,1);for(let r=-1;r>=-24;r--)Jr[31-r]=new U(E.negint,r,1);Jr[64]=new U(E.bytes,new Uint8Array(0),1);Jr[96]=new U(E.string,"",1);Jr[128]=new U(E.array,0,1);Jr[160]=new U(E.map,0,1);Jr[244]=new U(E.false,!1,1);Jr[245]=new U(E.true,!0,1);Jr[246]=new U(E.null,null,1);function rg(r){switch(r.type){case E.false:return In([244]);case E.true:return In([245]);case E.null:return In([246]);case E.bytes:return r.value.length?void 0:In([64]);case E.string:return r.value===""?In([96]):void 0;case E.array:return r.value===0?In([128]):void 0;case E.map:return r.value===0?In([160]):void 0;case E.uint:return r.value<24?In([Number(r.value)]):void 0;case E.negint:if(r.value>=-24)return In([31-Number(r.value)])}}var LA={float64:!1,mapSorter:BA,quickEncodeToken:rg};function DA(){let r=[];return r[E.uint.major]=Rr,r[E.negint.major]=c1,r[E.bytes.major]=gs,r[E.string.major]=C5,r[E.array.major]=u1,r[E.map.major]=d1,r[E.tag.major]=f1,r[E.float.major]=h1,r}var ng=DA(),Q2=new ac,g1=class r{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${Xn} object contains circular references`);return new r(t,e)}},Co={null:new U(E.null,null),undefined:new U(E.undefined,void 0),true:new U(E.true,!0),false:new U(E.false,!1),emptyArray:new U(E.array,0),emptyMap:new U(E.map,0)},Po={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new U(E.float,r):r>=0?new U(E.uint,r):new U(E.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new U(E.uint,r):new U(E.negint,r)},Uint8Array(r,e,t,n){return new U(E.bytes,r)},string(r,e,t,n){return new U(E.string,r)},boolean(r,e,t,n){return r?Co.true:Co.false},null(r,e,t,n){return Co.null},undefined(r,e,t,n){return Co.undefined},ArrayBuffer(r,e,t,n){return new U(E.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new U(E.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[Co.emptyArray,new U(E.break)]:Co.emptyArray;n=g1.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=m1(s,t,n);return t.addBreakTokens?[new U(E.array,r.length),o,new U(E.break)]:[new U(E.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",i=o?r.keys():Object.keys(r),s=o?r.size:i.length;if(!s)return t.addBreakTokens===!0?[Co.emptyMap,new U(E.break)]:Co.emptyMap;n=g1.createCheck(n,r);let a=[],c=0;for(let l of i)a[c++]=[m1(l,t,n),m1(o?r.get(l):r[l],t,n)];return NA(a,t),t.addBreakTokens?[new U(E.map,s),a,new U(E.break)]:[new U(E.map,s),a]}};Po.Map=Po.Object;Po.Buffer=Po.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Po[`${r}Array`]=Po.DataView;function m1(r,e={},t){let n=r5(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||Po[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=Po[n];if(!i)throw new Error(`${Xn} unsupported type: ${n}`);return i(r,n,e,t)}function NA(r,e){e.mapSorter&&r.sort(e.mapSorter)}function BA(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let o=t.type.major,i=ng[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function og(r,e,t,n){if(Array.isArray(e))for(let o of e)og(r,o,t,n);else t[e.type.major](r,e,n)}function Y2(r,e,t){let n=m1(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let o=t.quickEncodeToken(n);if(o)return o;let i=e[n.type.major];if(i.encodedSize){let s=i.encodedSize(n,t),a=new ac(s);if(i(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return sc(a.chunks[0])}}return Q2.reset(),og(Q2,n,e,t),Q2.toBytes(!0)}function Ro(r,e){return e=Object.assign({},LA,e),Y2(r,ng,e)}var OA={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},y1=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],t=Jr[e];if(t===void 0){let n=K[e];if(!n)throw new Error(`${j} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;t=n(this.data,this._pos,o,this.options)}return this._pos+=t.encodedLength,t}},dc=Symbol.for("DONE"),w1=Symbol.for("BREAK");function MA(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=bs(e,t);if(i===w1){if(r.value===1/0)break;throw new Error(`${j} got unexpected break to lengthed array`)}if(i===dc)throw new Error(`${j} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function UA(r,e,t){let n=t.useMaps===!0,o=n?void 0:{},i=n?new Map:void 0;for(let s=0;s<r.value;s++){let a=bs(e,t);if(a===w1){if(r.value===1/0)break;throw new Error(`${j} got unexpected break to lengthed map`)}if(a===dc)throw new Error(`${j} found map but not enough entries (got ${s} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${j} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&i.has(a)||!n&&a in o))throw new Error(`${j} found repeat map key "${a}"`);let c=bs(e,t);if(c===dc)throw new Error(`${j} found map but not enough entries (got ${s} [no value], expected ${r.value})`);n?i.set(a,c):o[a]=c}return n?i:o}function bs(r,e){if(r.done())return dc;let t=r.next();if(t.type===E.break)return w1;if(t.type.terminal)return t.value;if(t.type===E.array)return MA(t,r,e);if(t.type===E.map)return UA(t,r,e);if(t.type===E.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=bs(r,e);return e.tags[t.value](n)}throw new Error(`${j} tag not supported (${t.value})`)}throw new Error("unsupported")}function X2(r,e){if(!(r instanceof Uint8Array))throw new Error(`${j} data to decode must be a Uint8Array`);e=Object.assign({},OA,e);let t=e.tokenizer||new y1(r,e),n=bs(t,e);if(n===dc)throw new Error(`${j} did not find any content to decode`);if(n===w1)throw new Error(`${j} got unexpected break`);return[n,r.subarray(t.pos())]}function Er(r,e){let[t,n]=X2(r,e);if(n.length>0)throw new Error(`${j} too many terminals, data makes no sense`);return t}var Zn="/",ig=new TextEncoder().encode(Zn),b1=ig[0],De=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=M(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]!==b1)throw new Error("Invalid key")}toString(e="utf8"){return V(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Zn))}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=ig),this._buf[0]!==b1){let e=new Uint8Array(this._buf.byteLength+1);e.fill(b1,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===b1;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let i=t[o],s=n[o];if(i<s)return!0;if(i>s)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(Zn).slice(1)}type(){return FA(this.baseNamespace())}name(){return $A(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Zn)||(e+=Zn),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Zn):new r(e.slice(0,-1).join(Zn))}child(e){return this.toString()===Zn?e:e.toString()===Zn?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(),...VA(e.map(t=>t.namespaces()))])}};function FA(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function $A(r){let e=r.split(":");return e[e.length-1]}function VA(r){return[].concat(...r)}function x1({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*KA(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t],i=X.asCID(n);i!=null?yield[o.join("/"),i]:typeof n=="object"&&(yield*Z2(n,o))}else{let t=X.asCID(e);t!=null?yield[r.join("/"),t]:yield*Z2(e,r)}}function*Z2(r,e){if(r==null||r instanceof Uint8Array)return;let t=X.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,o]of Object.entries(r)){let i=[...e,n];yield*KA(i,o)}}function*HA(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t];yield o.join("/"),typeof n=="object"&&X.asCID(n)==null&&(yield*J2(n,o))}else yield*J2(e,r)}function*J2(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let o=[...e,t];yield o.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&X.asCID(n)==null&&(yield*HA(o,n))}}function qA(r,e){let t=r;for(let[n,o]of e.entries()){if(t=t[o],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let i=X.asCID(t);if(i!=null)return{value:i,remaining:e.slice(n+1).join("/")}}return{value:t}}var ep=class{cid;bytes;value;asBlock;constructor({cid:e,bytes:t,value:n}){if(e==null||t==null||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=t,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:x1(),bytes:x1(),value:x1(),asBlock:x1()})}links(){return Z2(this.value,[])}tree(){return J2(this.value,[])}get(e="/"){return qA(this.value,e.split("/").filter(Boolean))}};function sg({bytes:r,cid:e,value:t,codec:n}){let o=t!==void 0?t:n?.decode(r);if(o===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new ep({cid:e,bytes:r,value:o})}var lg="/pin/",ag="/pinned-block/",tp=mn,cg=1;function E1(r){return r.version===0&&(r=r.toV1()),new De(`${lg}${r.toString(tp)}`)}var v1=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=E1(e);if(await this.datastore.has(n))throw new Error("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new Error("Depth must be greater than or equal to 0");let i=new Mt({concurrency:cg});for await(let a of this.#e(e,i,{...t,depth:o}))await this.#t(a,c=>c.pinnedBy.find(l=>te(l,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),t),yield a;let s={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,Ro(s),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=await this.getCodec(e.code),i=await this.blockstore.get(e,n),s=sg({bytes:i,cid:e,codec:o});yield e;for await(let[,a]of s.links())yield*await t.add(async()=>this.#e(a,t,{...n,depth:n.depth-1}))}async#t(e,t,n){let o=new De(`${ag}${tp.encode(e.multihash.bytes)}`),i={pinCount:0,pinnedBy:[]};try{i=Er(await this.datastore.get(o,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(i)){if(i.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,Ro(i),n),n.onProgress?.(new H("helia:pin:add",e))}}async*rm(e,t={}){let n=E1(e),o=await this.datastore.get(n,t),i=Er(o);await this.datastore.delete(n,t);let s=new Mt({concurrency:cg});for await(let a of this.#e(e,s,{...t,depth:i.depth}))await this.#t(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>te(l,e.bytes)),!0),{...t,depth:i.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:lg+(e.cid!=null?`${e.cid.toString(mn)}`:"")},e)){let o=X.parse(t.toString().substring(5),mn),i=Er(n);yield{cid:o,...i}}}async isPinned(e,t={}){let n=new De(`${ag}${tp.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=E1(e),o=await this.datastore.get(n,t);return Er(o)}async setMetadata(e,t,n){let o=E1(e),i=await this.datastore.get(o,n),s=Er(i);s.metadata=t??{},await this.datastore.put(o,Ro(s),n)}};var rp=1,np=5;var fc=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},Lo=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},hc=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},pc=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}};var WA=5,S1=class{log;routers;providerLookupConcurrency;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??WA}async start(){await wt(...this.routers)}async stop(){await Tt(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new Lo("No content routers available");let n=new Ut({concurrency:this.providerLookupConcurrency});n.addEventListener("error",()=>{});for await(let o of $t(n.toGenerator(),...xs(this.routers,"findProviders").map(i=>i.findProviders(e,t))))if(o!=null){if(o.multiaddrs.length===0){if(n.find(o.id)!=null)continue;n.add(async()=>{try{let i=await this.findPeer(o.id,t);return i.multiaddrs.length===0?null:i}catch(i){return this.log.error("could not load multiaddrs for peer %p",o.id,i),null}},{peerId:o.id,signal:t.signal}).catch(i=>{this.log.error("could not load multiaddrs for peer %p",o.id,i)})}yield o}}async provide(e,t={}){if(this.routers.length===0)throw new Lo("No content routers available");await Promise.all(xs(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async put(e,t,n){await Promise.all(xs(this.routers,"put").map(async o=>{await o.put(e,t,n)}))}async get(e,t){return Promise.any(xs(this.routers,"get").map(async n=>n.get(e,t)))}async findPeer(e,t){if(this.routers.length===0)throw new Lo("No peer routers available");let n=this,o=$t(...xs(this.routers,"findPeer").map(i=>async function*(){try{yield await i.findPeer(e,t)}catch(s){n.log.error(s)}}()));for await(let i of o)if(i!=null)return i;throw new Oe("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Lo("No peer routers available");for await(let n of $t(...xs(this.routers,"getClosestPeers").map(o=>o.getClosestPeers(e,t))))n!=null&&(yield n)}};function xs(r,e){return r.filter(t=>t[e]!=null)}var Do={},Es=r=>{r.addEventListener("message",e=>{Es.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{Es.dispatchEvent("message",r,e)})};Es.addEventListener=(r,e)=>{Do[r]==null&&(Do[r]=[]),Do[r].push(e)};Es.removeEventListener=(r,e)=>{Do[r]!=null&&(Do[r]=Do[r].filter(t=>t===e))};Es.dispatchEvent=function(r,e,t){Do[r]!=null&&Do[r].forEach(n=>n(e,t))};var op=Es;var ip="lock:worker:request-read",sp="lock:worker:release-read",ap="lock:master:grant-read",cp="lock:worker:request-write",lp="lock:worker:release-write",up="lock:master:grant-write";var ug=(r=21)=>Math.random().toString().substring(2);var dg=(r,e,t,n,o)=>(i,s)=>{if(s.data.type!==t)return;let a={type:s.data.type,name:s.data.name,identifier:s.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{i.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let l=d=>{if(d?.data==null)return;let u={type:d.data.type,name:d.data.name,identifier:d.data.identifier};u.type===n&&u.identifier===a.identifier&&(i.removeEventListener("message",l),c())};i.addEventListener("message",l)})}}}))},fg=(r,e,t,n)=>async()=>{let o=ug();return globalThis.postMessage({type:e,identifier:o,name:r}),new Promise(i=>{let s=a=>{if(a?.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===o&&(globalThis.removeEventListener("message",s),i(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",s)})},zA={singleProcess:!1},hg=r=>{if(r=Object.assign({},zA,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return op.addEventListener("message",dg(t,"requestReadLock",ip,sp,ap)),op.addEventListener("message",dg(t,"requestWriteLock",cp,lp,up)),t}return{isWorker:!0,readLock:t=>fg(t,ip,ap,sp),writeLock:t=>fg(t,cp,up,lp)}};var yi={},No;async function dp(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>jr((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var GA=(r,e)=>{if(No.isWorker===!0)return{readLock:No.readLock(r,e),writeLock:No.writeLock(r,e)};let t=new An({concurrency:1}),n;return{async readLock(){if(n!=null)return dp(n,e);n=new An({concurrency:e.concurrency,autoStart:!1});let o=n,i=dp(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),i},async writeLock(){return n=null,dp(t,e)}}},QA={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function wi(r){let e=Object.assign({},QA,r);return No==null&&(No=hg(e),No.isWorker!==!0&&(No.addEventListener("requestReadLock",t=>{yi[t.data.name]!=null&&yi[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),No.addEventListener("requestWriteLock",async t=>{yi[t.data.name]!=null&&yi[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),yi[e.name]==null&&(yi[e.name]=GA(e.name,e)),yi[e.name]}var A1=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=wi({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await wt(this.child),this.started=!0}async stop(){await Tt(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{o()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new Error("CID was pinned");await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let o=this;yield*this.child.deleteMany(async function*(){for await(let i of e){if(await o.pins.isPinned(i))throw new Error("CID was pinned");yield i}}(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var fp=new De("/version"),pg=1;async function mg(r){if(!await r.has(fp)){await r.put(fp,M(`${pg}`));return}let e=await r.get(fp),t=V(e);if(parseInt(t,10)!==pg)throw new Error("Unknown datastore version, a datastore migration may be required")}var mp={};Xe(mp,{code:()=>pp,decode:()=>nI,decodeOptions:()=>eI,encode:()=>rI,encodeOptions:()=>ZA,name:()=>tI,toByteView:()=>yg});var gg=42;function yg(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function YA(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=X.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new U(E.tag,gg),new U(E.bytes,t)]}function XA(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function jA(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var hp={float64:!0,typeEncoders:{Object:YA,undefined:XA,number:jA}},ZA={...hp,typeEncoders:{...hp.typeEncoders}};function JA(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return X.decode(r.subarray(1))}var I1={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};I1.tags[gg]=JA;var eI={...I1,tags:I1.tags.slice()},tI="dag-cbor",pp=113,rI=r=>Ro(r,hp),nI=r=>Er(yg(r),I1);var vp={};Xe(vp,{code:()=>Ep,decode:()=>bg,encode:()=>wg,format:()=>pI,name:()=>hI,parse:()=>gI,stringify:()=>pI});var gp=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===E.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===E.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[E.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i);e.push(o)}[E.negint.major](e,t){this[E.uint.major](e,t)}[E.bytes.major](e,t){throw new Error(`${Xn} unsupported type: Uint8Array`)}[E.string.major](e,t){this.prefix(e);let n=a1(JSON.stringify(t.value));e.push(n.length>32?sc(n):n)}[E.array.major](e,t){this.prefix(e),this.inRecursive.push({type:E.array,elements:0}),e.push([91])}[E.map.major](e,t){this.prefix(e),this.inRecursive.push({type:E.map,elements:0}),e.push([123])}[E.tag.major](e,t){}[E.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===E.array)e.push([93]);else if(s.type===E.map)e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(t.value===void 0)throw new Error(`${Xn} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),o=[],i=!1;for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s),!i&&(o[s]===46||o[s]===101||o[s]===69)&&(i=!0);i||(o.push(46),o.push(48)),e.push(o)}};function oI(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${Xn} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==E.string||n.type!==E.string)throw new Error(`${Xn} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${Xn} unexpected duplicate map keys, this is not supported`)}var iI={addBreakTokens:!0,mapSorter:oI};function yp(r,e){return e=Object.assign({},iI,e),Y2(r,new gp,e)}var vs=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos<e.length)throw new Error(`${j} unexpected end of input at position ${this._pos}`);for(let t=0;t<e.length;t++)if(this.data[this._pos++]!==e[t])throw new Error(`${j} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,o=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new U(E.uint,0,this._pos-e);if(o([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${j} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${j} unexpected token at position ${this._pos}`);n=!0,this._pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,o([48,49,50,51,52,53,54,55,56,57]));let i=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),s=parseFloat(i);return n?new U(E.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new U(s>=0?E.uint:E.negint,s,this._pos-e):new U(s>=0?E.uint:E.negint,BigInt(i),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${j} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let i=this._pos,s=0;i<this.data.length&&s<65536;i++,s++){let a=this.data[i];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,i));return this._pos=i+1,new U(E.string,c,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${j} unexpected end of unicode escape sequence at position ${this._pos}`);let i=0;for(let s=0;s<4;s++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${j} unexpected unicode escape character at position ${this._pos}`);i=i*16+a,this._pos++}return i},o=()=>{let i=this.ch(),s=null,a=i>239?4:i>223?3:i>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${j} unexpected unicode sequence at position ${this._pos}`);let c,l,d,u;switch(a){case 1:i<128&&(s=i);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(u=(i&31)<<6|c&63,u>127&&(s=u));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(u=(i&15)<<12|(c&63)<<6|l&63,u>2047&&(u<55296||u>57343)&&(s=u));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],d=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(d&192)===128&&(u=(i&15)<<18|(c&63)<<12|(l&63)<<6|d&63,u>65535&&u<1114112&&(s=u))}s===null?(s=65533,a=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.push(s),this._pos+=a};for(;!this.done();){let i=this.ch(),s;switch(i){case 92:if(this._pos++,this.done())throw new Error(`${j} unexpected string termination at position ${this._pos}`);switch(s=this.ch(),this._pos++,s){case 34:case 39:case 92:case 47:t.push(s);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${j} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new U(E.string,H2(t),this._pos-e);default:if(i<32)throw new Error(`${j} invalid control character at position ${this._pos}`);i<128?(t.push(i),this._pos++):o()}}throw new Error(`${j} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new U(E.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new U(E.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new U(E.null,null,4);case 102:return this.expect([102,97,108,115,101]),new U(E.false,!1,5);case 116:return this.expect([116,114,117,101]),new U(E.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${j} unexpected character at position ${this._pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this._pos++,this.skipWhitespace(),new U(E.break,void 0,1);if(this.ch()!==44)throw new Error(`${j} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this._pos++,this.skipWhitespace(),new U(E.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new U(E.break,void 0,1);if(this.ch()!==44)throw new Error(`${j} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this._pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this._pos++,this.skipWhitespace(),new U(E.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${j} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${j} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function wp(r,e){return e=Object.assign({tokenizer:new vs(r,e)},e),Er(r,e)}function aI(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function cI(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=X.asCID(r);if(!e)return null;let t=e.toString();return[new U(E.map,1/0,1),new U(E.string,"/",1),new U(E.string,t,t.length),new U(E.break,void 0,1)]}function _1(r){let e=it.encode(r).slice(1);return[new U(E.map,1/0,1),new U(E.string,"/",1),new U(E.map,1/0,1),new U(E.string,"bytes",5),new U(E.string,e,e.length),new U(E.break,void 0,1),new U(E.break,void 0,1)]}function en(r){return _1(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function lI(r){return _1(new Uint8Array(r))}function uI(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function dI(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var fI={typeEncoders:{Object:cI,Buffer:_1,Uint8Array:_1,Int8Array:en,Uint16Array:en,Int16Array:en,Uint32Array:en,Int32Array:en,Float32Array:en,Float64Array:en,Uint8ClampedArray:en,BigInt64Array:en,BigUint64Array:en,DataView:en,ArrayBuffer:lI,undefined:uI,number:dI}},bp=class extends vs{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===E.map){let t=this._next();if(t.type===E.string&&t.value==="/"){let n=this._next();if(n.type===E.string){if(this._next().type!==E.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new U(E.tag,42,0)}if(n.type===E.map){let o=this._next();if(o.type===E.string&&o.value==="bytes"){let i=this._next();if(i.type===E.string){for(let a=0;a<2;a++)if(this._next().type!==E.break)throw new Error("Invalid encoded Bytes form");let s=it.decode(`m${i.value}`);return new U(E.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},xp={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};xp.tags[42]=X.parse;var hI="dag-json",Ep=297,wg=r=>yp(r,fI),bg=r=>{let e=aI(r),t=Object.assign(xp,{tokenizer:new bp(e,xp)});return wp(e,t)},pI=r=>mI.decode(wg(r));var mI=new TextDecoder,gI=r=>bg(yI.encode(r)),yI=new TextEncoder;var kp={};Xe(kp,{code:()=>Tp,createLink:()=>Cg,createNode:()=>kg,decode:()=>PI,encode:()=>CI,name:()=>kI,prepare:()=>Ip,validate:()=>_p});var wI=new TextDecoder;function Sp(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let o=r[e++];if(t+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[t,e]}function T1(r,e){let t;[t,e]=Sp(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function xg(r,e){let t;return[t,e]=Sp(r,e),[t&7,t>>3,e]}function bI(r){let e={},t=r.length,n=0;for(;n<t;){let o,i;if([o,i,n]=xg(r,n),i===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=T1(r,n)}else if(i===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=T1(r,n),e.Name=wI.decode(s)}else if(i===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=Sp(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${i}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function Eg(r){let e=r.length,t=0,n,o=!1,i;for(;t<e;){let a,c;if([a,c,t]=xg(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(i)throw new Error("protobuf: (PBNode) duplicate Data section");[i,t]=T1(r,t),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=T1(r,t),n.push(bI(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return i&&(s.Data=i),s.Links=n||[],s}var Sg=new TextEncoder,vg=2**32,xI=2**31;function EI(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=mc(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=Sg.encode(r.Name);t-=n.length,e.set(n,t),t=mc(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=mc(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function Ag(r){let e=SI(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=mc(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let i=EI(r.Links[o],t.subarray(0,n));n-=i,n=mc(t,n,i)-1,t[n]=18}return t}function vI(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+Ss(t)}if(typeof r.Name=="string"){let t=Sg.encode(r.Name).length;e+=1+t+Ss(t)}return typeof r.Tsize=="number"&&(e+=1+Ss(r.Tsize)),e}function SI(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+Ss(t)}if(r.Links)for(let t of r.Links){let n=vI(t);e+=1+n+Ss(n)}return e}function mc(r,e,t){e-=Ss(t);let n=e;for(;t>=xI;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function Ss(r){return r%2===0&&r++,Math.floor((AI(r)+6)/7)}function AI(r){let e=0;return r>=vg&&(r=Math.floor(r/vg),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+II[r]}var II=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var _I=["Data","Links"],TI=["Hash","Name","Tsize"],Ap=new TextEncoder;function _g(r,e){if(r===e)return 0;let t=r.Name?Ap.encode(r.Name):[],n=e.Name?Ap.encode(e.Name):[],o=t.length,i=n.length;for(let s=0,a=Math.min(o,i);s<a;++s)if(t[s]!==n[s]){o=t[s],i=n[s];break}return o<i?-1:i<o?1:0}function Ig(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function Tg(r){if(typeof r.asCID=="object"){let t=X.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=X.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=X.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=X.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function Ip(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=Ap.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(Tg),e.Links.sort(_g);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function _p(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!Ig(r,_I))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<r.Links.length;e++){let t=r.Links[e];if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!Ig(t,TI))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(t.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(t.Hash==null||!t.Hash["/"]||t.Hash["/"]!==t.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(t.Name!==void 0&&typeof t.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(t.Tsize!==void 0){if(typeof t.Tsize!="number"||t.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(t.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&_g(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function kg(r,e=[]){return Ip({Data:r,Links:e})}function Cg(r,e,t){return Tg({Hash:t,Name:r,Tsize:e})}function Pg(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var kI="dag-pb",Tp=112;function CI(r){_p(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),Ag(e)}function PI(r){let e=Pg(r),t=Eg(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let i={};try{i.Hash=X.decode(o.Hash)}catch{}if(!i.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(i.Name=o.Name),o.Tsize!==void 0&&(i.Tsize=o.Tsize),i})),n}function As(r){return r?.then!=null}function Rg(r=[],e){let t={[Tp]:kp,[Jo]:Gi,[pp]:mp,[Ep]:vp,[T0]:Rl};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);As(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new pc(`Could not load codec for ${n}`)}}function Lg(r=[],e){let t={[ut.code]:ut,[Dl.code]:Dl,[Jt.code]:Jt};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);As(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new hc(`No hasher configured for multihash code 0x${n.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`)}}var Dr=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};var Jn=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,block:o}of e)await this.put(n,o,t),yield n}get(e,t){return Promise.reject(new Error(".get is not implemented"))}async*getMany(e,t){for await(let n of e)yield{cid:n,block:await this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var k1=0,C1=class extends Jn{child;constructor(e){super(),this.child=e}put(e,t){return e.multihash.code===k1||this.child==null?e:this.child.put(e,t)}get(e){if(e.multihash.code===k1)return e.multihash.digest;if(this.child==null)throw new Dr;return this.child.get(e)}has(e){return e.multihash.code===k1?!0:this.child==null?!1:this.child.has(e)}delete(e){if(e.code!==k1&&this.child!=null)return this.child.delete(e)}getAll(e){return this.child!=null?this.child.getAll(e):[]}};function RI(r){return r[Symbol.asyncIterator]!=null}function LI(r,e){let t=0;if(RI(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=Wi(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();let s=e(o,t++);if(typeof s.then=="function")return async function*(){await s&&(yield o);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){s===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)}()}var tn=LI;function DI(r){return r[Symbol.asyncIterator]!=null}function Dg(r){return r?.then!=null}function NI(r,e){let t=0;if(DI(r))return async function*(){for await(let c of r){let l=e(c,t++);Dg(l)&&await l,yield c}}();let n=Wi(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();if(typeof e(o,t++)?.then=="function")return async function*(){yield o;for await(let c of n){let l=e(c,t++);Dg(l)&&await l,yield c}}();let a=e;return function*(){yield o;for(let c of n)a(c,t++),yield c}()}var bi=NI;var P1=class{child;getHasher;log;logger;components;constructor(e){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.components=e,this.child=new C1(e.blockstore),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new H("blocks:put:duplicate",e)),e):(n.onProgress?.(new H("blocks:put:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,t,n))),n.onProgress?.(new H("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=tn(e,async({cid:i})=>{let s=await this.child.has(i,t);return s&&t.onProgress?.(new H("blocks:put-many:duplicate",i)),!s}),o=bi(n,async({cid:i,block:s})=>{t.onProgress?.(new H("blocks:put-many:providers:notify",i)),await Promise.all(this.components.blockBrokers.map(async a=>a.announce?.(i,s,t)))});t.onProgress?.(new H("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async get(e,t={}){if(t.offline!==!0&&!await this.child.has(e,t)){let n=await this.getHasher(e.multihash.code);t.onProgress?.(new H("blocks:get:providers:get",e));let o=await Ng(e,this.components.blockBrokers,n,{...t,log:this.log});return t.onProgress?.(new H("blocks:get:blockstore:put",e)),await this.child.put(e,o,t),t.onProgress?.(new H("blocks:get:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async i=>i.announce?.(e,o,t))),o}return t.onProgress?.(new H("blocks:get:blockstore:get",e)),this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new H("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(bi(e,async n=>{if(t.offline!==!0&&!await this.child.has(n,t)){let o=await this.getHasher(n.multihash.code);t.onProgress?.(new H("blocks:get-many:providers:get",n));let i=await Ng(n,this.components.blockBrokers,o,{...t,log:this.log});t.onProgress?.(new H("blocks:get-many:blockstore:put",n)),await this.child.put(n,i,t),t.onProgress?.(new H("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(n,i,t)))}}))}async delete(e,t={}){t.onProgress?.(new H("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new H("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany(async function*(){for await(let n of e)yield n}(),t)}async has(e,t={}){return this.child.has(e,t)}async*getAll(e={}){e.onProgress?.(new H("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}},R1=class extends P1{started;constructor(e){super(e),this.started=!1}isStarted(){return this.started}async start(){await wt(this.child,...this.components.blockBrokers),this.started=!0}async stop(){await Tt(this.child,...this.components.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){let n=this.components.blockBrokers.map(o=>o.createSession==null?o:o.createSession(t));return new Cp({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}},Cp=class extends P1{closeController;constructor(e,t){super(e),this.closeController=new AbortController,$(1/0,this.closeController.signal),this.log=e.logger.forComponent(`helia:session-storage:${t.root}`)}close(){this.closeController.abort()}async put(e,t,n={}){let o=he([this.closeController.signal,n.signal]);$(1/0,o);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=he([this.closeController.signal,t.signal]);$(1/0,n);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async get(e,t={}){let n=he([this.closeController.signal,t.signal]);$(1/0,n);try{return await super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=he([this.closeController.signal,t.signal]);$(1/0,n);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=he([this.closeController.signal,t.signal]);$(1/0,n);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=he([this.closeController.signal,t.signal]);$(1/0,n);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=he([this.closeController.signal,t.signal]);$(1/0,n);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=he([this.closeController.signal,e.signal]);$(1/0,t);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};function BI(r){return typeof r.retrieve=="function"}var OI=(r,e)=>{if(e==null)throw new C(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`);return async t=>{let n,o=e.digest(t);if(As(o)?n=await o:n=o,!te(n.digest,r.multihash.digest))throw new co("Hash of downloaded block did not match multihash from passed CID")}};async function Ng(r,e,t,n){let o=OI(r,t),i=new AbortController,s=he([i.signal,n.signal]);$(1/0,i.signal,s);let a=[];for(let c of e)BI(c)&&a.push(c);try{return await Promise.any(a.map(async c=>{try{let l=!1,d=await c.retrieve(r,{...n,signal:s,validateFn:async u=>{await o(u),l=!0}});return l||await o(d),d}catch(l){throw n.log.error("could not retrieve verified block for %c",r,l),l}}))}finally{i.abort(),s.clear()}}var xi=class extends ge{intialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;constructor(e,t){super(),$(1/0,this),this.name=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.name),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.providers=[],this.evictionFilter=Sn(this.maxProviders)}async retrieve(e,t={}){let n=it.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o;let i=J();if(this.requests.set(n,i.promise),this.providers.length===0){let l=!1;this.intialPeerSearchComplete==null&&(l=!0,this.log=this.logger.forComponent(`${this.name}:${e}`),this.intialPeerSearchComplete=this.findProviders(e,this.minProviders,t)),await this.intialPeerSearchComplete,l&&this.log("found initial session peers for %c",e)}let s=!1,a=new Mt({concurrency:this.maxProviders});a.addEventListener("error",()=>{}),a.addEventListener("failure",l=>{this.log.error("error querying provider %o, evicting from session",l.detail.job.options.provider,l.detail.error),this.evict(l.detail.job.options.provider)}),a.addEventListener("success",l=>{s=!0,i.resolve(l.detail.result)}),a.addEventListener("idle",()=>{s||t.signal?.aborted===!0||Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let l=0;l<this.minProviders&&this.providers.length!==0;l++){let d=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(d)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),i.resolve(await this.retrieve(e,t))}).catch(l=>{this.log.error("could not find new providers for %c",e,l),i.reject(l)})});let c=l=>{a.add(async()=>this.queryProvider(e,l.detail,t),{provider:l.detail}).catch(d=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,d)})};this.addEventListener("provider",c),Promise.all([...this.providers].map(async l=>a.add(async()=>this.queryProvider(e,l,t),{provider:l}))).catch(l=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,l)});try{return await i.promise}finally{this.removeEventListener("provider",c),a.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toEvictionKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toEvictionKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async findProviders(e,t,n){let o=J(),i=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c",t,this.maxProviders,e);for await(let s of this.findNewProviders(e,n)){if(i===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(s)&&(this.log("found %d/%d new providers",i,this.maxProviders),this.providers.push(s),this.safeDispatchEvent("provider",{detail:s}),i++,i===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",i);break}}if(this.log("found %d/%d new session peers",i,this.maxProviders),i<t)throw new fc(`Found ${i} of ${t} ${this.name} providers for ${e}`)}).catch(s=>{this.log.error("error searching routing for potential session peers for %c",e,s.errors??s),o.reject(s)}),o.promise}};var L1=class{blockstore;datastore;pins;logger;routing;getCodec;getHasher;dns;metrics;log;constructor(e){this.logger=e.logger??ko(),this.log=this.logger.forComponent("helia"),this.getHasher=Lg(e.hashers,e.loadHasher),this.getCodec=Rg(e.codecs,e.loadCodec),this.dns=e.dns??i1(),this.metrics=e.metrics;let t={blockstore:e.blockstore,datastore:e.datastore,logger:this.logger,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,dns:this.dns,metrics:this.metrics,...e.components??{}};this.routing=t.routing=new S1(t,{routers:(e.routers??[]).flatMap(o=>{let i=[o];return o[ln]!=null&&i.push(o[ln]),o[un]!=null&&i.push(o[un]),i}),providerLookupConcurrency:e.providerLookupConcurrency});let n=new R1(t);this.pins=new v1(e.datastore,n,this.getCodec),this.blockstore=new A1(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,t.blockBrokers=e.blockBrokers.map(o=>o(t))}async start(){await mg(this.datastore),await wt(this.blockstore,this.datastore,this.routing)}async stop(){await Tt(this.blockstore,this.datastore,this.routing)}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,o=this.blockstore.unwrap();this.log("gc start"),await Ct(o.deleteMany(async function*(){for await(let{cid:i}of o.getAll())try{if(await n.pins.isPinned(i,e))continue;yield i,e.onProgress?.(new H("helia:gc:deleted",i))}catch(s){n.log.error("Error during gc",s),e.onProgress?.(new H("helia:gc:error",s))}}()))}finally{t()}this.log("gc finished")}};var Pp=class extends xi{wantList;network;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network}async queryProvider(e,t,n){this.log("sending WANT-BLOCK for %c to %p",e,t);let o=await this.wantList.wantSessionBlock(e,t,n);if(this.log("%p %s %c",t,o.has?"has":"does not have",e),o.has&&o.block!=null)return o.block;throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield n.id}toEvictionKey(e){return e.toMultihash().bytes}equals(e,t){return e.equals(t)}};function Bg(r,e){return new Pp(r,e)}var D1=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=e.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};var Rp=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 N1(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Rp({name:e,metrics:t}):n=new Map,n}function MI(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=Ft(r);e.push(t),r=r.slice(pe(t))}return e}var Og=MI;var B1=class extends ge{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(e,t={}){super(),$(1/0,this),this.peers=rc({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=N1({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendMessagesDelay=t.sendMessagesDelay??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=t.hashLoader,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,o)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(o=>{this.log.error("error processing newly connected bitswap peer %p",n.detail,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=V(e.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:e,priority:t.priority??1,wantType:t.wantType??et.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,o)),o.wantType===et.WantHave&&t.wantType===et.WantBlock&&(o.wantType=et.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===et.WantBlock?(await hr(this,"block",t?.signal,{filter:a=>te(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await hr(this,"presence",t?.signal,{filter:s=>te(e.multihash.digest,s.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),o.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers",e)})},this.sendMessagesDelay)}async sendMessages(){this.sendingMessages=J(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,o=new Yn;for(let[i,s]of this.wants.entries())t.has(i)||s.cancel||(n.add(i),o.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:s.priority,wantType:s.wantType,cancel:s.cancel,sendDontHave:s.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(e,o);for(let i of n)t.add(i)}catch(i){this.log.error("error sending full wantlist to new peer",i)}})).catch(e=>{this.log.error("error sending messages",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=V(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let o=new Yn;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:et.WantHave,priority:1}),await this.network.sendMessage(t,o),(await hr(this,"presence",n.signal,{filter:s=>t.equals(s.detail.sender)&&te(e.multihash.digest,s.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:et.WantBlock})}async wantSessionBlock(e,t,n={}){let o=new Yn;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:et.WantBlock,priority:1}),await this.network.sendMessage(t,o),(await hr(this,"presence",n.signal,{filter:s=>t.equals(s.detail.sender)&&te(e.multihash.digest,s.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=V(e.multihash.bytes,"base64"),o=this.wants.get(n);o!=null&&(o.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e,t.blocks.length);let n=!1;for(let o of t.blocks){if(o.prefix==null||o.data==null)continue;let i=Og(o.prefix),s=i[0],a=i[1],c=i[2],l=c===ut.code?ut:await this.hashLoader?.getHasher(c);if(l==null){this.log.error("unknown hash algorithm",c);continue}let d=l.digest(o.data);d.then!=null&&(d=await d);let u=X.create(s===0?0:1,a,d);this.log("received block from %p for %c",e,u),this.safeDispatchEvent("block",{detail:{sender:e,cid:u,block:o.data}}),this.safeDispatchEvent("presence",{detail:{sender:e,cid:u,has:!0,block:o.data}});let f=V(u.multihash.bytes,"base64"),h=this.wants.get(f);h!=null&&(h.cancel=!0,n=!0)}for(let{cid:o,type:i}of t.blockPresences){let s=X.decode(o);this.log("received %s from %p for %c",i,e,s),this.safeDispatchEvent("presence",{detail:{sender:e,cid:s,has:i===Ir.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new Yn(!0);for(let[o,i]of this.wants.entries())i.cancel||(t.add(o),n.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:1,wantType:et.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n),this.peers.set(e,t)}catch(o){this.log.error("error sending full wantlist to new peer %p",e,o)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var O1=class{log;logger;stats;network;blockstore;peerWantLists;wantList;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.stats=new D1(e),this.network=new $l(e,t),this.peerWantLists=new ju({...e,network:this.network},t),this.wantList=new B1({...e,network:this.network},t)}createSession(e={}){return Bg({wantList:this.wantList,network:this.network,logger:this.logger},e)}async want(e,t={}){let n=new AbortController,o=he([n.signal,t.signal]);$(1/0,n.signal,o),this.network.findAndConnect(e,{...t,signal:o}).catch(i=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c",e,i)});try{return(await this.wantList.wantBlock(e,{...t,signal:o})).block}finally{n.abort(),o.clear()}}async notify(e,t,n={}){await Promise.all([this.peerWantLists.receivedBlock(e,n),this.wantList.receivedBlock(e,n)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var Mg=(r,e={})=>new O1(r,e);var Lp=class{bitswap;started;constructor(e,t={}){let{getHasher:n}=e;this.bitswap=Mg(e,{hashLoader:{getHasher:async o=>n(o)},...t}),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(e,t,n){await this.bitswap.notify(e,t,n)}async retrieve(e,t={}){return this.bitswap.want(e,t)}createSession(e){let t=this.bitswap.createSession(e);return{announce:async(n,o,i)=>{await this.bitswap.notify(n,o,i)},retrieve:async(n,o)=>t.retrieve(n,o)}}};function Dp(r={}){return e=>new Lp(e,r)}var M1=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,o){return this.readAtomically(()=>{let i=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let d=this.readAtomically(()=>{let u=this.readChar();if(u===void 0)return;let f=Number.parseInt(u,e);if(!Number.isNaN(f))return f});if(d===void 0)break;if(i*=e,i+=d,i>l||(s+=1,t!==void 0&&s>t))return}if(s!==0)return!n&&c&&s>1?void 0:i})}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 o=n*2;if(n<t.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return t[o]=s[0],t[o+1]=s[1],t[o+2]=s[2],t[o+3]=s[3],[o+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[o,!1];t[o]=i>>8,t[o+1]=i&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),s=16-(n+2),[a]=e(i.subarray(0,s));return t.set(i.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Ug=45,UI=15,Is=new M1;function Np(r){if(!(r.length>UI))return Is.new(r).parseWith(()=>Is.readIPv4Addr())}function Bp(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ug))return Is.new(r).parseWith(()=>Is.readIPv6Addr())}function U1(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ug))return Is.new(r).parseWith(()=>Is.readIPAddr())}function _s(r){return!!Np(r)}function Ts(r){return!!Bp(r)}function F1(r){return!!U1(r)}var $g=fr(Fg(),1),FI=["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"],$I=FI.map(r=>new $g.Netmask(r));function Op(r){for(let e of $I)if(e.contains(r))return!0;return!1}function VI(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function KI(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"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return Op(o)}function HI(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function qI(r){let e=r.split(":"),t=e[e.length-1];return Op(t)}function WI(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 Bt(r){return _s(r)?Op(r):VI(r)?KI(r):HI(r)?qI(r):Ts(r)?WI(r):void 0}var zI=r=>r.toString().split("/").slice(1),ks=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),me=r=>({match:e=>ks(t=>t===r).match(e),pattern:r}),Cs=()=>({match:r=>ks(e=>typeof e=="string").match(r),pattern:"{string}"}),yc=()=>({match:r=>ks(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),We=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{Se.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),wc=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{S0.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),Le=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),qt=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),be=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function $e(...r){function e(o){let i=zI(o);for(let s of r){let a=s.match(i);if(a===!1)return!1;i=a}return i}function t(o){return e(o)!==!1}function n(o){let i=e(o);return i===!1?!1:i.length===0}return{matchers:r,matches:t,exactMatch:n}}var V1=be(me("dns4"),Cs()),K1=be(me("dns6"),Cs()),H1=be(me("dnsaddr"),Cs()),Up=be(me("dns"),Cs()),zK=$e(V1,Le(We())),GK=$e(K1,Le(We())),QK=$e(H1,Le(We())),bc=$e(qt(Up,H1,V1,K1),Le(We())),Vg=be(me("ip4"),ks(_s)),Kg=be(me("ip6"),ks(Ts)),Fp=qt(Vg,Kg),eo=qt(Fp,Up,V1,K1,H1),Hg=$e(qt(Fp,be(qt(Up,H1,V1,K1),Le(We())))),YK=$e(Vg),XK=$e(Kg),qg=$e(Fp),$p=be(eo,me("tcp"),yc()),xc=be(eo,me("udp"),yc()),Vp=$e(be($p,Le(We()))),jK=$e(xc),Kp=be(xc,me("quic")),q1=be(xc,me("quic-v1")),GI=qt(Kp,q1),ZK=$e(Kp),JK=$e(q1),Mp=qt(eo,$p,xc,Kp,q1),Wg=qt(be(Mp,me("ws"),Le(We()))),Ec=$e(Wg),zg=qt(be(Mp,me("wss"),Le(We())),be(Mp,me("tls"),Le(be(me("sni"),Cs())),me("ws"),Le(We()))),Ps=$e(zg),Gg=be(xc,me("webrtc-direct"),Le(wc()),Le(wc()),Le(We())),vc=$e(Gg),Qg=be(q1,me("webtransport"),Le(wc()),Le(wc()),Le(We())),Ei=$e(Qg),$1=qt(Wg,zg,be($p,Le(We())),be(GI,Le(We())),be(eo,Le(We())),Gg,Qg,We()),Yg=$e($1),QI=be($1,me("p2p-circuit"),We()),ir=$e(QI),YI=qt(be($1,me("p2p-circuit"),me("webrtc"),Le(We())),be($1,me("webrtc"),Le(We())),me("webrtc")),Sc=$e(YI),XI=qt(be(eo,me("tcp"),yc(),me("http"),Le(We())),be(eo,me("http"),Le(We()))),Xg=$e(XI),jI=qt(be(eo,me("tcp"),qt(be(me("443"),me("http")),be(yc(),me("https"))),Le(We())),be(eo,me("tls"),me("http"),Le(We())),be(eo,me("https"),Le(We()))),jg=$e(jI);var aH=parseInt("0xFFFF",16),cH=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var e7=_s,r_=Ts,Hp=function(r){let e=0;if(r=r.toString().trim(),e7(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(r_(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let i=e7(t[n]),s;i&&(s=Hp(t[n]),t[n]=V(s.slice(0,2),"base16")),s!=null&&++n<8&&t.splice(n,0,V(s.slice(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 i=[n,1];for(n=9-t.length;n>0;n--)i.push("0");t.splice.apply(t,i)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let i=parseInt(t[n],16);o[e++]=i>>8&255,o[e++]=i&255}return o}throw new Error("invalid ip address")},t7=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let i=0;i<t;i++)o.push(r[e+i]);return o.join(".")}if(t===16){let o=[];for(let i=0;i<t;i+=2)o.push(n.getUint16(e+i).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Rs={},qp={},o_=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];o_.forEach(r=>{let e=i_(...r);qp[e.code]=e,Rs[e.name]=e});function i_(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function ee(r){if(typeof r=="number"){if(qp[r]!=null)return qp[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Rs[r]!=null)return Rs[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var HH=ee("ip4"),qH=ee("ip6"),WH=ee("ipcidr");function Qp(r,e){switch(ee(r).code){case 4:case 41:return a_(e);case 42:return Gp(e);case 6:case 273:case 33:case 132:return o7(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Gp(e);case 421:return d_(e);case 444:return n7(e);case 445:return n7(e);case 466:return u_(e);case 481:return globalThis.encodeURIComponent(Gp(e));default:return V(e,"base16")}}function Yp(r,e){switch(ee(r).code){case 4:return r7(e);case 41:return r7(e);case 42:return zp(e);case 6:case 273:case 33:case 132:return Xp(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return zp(e);case 421:return c_(e);case 444:return f_(e);case 445:return h_(e);case 466:return l_(e);case 481:return zp(globalThis.decodeURIComponent(e));default:return M(e,"base16")}}var Wp=Object.values(Nn).map(r=>r.decoder),s_=function(){let r=Wp[0].or(Wp[1]);return Wp.slice(2).forEach(e=>r=r.or(e)),r}();function r7(r){if(!F1(r))throw new Error("invalid ip address");return Hp(r)}function a_(r){let e=t7(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!F1(e))throw new Error("invalid ip address");return e}function Xp(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function o7(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function zp(r){let e=M(r),t=Uint8Array.from(Ke(e.length));return Pe([t,e],t.length+e.length)}function Gp(r){let e=Ft(r);if(r=r.slice(pe(e)),r.length!==e)throw new Error("inconsistent lengths");return V(r)}function c_(r){let e;r[0]==="Q"||r[0]==="1"?e=ke(Se.decode(`z${r}`)).bytes:e=X.parse(r).multihash.bytes;let t=Uint8Array.from(Ke(e.length));return Pe([t,e],t.length+e.length)}function l_(r){let e=s_.decode(r),t=Uint8Array.from(Ke(e.length));return Pe([t,e],t.length+e.length)}function u_(r){let e=Ft(r),t=r.slice(pe(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+V(t,"base64url")}function d_(r){let e=Ft(r),t=r.slice(pe(e));if(t.length!==e)throw new Error("inconsistent lengths");return V(t,"base58btc")}function f_(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=lt.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 o=Xp(n);return Pe([t,o],t.length+o.length)}function h_(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=lt.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 o=Xp(n);return Pe([t,o],t.length+o.length)}function n7(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=V(e,"base32"),o=o7(t);return`${n}:${o}`}function i7(r){r=jp(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let i=0;i<o.length;i++){let s=o[i],a=ee(s);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(i++,i>=o.length)throw a7("invalid address: "+r);if(a.path===!0){n=jp(o.slice(i).join("/")),e.push([a.code,Yp(a.code,n)]),t.push([a.code,n]);break}let c=Yp(a.code,o[i]);e.push([a.code,c]),t.push([a.code,Qp(a.code,c)])}return{string:s7(t),bytes:Jp(e),tuples:e,stringTuples:t,path:n}}function Zp(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let i=Ft(r,o),s=pe(i),a=ee(i),c=p_(a,r.slice(o+s));if(c===0){e.push([i]),t.push([i]),o+=s;continue}let l=r.slice(o+s,o+s+c);if(o+=c+s,o>r.length)throw a7("Invalid address Uint8Array: "+V(r,"base16"));e.push([i,l]);let d=Qp(i,l);if(t.push([i,d]),a.path===!0){n=d;break}}return{bytes:Uint8Array.from(r),string:s7(t),tuples:e,stringTuples:t,path:n}}function s7(r){let e=[];return r.map(t=>{let n=ee(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),jp(e.join("/"))}function Jp(r){return Pe(r.map(e=>{let t=ee(e[0]),n=Uint8Array.from(Ke(t.code));return e.length>1&&e[1]!=null&&(n=Pe([n,e[1]])),n}))}function p_(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=Ft(e instanceof Uint8Array?e:Uint8Array.from(e));return t+pe(t)}}function jp(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function a7(r){return new Error("Error parsing address: "+r)}var m_=Symbol.for("nodejs.util.inspect.custom"),tm=Symbol.for("@multiformats/js-multiaddr/multiaddr"),g_=[ee("dns").code,ee("dns4").code,ee("dns6").code,ee("dnsaddr").code],em=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}},W1=class r{bytes;#e;#t;#r;#o;[tm]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=Zp(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=i7(e)}else if(Bo(e))t=Zp(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#r=t.stringTuples,this.#o=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,i="",s=ee("tcp"),a=ee("udp"),c=ee("ip4"),l=ee("ip6"),d=ee("dns6"),u=ee("ip6zone");for(let[h,p]of this.stringTuples())h===u.code&&(i=`%${p??""}`),g_.includes(h)&&(t=s.name,o=443,n=`${p??""}${i}`,e=h===d.code?6:4),(h===s.code||h===a.code)&&(t=ee(h).name,o=parseInt(p??"")),(h===c.code||h===l.code)&&(t=ee(h).name,n=`${p??""}${i}`,e=h===l.code?6:4);if(e==null||t==null||n==null||o==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:o}}protos(){return this.#t.map(([e])=>Object.assign({},ee(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>ee(e).name)}tuples(){return this.#t}stringTuples(){return this.#r}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(Jp(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===Rs.p2p.code&&e.push([n,o]),n===Rs["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?V(Se.decode(`z${n}`),"base58btc"):V(X.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#o}equals(e){return te(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(i=>i.resolvable);if(t==null)return[this];let n=Ls.get(t.name);if(n==null)throw new em(`no available resolver for ${t.name}`);return(await n(this,e)).map(i=>Q(i))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[m_](){return`Multiaddr(${this.#e})`}};var Ls=new Map;function Bo(r){return!!r?.[tm]}function Q(r){return new W1(r)}var y_=[ee("tcp").code,ee("dns").code,ee("dnsaddr").code,ee("dns4").code,ee("dns6").code];function c7(r){return d7("sni",r)?.[1]}function l7(r){let e=d7("tcp",r)?.[1];return e==null?"":`:${e}`}function d7(r,e){let t;try{t=ee(r).code}catch{return}for(let[n,o]of e)if(n===t&&o!=null)return[n,o]}function u7(r){return r.some(([e,t])=>e===ee("tls").code)}function sr(r,e,t){let n=f7[ee(r).name];if(n==null)throw new Error(`Can't interpret protocol ${ee(r).name}`);let o=n(e,t);return r===ee("ip6").code?`[${o}]`:o}var f7={ip4:(r,e)=>r,ip6:(r,e)=>e.length===0?r:`[${r}]`,tcp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`tcp://${sr(t[0],t[1]??"",e)}:${r}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${sr(t[0],t[1]??"",e)}:${r}`},dnsaddr:(r,e)=>r,dns4:(r,e)=>r,dns6:(r,e)=>r,dns:(r,e)=>r,ipfs:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${sr(t[0],t[1]??"",e)}/ipfs/${r}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${sr(t[0],t[1]??"",e)}/p2p/${r}`},http:(r,e)=>{let t=u7(e),n=c7(e),o=l7(e);if(t&&n!=null)return`https://${n}${o}`;let i=t?"https://":"http://",s=e.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let a=sr(s[0],s[1]??"",e);return a=a.replace("tcp://",""),`${i}${a}`},"http-path":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=sr(t[0],t[1]??"",e),o=decodeURIComponent(r);return`${n}/${o}`},tls:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return sr(t[0],t[1]??"",e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return sr(t[0],t[1]??"",e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=sr(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=u7(e),n=c7(e),o=l7(e);if(t&&n!=null)return`wss://${n}${o}`;let i=t?"wss://":"ws://",s=e.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let a=sr(s[0],s[1]??"",e);return a=a.replace("tcp://",""),`${i}${a}`},wss:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=sr(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${sr(t[0],t[1]??"",e)}/p2p-websocket-star`},"p2p-webrtc-star":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${sr(t[0],t[1]??"",e)}/p2p-webrtc-star`},"p2p-webrtc-direct":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${sr(t[0],t[1]??"",e)}/p2p-webrtc-direct`}};function z1(r,e){let n=Q(r).stringTuples(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let i=ee(o[0]),s=f7[i.name];if(s==null)throw new Error(`No interpreter found for ${i.name}`);let a=s(o[1]??"",n);return e?.assumeHttp!==!1&&y_.includes(o[0])&&(a=a.replace(/^.*:\/\//,""),o[1]==="443"?a=`https://${a}`:a=`http://${a}`),(a.startsWith("http://")||a.startsWith("https://")||a.startsWith("ws://")||a.startsWith("wss://"))&&(a=new URL(a).toString(),a.endsWith("/")&&(a=a.substring(0,a.length-1))),a}var G1=class{url;#e=0;#t=0;#r=0;#o=0;#a=new Map;log;constructor(e,t){this.url=e instanceof URL?e:new URL(e),this.log=t.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#l(e){let t=e.multihash.bytes;return it.encode(t)}async getRawBlock(e,t){let n=new URL(this.url.toString());if(n.pathname=`/ipfs/${e.toString()}`,n.search="?format=raw",t?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${e} from gateway ${this.url} was aborted prior to fetch`);let o=this.#l(e),i=new AbortController,s=()=>{i.abort()};t?.addEventListener("abort",s);try{let a=this.#a.get(o);return a==null&&(this.#e++,a=fetch(n.toString(),{signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"}).then(async c=>{if(this.log("GET %s %d",n,c.status),!c.ok)throw this.#t++,new Error(`unable to fetch raw block for CID ${e} from gateway ${this.url}`);return this.#o++,new Uint8Array(await c.arrayBuffer())}),this.#a.set(o,a)),await a}catch{throw t?.aborted===!0?new Error(`fetching raw block for CID ${e} from gateway ${this.url} was aborted`):(this.#t++,new Error(`unable to fetch raw block for CID ${e}`))}finally{t?.removeEventListener("abort",s),this.#a.delete(o)}}reliability(){return this.#e===0?1:this.#r>0?-1/0:this.#o/(this.#e+this.#t*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#e,errors:this.#t,invalidBlocks:this.#r,successes:this.#o,pendingResponses:this.#a.size}}};function w_(r,e,t){return r.filter(n=>{if(jg.matches(n)||e&&Xg.matches(n))return t||bc.matches(n)?!0:Bt(n.toOptions().host)===!1;if(!e&&t){let{host:o}=n.toOptions();if(o==="127.0.0.1"||o==="localhost"||o.endsWith(".localhost"))return!0}return!1})}async function*Q1(r,e,t,n,o,i){for await(let s of e.findProviders(r,i)){let a=w_(s.multiaddrs,n,o);if(a.length===0)continue;let c=z1(a[0]);yield new G1(c,t)}}var rm=class extends xi{routing;allowInsecure;allowLocal;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??Y1,this.allowLocal=t.allowLocal??X1}async queryProvider(e,t,n){this.log("fetching BLOCK for %c from %s",e,t.url);let o=await t.getRawBlock(e,n.signal);return this.log.trace("got block for %c from %s",e,t.url),await n.validateFn?.(o),o}async*findNewProviders(e,t={}){yield*Q1(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,t)}toEvictionKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}};function h7(r,e){return new rm(r,e)}var j1=class{allowInsecure;allowLocal;routing;log;logger;constructor(e,t={}){this.log=e.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=e.logger,this.routing=e.routing,this.allowInsecure=t.allowInsecure??Y1,this.allowLocal=t.allowLocal??X1}async retrieve(e,t={}){let n=[];for await(let o of Q1(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,t)){this.log("getting block for %c from %s",e,o.url);try{let i=await o.getRawBlock(e,t.signal);this.log.trace("got block for %c from %s",e,o.url);try{await t.validateFn?.(i)}catch(s){this.log.error("failed to validate block for %c from %s",e,o.url,s);continue}return i}catch(i){if(this.log.error("failed to get block for %c from %s",e,o.url,i),i instanceof Error?n.push(i):n.push(new Error(`Unable to fetch raw block for CID ${e} from gateway ${o.url}`)),t.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${e} from any gateway`):new Error(`Unable to fetch raw block for CID ${e} from any gateway`)}createSession(e={}){return h7({logger:this.logger,routing:this.routing},{...e,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure})}};var Y1=!1,X1=!1;function nm(r={}){return e=>new j1(e,r)}async function*Z1(r,e={}){let t=r.getReader();try{for(;;){let n=await t.read();if(n.done)return;yield n.value}}finally{e.preventCancel!==!0&&await t.cancel(),t.releaseLock()}}var A_=fr(J1(),1);var rn=class extends Error{static name="SignatureVerificationError";constructor(e="Record signature verification failed"){super(e),this.name="SignatureVerificationError"}},ed=class extends Error{static name="RecordExpiredError";constructor(e="Record has expired"){super(e),this.name="RecordExpiredError"}},Ds=class extends Error{static name="UnsupportedValidityError";constructor(e="The validity type is unsupported"){super(e),this.name="UnsupportedValidityError"}},td=class extends Error{static name="RecordTooLargeError";constructor(e="The record is too large"){super(e),this.name="RecordTooLargeError"}},rd=class extends Error{static name="InvalidValueError";constructor(e="Value must be a valid content path starting with /"){super(e),this.name="InvalidValueError"}},nd=class extends Error{static name="InvalidRecordDataError";constructor(e="Invalid record data"){super(e),this.name="InvalidRecordDataError"}},Ac=class extends Error{static name="InvalidEmbeddedPublicKeyError";constructor(e="Invalid embedded public key"){super(e),this.name="InvalidEmbeddedPublicKeyError"}};var ar;(function(r){let e;(function(o){o.EOL="EOL"})(e=r.ValidityType||(r.ValidityType={}));let t;(function(o){o[o.EOL=0]="EOL"})(t||(t={})),function(o){o.codec=()=>He(t)}(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=oe((o,i,s={})=>{s.lengthDelimited!==!1&&i.fork(),o.value!=null&&(i.uint32(10),i.bytes(o.value)),o.signatureV1!=null&&(i.uint32(18),i.bytes(o.signatureV1)),o.validityType!=null&&(i.uint32(24),r.ValidityType.codec().encode(o.validityType,i)),o.validity!=null&&(i.uint32(34),i.bytes(o.validity)),o.sequence!=null&&(i.uint32(40),i.uint64(o.sequence)),o.ttl!=null&&(i.uint32(48),i.uint64(o.ttl)),o.pubKey!=null&&(i.uint32(58),i.bytes(o.pubKey)),o.signatureV2!=null&&(i.uint32(66),i.bytes(o.signatureV2)),o.data!=null&&(i.uint32(74),i.bytes(o.data)),s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.value=o.bytes();break}case 2:{a.signatureV1=o.bytes();break}case 3:{a.validityType=r.ValidityType.codec().decode(o);break}case 4:{a.validity=o.bytes();break}case 5:{a.sequence=o.uint64();break}case 6:{a.ttl=o.uint64();break}case 7:{a.pubKey=o.bytes();break}case 8:{a.signatureV2=o.bytes();break}case 9:{a.data=o.bytes();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>ne(o,r.codec()),r.decode=(o,i)=>re(o,r.codec(),i)})(ar||(ar={}));var b_=mr("ipns:utils"),p7=M("/ipns/");var x_=0,E_=18;function m7(r){let e;if(r.pubKey!=null)try{e=rt(r.pubKey)}catch(t){throw b_.error(t),t}if(e!=null)return e}function g7(r){let e=M("ipns-signature:");return Pe([e,r])}function Ic(r){return"signatureV1"in r?ar.encode({value:M(r.value),signatureV1:r.signatureV1,validityType:r.validityType,validity:M(r.validity),sequence:r.sequence,ttl:r.ttl,pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data}):ar.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data})}function _n(r){let e=ar.decode(r);if(e.sequence!=null&&(e.sequence=BigInt(e.sequence)),e.ttl!=null&&(e.ttl=BigInt(e.ttl)),e.signatureV2==null||e.data==null)throw new rn("Missing data or signatureV2");let t=y7(e.data),n=v_(t.Value),o=V(t.Validity);if(e.value!=null&&e.signatureV1!=null)return S_(e),{value:n,validityType:ar.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV1:e.signatureV1,signatureV2:e.signatureV2,data:e.data};if(e.signatureV2!=null)return{value:n,validityType:ar.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV2:e.signatureV2,data:e.data};throw new Error("invalid record: does not include signatureV1 or signatureV2")}function _c(r){return Pe([p7,r.bytes])}function Ns(r){let e=ke(r.slice(p7.length));if(!od(e,x_)&&!od(e,E_))throw new co("Multihash in IPNS key was not identity or sha2-256");return e}function y7(r){let e=Er(r);if(e.ValidityType===0)e.ValidityType=ar.ValidityType.EOL;else throw new Ds("The validity type is unsupported");return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e}function v_(r){let e=V(r).trim();if(e.startsWith("/"))return e;try{return`/ipfs/${X.decode(r).toV1().toString()}`}catch{}try{return`/ipfs/${X.parse(e).toV1().toString()}`}catch{}throw new rd("Value must be a valid content path starting with /")}function S_(r){if(r.data==null)throw new nd("Record data is missing");let e=y7(r.data);if(!te(e.Value,r.value??new Uint8Array(0)))throw new rn('Field "value" did not match between protobuf and CBOR');if(!te(e.Validity,r.validity??new Uint8Array(0)))throw new rn('Field "validity" did not match between protobuf and CBOR');if(e.ValidityType!==r.validityType)throw new rn('Field "validityType" did not match between protobuf and CBOR');if(e.Sequence!==r.sequence)throw new rn('Field "sequence" did not match between protobuf and CBOR');if(e.TTL!==r.ttl)throw new rn('Field "ttl" did not match between protobuf and CBOR')}function od(r,e){return r.code===e}var oW=mr("ipns"),iW=60*60*1e9,I_="/ipns/",sW=I_.length;var w7=fr(J1(),1);var id=mr("ipns:validator"),__=1024*10,T_=async(r,e)=>{let t=_n(e),n;try{let o=g7(t.data);n=await r.verify(o,t.signatureV2)}catch{n=!1}if(!n)throw id.error("record signature verification failed"),new rn("Record signature verification failed");if(t.validityType===ar.ValidityType.EOL){if(w7.default.fromString(t.validity).toDate().getTime()<Date.now())throw id.error("record has expired"),new ed("record has expired")}else if(t.validityType!=null)throw id.error("the validity type is unsupported"),new Ds("The validity type is unsupported");id("ipns record for %s is valid",t.value)};async function sd(r,e){if(e.byteLength>__)throw new td("The record is too large");let t=Ns(r),n;od(t,0)&&(n=qu(t));let o=_n(e),i=m7(o)??n;if(i==null)throw new Ac("Could not extract public key from IPNS record or routing key");let s=_c(i.toMultihash());if(!te(r,s))throw new Ac("Embedded public key did not match routing key");await T_(i,e)}async function*Tc(r){let e=/\r?\n/,t=new TextDecoder("utf8"),n="";for await(let o of r){typeof o=="string"&&(o=new TextEncoder().encode(o)),n+=t.decode(o,{stream:!0});let i=n.split(e);n=i.pop()??"";for(let s=0;s<i.length;s++)yield JSON.parse(i[s])}n+=t.decode(),n!==""&&(yield JSON.parse(n))}var Bs=class extends Error{static name="InvalidRequestError";constructor(e="Invalid request"){super(e),this.name="InvalidRequestError"}},vi=class extends Error{static name="BadResponseError";constructor(e="Bad response"){super(e),this.name="BadResponseError"}};function k_(r){return r[Symbol.asyncIterator]!=null}function C_(r){if(k_(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var kc=C_;var b7=M("/ipns/");function x7(r){return te(r.subarray(0,b7.byteLength),b7)}var ad=class{client;constructor(e){this.client=e}async*findProviders(e,t={}){yield*jt(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs??[]}))}async provide(){}async cancelReprovide(){}async put(e,t,n){if(!x7(e))return;let o=Ns(e),i=X.createV1(114,o),s=_n(t);await this.client.putIPNS(i,s,n)}async get(e,t){if(!x7(e))throw new Oe("Not found");let n=Ns(e),o=X.createV1(114,n);try{let i=await this.client.getIPNS(o,t);return Ic(i)}catch(i){throw i.name==="BadResponseError"?new Oe("Not found"):i}}},cd=class{client;constructor(e){this.client=e}async findPeer(e,t={}){let n=await kc(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new Oe("Not found")}async*getClosestPeers(e,t={}){}};var Wt=mr("delegated-routing-v1-http-api-client"),E7={concurrentRequests:4,timeout:3e4},ld=class{started;httpQueue;shutDownController;clientUrl;timeout;contentRouting;peerRouting;filterAddrs;filterProtocols;constructor(e,t={}){this.started=!1,this.shutDownController=new AbortController,$(1/0,this.shutDownController.signal),this.httpQueue=new An({concurrency:t.concurrentRequests??E7.concurrentRequests}),this.clientUrl=e instanceof URL?e:new URL(e),this.timeout=t.timeout??E7.timeout,this.filterAddrs=t.filterAddrs,this.filterProtocols=t.filterProtocols,this.contentRouting=new ad(this),this.peerRouting=new cd(this)}get[ln](){return this.contentRouting}get[un](){return this.peerRouting}isStarted(){return this.started}start(){this.started=!0}stop(){this.httpQueue.clear(),this.shutDownController.abort(),this.started=!1}async*getProviders(e,t={}){Wt("getProviders starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=he([this.shutDownController.signal,n,t.signal]);$(1/0,n,o);let i=J(),s=J();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let a=new URL(`${this.clientUrl}routing/v1/providers/${e.toString()}`);this.#t(a,t.filterAddrs,t.filterProtocols);let l=await fetch(a,{headers:{Accept:"application/x-ndjson"},signal:o});if(l.status===404)throw new Oe("No matching records found");if(l.status===422)throw new Bs("Request does not conform to schema or semantic constraints");if(l.body==null)throw new vi("Routing response had no body");if(l.headers.get("Content-Type")==="application/json"){let u=await l.json();for(let f of u.Providers){let h=this.#e(f);h!=null&&(yield h)}}else for await(let u of Tc(Z1(l.body))){let f=this.#e(u);f!=null&&(yield f)}}catch(a){Wt.error("getProviders errored:",a)}finally{o.clear(),s.resolve(),Wt("getProviders finished: %c",e)}}async*getPeers(e,t={}){Wt("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=he([this.shutDownController.signal,n,t.signal]);$(1/0,n,o);let i=J(),s=J();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let a=new URL(`${this.clientUrl}routing/v1/peers/${e.toCID().toString()}`);this.#t(a,t.filterAddrs,t.filterProtocols);let l=await fetch(a,{headers:{Accept:"application/x-ndjson"},signal:o});if(l.status===404)throw new Oe("No matching records found");if(l.status===422)throw new Bs("Request does not conform to schema or semantic constraints");if(l.body==null)throw new vi("Routing response had no body");if(l.headers.get("Content-Type")==="application/json"){let u=await l.json();for(let f of u.Peers){let h=this.#e(f);h!=null&&(yield h)}}else for await(let u of Tc(Z1(l.body))){let f=this.#e(u);f!=null&&(yield f)}}catch(a){Wt.error("getPeers errored:",a)}finally{o.clear(),s.resolve(),Wt("getPeers finished: %c",e)}}async getIPNS(e,t={}){Wt("getIPNS starts: %s",e);let n=AbortSignal.timeout(this.timeout),o=he([this.shutDownController.signal,n,t.signal]);$(1/0,n,o);let i=J(),s=J();this.httpQueue.add(async()=>(i.resolve(),s.promise));let a=`${this.clientUrl}routing/v1/ipns/${e}`;try{await i.promise;let l=await fetch(a,{headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o});if(Wt("getIPNS GET %s %d",a,l.status),l.status===404)throw new Oe("No matching records found");if(l.status===422)throw new Bs("Request does not conform to schema or semantic constraints");if(l.body==null)throw new vi("GET ipns response had no body");let d=await l.arrayBuffer(),u=new Uint8Array(d,0,d.byteLength);return t.validate!==!1&&await sd(_c(e.multihash),u),_n(u)}catch(c){throw Wt.error("getIPNS GET %s error:",a,c),c}finally{o.clear(),s.resolve(),Wt("getIPNS finished: %s",e)}}async putIPNS(e,t,n={}){Wt("putIPNS starts: %c",e);let o=AbortSignal.timeout(this.timeout),i=he([this.shutDownController.signal,o,n.signal]);$(1/0,o,i);let s=J(),a=J();this.httpQueue.add(async()=>(s.resolve(),a.promise));let c=`${this.clientUrl}routing/v1/ipns/${e}`;try{await s.promise;let l=Ic(t),u=await fetch(c,{method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:l,signal:i});if(Wt("putIPNS PUT %s %d",c,u.status),u.status!==200)throw new vi("PUT ipns response had status other than 200")}catch(l){throw Wt.error("putIPNS PUT %s error:",c,l.stack),l}finally{i.clear(),a.resolve(),Wt("putIPNS finished: %c",e)}}#e(e){try{let t=[],n=e.Addrs?.map(Q)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:Re(e.ID),Addrs:n,Protocols:t}}catch(t){Wt.error("could not conform record to peer schema",t)}}#t(e,t,n){if(t!=null||this.filterAddrs!=null){let o=t?.join(",")??this.filterAddrs?.join(",")??"";o!==""&&e.searchParams.set("filter-addrs",o)}if(n!=null||this.filterProtocols!=null){let o=n?.join(",")??this.filterProtocols?.join(",")??"";o!==""&&e.searchParams.set("filter-protocols",o)}}};function v7(r,e={}){return new ld(new URL(r),e)}var S7="[a-fA-F\\d:]",Oo=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${S7})|(?<=${S7})(?=\\s|$))`:"",nn="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",st="[a-fA-F\\d]{1,4}",ud=`
|
|
8
8
|
(?:
|
|
9
9
|
(?:${st}:){7}(?:${st}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
|
|
10
10
|
(?:${st}:){6}(?:${nn}|:${st}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4
|
|
@@ -35,7 +35,7 @@ a=candidate:1467250027 1 UDP 1467250027 ${t} ${n} typ host\r
|
|
|
35
35
|
a=ice-ufrag:`+e+`
|
|
36
36
|
`).replace(/\na=ice-pwd:[^\n]*\n/,`
|
|
37
37
|
a=ice-pwd:`+e+`
|
|
38
|
-
`),r}var $w=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Vw=r=>[...Array(r)].map(()=>$w.at(Math.floor(Math.random()*$w.length))).join("");var BC=1e4,Uae=ee("webrtc-direct").code,Fw=ee("certhash").code,uh=class{log;metrics;components;init;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[dn]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Ie]=["@libp2p/transport"];async dial(e,t){let n=await this._connect(e,t);return this.log("dialing address: %a",e),n}createListener(e){throw new rh("WebRTCTransport.createListener")}listenFilter(e){return e.filter(vc.exactMatch)}dialFilter(e){return this.listenFilter(e)}async _connect(e,t){let n=new AbortController,o=n.signal,i=e.getPeerId();if(i===null)throw new th("we need to have the remote's PeerId");let s=Re(i),a=L3(lh(e)),c=await Di.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:D3(a.code)}),l=new Di({...await Zc(this.init.rtcConfiguration),certificates:[c]});try{let d=new Promise((v,S)=>{let _=l.createDataChannel("",{negotiated:!0,id:0}),F=setTimeout(()=>{let N=`Data channel was never opened: state: ${_.readyState}`;this.log.error(N),this.metrics?.dialerEvents.increment({open_error:!0}),S(new Jc("data",N))},BC);_.onopen=N=>{clearTimeout(F),v(_)},_.onerror=N=>{clearTimeout(F);let B=`Error opening a data channel for handshaking: ${N.target?.toString()??"not specified"}`;this.log.error(B),this.metrics?.dialerEvents.increment({unknown_error:!0}),S(new Jc("data",B))}}),u="libp2p+webrtc+v1/"+Vw(32),f=await l.createOffer(),h=Uw(f,u);await l.setLocalDescription(h);let p=Mw(e,u);await l.setRemoteDescription(p);let m=await d,g=this.generateNoisePrologue(l,a.code,e),y=$s({prologueBytes:g})(this.components),b=ca({channel:m,direction:"inbound",logger:this.components.logger,...this.init.dataChannel??{}}),w={...b,sink:b.sink.bind(b),source:async function*(){for await(let v of b.source)for(let S of v)yield S}()},x=new Li(this.components,{peerConnection:l,remoteAddr:e,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),T=jc?"iceconnectionstatechange":"connectionstatechange";l.addEventListener(T,()=>{switch(l.connectionState){case"failed":case"disconnected":case"closed":x.close().catch(v=>{this.log.error("error closing connection",v)}).finally(()=>{n.abort()});break;default:break}},{signal:o}),this.metrics?.dialerEvents.increment({peer_connection:!0});let k=new Wo(this.components,{peerConnection:l,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await y.secureInbound(w,{signal:o,remotePeer:s}),await t.upgrader.upgradeOutbound(x,{skipProtection:!0,skipEncryption:!0,muxerFactory:k})}catch(d){throw l.close(),d}}generateNoisePrologue(e,t,n){if(e.getConfiguration().certificates?.length===0)throw new C("no local certificate");let o=Ow(e,{log:this.log});if(o==null)throw new C("no local fingerprint found");let i=o.trim().toLowerCase().replaceAll(":",""),s=M(i,"hex"),a=Zt(t,s),c=R3.decode(lh(n)),l=M("libp2p-webrtc-noise:");return Pe([l,a.bytes,c])}};function Kw(r){return e=>new uh(e,r)}function Hw(r){return e=>new ch(e,r)}var qw=async r=>{if(r.readyState>=2)throw new Error("socket closed");r.readyState!==1&&await new Promise((e,t)=>{function n(){r.removeEventListener("open",o),r.removeEventListener("error",i)}function o(){n(),e()}function i(s){n(),t(s.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",o),r.addEventListener("error",i)})};var Ww=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let o of n){try{await qw(r)}catch(i){if(i.message==="socket closed")break;throw i}if(r.readyState===r.CLOSING||r.readyState===r.CLOSED)break;r.send(o)}e.closeOnEnd!=null&&r.readyState<=1&&await new Promise((o,i)=>{r.addEventListener("close",s=>{if(s.wasClean||s.code===1006)o();else{let a=Object.assign(new Error("ws error"),{event:s});i(a)}}),setTimeout(()=>{r.close()})})});var Yw=fr(Gw(),1);function Qw(r){return r instanceof ArrayBuffer||r?.constructor?.name==="ArrayBuffer"&&typeof r?.byteLength=="number"}var Xw=r=>{r.binaryType="arraybuffer";let e=async()=>{await new Promise((i,s)=>{if(n){i();return}if(o!=null){s(o);return}let a=d=>{r.removeEventListener("open",c),r.removeEventListener("error",l),d()},c=()=>{a(i)},l=d=>{a(()=>{s(d.error??new Error(`connect ECONNREFUSED ${r.url}`))})};r.addEventListener("open",c),r.addEventListener("error",l)})},t=async function*(){let i=new Yw.EventIterator(({push:s,stop:a,fail:c})=>{let l=u=>{let f=null;typeof u.data=="string"&&(f=M(u.data)),Qw(u.data)&&(f=new Uint8Array(u.data)),u.data instanceof Uint8Array&&(f=u.data),f!=null&&s(f)},d=u=>{c(u.error??new Error("Socket error"))};return r.addEventListener("message",l),r.addEventListener("error",d),r.addEventListener("close",a),()=>{r.removeEventListener("message",l),r.removeEventListener("error",d),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let s of i)yield Qw(s)?new Uint8Array(s):s}(),n=r.readyState===1,o;return r.addEventListener("open",()=>{n=!0,o=null}),r.addEventListener("close",()=>{n=!1,o=null}),r.addEventListener("error",i=>{n||(o=i.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var jw=(r,e)=>{e=e??{};let t=Xw(r),n=e.remoteAddress,o=e.remotePort;if(r.url!=null)try{let s=new URL(r.url);n=s.hostname,o=parseInt(s.port,10)}catch{}if(n==null||o==null)throw new Error("Remote connection did not have address and/or port");return{sink:Ww(r,e),source:t,connected:async()=>{await t.connected()},close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(s=>{r.addEventListener("close",()=>{s()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:o,socket:r}};var Zw=WebSocket;var MC={"http:":"ws:","https:":"wss:"},Jw="ws:",eb=(r,e)=>{if(r.startsWith("//")&&(r=`${e?.protocol??Jw}${r}`),r.startsWith("/")&&e!=null){let n=e.protocol??Jw,o=e.host,i=e.port!=null&&o?.endsWith(`:${e.port}`)!==!0?`:${e.port}`:"";r=`${n}//${o}${i}${r}`}let t=new URL(r);for(let[n,o]of Object.entries(MC))t.protocol===n&&(t.protocol=o);return t};function tb(r,e){let t=typeof window>"u"?void 0:window.location;e=e??{};let n=eb(r,t),o=new Zw(n.toString(),e.websocket);return jw(o,e)}function rb(r){return r.filter(e=>Ps.exactMatch(e)||Ec.exactMatch(e))}function nb(r){return r.filter(e=>Ps.exactMatch(e))}function ob(){throw new Error("WebSocket Servers can not be created in the browser!")}function ib(r,e,t){let n=t.logger.forComponent("libp2p:websockets:maconn"),o=t.metrics,i=t.metricPrefix??"",s={log:n,async sink(a){try{await r.sink(async function*(){for await(let c of a)c instanceof Uint8Array?yield c:yield c.subarray()}())}catch(c){c.type!=="aborted"&&n.error(c)}},source:r.source,remoteAddr:e,timeline:{open:Date.now()},async close(a={}){let c=Date.now();if(a.signal==null){let d=AbortSignal.timeout(500);a={...a,signal:d}}let l=()=>{let{host:d,port:u}=s.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",d,u,Date.now()-c),this.abort(new ht("Socket close timeout"))};a.signal?.addEventListener("abort",l);try{await r.close()}catch(d){n.error("error closing WebSocket gracefully",d),this.abort(d)}finally{a.signal?.removeEventListener("abort",l),s.timeline.close=Date.now()}},abort(a){let{host:c,port:l}=s.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",c,l,a),r.destroy(),s.timeline.close=Date.now(),o?.increment({[`${i}error`]:!0})}};return r.socket.addEventListener("close",()=>{o?.increment({[`${i}close`]:!0}),s.timeline.close==null&&(s.timeline.close=Date.now())},{once:!0}),s}var O3=class{log;init;logger;metrics;components;constructor(e,t){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[dn]=!0;[Symbol.toStringTag]="@libp2p/websockets";[Ie]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=await this._connect(e,t),o=ib(n,e,{logger:this.logger,metrics:this.metrics?.dialerEvents});this.log("new outbound connection %s",o.remoteAddr);let i=await t.upgrader.upgradeOutbound(o,t);return this.log("outbound connection %s upgraded",o.remoteAddr),i}async _connect(e,t){t?.signal?.throwIfAborted();let n=e.toOptions();this.log("dialing %s:%s",n.host,n.port);let o=J(),i=tb(z1(e),this.init);i.socket.addEventListener("error",()=>{let s=new Vi(`Could not connect to ${e.toString()}`);this.log.error("connection error:",s),this.metrics?.dialerEvents.increment({error:!0}),o.reject(s)});try{t.onProgress?.(new H("websockets:open-connection")),await Ce(Promise.race([i.connected(),o.promise]),t.signal)}catch(s){throw t.signal?.aborted===!0&&this.metrics?.dialerEvents.increment({abort:!0}),i.close().catch(a=>{this.log.error("error closing raw socket",a)}),s}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),i}createListener(e){return ob({logger:this.logger,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):tf||rf?nb(e):rb(e)}dialFilter(e){return this.listenFilter(e)}};function sb(r={}){return e=>new O3(e,r)}function M3(r){throw new Error("Not implemented")}var U3=class extends kn{writer;reader;constructor(e){super(e),this.writer=e.bidiStream.writable.getWriter(),this.reader=e.bidiStream.readable.getReader(),Promise.resolve().then(async()=>{for(;;){let t=await this.reader.read();if(t.done){e.log("remote closed write");return}t.value!=null&&this.sourcePush(new le(t.value))}}).catch(t=>{e.log.error("error reading from stream",t),this.abort(t)}).finally(()=>{this.remoteCloseWrite()}),this.writer.closed.then(()=>{e.log("writer closed")}).catch(t=>{e.log("writer close promise rejected",t)}).finally(()=>{this.remoteCloseRead()})}sendNewStream(e){}async sendData(e,t){for await(let n of e)this.log("sendData waiting for writer to be ready"),await Ce(this.writer.ready,t?.signal),this.writer.write(n).catch(o=>{this.log.error("error sending stream data",o)})}async sendReset(e){this.log("sendReset aborting writer"),await Ce(this.writer.abort(),e?.signal),this.log("sendReset aborted writer")}async sendCloseWrite(e){this.log("sendCloseWrite closing writer"),await Ce(this.writer.close(),e?.signal),this.log("sendCloseWrite closed writer")}async sendCloseRead(e){this.log("sendCloseRead cancelling reader"),await Ce(this.reader.cancel(),e?.signal),this.log("sendCloseRead cancelled reader")}};async function F3(r,e,t,n,o,i){let s=i.forComponent(`libp2p:webtransport:stream:${t}:${e}`),a=new U3({bidiStream:r,id:e,direction:t,log:s,onEnd:()=>{let c=n.findIndex(l=>l===a);c!==-1&&n.splice(c,1),o?.(a)}});return a}function hh(){return{source:{[Symbol.asyncIterator](){return{async next(){return new Promise(()=>{})}}}},sink:async r=>new Promise(()=>{})}}function ab(r,e,t,n){let o=0,i=t.forComponent("libp2p:webtransport:muxer");return{protocol:"webtransport",createStreamMuxer:s=>{typeof s=="function"&&(s={onIncomingStream:s});let a=[];Promise.resolve().then(async()=>{for(;;){let{done:l,value:d}=await e.read();if(l)break;if(a.length>=n.maxInboundStreams)i(`too many inbound streams open - ${a.length}/${n.maxInboundStreams}, closing new incoming stream`),d.writable.close().catch(u=>{i.error(`failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)}),d.readable.cancel().catch(u=>{i.error(`failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)});else{let u=await F3(d,String(o++),"inbound",a,s?.onStreamEnd,t);a.push(u),s?.onIncomingStream?.(u)}}}).catch(l=>{i.error("could not create a new stream",l)});let c={protocol:"webtransport",streams:a,newStream:async l=>{i("new outgoing stream",l);let d=await r.createBidirectionalStream(),u=await F3(d,String(o++),s?.direction??"outbound",a,s?.onStreamEnd,t);return a.push(u),u},close:async()=>{i("closing webtransport muxer gracefully");try{r.close()}catch(l){c.abort(l)}},abort:l=>{i("closing webtransport muxer with err:",l);try{r.close()}catch(d){i.error("webtransport session threw error during close",d)}},...hh()};return c}}}function cb(r,e){return e.filter(n=>!!r.find(o=>te(n,o))).length===e.length}var FC=Object.values(Nn).map(r=>r.decoder).reduce((r,e)=>r.or(e));function $C(r){return Qe.decode(FC.decode(r))}function $3(r){if(!Ei.matches(r))throw new hn("Invalid multiaddr, was not a WebTransport address");let e=r.stringTuples(),t=e.filter(([s,a])=>s===ee("certhash").code).map(([s,a])=>$C(a??"")),n=e.filter(([s,a])=>s===ee("p2p").code).map(([s,a])=>Re(a??""))[0],o=r.toOptions(),i=o.host;return o.family===6&&i?.includes(":")&&(i=`[${i}]`),{url:`https://${i}:${o.port}`,certhashes:t,remotePeer:n}}var lb=globalThis.WebTransport;var V3=class{log;components;config;metrics;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webtransport"),this.components=e,this.config={...t,maxInboundStreams:t.maxInboundStreams??1e3,certificates:t.certificates??[]},e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webtransport_dialer_events_total",{label:"event",help:"Total count of WebTransport dialer events by type"})})}[Symbol.toStringTag]="@libp2p/webtransport";[dn]=!0;[Ie]=["@libp2p/transport"];async dial(e,t){t?.signal?.throwIfAborted(),this.log("dialing %s",e),t=t??{};let{url:n,certhashes:o,remotePeer:i}=$3(e),s,a,c=()=>{},l=!1,d=!1,u=!1;try{this.metrics?.dialerEvents.increment({pending:!0});let f=new lb(`${n}/.well-known/libp2p-webtransport?type=noise`,{serverCertificateHashes:o.map(h=>({algorithm:"sha-256",value:h.digest}))});if(c=h=>{if(!l)try{this.metrics?.dialerEvents.increment({[h]:!0}),f.close()}catch(p){this.log.error("error closing wt session",p)}finally{a!=null&&(a.timeline.close=Date.now()),l=!0}},s=()=>{c(d?"noise_timeout":"ready_timeout")},t.signal?.addEventListener("abort",s,{once:!0}),this.log("wait for session to be ready"),t.onProgress?.(new H("webtransport:wait-for-session")),await Promise.race([f.closed,f.ready]),this.log("session became ready"),d=!0,this.metrics?.dialerEvents.increment({ready:!0}),f.closed.catch(h=>{this.log.error("error on remote wt session close",h)}).finally(()=>{c("remote_close")}),u=await Ce(this.authenticateWebTransport({wt:f,remotePeer:i,certhashes:o,...t}),t.signal),!u)throw new ul("Failed to authenticate webtransport");return this.metrics?.dialerEvents.increment({open:!0}),a={close:async()=>{this.log("closing webtransport"),c("close")},abort:h=>{this.log("aborting webtransport due to passed err",h),c("abort")},remoteAddr:e,timeline:{open:Date.now()},log:this.components.logger.forComponent("libp2p:webtransport:maconn"),...hh()},await t.upgrader.upgradeOutbound(a,{skipEncryption:!0,muxerFactory:ab(f,f.incomingBidirectionalStreams.getReader(),this.components.logger,this.config),skipProtection:!0,onProgress:t.onProgress})}catch(f){throw this.log.error("caught wt session err",f),c(u?"upgrade_error":d?"noise_error":"ready_error"),f}finally{s!=null&&t.signal?.removeEventListener("abort",s)}}async authenticateWebTransport({wt:e,remotePeer:t,certhashes:n,onProgress:o,signal:i}){i?.throwIfAborted(),o?.(new H("webtransport:open-authentication-stream"));let s=await e.createBidirectionalStream(),a=s.writable.getWriter(),c=s.readable.getReader(),l={source:async function*(){for(;;){let f=await c.read();if(f.value!=null&&(yield f.value),f.done)break}}(),sink:async f=>{for await(let h of f){await Ce(a.ready,i);let p=h instanceof Uint8Array?h:h.subarray();a.write(p).catch(m=>{this.log.error("could not write chunk during authentication of WebTransport stream",m)})}}},d=$s()(this.components);o?.(new H("webtransport:secure-outbound-connection"));let{remoteExtensions:u}=await d.secureOutbound(l,{signal:i,remotePeer:t});if(o?.(new H("webtransport:close-authentication-stream")),a.close().catch(f=>{this.log.error(`Failed to close authentication stream writer: ${f.message}`)}),c.cancel().catch(f=>{this.log.error(`Failed to close authentication stream reader: ${f.message}`)}),!cb(u?.webtransportCerthashes??[],n.map(f=>f.bytes)))throw new C("Our certhashes are not a subset of the remote's reported certhashes");return!0}createListener(e){return M3(this.components,{...e,certificates:this.config.certificates,maxInboundStreams:this.config.maxInboundStreams})}listenFilter(){return[]}dialFilter(e){return globalThis.WebTransport==null?[]:e.filter(t=>{if(!Ei.exactMatch(t))return!1;let{url:n,certhashes:o}=$3(t);return n!=null&&o.length>0})}};function ub(r={}){return e=>new V3(e,r)}var K3=fr(J1(),1);function db(r,e){let t=e.map((n,o)=>({record:_n(n),index:o}));return t.sort((n,o)=>{let i=n.record.sequence,s=o.record.sequence;if(i>s)return-1;if(i<s)return 1;if(n.record.validityType===ar.ValidityType.EOL&&o.record.validityType===ar.ValidityType.EOL){let a=K3.default.fromString(n.record.validity).toDate(),c=K3.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var ph="2.2.1",mh="libp2p";var hb="5.1.0-dff82ec",pb="helia";var mb={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dnsaddr/va1.bootstrap.libp2p.io/p2p/12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function gh(r={}){let e=`${pb}/${hb} ${mh}/${ph} UserAgent=${globalThis.navigator.userAgent}`;return{privateKey:r.privateKey,dns:r.dns,addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[r3(),Hw(),Kw(),ub(),sb()],connectionEncrypters:[$s()],streamMuxers:[y9(),ww()],peerDiscovery:[L9(mb)],services:{autoNAT:E9(),dcutr:X9(),delegatedRouting:()=>v7("https://delegated-ipfs.dev",{filterProtocols:["unknown","transport-bitswap","transport-ipfs-gateway-http"],filterAddrs:["https","webtransport","webrtc","webrtc-direct","wss"]}),dht:Hy({clientMode:!0,validators:{ipns:sd},selectors:{ipns:db}}),identify:uy({agentVersion:e}),identifyPush:dy({agentVersion:e}),keychain:zf(r.keychain),ping:vw()}}}var VC=32,{code:KC}=ee("dnsaddr"),H3=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}},Ni=async function(e,t={}){let n=t.maxRecursiveDepth??VC;if(n===0)throw new H3("Max recursive depth reached");let[,o]=e.stringTuples().find(([l])=>l===KC)??[],s=await(t?.dns??i1()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[gr.TXT]}),a=e.getPeerId(),c=[];for(let l of s.Answer){let d=l.data.replace(/["']/g,"").trim().split("=")[1];if(d==null||a!=null&&!d.includes(a))continue;let u=Q(d);if(d.startsWith("/dnsaddr")){let f=await u.resolve({...t,maxRecursiveDepth:n-1});c.push(...f.map(h=>h.toString()))}else c.push(u.toString())}return c};var HC={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Ni}},transportManager:{faultTolerance:ao.FATAL_ALL}};async function gb(r){let e=na(HC,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new C("Private network is enforced, but no protector was provided");return e}var la;(function(r){let e;(function(o){let i;o.codec=()=>(i==null&&(i=oe((s,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),s.key!=null&&s.key!==""&&(a.uint32(10),a.string(s.key)),s.value!=null&&s.value.byteLength>0&&(a.uint32(18),a.bytes(s.value)),c.lengthDelimited!==!1&&a.ldelim()},(s,a,c={})=>{let l={key:"",value:se(0)},d=a==null?s.len:s.pos+a;for(;s.pos<d;){let u=s.uint32();switch(u>>>3){case 1:{l.key=s.string();break}case 2:{l.value=s.bytes();break}default:{s.skipType(u&7);break}}}return l})),i),o.encode=s=>ne(s,o.codec()),o.decode=(s,a)=>re(s,o.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let i;o.codec=()=>(i==null&&(i=oe((s,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),s.key!=null&&s.key!==""&&(a.uint32(10),a.string(s.key)),s.value!=null&&(a.uint32(18),wh.codec().encode(s.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(s,a,c={})=>{let l={key:""},d=a==null?s.len:s.pos+a;for(;s.pos<d;){let u=s.uint32();switch(u>>>3){case 1:{l.key=s.string();break}case 2:{l.value=wh.codec().decode(s,s.uint32(),{limits:c.limits?.value});break}default:{s.skipType(u&7);break}}}return l})),i),o.encode=s=>ne(s,o.codec()),o.decode=(s,a)=>re(s,o.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=oe((o,i,s={})=>{if(s.lengthDelimited!==!1&&i.fork(),o.addresses!=null)for(let a of o.addresses)i.uint32(10),yh.codec().encode(a,i);if(o.protocols!=null)for(let a of o.protocols)i.uint32(18),i.string(a);if(o.publicKey!=null&&(i.uint32(34),i.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(i.uint32(42),i.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())i.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},i);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())i.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},i);s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{if(s.limits?.addresses!=null&&a.addresses.length===s.limits.addresses)throw new Me('Decode error - map field "addresses" had too many elements');a.addresses.push(yh.codec().decode(o,o.uint32(),{limits:s.limits?.addresses$}));break}case 2:{if(s.limits?.protocols!=null&&a.protocols.length===s.limits.protocols)throw new Me('Decode error - map field "protocols" had too many elements');a.protocols.push(o.string());break}case 4:{a.publicKey=o.bytes();break}case 5:{a.peerRecordEnvelope=o.bytes();break}case 6:{if(s.limits?.metadata!=null&&a.metadata.size===s.limits.metadata)throw new Sa('Decode error - map field "metadata" had too many elements');let d=r.Peer$metadataEntry.codec().decode(o,o.uint32());a.metadata.set(d.key,d.value);break}case 7:{if(s.limits?.tags!=null&&a.tags.size===s.limits.tags)throw new Sa('Decode error - map field "tags" had too many elements');let d=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:s.limits?.tags$value}});a.tags.set(d.key,d.value);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>ne(o,r.codec()),r.decode=(o,i)=>re(o,r.codec(),i)})(la||(la={}));var yh;(function(r){let e;r.codec=()=>(e==null&&(e=oe((t,n,o={})=>{o.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)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={multiaddr:se(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.multiaddr=t.bytes();break}case 2:{i.isCertified=t.bool();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>ne(t,r.codec()),r.decode=(t,n)=>re(t,r.codec(),n)})(yh||(yh={}));var wh;(function(r){let e;r.codec=()=>(e==null&&(e=oe((t,n,o={})=>{o.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)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.value=t.uint32();break}case 2:{i.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>ne(t,r.codec()),r.decode=(t,n)=>re(t,r.codec(),n)})(wh||(wh={}));function ua(r,e){let t=la.decode(e);if(t.publicKey!=null&&r.publicKey==null){let i=rt(t.publicKey);r=En(i)}let n=new Map,o=BigInt(Date.now());for(let[i,s]of t.tags.entries())s.expiry!=null&&s.expiry<o||n.set(i,s);return{...t,id:r,addresses:t.addresses.map(({multiaddr:i,isCertified:s})=>({multiaddr:Q(i),isCertified:s??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var q3="/peers/";function da(r){if(!cl(r)||r.type==null)throw new C("Invalid PeerId");let e=r.toCID().toString();return new De(`${q3}${e}`)}async function yb(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=Q(o.multiaddr)),!Bo(o.multiaddr))throw new C("Multiaddr was invalid");if(!await e(r,o.multiaddr))continue;let i=o.isCertified??!1,s=o.multiaddr.toString(),a=n.get(s);a!=null?o.isCertified=a.isCertified||i:n.set(s,{multiaddr:o.multiaddr,isCertified:i})}return[...n.values()].sort((o,i)=>o.multiaddr.toString().localeCompare(i.multiaddr.toString())).map(({isCertified:o,multiaddr:i})=>({isCertified:o,multiaddr:i.bytes}))}async function xh(r,e,t,n){if(e==null)throw new C("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new C("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new C("peer id did not match existing peer id");let i=o?.addresses??[],s=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,l=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(i=[],e.multiaddrs!=null&&i.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&i.push(...e.addresses)),e.protocols!=null&&(s=new Set(e.protocols)),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=bh(f,{validate:wb})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=bh(f,{validate:bb,map:xb})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&i.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&i.push(...e.addresses),e.protocols!=null&&(s=new Set([...s,...e.protocols])),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,p]of f)p==null?a.delete(h):a.set(h,p);a=bh([...a.entries()],{validate:wb})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,m]of f)m==null?h.delete(p):h.set(p,m);c=bh([...h.entries()],{validate:bb,map:xb})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let d;o?.id.publicKey!=null?d=Lt(o.id.publicKey):e.publicKey!=null?d=Lt(e.publicKey):r.publicKey!=null&&(d=Lt(r.publicKey));let u={addresses:await yb(r,n.addressFilter??(async()=>!0),i),protocols:[...s.values()].sort((f,h)=>f.localeCompare(h)),metadata:a,tags:c,publicKey:d,peerRecordEnvelope:l};return r.type!=="RSA"&&delete u.publicKey,u}function bh(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([i],[s])=>i.localeCompare(s)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function wb(r,e){if(typeof r!="string")throw new C("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new C("Metadata value must be a Uint8Array")}function bb(r,e){if(typeof r!="string")throw new C("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new C("Tag value must be an integer");if(e.value<0||e.value>100)throw new C("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new C("Tag ttl must be an integer");if(e.ttl<0)throw new C("Tag ttl must be between greater than 0")}}function xb(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}function Eh(r,e){let t=r.toString().split("/")[2],n=X.parse(t,lt),o=vn(n);return ua(o,e)}function qC(r){return r==null?{}:{prefix:q3,filters:(r.filters??[]).map(e=>({key:t,value:n})=>e(Eh(t,n))),orders:(r.orders??[]).map(e=>(t,n)=>e(Eh(t.key,t.value),Eh(n.key,n.value)))}}var vh=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=wi({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(da(e))}async delete(e){if(this.peerId.equals(e))throw new C("Cannot delete self peer");await this.datastore.delete(da(e))}async load(e){let t=await this.datastore.get(da(e));return ua(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),i=await xh(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,i,n,o)}async patch(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),i=await xh(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,i,n,o)}async merge(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),i=await xh(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,i,n,o)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(qC(e??{}))){let o=Eh(t,n);o.id.equals(this.peerId)||(yield o)}}async#e(e){try{let t=await this.datastore.get(da(e)),n=ua(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.name!=="NotFoundError")throw t}return{}}async#t(e,t,n,o){let i=la.encode(t);return n!=null&&te(i,n)?{peer:ua(e,i),previous:o,updated:!1}:(await this.datastore.put(da(e),i),{peer:ua(e,i),previous:o,updated:!0})}};var W3=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 vh(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(t))e(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(e){this.log.trace("all await read lock");let t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await Pc(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await Sr.openAndCertify(e,zt.DOMAIN),o=vn(n.publicKey.toCID());if(t?.equals(o)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,o),!1;let i=zt.createFromProtobuf(n.payload),s;try{s=await this.get(o)}catch(a){if(a.name!=="NotFoundError")throw a}if(s?.peerRecordEnvelope!=null){let a=await Sr.createFromProtobuf(s.peerRecordEnvelope),c=zt.createFromProtobuf(a.payload);if(c.seqNumber>=i.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",c.seqNumber,i.seqNumber),!1}return await this.patch(i.peerId,{peerRecordEnvelope:e,addresses:i.multiaddrs.map(a=>({isCertified:!0,multiaddr:a}))}),!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 Eb(r,e={}){return new W3(r,e)}function vb(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var WC=r=>r;function z3(r,e){let t=r.getPeerId();return t!=null&&Re(t).equals(e)&&(r=r.decapsulate(Q(`/p2p/${e.toString()}`))),r}var Sh=class{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(o.map(i=>i.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??WC,this._updatePeerStoreAddresses=vb(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.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>Q(t))).map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>Q(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>Q(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>Q(e))}addObservedAddr(e){e=z3(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=z3(e,this.components.peerId);let t=e.toString(),o=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=z3(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,o])=>o.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>Q(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var Sb;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(Sb||(Sb={}));var Ah=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},Ih=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},fa=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},rl=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},_h=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},Th=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},kh=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},nl=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},Bi=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},Ch=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},Ph=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},Oi=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Mi=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},Rh=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}};var G3=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=ko())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>gl(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")}},GC=["metrics","connectionProtector","dns"],QC=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Ab(r={}){let e=new G3(r);return new Proxy(e,{get(n,o,i){if(typeof o=="string"&&!QC.includes(o)){let s=e.components[o];if(s==null&&!GC.includes(o))throw new Ah(`${o} not set`);return s}return Reflect.get(n,o,i)},set(n,o,i){return typeof o=="string"?e.components[o]=i:Reflect.set(n,o,i),!0}})}function Ib(r){let e={};for(let t of Object.values(r.components))for(let n of YC(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of XC(t))if(e[n]!==!0)throw new Ih(`Service "${jC(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function YC(r){return Array.isArray(r?.[Ie])?r[Ie]:[]}function XC(r){return Array.isArray(r?.[Vr])?r[Vr]:[]}function jC(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function _b(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!Bt(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}function Lh(r){if(cl(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:Re(t),r.forEach(n=>{if(!Bo(n))throw new hn("Invalid multiaddr");let o=n.getPeerId();if(o==null){if(e!=null)throw new C("Multiaddrs must all have the same peer id or have no peer id")}else{let i=Re(o);if(e?.equals(i)!==!0)throw new C("Multiaddrs must all have the same peer id or have no peer id")}})}return{peerId:e,multiaddrs:r}}var ZC=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function Tb(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??ZC;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var kb="last-dial-failure",Cb="last-dial-success";var Dh=100,Nh=50;var Pb={maxConnections:Dh,allow:[]},Bh=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Pb.maxConnections,this.allow=t.allow??Pb.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;let n=new gt;for(let a of e){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let l=await this.peerStore.get(c);n.set(c,[...l.tags.values()].reduce((d,u)=>d+u.value,0))}catch(l){l.name!=="NotFoundError"&&this.log.error("error loading peer tags",l)}}}let o=this.sortConnections(e,n),i=Math.max(t-this.maxConnections,0),s=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(l=>a.remoteAddr.toString().startsWith(l.toString()))||s.push(a),s.length===i)break;await Promise.all(s.map(async a=>{await Tb(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:s})}sortConnections(e,t){return e.sort((n,o)=>{let i=n.timeline.open,s=o.timeline.open;return i<s?1:i>s?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let i=t.get(n.remotePeer)??0,s=t.get(o.remotePeer)??0;return i>s?1:i<s?-1:0})}};var Oh=class extends Mt{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};function Q3(r){try{let{address:e}=r.nodeAddress();return!!Bt(e)}catch{return!0}}function JC(r,e){let t=Vp.exactMatch(r.multiaddr),n=Vp.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let o=Ps.exactMatch(r.multiaddr),i=Ps.exactMatch(e.multiaddr);if(o&&!i)return-1;if(!o&&i)return 1;let s=Ec.exactMatch(r.multiaddr),a=Ec.exactMatch(e.multiaddr);if(s&&!a)return-1;if(!s&&a)return 1;let c=Sc.exactMatch(r.multiaddr),l=Sc.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let d=vc.exactMatch(r.multiaddr),u=vc.exactMatch(e.multiaddr);if(d&&!u)return-1;if(!d&&u)return 1;let f=Ei.exactMatch(r.multiaddr),h=Ei.exactMatch(e.multiaddr);return f&&!h?-1:!f&&h?1:0}function eP(r,e){let t=Q3(r.multiaddr),n=Q3(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function tP(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function rP(r,e){let t=ir.exactMatch(r.multiaddr),n=ir.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Rb(r){return r.sort(JC).sort(tP).sort(rP).sort(eP)}async function Lb(r,e){let t=!1;for(let o of Ls.keys())if(t=r.protoNames().includes(o),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(o=>o.toString())),n}var Mh={maxParallelDials:Nh,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:Ni}},Uh=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Mh.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Mh.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Mh.dialTimeout,this.connections=t.connections??new gt,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,$(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))Ls.set(n,o);this.queue=new Oh({concurrency:t.maxParallelDials??Mh.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{n.detail.name!==ht.name&&this.log.error("error in dial queue - %e",n.detail)})}start(){this.shutDownController=new AbortController,$(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=Lh(e),i=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(i?.status==="open")return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new H("dial-queue:already-connected")),i;let s=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let l of o)if(c.has(l.toString()))return!0;return!1});if(s!=null){this.log("joining existing dial target for %p",n);for(let a of o)s.options.multiaddrs.add(a.toString());return t.onProgress?.(new H("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Dn("Dial queue is full");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),t.onProgress?.(new H("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a?.onProgress?.(new H("dial-queue:start-dial"));let c=this.createDialAbortController(a?.signal),l;try{l=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),a?.onProgress?.(new H("dial-queue:calculated-addresses",l)),l.map(({multiaddr:d})=>d.toString()).forEach(d=>{a?.multiaddrs.add(d)})}catch(d){throw c.clear(),d}try{let d=0,u=[];for(let f of l){if(d===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",d,n),new Dn("Peer had more than maxPeerAddrsToDial");d++;try{let h=await this.components.transportManager.dial(f.multiaddr,{...a,signal:c});this.log("dial to %a succeeded",f.multiaddr);try{await this.components.peerStore.merge(h.remotePeer,{multiaddrs:[h.remoteAddr],metadata:{[Cb]:M(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}return h}catch(h){if(this.log.error("dial failed to %a",f.multiaddr,h),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[kb]:M(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}if(c.aborted)throw new Ur(h.message);u.push(h)}}throw u.length===1?u[0]:new AggregateError(u,"All multiaddr dials failed")}finally{c.clear()}},{peerId:n,priority:t.priority??Z3,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal,onProgress:t.onProgress})}createDialAbortController(e){let t=he([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return $(1/0,t),t}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(u=>({multiaddr:Q(u),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Dn("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new nl("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let u=await this.components.peerStore.get(e);o.push(...u.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:f})=>f.toString()))}catch(u){if(u.name!=="NotFoundError")throw u}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let u=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:f})=>f.toString())),o.push(...u.multiaddrs.map(f=>({multiaddr:f,isCertified:!1})))}catch(u){u.name!=="NoPeerRoutersError"&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,u)}}}let i=(await Promise.all(o.map(async u=>{let f=await Lb(u.multiaddr,{dns:this.components.dns,...n,log:this.log});return f.length===1&&f[0].equals(u.multiaddr)?u:f.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let u=`/p2p/${e.toString()}`;i=i.map(f=>f.multiaddr.protos().pop()?.path===!0?f:f.multiaddr.getPeerId()==null?{multiaddr:f.multiaddr.encapsulate(u),isCertified:f.isCertified}:f)}let s=i.filter(u=>{if(this.components.transportManager.dialTransportForMultiaddr(u.multiaddr)==null)return!1;let f=u.multiaddr.getPeerId();return e!=null&&f!=null?e.equals(f):!0}),a=new Map;for(let u of s){let f=u.multiaddr.toString(),h=a.get(f);if(h!=null){h.isCertified=h.isCertified||u.isCertified||!1;continue}a.set(f,u)}let c=[...a.values()];if(c.length===0)throw new Bi("The dial request has no valid addresses");let l=[];for(let u of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(u.multiaddr)||l.push(u);let d=this.addressSorter==null?Rb(l):l.sort(this.addressSorter);if(d.length===0)throw new nl("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:u})=>u.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",d.map(({multiaddr:u})=>u.toString())),d}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnLimitedConnection===!1?n.find(o=>!ir.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var Fb=fr(Mb(),1);var oP=Object.prototype.toString,iP=r=>oP.call(r)==="[object Error]",sP=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function J3(r){return r&&iP(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:sP.has(r.message):!1}var e4=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}},Ub=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function t4(r,e){return new Promise((t,n)=>{e={onFailedAttempt(){},retries:10,shouldRetry:()=>!0,...e};let o=Fb.default.operation(e),i=()=>{o.stop(),n(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",i,{once:!0});let s=()=>{e.signal?.removeEventListener("abort",i),o.stop()};o.attempt(async a=>{try{let c=await r(a);s(),t(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof e4)throw c.originalError;if(c instanceof TypeError&&!J3(c))throw c;if(Ub(c,a,e),await e.shouldRetry(c)||(o.stop(),n(c)),await e.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(l){Ub(l,a,e),s(),n(l)}}})})}var Fh=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 Ut({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(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);$b(t)&&(this.queue.has(e)||this.queue.add(async n=>{await t4(async o=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(i){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,o,this.retries,i),i}},{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 o={};[...t.tags.keys()].forEach(i=>{i.startsWith(so)&&(o[i]=void 0)}),await this.peerStore.merge(e,{tags:o}),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=>$b(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)})}stop(){this.started=!1,this.queue.abort()}};function $b(r){for(let e of r.tags.keys())if(e.startsWith(so))return!0;return!1}var Z3=50,r4={maxConnections:Dh,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},$h=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??r4.maxConnections,this.maxConnections<1)throw new C("Connection Manager maxConnections must be greater than 0");this.connections=new gt,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=>Q(n)),this.deny=(t.deny??[]).map(n=>Q(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??r4.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new aa({points:t.inboundConnectionThreshold??r4.inboundConnectionThreshold,duration:1}),this.connectionPruner=new Bh({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Uh(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??Nh,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:Ni},connections:this.connections}),this.reconnectQueue=new Fh({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 o of n.streams){let i=`${o.direction} ${o.protocol??"unnegotiated"}`;e[i]=(e[i]??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 o of n){let i={};for(let s of o.streams){let a=`${s.direction} ${s.protocol??"unnegotiated"}`;i[a]=(i[a]??0)+1}for(let[s,a]of Object.entries(i))e[s]=e[s]??[],e[s].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((s,a)=>s-a);let i=Math.floor(o.length*.9);t[n]=o[i]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await wt(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 Tt(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,o=!this.connections.has(n),i=this.connections.get(n)??[];i.push(t),this.connections.set(n,i),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,i=(this.connections.get(n)??[]).filter(s=>s.id!==t.id);this.connections.set(n,i),i.length===0&&(this.log("onDisconnect remove all connections for peer %p",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new Fr("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:n}=Lh(e);if(this.peerId.equals(n))throw new Ki("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p",n),t.onProgress?.(new H("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??Z3});if(o.status!=="open")throw new $i("Remote closed connection during opening");let i=this.connections.get(o.remotePeer);i==null&&(i=[],this.connections.set(o.remotePeer,i));let s=!1;for(let a of i)if(a.id===o.id&&(s=!0),t.force!==!0&&a.id!==o.id&&a.remoteAddr.equals(o.remoteAddr))return o.abort(new hn("Duplicate multiaddr connection")),a;return s||i.push(o),o}finally{this.outboundPendingConnections--}}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(i){o.abort(i)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let o=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!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)}};var lP=1e4,uP="1.0.0",dP="ping",fP="ipfs",Vb=32,hP=!0,Vh=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??fP}/${dP}/${uP}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??lP,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??hP,this.timeout=new cn({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Ie]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,$(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}),o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),i=Ai(o);t=Date.now(),await Promise.all([i.write(Kt(Vb),{signal:n}),i.read(Vb,{signal:n})]),e.rtt=Date.now()-t,await i.unwrap().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",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)}};var Kh=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new fa("No content routers available");let n=this,o=new nr;for await(let i of $t(...n.routers.map(s=>s.findProviders(e,t))))i!=null&&(i.multiaddrs.length>0&&await this.components.peerStore.merge(i.id,{multiaddrs:i.multiaddrs}),!o.has(i.id)&&(o.add(i.id),yield i))}async provide(e,t={}){if(this.routers.length===0)throw new fa("No content routers available");await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new fa("No content routers available");await Promise.all(this.routers.map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new Fr;await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new Fr;return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var Hh=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??[]}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new rl("No peer routers available");if(e.toString()===this.peerId.toString())throw new _h("Should not try to find self");let n=this,o=$t(...this.routers.map(i=>async function*(){try{yield await i.findPeer(e,t)}catch(s){n.log.error(s)}}()));for await(let i of o)if(i!=null)return i.multiaddrs.length>0&&await this.peerStore.merge(i.id,{multiaddrs:i.multiaddrs}),i;throw new Oe}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new rl("No peer routers available");let n=this,o=Sn(1024);for await(let i of vr(async function*(){let s=$t(...n.routers.map(a=>a.getClosestPeers(e,t)));for await(let a of s)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",c);return}return a}}()))i!=null&&(i.multiaddrs.length>0&&await this.peerStore.merge(i.id,{multiaddrs:i.multiaddrs}),!o.has(i.id.toMultihash().bytes)&&(o.add(i.id.toMultihash().bytes),yield i))}};var qh=class extends ge{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,$(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,$(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=he([this.shutdownController.signal,e?.signal]);$(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=J(),yield(await hr(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,$(1/0,this.walkController.signal);let e=he([this.walkController.signal,this.shutdownController.signal]);$(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=Kt(32),i=Date.now();for await(let s of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",s.id,Date.now()-i,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:s}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await Ce(this.needNext.promise,e)),i=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("randomwalk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var n4=32,o4=64,Wh=class{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new Th(`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))throw new kh(`Handler already registered for protocol ${e}`);let o=na.bind({ignoreUndefined:!0})({maxInboundStreams:n4,maxOutboundStreams:o4},n);this.handlers.set(e,{handler:t,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(t==null)throw new C("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{for(let o of n.protocols){let i=this.topologies.get(o);if(i!=null)for(let s of i.values())s.filter?.has(t)!==!1&&(s.filter?.remove(t),s.onDisconnect?.(t))}}).catch(n=>{n.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(i=>!t.protocols.includes(i));for(let i of o){let s=this.topologies.get(i);if(s!=null)for(let a of s.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;for(let i of t){let s=this.topologies.get(i);if(s!=null)for(let a of s.values())n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var zh=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=new Map,this.listeners=N1({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??ao.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new C("Transport must have a valid tag");if(this.transports.has(t))throw new C(`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 o=n.pop();o!=null&&e.push(o.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 Rh(`No transport available for address ${String(e)}`);return t?.onProgress?.(new H("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 Fr("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[n,o]of this.transports.entries()){let i=o.listenFilter(e),s=[];for(let l of i){this.log("creating listener for %s on %a",n,l);let d=o.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(n)??[];u==null&&(u=[],this.listeners.set(n,u)),u.push(d),d.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:d})}),d.addEventListener("close",()=>{let f=u.findIndex(h=>h===d);u.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:d})}),s.push(d.listen(l))}if(s.length===0){t.push(n);continue}if((await Promise.allSettled(s)).find(l=>l.status==="fulfilled")==null&&this.faultTolerance!==ao.NO_FATAL)throw new Bi(`Transport (${n}) could not listen on any available address`)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===ao.FATAL_ALL)throw new Bi(n);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var _t="/multistream/1.0.0";var pP=M(`
|
|
38
|
+
`),r}var $w=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Vw=r=>[...Array(r)].map(()=>$w.at(Math.floor(Math.random()*$w.length))).join("");var BC=1e4,Uae=ee("webrtc-direct").code,Fw=ee("certhash").code,uh=class{log;metrics;components;init;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[dn]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Ie]=["@libp2p/transport"];async dial(e,t){let n=await this._connect(e,t);return this.log("dialing address: %a",e),n}createListener(e){throw new rh("WebRTCTransport.createListener")}listenFilter(e){return e.filter(vc.exactMatch)}dialFilter(e){return this.listenFilter(e)}async _connect(e,t){let n=new AbortController,o=n.signal,i=e.getPeerId();if(i===null)throw new th("we need to have the remote's PeerId");let s=Re(i),a=L3(lh(e)),c=await Di.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:D3(a.code)}),l=new Di({...await Zc(this.init.rtcConfiguration),certificates:[c]});try{let d=new Promise((v,S)=>{let _=l.createDataChannel("",{negotiated:!0,id:0}),F=setTimeout(()=>{let N=`Data channel was never opened: state: ${_.readyState}`;this.log.error(N),this.metrics?.dialerEvents.increment({open_error:!0}),S(new Jc("data",N))},BC);_.onopen=N=>{clearTimeout(F),v(_)},_.onerror=N=>{clearTimeout(F);let B=`Error opening a data channel for handshaking: ${N.target?.toString()??"not specified"}`;this.log.error(B),this.metrics?.dialerEvents.increment({unknown_error:!0}),S(new Jc("data",B))}}),u="libp2p+webrtc+v1/"+Vw(32),f=await l.createOffer(),h=Uw(f,u);await l.setLocalDescription(h);let p=Mw(e,u);await l.setRemoteDescription(p);let m=await d,g=this.generateNoisePrologue(l,a.code,e),y=$s({prologueBytes:g})(this.components),b=ca({channel:m,direction:"inbound",logger:this.components.logger,...this.init.dataChannel??{}}),w={...b,sink:b.sink.bind(b),source:async function*(){for await(let v of b.source)for(let S of v)yield S}()},x=new Li(this.components,{peerConnection:l,remoteAddr:e,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),T=jc?"iceconnectionstatechange":"connectionstatechange";l.addEventListener(T,()=>{switch(l.connectionState){case"failed":case"disconnected":case"closed":x.close().catch(v=>{this.log.error("error closing connection",v)}).finally(()=>{n.abort()});break;default:break}},{signal:o}),this.metrics?.dialerEvents.increment({peer_connection:!0});let k=new Wo(this.components,{peerConnection:l,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await y.secureInbound(w,{signal:o,remotePeer:s}),await t.upgrader.upgradeOutbound(x,{skipProtection:!0,skipEncryption:!0,muxerFactory:k})}catch(d){throw l.close(),d}}generateNoisePrologue(e,t,n){if(e.getConfiguration().certificates?.length===0)throw new C("no local certificate");let o=Ow(e,{log:this.log});if(o==null)throw new C("no local fingerprint found");let i=o.trim().toLowerCase().replaceAll(":",""),s=M(i,"hex"),a=Zt(t,s),c=R3.decode(lh(n)),l=M("libp2p-webrtc-noise:");return Pe([l,a.bytes,c])}};function Kw(r){return e=>new uh(e,r)}function Hw(r){return e=>new ch(e,r)}var qw=async r=>{if(r.readyState>=2)throw new Error("socket closed");r.readyState!==1&&await new Promise((e,t)=>{function n(){r.removeEventListener("open",o),r.removeEventListener("error",i)}function o(){n(),e()}function i(s){n(),t(s.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",o),r.addEventListener("error",i)})};var Ww=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let o of n){try{await qw(r)}catch(i){if(i.message==="socket closed")break;throw i}if(r.readyState===r.CLOSING||r.readyState===r.CLOSED)break;r.send(o)}e.closeOnEnd!=null&&r.readyState<=1&&await new Promise((o,i)=>{r.addEventListener("close",s=>{if(s.wasClean||s.code===1006)o();else{let a=Object.assign(new Error("ws error"),{event:s});i(a)}}),setTimeout(()=>{r.close()})})});var Yw=fr(Gw(),1);function Qw(r){return r instanceof ArrayBuffer||r?.constructor?.name==="ArrayBuffer"&&typeof r?.byteLength=="number"}var Xw=r=>{r.binaryType="arraybuffer";let e=async()=>{await new Promise((i,s)=>{if(n){i();return}if(o!=null){s(o);return}let a=d=>{r.removeEventListener("open",c),r.removeEventListener("error",l),d()},c=()=>{a(i)},l=d=>{a(()=>{s(d.error??new Error(`connect ECONNREFUSED ${r.url}`))})};r.addEventListener("open",c),r.addEventListener("error",l)})},t=async function*(){let i=new Yw.EventIterator(({push:s,stop:a,fail:c})=>{let l=u=>{let f=null;typeof u.data=="string"&&(f=M(u.data)),Qw(u.data)&&(f=new Uint8Array(u.data)),u.data instanceof Uint8Array&&(f=u.data),f!=null&&s(f)},d=u=>{c(u.error??new Error("Socket error"))};return r.addEventListener("message",l),r.addEventListener("error",d),r.addEventListener("close",a),()=>{r.removeEventListener("message",l),r.removeEventListener("error",d),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let s of i)yield Qw(s)?new Uint8Array(s):s}(),n=r.readyState===1,o;return r.addEventListener("open",()=>{n=!0,o=null}),r.addEventListener("close",()=>{n=!1,o=null}),r.addEventListener("error",i=>{n||(o=i.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var jw=(r,e)=>{e=e??{};let t=Xw(r),n=e.remoteAddress,o=e.remotePort;if(r.url!=null)try{let s=new URL(r.url);n=s.hostname,o=parseInt(s.port,10)}catch{}if(n==null||o==null)throw new Error("Remote connection did not have address and/or port");return{sink:Ww(r,e),source:t,connected:async()=>{await t.connected()},close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(s=>{r.addEventListener("close",()=>{s()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:o,socket:r}};var Zw=WebSocket;var MC={"http:":"ws:","https:":"wss:"},Jw="ws:",eb=(r,e)=>{if(r.startsWith("//")&&(r=`${e?.protocol??Jw}${r}`),r.startsWith("/")&&e!=null){let n=e.protocol??Jw,o=e.host,i=e.port!=null&&o?.endsWith(`:${e.port}`)!==!0?`:${e.port}`:"";r=`${n}//${o}${i}${r}`}let t=new URL(r);for(let[n,o]of Object.entries(MC))t.protocol===n&&(t.protocol=o);return t};function tb(r,e){let t=typeof window>"u"?void 0:window.location;e=e??{};let n=eb(r,t),o=new Zw(n.toString(),e.websocket);return jw(o,e)}function rb(r){return r.filter(e=>Ps.exactMatch(e)||Ec.exactMatch(e))}function nb(r){return r.filter(e=>Ps.exactMatch(e))}function ob(){throw new Error("WebSocket Servers can not be created in the browser!")}function ib(r,e,t){let n=t.logger.forComponent("libp2p:websockets:maconn"),o=t.metrics,i=t.metricPrefix??"",s={log:n,async sink(a){try{await r.sink(async function*(){for await(let c of a)c instanceof Uint8Array?yield c:yield c.subarray()}())}catch(c){c.type!=="aborted"&&n.error(c)}},source:r.source,remoteAddr:e,timeline:{open:Date.now()},async close(a={}){let c=Date.now();if(a.signal==null){let d=AbortSignal.timeout(500);a={...a,signal:d}}let l=()=>{let{host:d,port:u}=s.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",d,u,Date.now()-c),this.abort(new ht("Socket close timeout"))};a.signal?.addEventListener("abort",l);try{await r.close()}catch(d){n.error("error closing WebSocket gracefully",d),this.abort(d)}finally{a.signal?.removeEventListener("abort",l),s.timeline.close=Date.now()}},abort(a){let{host:c,port:l}=s.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",c,l,a),r.destroy(),s.timeline.close=Date.now(),o?.increment({[`${i}error`]:!0})}};return r.socket.addEventListener("close",()=>{o?.increment({[`${i}close`]:!0}),s.timeline.close==null&&(s.timeline.close=Date.now())},{once:!0}),s}var O3=class{log;init;logger;metrics;components;constructor(e,t){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[dn]=!0;[Symbol.toStringTag]="@libp2p/websockets";[Ie]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=await this._connect(e,t),o=ib(n,e,{logger:this.logger,metrics:this.metrics?.dialerEvents});this.log("new outbound connection %s",o.remoteAddr);let i=await t.upgrader.upgradeOutbound(o,t);return this.log("outbound connection %s upgraded",o.remoteAddr),i}async _connect(e,t){t?.signal?.throwIfAborted();let n=e.toOptions();this.log("dialing %s:%s",n.host,n.port);let o=J(),i=tb(z1(e),this.init);i.socket.addEventListener("error",()=>{let s=new Vi(`Could not connect to ${e.toString()}`);this.log.error("connection error:",s),this.metrics?.dialerEvents.increment({error:!0}),o.reject(s)});try{t.onProgress?.(new H("websockets:open-connection")),await Ce(Promise.race([i.connected(),o.promise]),t.signal)}catch(s){throw t.signal?.aborted===!0&&this.metrics?.dialerEvents.increment({abort:!0}),i.close().catch(a=>{this.log.error("error closing raw socket",a)}),s}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),i}createListener(e){return ob({logger:this.logger,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):tf||rf?nb(e):rb(e)}dialFilter(e){return this.listenFilter(e)}};function sb(r={}){return e=>new O3(e,r)}function M3(r){throw new Error("Not implemented")}var U3=class extends kn{writer;reader;constructor(e){super(e),this.writer=e.bidiStream.writable.getWriter(),this.reader=e.bidiStream.readable.getReader(),Promise.resolve().then(async()=>{for(;;){let t=await this.reader.read();if(t.done){e.log("remote closed write");return}t.value!=null&&this.sourcePush(new le(t.value))}}).catch(t=>{e.log.error("error reading from stream",t),this.abort(t)}).finally(()=>{this.remoteCloseWrite()}),this.writer.closed.then(()=>{e.log("writer closed")}).catch(t=>{e.log("writer close promise rejected",t)}).finally(()=>{this.remoteCloseRead()})}sendNewStream(e){}async sendData(e,t){for await(let n of e)this.log("sendData waiting for writer to be ready"),await Ce(this.writer.ready,t?.signal),this.writer.write(n).catch(o=>{this.log.error("error sending stream data",o)})}async sendReset(e){this.log("sendReset aborting writer"),await Ce(this.writer.abort(),e?.signal),this.log("sendReset aborted writer")}async sendCloseWrite(e){this.log("sendCloseWrite closing writer"),await Ce(this.writer.close(),e?.signal),this.log("sendCloseWrite closed writer")}async sendCloseRead(e){this.log("sendCloseRead cancelling reader"),await Ce(this.reader.cancel(),e?.signal),this.log("sendCloseRead cancelled reader")}};async function F3(r,e,t,n,o,i){let s=i.forComponent(`libp2p:webtransport:stream:${t}:${e}`),a=new U3({bidiStream:r,id:e,direction:t,log:s,onEnd:()=>{let c=n.findIndex(l=>l===a);c!==-1&&n.splice(c,1),o?.(a)}});return a}function hh(){return{source:{[Symbol.asyncIterator](){return{async next(){return new Promise(()=>{})}}}},sink:async r=>new Promise(()=>{})}}function ab(r,e,t,n){let o=0,i=t.forComponent("libp2p:webtransport:muxer");return{protocol:"webtransport",createStreamMuxer:s=>{typeof s=="function"&&(s={onIncomingStream:s});let a=[];Promise.resolve().then(async()=>{for(;;){let{done:l,value:d}=await e.read();if(l)break;if(a.length>=n.maxInboundStreams)i(`too many inbound streams open - ${a.length}/${n.maxInboundStreams}, closing new incoming stream`),d.writable.close().catch(u=>{i.error(`failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)}),d.readable.cancel().catch(u=>{i.error(`failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)});else{let u=await F3(d,String(o++),"inbound",a,s?.onStreamEnd,t);a.push(u),s?.onIncomingStream?.(u)}}}).catch(l=>{i.error("could not create a new stream",l)});let c={protocol:"webtransport",streams:a,newStream:async l=>{i("new outgoing stream",l);let d=await r.createBidirectionalStream(),u=await F3(d,String(o++),s?.direction??"outbound",a,s?.onStreamEnd,t);return a.push(u),u},close:async()=>{i("closing webtransport muxer gracefully");try{r.close()}catch(l){c.abort(l)}},abort:l=>{i("closing webtransport muxer with err:",l);try{r.close()}catch(d){i.error("webtransport session threw error during close",d)}},...hh()};return c}}}function cb(r,e){return e.filter(n=>!!r.find(o=>te(n,o))).length===e.length}var FC=Object.values(Nn).map(r=>r.decoder).reduce((r,e)=>r.or(e));function $C(r){return Qe.decode(FC.decode(r))}function $3(r){if(!Ei.matches(r))throw new hn("Invalid multiaddr, was not a WebTransport address");let e=r.stringTuples(),t=e.filter(([s,a])=>s===ee("certhash").code).map(([s,a])=>$C(a??"")),n=e.filter(([s,a])=>s===ee("p2p").code).map(([s,a])=>Re(a??""))[0],o=r.toOptions(),i=o.host;return o.family===6&&i?.includes(":")&&(i=`[${i}]`),{url:`https://${i}:${o.port}`,certhashes:t,remotePeer:n}}var lb=globalThis.WebTransport;var V3=class{log;components;config;metrics;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webtransport"),this.components=e,this.config={...t,maxInboundStreams:t.maxInboundStreams??1e3,certificates:t.certificates??[]},e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webtransport_dialer_events_total",{label:"event",help:"Total count of WebTransport dialer events by type"})})}[Symbol.toStringTag]="@libp2p/webtransport";[dn]=!0;[Ie]=["@libp2p/transport"];async dial(e,t){t?.signal?.throwIfAborted(),this.log("dialing %s",e),t=t??{};let{url:n,certhashes:o,remotePeer:i}=$3(e),s,a,c=()=>{},l=!1,d=!1,u=!1;try{this.metrics?.dialerEvents.increment({pending:!0});let f=new lb(`${n}/.well-known/libp2p-webtransport?type=noise`,{serverCertificateHashes:o.map(h=>({algorithm:"sha-256",value:h.digest}))});if(c=h=>{if(!l)try{this.metrics?.dialerEvents.increment({[h]:!0}),f.close()}catch(p){this.log.error("error closing wt session",p)}finally{a!=null&&(a.timeline.close=Date.now()),l=!0}},s=()=>{c(d?"noise_timeout":"ready_timeout")},t.signal?.addEventListener("abort",s,{once:!0}),this.log("wait for session to be ready"),t.onProgress?.(new H("webtransport:wait-for-session")),await Promise.race([f.closed,f.ready]),this.log("session became ready"),d=!0,this.metrics?.dialerEvents.increment({ready:!0}),f.closed.catch(h=>{this.log.error("error on remote wt session close",h)}).finally(()=>{c("remote_close")}),u=await Ce(this.authenticateWebTransport({wt:f,remotePeer:i,certhashes:o,...t}),t.signal),!u)throw new ul("Failed to authenticate webtransport");return this.metrics?.dialerEvents.increment({open:!0}),a={close:async()=>{this.log("closing webtransport"),c("close")},abort:h=>{this.log("aborting webtransport due to passed err",h),c("abort")},remoteAddr:e,timeline:{open:Date.now()},log:this.components.logger.forComponent("libp2p:webtransport:maconn"),...hh()},await t.upgrader.upgradeOutbound(a,{skipEncryption:!0,muxerFactory:ab(f,f.incomingBidirectionalStreams.getReader(),this.components.logger,this.config),skipProtection:!0,onProgress:t.onProgress})}catch(f){throw this.log.error("caught wt session err",f),c(u?"upgrade_error":d?"noise_error":"ready_error"),f}finally{s!=null&&t.signal?.removeEventListener("abort",s)}}async authenticateWebTransport({wt:e,remotePeer:t,certhashes:n,onProgress:o,signal:i}){i?.throwIfAborted(),o?.(new H("webtransport:open-authentication-stream"));let s=await e.createBidirectionalStream(),a=s.writable.getWriter(),c=s.readable.getReader(),l={source:async function*(){for(;;){let f=await c.read();if(f.value!=null&&(yield f.value),f.done)break}}(),sink:async f=>{for await(let h of f){await Ce(a.ready,i);let p=h instanceof Uint8Array?h:h.subarray();a.write(p).catch(m=>{this.log.error("could not write chunk during authentication of WebTransport stream",m)})}}},d=$s()(this.components);o?.(new H("webtransport:secure-outbound-connection"));let{remoteExtensions:u}=await d.secureOutbound(l,{signal:i,remotePeer:t});if(o?.(new H("webtransport:close-authentication-stream")),a.close().catch(f=>{this.log.error(`Failed to close authentication stream writer: ${f.message}`)}),c.cancel().catch(f=>{this.log.error(`Failed to close authentication stream reader: ${f.message}`)}),!cb(u?.webtransportCerthashes??[],n.map(f=>f.bytes)))throw new C("Our certhashes are not a subset of the remote's reported certhashes");return!0}createListener(e){return M3(this.components,{...e,certificates:this.config.certificates,maxInboundStreams:this.config.maxInboundStreams})}listenFilter(){return[]}dialFilter(e){return globalThis.WebTransport==null?[]:e.filter(t=>{if(!Ei.exactMatch(t))return!1;let{url:n,certhashes:o}=$3(t);return n!=null&&o.length>0})}};function ub(r={}){return e=>new V3(e,r)}var K3=fr(J1(),1);function db(r,e){let t=e.map((n,o)=>({record:_n(n),index:o}));return t.sort((n,o)=>{let i=n.record.sequence,s=o.record.sequence;if(i>s)return-1;if(i<s)return 1;if(n.record.validityType===ar.ValidityType.EOL&&o.record.validityType===ar.ValidityType.EOL){let a=K3.default.fromString(n.record.validity).toDate(),c=K3.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var ph="2.2.1",mh="libp2p";var hb="5.1.0-e58e49c",pb="helia";var mb={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dnsaddr/va1.bootstrap.libp2p.io/p2p/12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function gh(r={}){let e=`${pb}/${hb} ${mh}/${ph} UserAgent=${globalThis.navigator.userAgent}`;return{privateKey:r.privateKey,dns:r.dns,addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[r3(),Hw(),Kw(),ub(),sb()],connectionEncrypters:[$s()],streamMuxers:[y9(),ww()],peerDiscovery:[L9(mb)],services:{autoNAT:E9(),dcutr:X9(),delegatedRouting:()=>v7("https://delegated-ipfs.dev",{filterProtocols:["unknown","transport-bitswap","transport-ipfs-gateway-http"],filterAddrs:["https","webtransport","webrtc","webrtc-direct","wss"]}),dht:Hy({clientMode:!0,validators:{ipns:sd},selectors:{ipns:db}}),identify:uy({agentVersion:e}),identifyPush:dy({agentVersion:e}),keychain:zf(r.keychain),ping:vw()}}}var VC=32,{code:KC}=ee("dnsaddr"),H3=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}},Ni=async function(e,t={}){let n=t.maxRecursiveDepth??VC;if(n===0)throw new H3("Max recursive depth reached");let[,o]=e.stringTuples().find(([l])=>l===KC)??[],s=await(t?.dns??i1()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[gr.TXT]}),a=e.getPeerId(),c=[];for(let l of s.Answer){let d=l.data.replace(/["']/g,"").trim().split("=")[1];if(d==null||a!=null&&!d.includes(a))continue;let u=Q(d);if(d.startsWith("/dnsaddr")){let f=await u.resolve({...t,maxRecursiveDepth:n-1});c.push(...f.map(h=>h.toString()))}else c.push(u.toString())}return c};var HC={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Ni}},transportManager:{faultTolerance:ao.FATAL_ALL}};async function gb(r){let e=na(HC,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new C("Private network is enforced, but no protector was provided");return e}var la;(function(r){let e;(function(o){let i;o.codec=()=>(i==null&&(i=oe((s,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),s.key!=null&&s.key!==""&&(a.uint32(10),a.string(s.key)),s.value!=null&&s.value.byteLength>0&&(a.uint32(18),a.bytes(s.value)),c.lengthDelimited!==!1&&a.ldelim()},(s,a,c={})=>{let l={key:"",value:se(0)},d=a==null?s.len:s.pos+a;for(;s.pos<d;){let u=s.uint32();switch(u>>>3){case 1:{l.key=s.string();break}case 2:{l.value=s.bytes();break}default:{s.skipType(u&7);break}}}return l})),i),o.encode=s=>ne(s,o.codec()),o.decode=(s,a)=>re(s,o.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let i;o.codec=()=>(i==null&&(i=oe((s,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),s.key!=null&&s.key!==""&&(a.uint32(10),a.string(s.key)),s.value!=null&&(a.uint32(18),wh.codec().encode(s.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(s,a,c={})=>{let l={key:""},d=a==null?s.len:s.pos+a;for(;s.pos<d;){let u=s.uint32();switch(u>>>3){case 1:{l.key=s.string();break}case 2:{l.value=wh.codec().decode(s,s.uint32(),{limits:c.limits?.value});break}default:{s.skipType(u&7);break}}}return l})),i),o.encode=s=>ne(s,o.codec()),o.decode=(s,a)=>re(s,o.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=oe((o,i,s={})=>{if(s.lengthDelimited!==!1&&i.fork(),o.addresses!=null)for(let a of o.addresses)i.uint32(10),yh.codec().encode(a,i);if(o.protocols!=null)for(let a of o.protocols)i.uint32(18),i.string(a);if(o.publicKey!=null&&(i.uint32(34),i.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(i.uint32(42),i.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())i.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},i);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())i.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},i);s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{if(s.limits?.addresses!=null&&a.addresses.length===s.limits.addresses)throw new Me('Decode error - map field "addresses" had too many elements');a.addresses.push(yh.codec().decode(o,o.uint32(),{limits:s.limits?.addresses$}));break}case 2:{if(s.limits?.protocols!=null&&a.protocols.length===s.limits.protocols)throw new Me('Decode error - map field "protocols" had too many elements');a.protocols.push(o.string());break}case 4:{a.publicKey=o.bytes();break}case 5:{a.peerRecordEnvelope=o.bytes();break}case 6:{if(s.limits?.metadata!=null&&a.metadata.size===s.limits.metadata)throw new Sa('Decode error - map field "metadata" had too many elements');let d=r.Peer$metadataEntry.codec().decode(o,o.uint32());a.metadata.set(d.key,d.value);break}case 7:{if(s.limits?.tags!=null&&a.tags.size===s.limits.tags)throw new Sa('Decode error - map field "tags" had too many elements');let d=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:s.limits?.tags$value}});a.tags.set(d.key,d.value);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>ne(o,r.codec()),r.decode=(o,i)=>re(o,r.codec(),i)})(la||(la={}));var yh;(function(r){let e;r.codec=()=>(e==null&&(e=oe((t,n,o={})=>{o.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)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={multiaddr:se(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.multiaddr=t.bytes();break}case 2:{i.isCertified=t.bool();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>ne(t,r.codec()),r.decode=(t,n)=>re(t,r.codec(),n)})(yh||(yh={}));var wh;(function(r){let e;r.codec=()=>(e==null&&(e=oe((t,n,o={})=>{o.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)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.value=t.uint32();break}case 2:{i.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>ne(t,r.codec()),r.decode=(t,n)=>re(t,r.codec(),n)})(wh||(wh={}));function ua(r,e){let t=la.decode(e);if(t.publicKey!=null&&r.publicKey==null){let i=rt(t.publicKey);r=En(i)}let n=new Map,o=BigInt(Date.now());for(let[i,s]of t.tags.entries())s.expiry!=null&&s.expiry<o||n.set(i,s);return{...t,id:r,addresses:t.addresses.map(({multiaddr:i,isCertified:s})=>({multiaddr:Q(i),isCertified:s??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var q3="/peers/";function da(r){if(!cl(r)||r.type==null)throw new C("Invalid PeerId");let e=r.toCID().toString();return new De(`${q3}${e}`)}async function yb(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=Q(o.multiaddr)),!Bo(o.multiaddr))throw new C("Multiaddr was invalid");if(!await e(r,o.multiaddr))continue;let i=o.isCertified??!1,s=o.multiaddr.toString(),a=n.get(s);a!=null?o.isCertified=a.isCertified||i:n.set(s,{multiaddr:o.multiaddr,isCertified:i})}return[...n.values()].sort((o,i)=>o.multiaddr.toString().localeCompare(i.multiaddr.toString())).map(({isCertified:o,multiaddr:i})=>({isCertified:o,multiaddr:i.bytes}))}async function xh(r,e,t,n){if(e==null)throw new C("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new C("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new C("peer id did not match existing peer id");let i=o?.addresses??[],s=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,l=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(i=[],e.multiaddrs!=null&&i.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&i.push(...e.addresses)),e.protocols!=null&&(s=new Set(e.protocols)),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=bh(f,{validate:wb})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=bh(f,{validate:bb,map:xb})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&i.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&i.push(...e.addresses),e.protocols!=null&&(s=new Set([...s,...e.protocols])),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,p]of f)p==null?a.delete(h):a.set(h,p);a=bh([...a.entries()],{validate:wb})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,m]of f)m==null?h.delete(p):h.set(p,m);c=bh([...h.entries()],{validate:bb,map:xb})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let d;o?.id.publicKey!=null?d=Lt(o.id.publicKey):e.publicKey!=null?d=Lt(e.publicKey):r.publicKey!=null&&(d=Lt(r.publicKey));let u={addresses:await yb(r,n.addressFilter??(async()=>!0),i),protocols:[...s.values()].sort((f,h)=>f.localeCompare(h)),metadata:a,tags:c,publicKey:d,peerRecordEnvelope:l};return r.type!=="RSA"&&delete u.publicKey,u}function bh(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([i],[s])=>i.localeCompare(s)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function wb(r,e){if(typeof r!="string")throw new C("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new C("Metadata value must be a Uint8Array")}function bb(r,e){if(typeof r!="string")throw new C("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new C("Tag value must be an integer");if(e.value<0||e.value>100)throw new C("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new C("Tag ttl must be an integer");if(e.ttl<0)throw new C("Tag ttl must be between greater than 0")}}function xb(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}function Eh(r,e){let t=r.toString().split("/")[2],n=X.parse(t,lt),o=vn(n);return ua(o,e)}function qC(r){return r==null?{}:{prefix:q3,filters:(r.filters??[]).map(e=>({key:t,value:n})=>e(Eh(t,n))),orders:(r.orders??[]).map(e=>(t,n)=>e(Eh(t.key,t.value),Eh(n.key,n.value)))}}var vh=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=wi({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(da(e))}async delete(e){if(this.peerId.equals(e))throw new C("Cannot delete self peer");await this.datastore.delete(da(e))}async load(e){let t=await this.datastore.get(da(e));return ua(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),i=await xh(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,i,n,o)}async patch(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),i=await xh(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,i,n,o)}async merge(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),i=await xh(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,i,n,o)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(qC(e??{}))){let o=Eh(t,n);o.id.equals(this.peerId)||(yield o)}}async#e(e){try{let t=await this.datastore.get(da(e)),n=ua(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.name!=="NotFoundError")throw t}return{}}async#t(e,t,n,o){let i=la.encode(t);return n!=null&&te(i,n)?{peer:ua(e,i),previous:o,updated:!1}:(await this.datastore.put(da(e),i),{peer:ua(e,i),previous:o,updated:!0})}};var W3=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 vh(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(t))e(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(e){this.log.trace("all await read lock");let t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await Pc(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await Sr.openAndCertify(e,zt.DOMAIN),o=vn(n.publicKey.toCID());if(t?.equals(o)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,o),!1;let i=zt.createFromProtobuf(n.payload),s;try{s=await this.get(o)}catch(a){if(a.name!=="NotFoundError")throw a}if(s?.peerRecordEnvelope!=null){let a=await Sr.createFromProtobuf(s.peerRecordEnvelope),c=zt.createFromProtobuf(a.payload);if(c.seqNumber>=i.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",c.seqNumber,i.seqNumber),!1}return await this.patch(i.peerId,{peerRecordEnvelope:e,addresses:i.multiaddrs.map(a=>({isCertified:!0,multiaddr:a}))}),!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 Eb(r,e={}){return new W3(r,e)}function vb(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var WC=r=>r;function z3(r,e){let t=r.getPeerId();return t!=null&&Re(t).equals(e)&&(r=r.decapsulate(Q(`/p2p/${e.toString()}`))),r}var Sh=class{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(o.map(i=>i.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??WC,this._updatePeerStoreAddresses=vb(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.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>Q(t))).map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>Q(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>Q(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>Q(e))}addObservedAddr(e){e=z3(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=z3(e,this.components.peerId);let t=e.toString(),o=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=z3(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,o])=>o.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>Q(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var Sb;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(Sb||(Sb={}));var Ah=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},Ih=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},fa=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},rl=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},_h=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},Th=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},kh=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},nl=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},Bi=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},Ch=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},Ph=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},Oi=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Mi=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},Rh=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}};var G3=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=ko())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>gl(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")}},GC=["metrics","connectionProtector","dns"],QC=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Ab(r={}){let e=new G3(r);return new Proxy(e,{get(n,o,i){if(typeof o=="string"&&!QC.includes(o)){let s=e.components[o];if(s==null&&!GC.includes(o))throw new Ah(`${o} not set`);return s}return Reflect.get(n,o,i)},set(n,o,i){return typeof o=="string"?e.components[o]=i:Reflect.set(n,o,i),!0}})}function Ib(r){let e={};for(let t of Object.values(r.components))for(let n of YC(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of XC(t))if(e[n]!==!0)throw new Ih(`Service "${jC(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function YC(r){return Array.isArray(r?.[Ie])?r[Ie]:[]}function XC(r){return Array.isArray(r?.[Vr])?r[Vr]:[]}function jC(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function _b(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!Bt(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}function Lh(r){if(cl(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:Re(t),r.forEach(n=>{if(!Bo(n))throw new hn("Invalid multiaddr");let o=n.getPeerId();if(o==null){if(e!=null)throw new C("Multiaddrs must all have the same peer id or have no peer id")}else{let i=Re(o);if(e?.equals(i)!==!0)throw new C("Multiaddrs must all have the same peer id or have no peer id")}})}return{peerId:e,multiaddrs:r}}var ZC=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function Tb(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??ZC;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var kb="last-dial-failure",Cb="last-dial-success";var Dh=100,Nh=50;var Pb={maxConnections:Dh,allow:[]},Bh=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Pb.maxConnections,this.allow=t.allow??Pb.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;let n=new gt;for(let a of e){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let l=await this.peerStore.get(c);n.set(c,[...l.tags.values()].reduce((d,u)=>d+u.value,0))}catch(l){l.name!=="NotFoundError"&&this.log.error("error loading peer tags",l)}}}let o=this.sortConnections(e,n),i=Math.max(t-this.maxConnections,0),s=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(l=>a.remoteAddr.toString().startsWith(l.toString()))||s.push(a),s.length===i)break;await Promise.all(s.map(async a=>{await Tb(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:s})}sortConnections(e,t){return e.sort((n,o)=>{let i=n.timeline.open,s=o.timeline.open;return i<s?1:i>s?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let i=t.get(n.remotePeer)??0,s=t.get(o.remotePeer)??0;return i>s?1:i<s?-1:0})}};var Oh=class extends Mt{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};function Q3(r){try{let{address:e}=r.nodeAddress();return!!Bt(e)}catch{return!0}}function JC(r,e){let t=Vp.exactMatch(r.multiaddr),n=Vp.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let o=Ps.exactMatch(r.multiaddr),i=Ps.exactMatch(e.multiaddr);if(o&&!i)return-1;if(!o&&i)return 1;let s=Ec.exactMatch(r.multiaddr),a=Ec.exactMatch(e.multiaddr);if(s&&!a)return-1;if(!s&&a)return 1;let c=Sc.exactMatch(r.multiaddr),l=Sc.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let d=vc.exactMatch(r.multiaddr),u=vc.exactMatch(e.multiaddr);if(d&&!u)return-1;if(!d&&u)return 1;let f=Ei.exactMatch(r.multiaddr),h=Ei.exactMatch(e.multiaddr);return f&&!h?-1:!f&&h?1:0}function eP(r,e){let t=Q3(r.multiaddr),n=Q3(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function tP(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function rP(r,e){let t=ir.exactMatch(r.multiaddr),n=ir.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Rb(r){return r.sort(JC).sort(tP).sort(rP).sort(eP)}async function Lb(r,e){let t=!1;for(let o of Ls.keys())if(t=r.protoNames().includes(o),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(o=>o.toString())),n}var Mh={maxParallelDials:Nh,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:Ni}},Uh=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Mh.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Mh.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Mh.dialTimeout,this.connections=t.connections??new gt,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,$(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))Ls.set(n,o);this.queue=new Oh({concurrency:t.maxParallelDials??Mh.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{n.detail.name!==ht.name&&this.log.error("error in dial queue - %e",n.detail)})}start(){this.shutDownController=new AbortController,$(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=Lh(e),i=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(i?.status==="open")return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new H("dial-queue:already-connected")),i;let s=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let l of o)if(c.has(l.toString()))return!0;return!1});if(s!=null){this.log("joining existing dial target for %p",n);for(let a of o)s.options.multiaddrs.add(a.toString());return t.onProgress?.(new H("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Dn("Dial queue is full");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),t.onProgress?.(new H("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a?.onProgress?.(new H("dial-queue:start-dial"));let c=this.createDialAbortController(a?.signal),l;try{l=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),a?.onProgress?.(new H("dial-queue:calculated-addresses",l)),l.map(({multiaddr:d})=>d.toString()).forEach(d=>{a?.multiaddrs.add(d)})}catch(d){throw c.clear(),d}try{let d=0,u=[];for(let f of l){if(d===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",d,n),new Dn("Peer had more than maxPeerAddrsToDial");d++;try{let h=await this.components.transportManager.dial(f.multiaddr,{...a,signal:c});this.log("dial to %a succeeded",f.multiaddr);try{await this.components.peerStore.merge(h.remotePeer,{multiaddrs:[h.remoteAddr],metadata:{[Cb]:M(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}return h}catch(h){if(this.log.error("dial failed to %a",f.multiaddr,h),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[kb]:M(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}if(c.aborted)throw new Ur(h.message);u.push(h)}}throw u.length===1?u[0]:new AggregateError(u,"All multiaddr dials failed")}finally{c.clear()}},{peerId:n,priority:t.priority??Z3,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal,onProgress:t.onProgress})}createDialAbortController(e){let t=he([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return $(1/0,t),t}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(u=>({multiaddr:Q(u),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Dn("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new nl("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let u=await this.components.peerStore.get(e);o.push(...u.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:f})=>f.toString()))}catch(u){if(u.name!=="NotFoundError")throw u}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let u=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:f})=>f.toString())),o.push(...u.multiaddrs.map(f=>({multiaddr:f,isCertified:!1})))}catch(u){u.name!=="NoPeerRoutersError"&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,u)}}}let i=(await Promise.all(o.map(async u=>{let f=await Lb(u.multiaddr,{dns:this.components.dns,...n,log:this.log});return f.length===1&&f[0].equals(u.multiaddr)?u:f.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let u=`/p2p/${e.toString()}`;i=i.map(f=>f.multiaddr.protos().pop()?.path===!0?f:f.multiaddr.getPeerId()==null?{multiaddr:f.multiaddr.encapsulate(u),isCertified:f.isCertified}:f)}let s=i.filter(u=>{if(this.components.transportManager.dialTransportForMultiaddr(u.multiaddr)==null)return!1;let f=u.multiaddr.getPeerId();return e!=null&&f!=null?e.equals(f):!0}),a=new Map;for(let u of s){let f=u.multiaddr.toString(),h=a.get(f);if(h!=null){h.isCertified=h.isCertified||u.isCertified||!1;continue}a.set(f,u)}let c=[...a.values()];if(c.length===0)throw new Bi("The dial request has no valid addresses");let l=[];for(let u of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(u.multiaddr)||l.push(u);let d=this.addressSorter==null?Rb(l):l.sort(this.addressSorter);if(d.length===0)throw new nl("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:u})=>u.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",d.map(({multiaddr:u})=>u.toString())),d}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnLimitedConnection===!1?n.find(o=>!ir.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var Fb=fr(Mb(),1);var oP=Object.prototype.toString,iP=r=>oP.call(r)==="[object Error]",sP=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function J3(r){return r&&iP(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:sP.has(r.message):!1}var e4=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}},Ub=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function t4(r,e){return new Promise((t,n)=>{e={onFailedAttempt(){},retries:10,shouldRetry:()=>!0,...e};let o=Fb.default.operation(e),i=()=>{o.stop(),n(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",i,{once:!0});let s=()=>{e.signal?.removeEventListener("abort",i),o.stop()};o.attempt(async a=>{try{let c=await r(a);s(),t(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof e4)throw c.originalError;if(c instanceof TypeError&&!J3(c))throw c;if(Ub(c,a,e),await e.shouldRetry(c)||(o.stop(),n(c)),await e.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(l){Ub(l,a,e),s(),n(l)}}})})}var Fh=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 Ut({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(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);$b(t)&&(this.queue.has(e)||this.queue.add(async n=>{await t4(async o=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(i){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,o,this.retries,i),i}},{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 o={};[...t.tags.keys()].forEach(i=>{i.startsWith(so)&&(o[i]=void 0)}),await this.peerStore.merge(e,{tags:o}),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=>$b(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)})}stop(){this.started=!1,this.queue.abort()}};function $b(r){for(let e of r.tags.keys())if(e.startsWith(so))return!0;return!1}var Z3=50,r4={maxConnections:Dh,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},$h=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??r4.maxConnections,this.maxConnections<1)throw new C("Connection Manager maxConnections must be greater than 0");this.connections=new gt,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=>Q(n)),this.deny=(t.deny??[]).map(n=>Q(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??r4.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new aa({points:t.inboundConnectionThreshold??r4.inboundConnectionThreshold,duration:1}),this.connectionPruner=new Bh({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Uh(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??Nh,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:Ni},connections:this.connections}),this.reconnectQueue=new Fh({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 o of n.streams){let i=`${o.direction} ${o.protocol??"unnegotiated"}`;e[i]=(e[i]??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 o of n){let i={};for(let s of o.streams){let a=`${s.direction} ${s.protocol??"unnegotiated"}`;i[a]=(i[a]??0)+1}for(let[s,a]of Object.entries(i))e[s]=e[s]??[],e[s].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((s,a)=>s-a);let i=Math.floor(o.length*.9);t[n]=o[i]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await wt(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 Tt(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,o=!this.connections.has(n),i=this.connections.get(n)??[];i.push(t),this.connections.set(n,i),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,i=(this.connections.get(n)??[]).filter(s=>s.id!==t.id);this.connections.set(n,i),i.length===0&&(this.log("onDisconnect remove all connections for peer %p",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new Fr("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:n}=Lh(e);if(this.peerId.equals(n))throw new Ki("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p",n),t.onProgress?.(new H("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??Z3});if(o.status!=="open")throw new $i("Remote closed connection during opening");let i=this.connections.get(o.remotePeer);i==null&&(i=[],this.connections.set(o.remotePeer,i));let s=!1;for(let a of i)if(a.id===o.id&&(s=!0),t.force!==!0&&a.id!==o.id&&a.remoteAddr.equals(o.remoteAddr))return o.abort(new hn("Duplicate multiaddr connection")),a;return s||i.push(o),o}finally{this.outboundPendingConnections--}}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(i){o.abort(i)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let o=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!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)}};var lP=1e4,uP="1.0.0",dP="ping",fP="ipfs",Vb=32,hP=!0,Vh=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??fP}/${dP}/${uP}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??lP,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??hP,this.timeout=new cn({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Ie]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,$(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}),o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),i=Ai(o);t=Date.now(),await Promise.all([i.write(Kt(Vb),{signal:n}),i.read(Vb,{signal:n})]),e.rtt=Date.now()-t,await i.unwrap().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",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)}};var Kh=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new fa("No content routers available");let n=this,o=new nr;for await(let i of $t(...n.routers.map(s=>s.findProviders(e,t))))i!=null&&(i.multiaddrs.length>0&&await this.components.peerStore.merge(i.id,{multiaddrs:i.multiaddrs}),!o.has(i.id)&&(o.add(i.id),yield i))}async provide(e,t={}){if(this.routers.length===0)throw new fa("No content routers available");await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new fa("No content routers available");await Promise.all(this.routers.map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new Fr;await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new Fr;return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var Hh=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??[]}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new rl("No peer routers available");if(e.toString()===this.peerId.toString())throw new _h("Should not try to find self");let n=this,o=$t(...this.routers.map(i=>async function*(){try{yield await i.findPeer(e,t)}catch(s){n.log.error(s)}}()));for await(let i of o)if(i!=null)return i.multiaddrs.length>0&&await this.peerStore.merge(i.id,{multiaddrs:i.multiaddrs}),i;throw new Oe}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new rl("No peer routers available");let n=this,o=Sn(1024);for await(let i of vr(async function*(){let s=$t(...n.routers.map(a=>a.getClosestPeers(e,t)));for await(let a of s)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",c);return}return a}}()))i!=null&&(i.multiaddrs.length>0&&await this.peerStore.merge(i.id,{multiaddrs:i.multiaddrs}),!o.has(i.id.toMultihash().bytes)&&(o.add(i.id.toMultihash().bytes),yield i))}};var qh=class extends ge{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,$(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,$(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=he([this.shutdownController.signal,e?.signal]);$(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=J(),yield(await hr(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,$(1/0,this.walkController.signal);let e=he([this.walkController.signal,this.shutdownController.signal]);$(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=Kt(32),i=Date.now();for await(let s of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",s.id,Date.now()-i,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:s}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await Ce(this.needNext.promise,e)),i=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("randomwalk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var n4=32,o4=64,Wh=class{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new Th(`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))throw new kh(`Handler already registered for protocol ${e}`);let o=na.bind({ignoreUndefined:!0})({maxInboundStreams:n4,maxOutboundStreams:o4},n);this.handlers.set(e,{handler:t,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(t==null)throw new C("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{for(let o of n.protocols){let i=this.topologies.get(o);if(i!=null)for(let s of i.values())s.filter?.has(t)!==!1&&(s.filter?.remove(t),s.onDisconnect?.(t))}}).catch(n=>{n.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(i=>!t.protocols.includes(i));for(let i of o){let s=this.topologies.get(i);if(s!=null)for(let a of s.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;for(let i of t){let s=this.topologies.get(i);if(s!=null)for(let a of s.values())n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var zh=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=new Map,this.listeners=N1({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??ao.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new C("Transport must have a valid tag");if(this.transports.has(t))throw new C(`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 o=n.pop();o!=null&&e.push(o.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 Rh(`No transport available for address ${String(e)}`);return t?.onProgress?.(new H("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 Fr("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[n,o]of this.transports.entries()){let i=o.listenFilter(e),s=[];for(let l of i){this.log("creating listener for %s on %a",n,l);let d=o.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(n)??[];u==null&&(u=[],this.listeners.set(n,u)),u.push(d),d.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:d})}),d.addEventListener("close",()=>{let f=u.findIndex(h=>h===d);u.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:d})}),s.push(d.listen(l))}if(s.length===0){t.push(n);continue}if((await Promise.allSettled(s)).find(l=>l.status==="fulfilled")==null&&this.faultTolerance!==ao.NO_FATAL)throw new Bi(`Transport (${n}) could not listen on any available address`)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===ao.FATAL_ALL)throw new Bi(n);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var _t="/multistream/1.0.0";var pP=M(`
|
|
39
39
|
`);async function Fi(r,e,t){await r.write(e,t)}async function Kb(r,e,t){await r.writeV(e,t)}async function mP(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==pP[0])throw e.log.error("Invalid mss message - missing newline",t),new de("Missing newline");return t.sublist(0,-1)}async function Go(r,e){let t=await mP(r,e);return V(t.subarray())}async function ol(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return gP(r,e[0],t);let n=Tn(r,{...t,maxDataLength:1024}),o=e.shift();if(o==null)throw new Error("At least one protocol must be specified");t.log.trace('select: write ["%s", "%s"]',_t,o);let i=M(`${_t}
|
|
40
40
|
`),s=M(`${o}
|
|
41
41
|
`);await Kb(n,[i,s],t),t.log.trace("select: reading multistream-select header");let a=await Go(n,t);if(t.log.trace('select: read "%s"',a),a===_t&&(t.log.trace("select: reading protocol response"),a=await Go(n,t),t.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(let c of e){t.log.trace('select: write "%s"',c),await Fi(n,M(`${c}
|