helia 1.2.2 → 1.3.0
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/storage.d.ts +3 -3
- package/dist/src/storage.d.ts.map +1 -1
- package/dist/src/storage.js.map +1 -1
- package/dist/src/utils/networked-storage.d.ts +3 -3
- package/dist/src/utils/networked-storage.d.ts.map +1 -1
- package/dist/src/utils/networked-storage.js +2 -2
- package/dist/src/utils/networked-storage.js.map +1 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +1 -1
- package/src/storage.ts +3 -3
- package/src/utils/networked-storage.ts +5 -5
- package/src/version.ts +1 -1
package/dist/index.min.js
CHANGED
|
@@ -49,7 +49,7 @@ if (cid) {
|
|
|
49
49
|
// Make sure to use cid instead of value
|
|
50
50
|
doSomethingWithCID(cid)
|
|
51
51
|
}
|
|
52
|
-
`});var JI=Xe(()=>{ZI();pd();ao();r5();Yu()});var s5,E5e,eA=Xe(()=>{AI();TI();DI();CI();PI();W8();kI();X8();NI();OI();HI();WI();YI();QI();JI();s5={...V8,...q8,...z8,...H8,...$8,...G8,...Y8,...Q8,...j8,...Z8},E5e={...n5,...i5}});function Wc(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}var yd=Xe(()=>{});function wd(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Wc(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}var o5=Xe(()=>{yd()});function rA(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var tA,a5,r$,bd,c5=Xe(()=>{eA();o5();tA=rA("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),a5=rA("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=wd(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),r$={utf8:tA,"utf-8":tA,hex:s5.base16,latin1:a5,ascii:a5,binary:a5,...s5},bd=r$});var nA={};Re(nA,{toString:()=>n$});function n$(r,e="utf8"){let t=bd[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}var iA=Xe(()=>{c5()});var sA={};Re(sA,{fromString:()=>i$});function i$(r,e="utf8"){let t=bd[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Wc(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}var oA=Xe(()=>{c5();yd()});var aA={};Re(aA,{concat:()=>s$});function s$(r,e){e||(e=r.reduce((i,s)=>i+s.length,0));let t=wd(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return Wc(t)}var cA=Xe(()=>{o5();yd()});var u5=D((N5e,pA)=>{"use strict";var lA=oI(),Yc=yI(),{names:Xu}=bI(),{toString:Ed}=(iA(),uh(nA)),{fromString:o$}=(oA(),uh(sA)),{concat:a$}=(cA(),uh(aA)),Qc={};for(let r in Xu){let e=r;Qc[Xu[e]]=e}Object.freeze(Qc);function c$(r){if(!(r instanceof Uint8Array))throw new Error("must be passed a Uint8Array");return Ed(r,"base16")}function l$(r){return o$(r,"base16")}function u$(r){if(!(r instanceof Uint8Array))throw new Error("must be passed a Uint8Array");return Ed(lA.encode("base58btc",r)).slice(1)}function h$(r){let e=r instanceof Uint8Array?Ed(r):r;return lA.decode("z"+e)}function uA(r){if(!(r instanceof Uint8Array))throw new Error("multihash must be a Uint8Array");if(r.length<2)throw new Error("multihash too short. must be > 2 bytes.");let e=Yc.decode(r);if(!fA(e))throw new Error(`multihash unknown function code: 0x${e.toString(16)}`);r=r.slice(Yc.decode.bytes);let t=Yc.decode(r);if(t<0)throw new Error(`multihash invalid length: ${t}`);if(r=r.slice(Yc.decode.bytes),r.length!==t)throw new Error(`multihash length inconsistent: 0x${Ed(r,"base16")}`);return{code:e,name:Qc[e],length:t,digest:r}}function f$(r,e,t){if(!r||e===void 0)throw new Error("multihash encode requires at least two args: digest, code");let n=hA(e);if(!(r instanceof Uint8Array))throw new Error("digest should be a Uint8Array");if(t==null&&(t=r.length),t&&r.length!==t)throw new Error("digest length should be equal to specified length.");let i=Yc.encode(n),s=Yc.encode(t);return a$([i,s,r],i.length+s.length+r.length)}function hA(r){let e=r;if(typeof r=="string"){if(Xu[r]===void 0)throw new Error(`Unrecognized hash function named: ${r}`);e=Xu[r]}if(typeof e!="number")throw new Error(`Hash function code should be a number. Got: ${e}`);if(Qc[e]===void 0&&!l5(e))throw new Error(`Unrecognized function code: ${e}`);return e}function l5(r){return r>0&&r<16}function fA(r){return!!(l5(r)||Qc[r])}function dA(r){uA(r)}function d$(r){return dA(r),r.subarray(0,2)}pA.exports={names:Xu,codes:Qc,toHexString:c$,fromHexString:l$,toB58String:u$,fromB58String:h$,decode:uA,encode:f$,coerceCode:hA,isAppCode:l5,validate:dA,prefix:d$,isValidCode:fA}});var DA=D(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});var g5=class{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;let t={value:e,done:!1};if(this.pullQueue.length){let n=this.pullQueue.shift();n&&n.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),this.highWaterMark!==void 0&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn(`EventIterator queue reached ${this.pushQueue.length} items`))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(let e of this.pullQueue)e.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(e){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(let t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{let t=Promise.reject(e);t.catch(()=>{}),this.pushQueue.push(t)}}remove(){Promise.resolve().then(()=>{this.removeCallback&&this.removeCallback()})}[Symbol.asyncIterator](){return{next:e=>{let t=this.pushQueue.shift();return t?(this.lowWaterMark!==void 0&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),t):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise((n,i)=>{this.pullQueue.push({resolve:n,reject:i})})},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}},Sd=class{constructor(e,{highWaterMark:t=100,lowWaterMark:n=1}={}){let i=new g5;i.highWaterMark=t,i.lowWaterMark=n,i.removeCallback=e({push:s=>i.push(s),stop:()=>i.stop(),fail:s=>i.fail(s),on:(s,o)=>{i.eventHandlers[s]=o}})||(()=>{}),this[Symbol.asyncIterator]=()=>i[Symbol.asyncIterator](),Object.freeze(this)}};Rd.EventIterator=Sd;Rd.default=Sd});var CA=D(ju=>{"use strict";Object.defineProperty(ju,"__esModule",{value:!0});var y5=DA();ju.EventIterator=y5.EventIterator;function _$(r,e,t){return new y5.EventIterator(({push:n})=>(this.addEventListener(r,n,e),()=>this.removeEventListener(r,n,e)),t)}ju.subscribe=_$;ju.default=y5.EventIterator});var b5=D((p6e,UA)=>{"use strict";var S$=typeof navigator<"u"&&navigator.product==="ReactNative";function R$(){return S$?"http://localhost":self.location?self.location.protocol+"//"+self.location.host:""}var Zu=self.URL,MA=R$(),w5=class{constructor(e="",t=MA){this.super=new Zu(e,t),this.path=this.pathname+this.search,this.auth=this.username&&this.password?this.username+":"+this.password:null,this.query=this.search&&this.search.startsWith("?")?this.search.slice(1):null}get hash(){return this.super.hash}get host(){return this.super.host}get hostname(){return this.super.hostname}get href(){return this.super.href}get origin(){return this.super.origin}get password(){return this.super.password}get pathname(){return this.super.pathname}get port(){return this.super.port}get protocol(){return this.super.protocol}get search(){return this.super.search}get searchParams(){return this.super.searchParams}get username(){return this.super.username}set hash(e){this.super.hash=e}set host(e){this.super.host=e}set hostname(e){this.super.hostname=e}set href(e){this.super.href=e}set password(e){this.super.password=e}set pathname(e){this.super.pathname=e}set port(e){this.super.port=e}set protocol(e){this.super.protocol=e}set search(e){this.super.search=e}set username(e){this.super.username=e}static createObjectURL(e){return Zu.createObjectURL(e)}static revokeObjectURL(e){Zu.revokeObjectURL(e)}toJSON(){return this.super.toJSON()}toString(){return this.super.toString()}format(){return this.toString()}};function I$(r){if(typeof r=="string")return new Zu(r).toString();if(!(r instanceof Zu)){let e=r.username&&r.password?`${r.username}:${r.password}@`:"",t=r.auth?r.auth+"@":"",n=r.port?":"+r.port:"",i=r.protocol?r.protocol+"//":"",s=r.host||"",o=r.hostname||"",a=r.search||(r.query?"?"+r.query:""),c=r.hash||"",l=r.pathname||"",u=r.path||l+a;return`${i}${e||t}${s||o+n}${u}${c}`}}UA.exports={URLWithLegacySupport:w5,URLSearchParams:self.URLSearchParams,defaultBase:MA,format:I$}});var VA=D((m6e,KA)=>{"use strict";var{URLWithLegacySupport:FA,format:A$}=b5();KA.exports=(r,e={},t={},n)=>{let i=e.protocol?e.protocol.replace(":",""):"http";i=(t[i]||n||i)+":";let s;try{s=new FA(r)}catch{s={}}let o=Object.assign({},e,{protocol:i||s.protocol,host:e.host||s.host});return new FA(r,A$(o)).toString()}});var zA=D((g6e,qA)=>{"use strict";var{URLWithLegacySupport:T$,format:D$,URLSearchParams:C$,defaultBase:P$}=b5(),k$=VA();qA.exports={URL:T$,URLSearchParams:C$,format:D$,relative:k$,defaultBase:P$}});var YA=D((x6e,WA)=>{function O$(){return!!(typeof window<"u"&&typeof window.process=="object"&&window.process.type==="renderer"||typeof process<"u"&&typeof process.versions=="object"&&process.versions.electron||typeof navigator=="object"&&typeof navigator.userAgent=="string"&&navigator.userAgent.indexOf("Electron")>=0)}WA.exports=O$});var gT=D(P5=>{"use strict";Object.defineProperty(P5,"__esModule",{value:!0});function $$(r){return typeof r.saveState<"u"&&typeof r.restoreState<"u"&&typeof r.cleanSavedState<"u"}P5.isSerializableHash=$$});var wT=D(th=>{"use strict";Object.defineProperty(th,"__esModule",{value:!0});var Mi=gT(),G$=i1(),W$=Li(),yT=function(){function r(e,t){this._finished=!1,this._inner=new e,this._outer=new e,this.blockSize=this._outer.blockSize,this.digestLength=this._outer.digestLength;var n=new Uint8Array(this.blockSize);t.length>this.blockSize?this._inner.update(t).finish(n).clean():n.set(t);for(var i=0;i<n.length;i++)n[i]^=54;this._inner.update(n);for(var i=0;i<n.length;i++)n[i]^=106;this._outer.update(n),Mi.isSerializableHash(this._inner)&&Mi.isSerializableHash(this._outer)&&(this._innerKeyedState=this._inner.saveState(),this._outerKeyedState=this._outer.saveState()),W$.wipe(n)}return r.prototype.reset=function(){if(!Mi.isSerializableHash(this._inner)||!Mi.isSerializableHash(this._outer))throw new Error("hmac: can't reset() because hash doesn't implement restoreState()");return this._inner.restoreState(this._innerKeyedState),this._outer.restoreState(this._outerKeyedState),this._finished=!1,this},r.prototype.clean=function(){Mi.isSerializableHash(this._inner)&&this._inner.cleanSavedState(this._innerKeyedState),Mi.isSerializableHash(this._outer)&&this._outer.cleanSavedState(this._outerKeyedState),this._inner.clean(),this._outer.clean()},r.prototype.update=function(e){return this._inner.update(e),this},r.prototype.finish=function(e){return this._finished?(this._outer.finish(e),this):(this._inner.finish(e),this._outer.update(e.subarray(0,this.digestLength)).finish(e),this._finished=!0,this)},r.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},r.prototype.saveState=function(){if(!Mi.isSerializableHash(this._inner))throw new Error("hmac: can't saveState() because hash doesn't implement it");return this._inner.saveState()},r.prototype.restoreState=function(e){if(!Mi.isSerializableHash(this._inner)||!Mi.isSerializableHash(this._outer))throw new Error("hmac: can't restoreState() because hash doesn't implement it");return this._inner.restoreState(e),this._outer.restoreState(this._outerKeyedState),this._finished=!1,this},r.prototype.cleanSavedState=function(e){if(!Mi.isSerializableHash(this._inner))throw new Error("hmac: can't cleanSavedState() because hash doesn't implement it");this._inner.cleanSavedState(e)},r}();th.HMAC=yT;function Y$(r,e,t){var n=new yT(r,e);n.update(t);var i=n.digest();return n.clean(),i}th.hmac=Y$;th.equal=G$.equal});var vT=D(k5=>{"use strict";Object.defineProperty(k5,"__esModule",{value:!0});var bT=wT(),ET=Li(),Q$=function(){function r(e,t,n,i){n===void 0&&(n=new Uint8Array(0)),this._counter=new Uint8Array(1),this._hash=e,this._info=i;var s=bT.hmac(this._hash,n,t);this._hmac=new bT.HMAC(e,s),this._buffer=new Uint8Array(this._hmac.digestLength),this._bufpos=this._buffer.length}return r.prototype._fillBuffer=function(){this._counter[0]++;var e=this._counter[0];if(e===0)throw new Error("hkdf: cannot expand more");this._hmac.reset(),e>1&&this._hmac.update(this._buffer),this._info&&this._hmac.update(this._info),this._hmac.update(this._counter),this._hmac.finish(this._buffer),this._bufpos=0},r.prototype.expand=function(e){for(var t=new Uint8Array(e),n=0;n<t.length;n++)this._bufpos===this._buffer.length&&this._fillBuffer(),t[n]=this._buffer[this._bufpos++];return t},r.prototype.clean=function(){this._hmac.clean(),ET.wipe(this._buffer),ET.wipe(this._counter),this._bufpos=0},r}();k5.HKDF=Q$});var _T=D(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});var Od=_u(),Ld=Li();uo.DIGEST_LENGTH=32;uo.BLOCK_SIZE=64;var xT=function(){function r(){this.digestLength=uo.DIGEST_LENGTH,this.blockSize=uo.BLOCK_SIZE,this._state=new Int32Array(8),this._temp=new Int32Array(64),this._buffer=new Uint8Array(128),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return r.prototype._initState=function(){this._state[0]=1779033703,this._state[1]=3144134277,this._state[2]=1013904242,this._state[3]=2773480762,this._state[4]=1359893119,this._state[5]=2600822924,this._state[6]=528734635,this._state[7]=1541459225},r.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},r.prototype.clean=function(){Ld.wipe(this._buffer),Ld.wipe(this._temp),this.reset()},r.prototype.update=function(e,t){if(t===void 0&&(t=e.length),this._finished)throw new Error("SHA256: can't update because hash was finished.");var n=0;if(this._bytesHashed+=t,this._bufferLength>0){for(;this._bufferLength<this.blockSize&&t>0;)this._buffer[this._bufferLength++]=e[n++],t--;this._bufferLength===this.blockSize&&(N5(this._temp,this._state,this._buffer,0,this.blockSize),this._bufferLength=0)}for(t>=this.blockSize&&(n=N5(this._temp,this._state,e,n,t),t%=this.blockSize);t>0;)this._buffer[this._bufferLength++]=e[n++],t--;return this},r.prototype.finish=function(e){if(!this._finished){var t=this._bytesHashed,n=this._bufferLength,i=t/536870912|0,s=t<<3,o=t%64<56?64:128;this._buffer[n]=128;for(var a=n+1;a<o-8;a++)this._buffer[a]=0;Od.writeUint32BE(i,this._buffer,o-8),Od.writeUint32BE(s,this._buffer,o-4),N5(this._temp,this._state,this._buffer,0,o),this._finished=!0}for(var a=0;a<this.digestLength/4;a++)Od.writeUint32BE(this._state[a],e,a*4);return this},r.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},r.prototype.saveState=function(){if(this._finished)throw new Error("SHA256: cannot save finished state");return{state:new Int32Array(this._state),buffer:this._bufferLength>0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},r.prototype.restoreState=function(e){return this._state.set(e.state),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},r.prototype.cleanSavedState=function(e){Ld.wipe(e.state),e.buffer&&Ld.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},r}();uo.SHA256=xT;var X$=new Int32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function N5(r,e,t,n,i){for(;i>=64;){for(var s=e[0],o=e[1],a=e[2],c=e[3],l=e[4],u=e[5],h=e[6],f=e[7],d=0;d<16;d++){var p=n+d*4;r[d]=Od.readUint32BE(t,p)}for(var d=16;d<64;d++){var m=r[d-2],g=(m>>>17|m<<32-17)^(m>>>19|m<<32-19)^m>>>10;m=r[d-15];var y=(m>>>7|m<<32-7)^(m>>>18|m<<32-18)^m>>>3;r[d]=(g+r[d-7]|0)+(y+r[d-16]|0)}for(var d=0;d<64;d++){var g=(((l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7))+(l&u^~l&h)|0)+(f+(X$[d]+r[d]|0)|0)|0,y=((s>>>2|s<<32-2)^(s>>>13|s<<32-13)^(s>>>22|s<<32-22))+(s&o^s&a^o&a)|0;f=h,h=u,u=l,l=c+g|0,c=a,a=o,o=s,s=g+y|0}e[0]+=s,e[1]+=o,e[2]+=a,e[3]+=c,e[4]+=l,e[5]+=u,e[6]+=h,e[7]+=f,n+=64,i-=64}return n}function j$(r){var e=new xT;e.update(r);var t=e.digest();return e.clean(),t}uo.hash=j$});var hD=D((D7e,uD)=>{function On(r,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}uD.exports=On;On.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};On.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};On.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var e=new Date().getTime();if(r&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},t),this._options.unref&&this._timer.unref(),!0};On.prototype.attempt=function(r,e){this._fn=r,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};On.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};On.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};On.prototype.start=On.prototype.try;On.prototype.errors=function(){return this._errors};On.prototype.attempts=function(){return this._attempts};On.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},e=null,t=0,n=0;n<this._errors.length;n++){var i=this._errors[n],s=i.message,o=(r[s]||0)+1;r[s]=o,o>=t&&(e=i,t=o)}return e}});var fD=D(ua=>{var yG=hD();ua.operation=function(r){var e=ua.timeouts(r);return new yG(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};ua.timeouts=function(r){if(r instanceof Array)return[].concat(r);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in r)e[t]=r[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],i=0;i<e.retries;i++)n.push(this.createTimeout(i,e));return r&&r.forever&&!n.length&&n.push(this.createTimeout(i,e)),n.sort(function(s,o){return s-o}),n};ua.createTimeout=function(r,e){var t=e.randomize?Math.random()+1:1,n=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,r));return n=Math.min(n,e.maxTimeout),n};ua.wrap=function(r,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var n in r)typeof r[n]=="function"&&t.push(n)}for(var i=0;i<t.length;i++){var s=t[i],o=r[s];r[s]=function(c){var l=ua.operation(e),u=Array.prototype.slice.call(arguments,1),h=u.pop();u.push(function(f){l.retry(f)||(f&&(arguments[0]=l.mainError()),h.apply(this,arguments))}),l.attempt(function(){c.apply(r,u)})}.bind(r,o),r[s].options=e}}});var pD=D((P7e,dD)=>{dD.exports=fD()});var CG={};Re(CG,{createHelia:()=>TG});var Wr=F(Zd(),1);var np={};Re(np,{base58btc:()=>me,base58flickr:()=>JD});function YD(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var i=0;i<r.length;i++){var s=r.charAt(i),o=s.charCodeAt(0);if(t[o]!==255)throw new TypeError(s+" is ambiguous");t[o]=i}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,g=0,y=0,b=p.length;y!==b&&p[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,I=new Uint8Array(E);y!==b;){for(var v=p[y],_=0,A=E-1;(v!==0||_<g)&&A!==-1;A--,_++)v+=256*I[A]>>>0,I[A]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=_,y++}for(var P=E-g;P!==E&&I[P]===0;)P++;for(var M=c.repeat(m);P<E;++P)M+=r.charAt(I[P]);return M}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var g=0,y=0;p[m]===c;)g++,m++;for(var b=(p.length-m)*l+1>>>0,E=new Uint8Array(b);p[m];){var I=t[p.charCodeAt(m)];if(I===255)return;for(var v=0,_=b-1;(I!==0||v<y)&&_!==-1;_--,v++)I+=a*E[_]>>>0,E[_]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");y=v,m++}if(p[m]!==" "){for(var A=b-y;A!==b&&E[A]===0;)A++;for(var P=new Uint8Array(g+(b-A)),M=g;A!==b;)P[M++]=E[A++];return P}}}function d(p){var m=f(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:d}}var QD=YD,XD=QD,a6=XD;var OG=new Uint8Array(0);var c6=(r,e)=>{if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0},Fi=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")};var l6=r=>new TextEncoder().encode(r),u6=r=>new TextDecoder().decode(r);var Jd=class{constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},ep=class{constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return f6(this,e)}},tp=class{constructor(e){this.decoders=e}or(e){return f6(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},f6=(r,e)=>new tp({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),rp=class{constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new Jd(e,t,n),this.decoder=new ep(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},pa=({name:r,prefix:e,encode:t,decode:n})=>new rp(r,e,t,n),ms=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:i}=a6(t,e);return pa({prefix:r,name:e,encode:n,decode:s=>Fi(i(s))})},jD=(r,e,t,n)=>{let i={};for(let u=0;u<e.length;++u)i[e[u]]=u;let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),a=0,c=0,l=0;for(let u=0;u<s;++u){let h=i[r[u]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|h,a+=t,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},ZD=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<<t)-1,s="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,s+=e[i&a>>o];if(o&&(s+=e[i&a<<t-o]),n)for(;s.length*t&7;)s+="=";return s},It=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>pa({prefix:e,name:r,encode(i){return ZD(i,n,t)},decode(i){return jD(i,n,t,r)}});var me=ms({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),JD=ms({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ip={};Re(ip,{base32:()=>Gt,base32hex:()=>nC,base32hexpad:()=>sC,base32hexpadupper:()=>oC,base32hexupper:()=>iC,base32pad:()=>tC,base32padupper:()=>rC,base32upper:()=>eC,base32z:()=>aC});var Gt=It({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),eC=It({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),tC=It({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),rC=It({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),nC=It({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),iC=It({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),sC=It({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),oC=It({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),aC=It({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var sp={};Re(sp,{base64:()=>Ki,base64pad:()=>cC,base64url:()=>lC,base64urlpad:()=>uC});var Ki=It({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),cC=It({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),lC=It({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),uC=It({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});Wr.default.formatters.b=r=>r==null?"undefined":me.baseEncode(r);Wr.default.formatters.t=r=>r==null?"undefined":Gt.baseEncode(r);Wr.default.formatters.m=r=>r==null?"undefined":Ki.baseEncode(r);Wr.default.formatters.p=r=>r==null?"undefined":r.toString();Wr.default.formatters.c=r=>r==null?"undefined":r.toString();Wr.default.formatters.k=r=>r==null?"undefined":r.toString();Wr.default.formatters.a=r=>r==null?"undefined":r.toString();function hC(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 T(r){let e=hC(`${r}:trace`);return Wr.default.enabled(`${r}:trace`)&&Wr.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,Wr.default)(`${r}:trace`)),Object.assign((0,Wr.default)(r),{error:(0,Wr.default)(`${r}:error`),trace:e})}var dh={};Re(dh,{abortedError:()=>bC,closeFailedError:()=>pC,deleteFailedError:()=>yC,getFailedError:()=>gC,hasFailedError:()=>wC,notFoundError:()=>op,openFailedError:()=>dC,putFailedError:()=>mC});var Vi=F(li(),1);function dC(r){return r=r??new Error("Open failed"),(0,Vi.default)(r,"ERR_OPEN_FAILED")}function pC(r){return r=r??new Error("Close failed"),(0,Vi.default)(r,"ERR_CLOSE_FAILED")}function mC(r){return r=r??new Error("Put failed"),(0,Vi.default)(r,"ERR_PUT_FAILED")}function gC(r){return r=r??new Error("Get failed"),(0,Vi.default)(r,"ERR_GET_FAILED")}function yC(r){return r=r??new Error("Delete failed"),(0,Vi.default)(r,"ERR_DELETE_FAILED")}function wC(r){return r=r??new Error("Has failed"),(0,Vi.default)(r,"ERR_HAS_FAILED")}function op(r){return r=r??new Error("Not Found"),(0,Vi.default)(r,"ERR_NOT_FOUND")}function bC(r){return r=r??new Error("Aborted"),(0,Vi.default)(r,"ERR_ABORTED")}var rl=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,block:i}of e)await this.put(n,i,t),yield n}get(e,t){return Promise.reject(new Error(".get is not implemented"))}async*getMany(e,t){for await(let n of e)yield{cid:n,block:await this.get(n,t)}}async delete(e,t){await Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var EC=y6,m6=128,vC=127,xC=~vC,_C=Math.pow(2,31);function y6(r,e,t){e=e||[],t=t||0;for(var n=t;r>=_C;)e[t++]=r&255|m6,r/=128;for(;r&xC;)e[t++]=r&255|m6,r>>>=7;return e[t]=r|0,y6.bytes=t-n+1,e}var SC=ap,RC=128,g6=127;function ap(r,n){var t=0,n=n||0,i=0,s=n,o,a=r.length;do{if(s>=a)throw ap.bytes=0,new RangeError("Could not decode varint");o=r[s++],t+=i<28?(o&g6)<<i:(o&g6)*Math.pow(2,i),i+=7}while(o>=RC);return ap.bytes=s-n,t}var IC=Math.pow(2,7),AC=Math.pow(2,14),TC=Math.pow(2,21),DC=Math.pow(2,28),CC=Math.pow(2,35),PC=Math.pow(2,42),kC=Math.pow(2,49),NC=Math.pow(2,56),LC=Math.pow(2,63),OC=function(r){return r<IC?1:r<AC?2:r<TC?3:r<DC?4:r<CC?5:r<PC?6:r<kC?7:r<NC?8:r<LC?9:10},BC={encode:EC,decode:SC,encodingLength:OC},MC=BC,nl=MC;var il=(r,e=0)=>[nl.decode(r,e),nl.decode.bytes],ma=(r,e,t=0)=>(nl.encode(r,e,t),e),ga=r=>nl.encodingLength(r);var Mn={};Re(Mn,{Digest:()=>yo,create:()=>Bn,decode:()=>ui,equals:()=>cp});var Bn=(r,e)=>{let t=e.byteLength,n=ga(r),i=n+ga(t),s=new Uint8Array(i+t);return ma(r,s,0),ma(t,s,n),s.set(e,i),new yo(r,t,e,s)},ui=r=>{let e=Fi(r),[t,n]=il(e),[i,s]=il(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new yo(t,i,o,e)},cp=(r,e)=>{if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&c6(r.bytes,t.bytes)}},yo=class{constructor(e,t,n,i){this.code=e,this.size=t,this.digest=n,this.bytes=i}};var w6=(r,e)=>{let{bytes:t,version:n}=r;switch(n){case 0:return FC(t,lp(r),e||me.encoder);default:return KC(t,lp(r),e||Gt.encoder)}};var b6=new WeakMap,lp=r=>{let e=b6.get(r);if(e==null){let t=new Map;return b6.set(r,t),t}return e},ee=class{constructor(e,t,n,i){this.code=t,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==sl)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==VC)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return ee.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Bn(e,t);return ee.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return ee.equals(this,e)}static equals(e,t){let n=t;return n&&e.code===n.code&&e.version===n.version&&cp(e.multihash,n.multihash)}toString(e){return w6(this,e)}toJSON(){return{"/":w6(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof ee)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:i,multihash:s,bytes:o}=t;return new ee(n,i,s,o||E6(n,i,s.bytes))}else if(t[qC]===!0){let{version:n,multihash:i,code:s}=t,o=ui(i);return ee.create(n,s,o)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==sl)throw new Error(`Version 0 CID must use dag-pb (code: ${sl}) block encoding`);return new ee(e,t,n,n.bytes)}case 1:{let i=E6(e,t,n.bytes);return new ee(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return ee.create(0,sl,e)}static createV1(e,t){return ee.create(1,e,t)}static decode(e){let[t,n]=ee.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=ee.inspectBytes(e),n=t.size-t.multihashSize,i=Fi(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=i.subarray(t.multihashSize-t.digestSize),o=new yo(t.multihashCode,t.digestSize,s,i);return[t.version===0?ee.createV0(o):ee.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,f]=il(e.subarray(t));return t+=f,h},i=n(),s=sl;if(i===18?(i=0,t=0):s=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=t,a=n(),c=n(),l=t+c,u=l-o;return{version:i,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,i]=UC(e,t),s=ee.decode(i);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return lp(s).set(n,e),s}},UC=(r,e)=>{switch(r[0]){case"Q":{let t=e||me;return[me.prefix,t.decode(`${me.prefix}${r}`)]}case me.prefix:{let t=e||me;return[me.prefix,t.decode(r)]}case Gt.prefix:{let t=e||Gt;return[Gt.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}},FC=(r,e,t)=>{let{prefix:n}=t;if(n!==me.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return i},KC=(r,e,t)=>{let{prefix:n}=t,i=e.get(n);if(i==null){let s=t.encode(r);return e.set(n,s),s}else return i},sl=112,VC=18,E6=(r,e,t)=>{let n=ga(r),i=n+ga(e),s=new Uint8Array(i+t.byteLength);return ma(r,s,0),ma(e,s,n),s.set(t,i),s},qC=Symbol.for("@ipld/js-cid/CID");var mh=85;var ol=class extends rl{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(Gt.encode(e.multihash.bytes),t),e}get(e){let t=this.data.get(Gt.encode(e.multihash.bytes));if(t==null)throw op();return t}has(e){return this.data.has(Gt.encode(e.multihash.bytes))}async delete(e){this.data.delete(Gt.encode(e.multihash.bytes))}async*getAll(){for(let[e,t]of this.data.entries())yield{cid:ee.createV1(mh,ui(Gt.decode(e))),block:t}}};var aW={...dh};var v6=F(li(),1);function gh(r){return r=r??new Error("Not Found"),(0,v6.default)(r,"ERR_NOT_FOUND")}var x6=(r=21)=>crypto.getRandomValues(new Uint8Array(r)).reduce((e,t)=>(t&=63,t<36?e+=t.toString(36):t<62?e+=(t-26).toString(36).toUpperCase():t>62?e+="-":e+="_",e),"");var hp={};Re(hp,{identity:()=>zC});var zC=pa({prefix:"\0",name:"identity",encode:r=>u6(r),decode:r=>l6(r)});var fp={};Re(fp,{base2:()=>HC});var HC=It({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var dp={};Re(dp,{base8:()=>$C});var $C=It({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var pp={};Re(pp,{base10:()=>GC});var GC=ms({prefix:"9",name:"base10",alphabet:"0123456789"});var mp={};Re(mp,{base16:()=>WC,base16upper:()=>YC});var WC=It({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),YC=It({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var gp={};Re(gp,{base36:()=>cl,base36upper:()=>QC});var cl=ms({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),QC=ms({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var yp={};Re(yp,{base256emoji:()=>eP});var _6=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),XC=_6.reduce((r,e,t)=>(r[t]=e,r),[]),jC=_6.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function ZC(r){return r.reduce((e,t)=>(e+=XC[t],e),"")}function JC(r){let e=[];for(let t of r){let n=jC[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var eP=pa({prefix:"\u{1F680}",name:"base256emoji",encode:ZC,decode:JC});var vp={};Re(vp,{sha256:()=>Ce,sha512:()=>Ep});var bp=({name:r,code:e,encode:t})=>new wp(r,e,t),wp=class{constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?Bn(this.code,t):t.then(n=>Bn(this.code,n))}else throw Error("Unknown type, must be binary type")}};var R6=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),Ce=bp({name:"sha2-256",code:18,encode:R6("SHA-256")}),Ep=bp({name:"sha2-512",code:19,encode:R6("SHA-512")});var xp={};Re(xp,{identity:()=>hi});var I6=0,tP="identity",A6=Fi,rP=r=>Bn(I6,A6(r)),hi={code:I6,name:tP,encode:A6,digest:rP};var xW=new TextEncoder,_W=new TextDecoder;var wn={...hp,...fp,...dp,...pp,...mp,...ip,...gp,...np,...sp,...yp},TW={...vp,...xp};function qi(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function zi(r=0){return globalThis.Buffer?.alloc!=null?qi(globalThis.Buffer.alloc(r)):new Uint8Array(r)}function Ir(r=0){return globalThis.Buffer?.allocUnsafe!=null?qi(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function D6(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var T6=D6("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),_p=D6("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Ir(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),iP={utf8:T6,"utf-8":T6,hex:wn.base16,latin1:_p,ascii:_p,binary:_p,...wn},yh=iP;function K(r,e="utf8"){let t=yh[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?qi(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}function O(r,e="utf8"){let t=yh[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}var Hi="/",C6=new TextEncoder().encode(Hi),wh=C6[0],ve=class{_buf;constructor(e,t){if(typeof e=="string")this._buf=K(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]!==wh)throw new Error("Invalid key")}toString(e="utf8"){return O(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new ve(e.join(Hi))}static random(){return new ve(x6().replace(/-/g,""))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new ve(e):typeof e.uint8Array=="function"?new ve(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=C6),this._buf[0]!==wh){let e=new Uint8Array(this._buf.byteLength+1);e.fill(wh,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===wh;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let i=0;i<t.length;i++){if(n.length<i+1)return!1;let s=t[i],o=n[i];if(s<o)return!0;if(s>o)return!1}return t.length<n.length}reverse(){return ve.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Hi).slice(1)}type(){return sP(this.baseNamespace())}name(){return oP(this.baseNamespace())}instance(e){return new ve(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Hi)||(e+=Hi),e+=this.type(),new ve(e)}parent(){let e=this.list();return e.length===1?new ve(Hi):new ve(e.slice(0,-1).join(Hi))}child(e){return this.toString()===Hi?e:e.toString()===Hi?this:new ve(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 ve.withNamespaces([...this.namespaces(),...aP(e.map(t=>t.namespaces()))])}};function sP(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function oP(r){let e=r.split(":");return e[e.length-1]}function aP(r){return[].concat(...r)}var P6="SHARDING";function lP(r){return r[Symbol.asyncIterator]!=null}function uP(r){if(lP(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Yr=uP;function hP(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:i=>{n.push(i)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var ya=hP;function fP(r){return r[Symbol.asyncIterator]!=null}function dP(r,e){if(fP(r))return async function*(){for await(let a of r)await e(a)&&(yield a)}();let t=ya(r),{value:n,done:i}=t.next();if(i===!0)return function*(){}();let s=e(n);if(typeof s.then=="function")return async function*(){await s&&(yield n);for await(let a of t)await e(a)&&(yield a)}();let o=e;return function*(){s===!0&&(yield n);for(let a of t)o(a)&&(yield a)}()}var Or=dP;function pP(r){return r[Symbol.asyncIterator]!=null}function mP(r){if(pP(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var Sp=mP;function gP(r){return r[Symbol.asyncIterator]!=null}function yP(r,e){return gP(r)?async function*(){yield*(await Sp(r)).sort(e)}():function*(){yield*Sp(r).sort(e)}()}var bh=yP;function wP(r){return r[Symbol.asyncIterator]!=null}function bP(r,e){return wP(r)?async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}():function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}}()}var gs=bP;var $i=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:i}of e)await this.put(n,i,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,i){e.push({key:n,value:i})},delete(n){t.push(n)},commit:async n=>{await Yr(this.putMany(e,n)),e=[],await Yr(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let i=e.prefix;n=Or(n,s=>s.key.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,s)=>Or(i,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,s)=>bh(i,s),n)),e.offset!=null){let i=0,s=e.offset;n=Or(n,()=>i++>=s)}return e.limit!=null&&(n=gs(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let i=e.prefix;n=Or(n,s=>s.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,s)=>Or(i,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,s)=>bh(i,s),n)),e.offset!=null){let i=e.offset,s=0;n=Or(n,()=>s++>=i)}return e.limit!=null&&(n=gs(n,e.limit)),n}};var wo=class extends $i{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){let t=this.data.get(e.toString());if(t==null)throw gh();return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,t]of this.data.entries())yield{key:new ve(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new ve(e)}};function EP(r){return r[Symbol.asyncIterator]!=null}function vP(r,e){if(EP(r))return async function*(){for await(let a of r)yield e(a)}();let t=ya(r),{value:n,done:i}=t.next();if(i===!0)return function*(){}();let s=e(n);if(typeof s.then=="function")return async function*(){yield await s;for await(let a of t)yield e(a)}();let o=e;return function*(){yield s;for(let a of t)yield o(a)}()}var Un=vP;var Eh=class{constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},wa=class{constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Eh(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Eh(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};function et(r={}){return N6(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function k6(r={}){return N6(t=>{let n,i=[];for(;!t.isEmpty()&&(n=t.shift(),n!=null);){if(n.error!=null)throw n.error;n.done===!1&&i.push(n.value)}return n==null?{done:!0}:{done:n.done===!0,value:i}},r)}function N6(r,e){e=e??{};let t=e.onEnd,n=new wa,i,s,o,a=async()=>n.isEmpty()?o?{done:!0}:await new Promise((m,g)=>{s=y=>{s=null,n.push(y);try{m(r(n))}catch(b){g(b)}return i}}):r(n),c=m=>s!=null?s(m):(n.push(m),i),l=m=>(n=new wa,s!=null?s({error:m}):(n.push({error:m}),i)),u=m=>{if(o)return i;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:m})},h=m=>o?i:(o=!0,m!=null?l(m):c({done:!0})),f=()=>(n=new wa,h(),{done:!0}),d=m=>(h(m),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:a,return:f,throw:d,push:u,end:h,get readableLength(){return n.size}},t==null)return i;let p=i;return i={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(m){return p.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return p.return(),t!=null&&(t(),t=void 0),{done:!0}},push:u,end(m){return p.end(m),t!=null&&(t(m),t=void 0),i},get readableLength(){return p.readableLength}},i}function xP(r){return r[Symbol.asyncIterator]!=null}function _P(...r){let e=[];for(let t of r)xP(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=et({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let i of n)t.push(i)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var Qt=_P;function be(r,...e){if(r==null)throw new Error("Empty pipeline");if(Rp(r)){let n=r;r=()=>n.source}else if(O6(r)||L6(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&Rp(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)Rp(t[n])&&(t[n]=RP(t[n]));return SP(...t)}var SP=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},L6=r=>r?.[Symbol.asyncIterator]!=null,O6=r=>r?.[Symbol.iterator]!=null,Rp=r=>r==null?!1:r.sink!=null&&r.source!=null,RP=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=et({objectMode:!0});t.then(()=>{n.end()},o=>{n.end(o)});let i,s=r.source;if(L6(s))i=async function*(){yield*s,n.end()};else if(O6(s))i=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Qt(n,i())}return r.source};var CY=new ve(P6);var qY=T("datastore:core:tiered");function st(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let i=e.signal;return i.clear=n,i}function TP(r){return r[Symbol.asyncIterator]!=null}function DP(r,e){if(TP(r))return async function*(){for await(let a of r)await e(a),yield a}();let t=ya(r),{value:n,done:i}=t.next();if(i===!0)return function*(){}();if(typeof e(n)?.then=="function")return async function*(){yield n;for await(let a of t)await e(a),yield a}();let o=e;return function*(){yield n;for(let a of t)o(a),yield a}()}var ll=DP;var Ip=class extends Map{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 fi(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Ip({name:e,metrics:t}):n=new Map,n}var vh=class extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.code=vh.code,this.type=vh.type}},Qr=vh;wr(Qr,"code","ABORT_ERR"),wr(Qr,"type","aborted");var w=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}};var Hg=F(X6(),1);function de(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var bo=class{_refCounter;cid;priority;wantType;constructor(e,t,n){this._refCounter=1,this.cid=e,this.priority=t??1,this.wantType=n}inc(){this._refCounter+=1}dec(){this._refCounter=Math.max(0,this._refCounter-1)}hasRefs(){return this._refCounter>0}get[Symbol.toStringTag](){return`WantlistEntry <key: ${this.cid.toString(me)}, priority: ${this.priority}, refs: ${this._refCounter}>`}equals(e){return this._refCounter===e._refCounter&&this.cid.equals(e.cid)&&this.priority===e.priority&&this.wantType===e.wantType}};var ys=class{entry;cancel;sendDontHave;constructor(e,t,n,i,s){this.entry=new bo(e,t,n),this.cancel=!!i,this.sendDontHave=!!s}get cid(){return this.entry.cid}set cid(e){this.entry.cid=e}get priority(){return this.entry.priority}set priority(e){this.entry.priority=e}get wantType(){return this.entry.wantType}set wantType(e){this.entry.wantType=e}get[Symbol.toStringTag](){return`BitswapMessageEntry ${this.cid.toString(me)} <cancel: ${this.cancel}, priority: ${this.priority}>`}equals(e){return this.cancel===e.cancel&&this.sendDontHave===e.sendDontHave&&this.wantType===e.wantType&&this.entry.equals(e.entry)}};var bn=(r,e)=>{let t=["bitswap"];return e!=null&&t.push(e),r!=null&&t.push(`${r.toString().slice(0,8)}`),T(t.join(":"))};var xh=(r,e)=>{if(r.size!==e.size)return!1;for(let[t,n]of r){let i=e.get(t);if(i===void 0||n instanceof Uint8Array&&i instanceof Uint8Array&&!de(n,i)||n instanceof ys&&i instanceof ys&&!n.equals(i))return!1}return!0};var ul=F(Eo(),1);function rk(r){let e=new Uint8Array(r.reduce((n,i)=>n+ul.default.encodingLength(i),0)),t=0;for(let n of r)e=ul.encode(n,e,t),t+=ul.default.encodingLength(n);return e}var og=rk;var Qp=F(Vp(),1),Kg=F(kg(),1),Vg=F(xo(),1),Xp=F(Yp(),1),qg=F(Fg(),1);function hk(){Vg.default._configure(),Qp.default._configure(Kg.default),Xp.default._configure(qg.default)}hk();var zg=["uint64","int64","sint64","fixed64","sfixed64"];function fk(r){for(let e of zg){if(r[e]==null)continue;let t=r[e];r[e]=function(){return BigInt(t.call(this).toString())}}return r}function jp(r){return fk(new Qp.default(r))}function dk(r){for(let e of zg){if(r[e]==null)continue;let t=r[e];r[e]=function(n){return t.call(this,n.toString())}}return r}function Zp(){return dk(Xp.default.create())}function te(r,e){let t=jp(r instanceof Uint8Array?r:r.subarray());return e.decode(t)}function re(r,e){let t=Zp();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Ea;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Ea||(Ea={}));function Ah(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function At(r){function e(i){if(r[i.toString()]==null)throw new Error("Invalid enum value");return r[i]}let t=function(s,o){let a=e(s);o.int32(a)},n=function(s){let o=s.int32();return e(o)};return Ah("enum",Ea.VARINT,t,n)}function ne(r,e){return Ah("message",Ea.LENGTH_DELIMITED,r,e)}var Br;(function(r){let e;(function(a){let c;(function(f){f.Block="Block",f.Have="Have"})(c=a.WantType||(a.WantType={}));let l;(function(f){f[f.Block=0]="Block",f[f.Have=1]="Have"})(l||(l={})),function(f){f.codec=()=>At(l)}(c=a.WantType||(a.WantType={}));let u;(function(f){let d;f.codec=()=>(d==null&&(d=ne((p,m,g={})=>{g.lengthDelimited!==!1&&m.fork(),p.block!=null&&p.block.byteLength>0&&(m.uint32(10),m.bytes(p.block)),p.priority!=null&&p.priority!==0&&(m.uint32(16),m.int32(p.priority)),p.cancel!=null&&p.cancel!==!1&&(m.uint32(24),m.bool(p.cancel)),p.wantType!=null&&l[p.wantType]!==0&&(m.uint32(32),r.Wantlist.WantType.codec().encode(p.wantType,m)),p.sendDontHave!=null&&p.sendDontHave!==!1&&(m.uint32(40),m.bool(p.sendDontHave)),g.lengthDelimited!==!1&&m.ldelim()},(p,m)=>{let g={block:new Uint8Array(0),priority:0,cancel:!1,wantType:c.Block,sendDontHave:!1},y=m==null?p.len:p.pos+m;for(;p.pos<y;){let b=p.uint32();switch(b>>>3){case 1:g.block=p.bytes();break;case 2:g.priority=p.int32();break;case 3:g.cancel=p.bool();break;case 4:g.wantType=r.Wantlist.WantType.codec().decode(p);break;case 5:g.sendDontHave=p.bool();break;default:p.skipType(b&7);break}}return g})),d),f.encode=p=>re(p,f.codec()),f.decode=p=>te(p,f.codec())})(u=a.Entry||(a.Entry={}));let h;a.codec=()=>(h==null&&(h=ne((f,d,p={})=>{if(p.lengthDelimited!==!1&&d.fork(),f.entries!=null)for(let m of f.entries)d.uint32(10),r.Wantlist.Entry.codec().encode(m,d);f.full!=null&&f.full!==!1&&(d.uint32(16),d.bool(f.full)),p.lengthDelimited!==!1&&d.ldelim()},(f,d)=>{let p={entries:[],full:!1},m=d==null?f.len:f.pos+d;for(;f.pos<m;){let g=f.uint32();switch(g>>>3){case 1:p.entries.push(r.Wantlist.Entry.codec().decode(f,f.uint32()));break;case 2:p.full=f.bool();break;default:f.skipType(g&7);break}}return p})),h),a.encode=f=>re(f,a.codec()),a.decode=f=>te(f,a.codec())})(e=r.Wantlist||(r.Wantlist={}));let t;(function(a){let c;a.codec=()=>(c==null&&(c=ne((l,u,h={})=>{h.lengthDelimited!==!1&&u.fork(),l.prefix!=null&&l.prefix.byteLength>0&&(u.uint32(10),u.bytes(l.prefix)),l.data!=null&&l.data.byteLength>0&&(u.uint32(18),u.bytes(l.data)),h.lengthDelimited!==!1&&u.ldelim()},(l,u)=>{let h={prefix:new Uint8Array(0),data:new Uint8Array(0)},f=u==null?l.len:l.pos+u;for(;l.pos<f;){let d=l.uint32();switch(d>>>3){case 1:h.prefix=l.bytes();break;case 2:h.data=l.bytes();break;default:l.skipType(d&7);break}}return h})),c),a.encode=l=>re(l,a.codec()),a.decode=l=>te(l,a.codec())})(t=r.Block||(r.Block={}));let n;(function(a){a.Have="Have",a.DontHave="DontHave"})(n=r.BlockPresenceType||(r.BlockPresenceType={}));let i;(function(a){a[a.Have=0]="Have",a[a.DontHave=1]="DontHave"})(i||(i={})),function(a){a.codec=()=>At(i)}(n=r.BlockPresenceType||(r.BlockPresenceType={}));let s;(function(a){let c;a.codec=()=>(c==null&&(c=ne((l,u,h={})=>{h.lengthDelimited!==!1&&u.fork(),l.cid!=null&&l.cid.byteLength>0&&(u.uint32(10),u.bytes(l.cid)),l.type!=null&&i[l.type]!==0&&(u.uint32(16),r.BlockPresenceType.codec().encode(l.type,u)),h.lengthDelimited!==!1&&u.ldelim()},(l,u)=>{let h={cid:new Uint8Array(0),type:n.Have},f=u==null?l.len:l.pos+u;for(;l.pos<f;){let d=l.uint32();switch(d>>>3){case 1:h.cid=l.bytes();break;case 2:h.type=r.BlockPresenceType.codec().decode(l);break;default:l.skipType(d&7);break}}return h})),c),a.encode=l=>re(l,a.codec()),a.decode=l=>te(l,a.codec())})(s=r.BlockPresence||(r.BlockPresence={}));let o;r.codec=()=>(o==null&&(o=ne((a,c,l={})=>{if(l.lengthDelimited!==!1&&c.fork(),a.wantlist!=null&&(c.uint32(10),r.Wantlist.codec().encode(a.wantlist,c)),a.blocks!=null)for(let u of a.blocks)c.uint32(18),c.bytes(u);if(a.payload!=null)for(let u of a.payload)c.uint32(26),r.Block.codec().encode(u,c);if(a.blockPresences!=null)for(let u of a.blockPresences)c.uint32(34),r.BlockPresence.codec().encode(u,c);a.pendingBytes!=null&&a.pendingBytes!==0&&(c.uint32(40),c.int32(a.pendingBytes)),l.lengthDelimited!==!1&&c.ldelim()},(a,c)=>{let l={blocks:[],payload:[],blockPresences:[],pendingBytes:0},u=c==null?a.len:a.pos+c;for(;a.pos<u;){let h=a.uint32();switch(h>>>3){case 1:l.wantlist=r.Wantlist.codec().decode(a,a.uint32());break;case 2:l.blocks.push(a.bytes());break;case 3:l.payload.push(r.Block.codec().decode(a,a.uint32()));break;case 4:l.blockPresences.push(r.BlockPresence.codec().decode(a,a.uint32()));break;case 5:l.pendingBytes=a.int32();break;default:a.skipType(h&7);break}}return l})),o),r.encode=a=>re(a,r.codec()),r.decode=a=>te(a,r.codec())})(Br||(Br={}));var mi=class{full;wantlist;blocks;blockPresences;pendingBytes;constructor(e){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}get empty(){return this.blocks.size===0&&this.wantlist.size===0&&this.blockPresences.size===0}addEntry(e,t,n,i,s){n==null&&(n=mi.WantType.Block);let o=e.toString(me),a=this.wantlist.get(o);a!=null?(a.wantType===n&&(a.priority=t),i===!0&&(a.cancel=!!i),s===!0&&(a.sendDontHave=!!s),n===mi.WantType.Block&&a.wantType===mi.WantType.Have&&(a.wantType=n)):this.wantlist.set(o,new ys(e,t,n,i,s))}addBlock(e,t){let n=e.toString(me);this.blocks.set(n,t)}addHave(e){let t=e.toString(me);this.blockPresences.has(t)||this.blockPresences.set(t,mi.BlockPresenceType.Have)}addDontHave(e){let t=e.toString(me);this.blockPresences.has(t)||this.blockPresences.set(t,mi.BlockPresenceType.DontHave)}cancel(e){let t=e.toString(me);this.wantlist.delete(t),this.addEntry(e,0,mi.WantType.Block,!0,!1)}setPendingBytes(e){this.pendingBytes=e}serializeToBitswap100(){return Br.encode({wantlist:{entries:Array.from(this.wantlist.values()).map(e=>({block:e.cid.bytes,priority:Number(e.priority),cancel:!!e.cancel,wantType:Br.Wantlist.WantType.Block,sendDontHave:!1})),full:!!this.full},blocks:Array.from(this.blocks.values())})}serializeToBitswap110(){let e={wantlist:{entries:Array.from(this.wantlist.values()).map(t=>({block:t.cid.bytes,priority:Number(t.priority),wantType:t.wantType,cancel:!!t.cancel,sendDontHave:!!t.sendDontHave})),full:!!this.full},blockPresences:[],payload:[],pendingBytes:this.pendingBytes,blocks:[]};for(let[t,n]of this.blocks.entries()){let i=ee.parse(t),s=i.version,o=i.code,a=i.multihash.code,c=i.multihash.digest.length,l=og([s,o,a,c]);e.payload.push({prefix:l,data:n})}for(let[t,n]of this.blockPresences)e.blockPresences.push({cid:ee.parse(t).bytes,type:n});return this.pendingBytes>0&&(e.pendingBytes=this.pendingBytes),Br.encode(e)}equals(e){return!(this.full!==e.full||this.pendingBytes!==e.pendingBytes||!xh(this.wantlist,e.wantlist)||!xh(this.blocks,e.blocks)||!xh(this.blockPresences,e.blockPresences))}get[Symbol.toStringTag](){let e=Array.from(this.wantlist.keys()),t=Array.from(this.blocks.keys());return`BitswapMessage <full: ${this.full}, list: ${e}, blocks: ${t}>`}},Lt=mi;wr(Lt,"Entry",ys),wr(Lt,"WantType",{Block:Br.Wantlist.WantType.Block,Have:Br.Wantlist.WantType.Have}),wr(Lt,"BlockPresenceType",{Have:Br.BlockPresenceType.Have,DontHave:Br.BlockPresenceType.DontHave}),wr(Lt,"deserialize",async(e,t)=>{let n=Br.decode(e),i=n.wantlist?.full===!0,s=new mi(i);return n.wantlist?.entries.forEach(o=>{if(o.block==null)return;let a=ee.decode(o.block);s.addEntry(a,o.priority??0,o.wantType,!!o.cancel,!!o.sendDontHave)}),n.blockPresences.forEach(o=>{if(o.cid==null)return;let a=ee.decode(o.cid);o.type===mi.BlockPresenceType.Have?s.addHave(a):s.addDontHave(a)}),n.blocks.length>0?(await Promise.all(n.blocks.map(async o=>{let a=await Ce.digest(o),c=ee.createV0(a);s.addBlock(c,o)})),s):(n.payload.length>0&&(await Promise.all(n.payload.map(async o=>{if(o.prefix==null||o.data==null)return;let a=(0,Hg.default)(o.prefix),c=a[0],l=a[1],u=a[2],h=u===Ce.code?Ce:await t?.getHasher(u);if(h==null)throw new w("Unknown hash algorithm","ERR_UNKNOWN_HASH_ALG");let f=await h.digest(o.data),d=ee.create(c,l,f);s.addBlock(d,o.data)})),s.setPendingBytes(n.pendingBytes)),s)}),wr(Lt,"blockPresenceSize",e=>e.bytes.length+1);var $g={Block:Br.Wantlist.WantType.Block,Have:Br.Wantlist.WantType.Have},pk=(r,e)=>Array.prototype.slice.call(e,0).sort((t,n)=>{let i=r(t),s=r(n);return i<s?-1:i>s?1:0}),Gi=class{set;_stats;constructor(e,t){this.set=t!=null?fi({name:"ipfs_bitswap_wantlist",metrics:t.metrics}):new Map,this._stats=e}get length(){return this.set.size}add(e,t,n){let i=e.toString(me),s=this.set.get(i);s!=null?(s.inc(),s.priority=t,s.wantType===$g.Have&&n===$g.Block&&(s.wantType=n)):(this.set.set(i,new bo(e,t,n)),this._stats!=null&&this._stats.push(void 0,"wantListSize",1))}remove(e){let t=e.toString(me),n=this.set.get(t);n!=null&&(n.dec(),!n.hasRefs()&&(this.set.delete(t),this._stats!=null&&this._stats.push(void 0,"wantListSize",-1)))}removeForce(e){this.set.has(e)&&this.set.delete(e)}forEach(e){this.set.forEach(e)}entries(){return this.set.entries()}sortedEntries(){return new Map(pk(e=>e[1].key,Array.from(this.set.entries())))}contains(e){let t=e.toString(me);return this.set.has(t)}get(e){let t=e.toString(me);return this.set.get(t)}};wr(Gi,"Entry",bo);var Th=class{partner;wantlist;exchangeCount;accounting;lastExchange;constructor(e){this.partner=e,this.wantlist=new Gi,this.exchangeCount=0,this.accounting={bytesSent:0,bytesRecv:0}}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.accounting.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.accounting.bytesRecv+=e}wants(e,t,n){this.wantlist.add(e,t,n)}cancelWant(e){this.wantlist.remove(e)}wantlistContains(e){return this.wantlist.get(e)}debtRatio(){return this.accounting.bytesSent/(this.accounting.bytesRecv+1)}};var dl=class extends Map{_cmp;_keys;constructor(e,t){super(),this._cmp=t??this._defaultSort,this._keys=[];for(let[n,i]of e??[])this.set(n,i)}update(e){if(e<0||e>=this._keys.length)return;let t=this._keys[e];this._keys.splice(e,1);let n=this._find(t);this._keys.splice(n,0,t)}set(e,t){if(this.has(e)){let i=this.indexOf(e);this._keys.splice(i,1)}super.set(e,t);let n=this._find(e);return this._keys.splice(n,0,e),this}clear(){super.clear(),this._keys=[]}delete(e){if(!this.has(e))return!1;let t=this.indexOf(e);return this._keys.splice(t,1),super.delete(e)}indexOf(e){if(!this.has(e))return-1;let t=this._find(e);if(this._keys[t]===e)return t;for(let n=1;n<this._keys.length;n++){if(this._keys[t+n]===e)return t+n;if(this._keys[t-n]===e)return t-n}return-1}_find(e){let t=0,n=this._keys.length;for(;t<n;){let i=t+n>>>1,s=this._kCmp(this._keys[i],e);if(s<0)t=i+1;else if(s>0)n=i;else return i}return t}*keys(){for(let e of this._keys)yield e}*values(){for(let e of this._keys)yield this.get(e)}*entries(){for(let e of this._keys)yield[e,this.get(e)]}*[Symbol.iterator](){yield*this.entries()}forEach(e,t=this){if(e!=null)for(let n of this._keys){let i=this.get(n);if(i==null)throw new Error("Value cannot be undefined");e.apply(t,[[n,i]])}}_defaultSort(e,t){return e[0]<t[0]?-1:t[0]<e[0]?1:0}_kCmp(e,t){return this._cmp([e,this.get(e)],[t,this.get(t)])}};var mk={hasNewInfo(){return!1},merge(){}},Dh=class{_taskMerger;_byPeer;constructor(e=mk){this._taskMerger=e,this._byPeer=new dl([],Ch.compare)}pushTasks(e,t){let n=this._byPeer.get(e.toString());n==null&&(n=new Ch(e,this._taskMerger)),n.pushTasks(t),this._byPeer.set(e.toString(),n)}popTasks(e){let t=this._head();if(t===void 0)return{tasks:[],pendingSize:0};let{tasks:n,pendingSize:i}=t.popTasks(e);if(n.length===0)return{tasks:n,pendingSize:i};let s=t.peerId;return t.isIdle()?this._byPeer.delete(s.toString()):this._byPeer.update(0),{peerId:s,tasks:n,pendingSize:i}}_head(){if(this._byPeer.size!==0)for(let[,e]of this._byPeer)return e}remove(e,t){this._byPeer.get(t.toString())?.remove(e)}tasksDone(e,t){let n=this._byPeer.get(e.toString());if(n==null)return;let i=this._byPeer.indexOf(e.toString());for(let s of t)n.taskDone(s);this._byPeer.update(i)}},Ch=class{peerId;_taskMerger;_activeTotalSize;_pending;_active;constructor(e,t){this.peerId=e,this._taskMerger=t,this._activeTotalSize=0,this._pending=new Jp,this._active=new Set}pushTasks(e){for(let t of e)this._pushTask(t)}_pushTask(e){if(!this._taskHasMoreInfoThanActiveTasks(e))return;let t=this._pending.get(e.topic);if(t!=null){e.priority>t.priority&&this._pending.updatePriority(e.topic,e.priority),this._taskMerger.merge(e,t);return}this._pending.add(e)}_taskHasMoreInfoThanActiveTasks(e){let t=[];for(let n of this._active)n.topic===e.topic&&t.push(n);return t.length===0?!0:this._taskMerger.hasNewInfo(e,t)}popTasks(e){let t=0,n=[],i=this._pending.tasks();for(let s=0;s<i.length&&t<e;s++){let o=i[s];n.push(o),t+=o.size,this._pending.delete(o.topic),this._activeTotalSize+=o.size,this._active.add(o)}return{tasks:n,pendingSize:this._pending.totalSize}}taskDone(e){this._active.has(e)&&(this._activeTotalSize-=e.size,this._active.delete(e))}remove(e){this._pending.delete(e)}isIdle(){return this._pending.length===0&&this._active.size===0}static compare(e,t){return e[1]._pending.length===0?1:t[1]._pending.length===0?-1:e[1]._activeTotalSize===t[1]._activeTotalSize?t[1]._pending.length-e[1]._pending.length:e[1]._activeTotalSize-t[1]._activeTotalSize}},Jp=class{_tasks;constructor(){this._tasks=new dl([],this._compare)}get length(){return this._tasks.size}get totalSize(){return[...this._tasks.values()].reduce((e,t)=>e+t.task.size,0)}get(e){return this._tasks?.get(e)?.task}add(e){this._tasks.set(e.topic,{created:Date.now(),task:e})}delete(e){this._tasks.delete(e)}tasks(){return[...this._tasks.values()].map(e=>e.task)}updatePriority(e,t){let n=this._tasks.get(e);if(n==null)return;let i=this._tasks.indexOf(e);n.task.priority=t,this._tasks.update(i)}_compare(e,t){return e[1].task.priority===t[1].task.priority?e[1].created-t[1].created:t[1].task.priority-e[1].task.priority}};var Gg={hasNewInfo(r,e){let t=!1,n=!1;for(let i of e)i.data.haveBlock&&(t=!0),i.data.isWantBlock&&(n=!0);return!!(!n&&r.data.isWantBlock||!t&&r.data.haveBlock)},merge(r,e){let t=r.data,n=e.data;!n.haveBlock&&t.haveBlock&&(n.haveBlock=t.haveBlock,n.blockSize=t.blockSize),!n.isWantBlock&&t.isWantBlock&&(n.isWantBlock=!0,(!n.haveBlock||t.haveBlock)&&(n.haveBlock=t.haveBlock,e.size=r.size)),n.isWantBlock&&n.haveBlock&&(e.size=n.blockSize)}};var Wg=Lt.WantType,gk=16*1024,yk=1024,Ph=class{_log;blockstore;network;_stats;_opts;ledgerMap;_running;_requestQueue;constructor(e,t,n,i,s,o={}){this._log=bn(e,"engine"),this.blockstore=t,this.network=n,this._stats=i,this._opts=this._processOpts(o),this.ledgerMap=fi({name:"ipfs_bitswap_ledger_map",metrics:s.metrics}),this._running=!1,this._requestQueue=new Dh(Gg)}_processOpts(e){return{maxSizeReplaceHasWithBlock:yk,targetMessageSize:gk,...e}}_scheduleProcessTasks(){setTimeout(()=>{this._processTasks().catch(e=>{this._log.error("error processing stats",e)})})}async _processTasks(){if(!this._running)return;let{peerId:e,tasks:t,pendingSize:n}=this._requestQueue.popTasks(this._opts.targetMessageSize);if(t.length===0)return;let i=new Lt(!1);i.setPendingBytes(n);let s=[],o=new Map;for(let c of t){let l=ee.parse(c.topic);c.data.haveBlock?c.data.isWantBlock?(s.push(l),o.set(c.topic,c.data)):i.addHave(l):i.addDontHave(l)}let a=await this._getBlocks(s);for(let[c,l]of o){let u=ee.parse(c),h=a.get(c);h!=null?i.addBlock(u,h):l.sendDontHave&&i.addDontHave(u)}if(i.empty){e!=null&&this._requestQueue.tasksDone(e,t),this._scheduleProcessTasks();return}try{e!=null&&await this.network.sendMessage(e,i);for(let[c,l]of a.entries())e!=null&&this.messageSent(e,ee.parse(c),l)}catch(c){this._log.error(c)}e!=null&&this._requestQueue.tasksDone(e,t),this._scheduleProcessTasks()}wantlistForPeer(e){let t=e.toString(),n=this.ledgerMap.get(t);return n!=null?n.wantlist.sortedEntries():new Map}ledgerForPeer(e){let t=e.toString(),n=this.ledgerMap.get(t);if(n!=null)return{peer:n.partner,value:n.debtRatio(),sent:n.accounting.bytesSent,recv:n.accounting.bytesRecv,exchanged:n.exchangeCount}}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.partner)}receivedBlocks(e){if(e.length!==0){for(let t of this.ledgerMap.values())for(let{cid:n,block:i}of e){let s=t.wantlistContains(n);if(s==null)continue;let o=i.length,a=this._sendAsBlock(s.wantType,o),c=o;a||(c=Lt.blockPresenceSize(s.cid)),this._requestQueue.pushTasks(t.partner,[{topic:s.cid.toString(me),priority:s.priority,size:c,data:{blockSize:o,isWantBlock:a,haveBlock:!0,sendDontHave:!1}}])}this._scheduleProcessTasks()}}async messageReceived(e,t){let n=this._findOrCreate(e);if(t.empty)return;if(t.full&&(n.wantlist=new Gi),this._updateBlockAccounting(t.blocks,n),t.wantlist.size===0){this._scheduleProcessTasks();return}let i=[],s=[];t.wantlist.forEach(o=>{o.cancel?(n.cancelWant(o.cid),i.push(o.cid)):(n.wants(o.cid,o.priority,o.wantType),s.push(o))}),this._cancelWants(e,i),await this._addWants(e,s),this._scheduleProcessTasks()}_cancelWants(e,t){for(let n of t)this._requestQueue.remove(n.toString(me),e)}async _addWants(e,t){let n=await this._getBlockSizes(t.map(s=>s.cid)),i=[];for(let s of t){let o=s.cid.toString(me),a=n.get(o);if(a==null)s.sendDontHave&&i.push({topic:o,priority:s.priority,size:Lt.blockPresenceSize(s.cid),data:{isWantBlock:s.wantType===Wg.Block,blockSize:0,haveBlock:!1,sendDontHave:s.sendDontHave}});else{let c=this._sendAsBlock(s.wantType,a),l=a;c||(l=Lt.blockPresenceSize(s.cid)),i.push({topic:o,priority:s.priority,size:l,data:{isWantBlock:c,blockSize:a,haveBlock:!0,sendDontHave:s.sendDontHave}})}this._requestQueue.pushTasks(e,i)}}_sendAsBlock(e,t){return e===Wg.Block||t<=this._opts.maxSizeReplaceHasWithBlock}async _getBlockSizes(e){let t=await this._getBlocks(e);return new Map([...t].map(([n,i])=>[n,i.length]))}async _getBlocks(e){let t=new Map;return await Promise.all(e.map(async n=>{try{let i=await this.blockstore.get(n);t.set(n.toString(me),i)}catch(i){i.code!=="ERR_NOT_FOUND"&&this._log.error("failed to query blockstore for %s: %s",n,i)}})),t}_updateBlockAccounting(e,t){for(let n of e.values())this._log("got block (%s bytes)",n.length),t.receivedBytes(n.length)}messageSent(e,t,n){let i=this._findOrCreate(e);i.sentBytes(n.length),i.wantlist.remove(t)}numBytesSentTo(e){return this._findOrCreate(e).accounting.bytesSent}numBytesReceivedFrom(e){return this._findOrCreate(e).accounting.bytesRecv}peerDisconnected(e){this.ledgerMap.delete(e.toString())}_findOrCreate(e){let t=e.toString(),n=this.ledgerMap.get(t);if(n!=null)return n;let i=new Th(e);return this.ledgerMap.set(t,i),this._stats!=null&&this._stats.push(t,"peerCount",1),i}start(){this._running=!0}stop(){this._running=!1}};var kh=Symbol.for("@libp2p/topology");function Yg(r){return r!=null&&!!r[kh]}var Qg=()=>{},e2=class{constructor(e){this.min=e.min??0,this.max=e.max??1/0,this.peers=new Set,this.onConnect=e.onConnect??Qg,this.onDisconnect=e.onDisconnect??Qg}get[Symbol.toStringTag](){return kh.toString()}get[kh](){return!0}async setRegistrar(e){this.registrar=e}disconnect(e){this.onDisconnect(e)}};function Es(r){return new e2(r)}var pl=class extends Error{constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Xg(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function gt(r,e,t){let n=t??{},i=Xg(r);async function*s(){let o,a=()=>{o?.()};for(e.addEventListener("abort",a);;){let c;try{if(e.aborted){let{abortMessage:u,abortCode:h}=n;throw new pl(u,h)}let l=new Promise((u,h)=>{o=()=>{let{abortMessage:f,abortCode:d}=n;h(new pl(f,d))}});c=await Promise.race([l,i.next()]),o=null}catch(l){e.removeEventListener("abort",a);let u=l.type==="aborted"&&e.aborted;if(u&&n.onAbort!=null&&n.onAbort(r),typeof i.return=="function")try{let h=i.return();h instanceof Promise&&h.catch(f=>{n.onReturnError!=null&&n.onReturnError(f)})}catch(h){n.onReturnError!=null&&n.onReturnError(h)}if(u&&n.returnOnAbort===!0)return;throw l}if(c.done===!0)break;yield c.value}e.removeEventListener("abort",a)}return s()}function wk(r,e,t){return n=>r(gt(n,e,t))}function br(r,e,t){return{sink:wk(r.sink,e,{...t,onAbort:void 0}),source:gt(r.source,e,t)}}function le(r,e){e==null&&(e=r.reduce((i,s)=>i+s.length,0));let t=Ir(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return qi(t)}var Zg=Symbol.for("@achingbrain/uint8arraylist");function jg(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let i=t+n.byteLength;if(e<i)return{buf:n,index:e-t};t=i}throw new RangeError("index is out of bounds")}function Nh(r){return!!r?.[Zg]}var j=class{constructor(...e){Object.defineProperty(this,Zg,{value:!0}),this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Nh(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Nh(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=jg(this.bufs,e);return t.buf[t.index]}set(e,t){let n=jg(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Nh(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:i}=this._subList(e,t);return le(n,i)}subarray(e,t){let{bufs:n,length:i}=this._subList(e,t);return n.length===1?n[0]:le(n,i)}sublist(e,t){let{bufs:n,length:i}=this._subList(e,t),s=new j;return s.length=i,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],i=0;for(let s=0;s<this.bufs.length;s++){let o=this.bufs[s],a=i,c=a+o.byteLength;if(i=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(o);break}let h=e-a;n.push(o.subarray(h,h+(t-e)));break}if(l){if(e===0){n.push(o);continue}n.push(o.subarray(e-a));continue}if(u){if(t===c){n.push(o);break}n.push(o.subarray(0,t-a));break}n.push(o)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Nh(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let s=256,o=new Int32Array(s);for(let h=0;h<s;h++)o[h]=-1;for(let h=0;h<i;h++)o[n[h]]=h;let a=o,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let h=t;h<=c;h+=u){u=0;for(let f=l;f>=0;f--){let d=this.get(h+f);if(n[f]!==d){u=Math.max(1,f-a[d]);break}}if(u===0)return h}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Ir(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let i=zi(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,t,n),this.write(i,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let i=zi(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,t,n),this.write(i,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let i=zi(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,t,n),this.write(i,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Ir(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let i=zi(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,t,n),this.write(i,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let i=zi(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,t,n),this.write(i,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let i=zi(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,t,n),this.write(i,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let i=zi(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,t,n),this.write(i,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let i=zi(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,t,n),this.write(i,e)}equals(e){if(e==null||!(e instanceof j)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!de(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new j;return n.bufs=e,t==null&&(t=e.reduce((i,s)=>i+s.byteLength,0)),n.length=t,n}};function Lh(r){return r instanceof Uint8Array?{get(e){return r[e]},set(e,t){r[e]=t}}:{get(e){return r.get(e)},set(e,t){r.set(e,t)}}}var Jg=4294967296,Xr=class{constructor(e=0,t=0){this.hi=e,this.lo=t}toBigInt(e){if(e===!0)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toNumber(e){return Number(this.toBigInt(e))}zzDecode(){let e=-(this.lo&1),t=((this.lo>>>1|this.hi<<31)^e)>>>0,n=(this.hi>>>1^e)>>>0;return new Xr(n,t)}zzEncode(){let e=this.hi>>31,t=((this.hi<<1|this.lo>>>31)^e)>>>0,n=(this.lo<<1^e)>>>0;return new Xr(t,n)}toBytes(e,t=0){let n=Lh(e);for(;this.hi>0;)n.set(t++,this.lo&127|128),this.lo=(this.lo>>>7|this.hi<<25)>>>0,this.hi>>>=7;for(;this.lo>127;)n.set(t++,this.lo&127|128),this.lo=this.lo>>>7;n.set(t++,this.lo)}static fromBigInt(e){if(e===0n)return new Xr;let t=e<0;t&&(e=-e);let n=Number(e>>32n)|0,i=Number(e-(BigInt(n)<<32n))|0;return t&&(n=~n>>>0,i=~i>>>0,++i>Jg&&(i=0,++n>Jg&&(n=0))),new Xr(n,i)}static fromNumber(e){if(e===0)return new Xr;let t=e<0;t&&(e=-e);let n=e>>>0,i=(e-n)/4294967296>>>0;return t&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new Xr(i,n)}static fromBytes(e,t=0){let n=Lh(e),i=new Xr,s=0;if(e.length-t>4){for(;s<4;++s)if(i.lo=(i.lo|(n.get(t)&127)<<s*7)>>>0,n.get(t++)<128)return i;if(i.lo=(i.lo|(n.get(t)&127)<<28)>>>0,i.hi=(i.hi|(n.get(t)&127)>>4)>>>0,n.get(t++)<128)return i;s=0}else for(;s<4;++s){if(t>=e.length)throw RangeError(`index out of range: ${t} > ${e.length}`);if(i.lo=(i.lo|(n.get(t)&127)<<s*7)>>>0,n.get(t++)<128)return i}if(e.length-t>4){for(;s<5;++s)if(i.hi=(i.hi|(n.get(t)&127)<<s*7+3)>>>0,n.get(t++)<128)return i}else if(t<e.byteLength)for(;s<5;++s){if(t>=e.length)throw RangeError(`index out of range: ${t} > ${e.length}`);if(i.hi=(i.hi|(n.get(t)&127)<<s*7+3)>>>0,n.get(t++)<128)return i}throw RangeError("invalid varint encoding")}};var bk=Math.pow(2,7),Ek=Math.pow(2,14),vk=Math.pow(2,21),xk=Math.pow(2,28),_k=Math.pow(2,35),Sk=Math.pow(2,42),Rk=Math.pow(2,49),Ik=Math.pow(2,56),Ak=Math.pow(2,63),ot={encodingLength(r){return r<bk?1:r<Ek?2:r<vk?3:r<xk?4:r<_k?5:r<Sk?6:r<Rk?7:r<Ik?8:r<Ak?9:10},encode(r,e,t=0){if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return e==null&&(e=Ir(ot.encodingLength(r))),Xr.fromNumber(r).toBytes(e,t),e},decode(r,e=0){return Xr.fromBytes(r,e).toNumber(!0)}};function Oh(r){return r[Symbol.asyncIterator]!=null}var Bh=r=>{let e=ot.encodingLength(r),t=Ir(e);return ot.encode(r,t),Bh.bytes=e,t};Bh.bytes=0;function yt(r,e){e=e??{};let t=e.lengthEncoder??Bh;function*n(i){let s=t(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return Oh(r)?async function*(){for await(let i of r)yield*n(i)}():function*(){for(let i of r)yield*n(i)}()}yt.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Bh;return new j(t(r.byteLength),r)};var va=F(li(),1);var Tk=8,Dk=1024*1024*4,So;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(So||(So={}));var t2=r=>{let e=ot.decode(r);return t2.bytes=ot.encodingLength(e),e};t2.bytes=0;function Tt(r,e){let t=new j,n=So.LENGTH,i=-1,s=e?.lengthDecoder??t2,o=e?.maxLengthLength??Tk,a=e?.maxDataLength??Dk;function*c(){for(;t.byteLength>0;){if(n===So.LENGTH)try{if(i=s(t),i<0)throw(0,va.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,va.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(i),n=So.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>o)throw(0,va.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw l}if(n===So.DATA){if(t.byteLength<i)break;let l=t.sublist(0,i);t.consume(i),e?.onData!=null&&e.onData(l),yield l,n=So.LENGTH}}}return Oh(r)?async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw(0,va.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw(0,va.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Tt.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:s,value:o}=await r.next(t);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}}();return Tt(n,{...e??{},onLength:s=>{t=s}})};var je=class extends Event{constructor(e,t){super(e),this.detail=t}};var uy=F(oy(),1);var ay=Math.pow(2,31)-1,cy=1e3,ly=1;var i2="/ipfs/bitswap/1.0.0",s2="/ipfs/bitswap/1.1.0",o2="/ipfs/bitswap/1.2.0",Nk=1024,Lk=1024,Ok=3e4,Uh=class{_log;_libp2p;_bitswap;_protocols;_stats;_running;_hashLoader;_maxInboundStreams;_maxOutboundStreams;_incomingStreamTimeout;_registrarIds;constructor(e,t,n,i={}){this._log=bn(e.peerId,"network"),this._libp2p=e,this._bitswap=t,this._protocols=[i2],i.b100Only!==!0&&(this._protocols.unshift(s2),this._protocols.unshift(o2)),this._stats=n,this._running=!1,this._onPeerConnect=this._onPeerConnect.bind(this),this._onPeerDisconnect=this._onPeerDisconnect.bind(this),this._onConnection=this._onConnection.bind(this),this._hashLoader=i.hashLoader??{async getHasher(){throw new Error("Not implemented")}},this._maxInboundStreams=i.maxInboundStreams??Nk,this._maxOutboundStreams=i.maxOutboundStreams??Lk,this._incomingStreamTimeout=i.incomingStreamTimeout??Ok}async start(){this._running=!0,await this._libp2p.handle(this._protocols,this._onConnection,{maxInboundStreams:this._maxInboundStreams,maxOutboundStreams:this._maxOutboundStreams});let e=Es({onConnect:this._onPeerConnect,onDisconnect:this._onPeerDisconnect});this._registrarIds=[];for(let t of this._protocols)this._registrarIds.push(await this._libp2p.register(t,e));this._libp2p.getConnections().forEach(t=>{this._onPeerConnect(t.remotePeer)})}async stop(){if(this._running=!1,await this._libp2p.unhandle(this._protocols),this._registrarIds!=null){for(let e of this._registrarIds)this._libp2p.unregister(e);this._registrarIds=[]}}_onConnection(e){if(!this._running)return;let{stream:t,connection:n}=e,i=new uy.TimeoutController(this._incomingStreamTimeout);Promise.resolve().then(async()=>{this._log("incoming new bitswap %s connection from %p",t.stat.protocol,n.remotePeer),await be(gt(t.source,i.signal),s=>Tt(s),async s=>{for await(let o of s){try{let a=await Lt.deserialize(o.subarray(),this._hashLoader);await this._bitswap._receiveMessage(n.remotePeer,a)}catch(a){this._bitswap._receiveError(a);break}i.reset()}})}).catch(s=>{this._log(s),t.abort(s)}).finally(()=>{i.clear(),t.close()})}_onPeerConnect(e){this._bitswap._onPeerConnected(e)}_onPeerDisconnect(e){this._bitswap._onPeerDisconnected(e)}findProviders(e,t={}){return t.onProgress?.(new je("bitswap:network:find-providers",e)),this._libp2p.contentRouting.findProviders(e,t)}async findAndConnect(e,t){await Yr(gs(Un(this.findProviders(e,t),async n=>this.connectTo(n.id,t).catch(i=>{this._log.error(i)})),3)).catch(n=>{this._log.error(n)})}async provide(e,t={}){t.onProgress?.(new je("bitswap:network:provide",e)),await this._libp2p.contentRouting.provide(e,t)}async sendMessage(e,t,n={}){if(!this._running)throw new Error("network isn't running");let i=e.toString();this._log("sendMessage to %s",i,t),n.onProgress?.(new je("bitswap:network:send-wantlist",e)),await this._writeMessage(e,t,n),this._updateSentStats(e,t.blocks)}async connectTo(e,t={}){if(!this._running)throw new Error("network isn't running");return t.onProgress?.(new je("bitswap:network:dial",e)),this._libp2p.dial(e,t)}_updateSentStats(e,t){let n=e.toString();if(this._stats!=null){for(let i of t.values())this._stats.push(n,"dataSent",i.length);this._stats.push(n,"blocksSent",t.size)}}async _writeMessage(e,t,n={}){let i=await this._libp2p.dialProtocol(e,[o2,s2,i2]);try{let s;switch(i.stat.protocol){case i2:s=t.serializeToBitswap100();break;case s2:case o2:s=t.serializeToBitswap110();break;default:throw new Error(`Unknown protocol: ${i.stat.protocol}`)}await be([s],o=>yt(o),i)}catch(s){n.onProgress?.(new je("bitswap:network:send-wantlist:error",{peer:e,error:s})),this._log(s)}finally{i.close()}}};var _y=F(jr(),1);var vy=r=>`unwant:${O(r.multihash.bytes,"base64")}`,xy=r=>`block:${O(r.multihash.bytes,"base64")}`,Vh=class extends _y.EventEmitter{_log;constructor(e){super(),this.setMaxListeners(cy),this._log=bn(e,"notif")}hasBlock(e,t){let n=xy(e);this._log(n),this.emit(n,t)}async wantBlock(e,t={}){if(e==null)throw new Error("Not a valid cid");let n=xy(e),i=vy(e);return this._log(`wantBlock:${e}`),new Promise((s,o)=>{let a=()=>{this.removeListener(n,c),t.onProgress?.(new je("bitswap:want-block:unwant",e)),o(new Error(`Block for ${e} unwanted`))},c=l=>{this.removeListener(i,a),t.onProgress?.(new je("bitswap:want-block:block",e)),s(l)};this.once(i,a),this.once(n,c),t.signal?.addEventListener("abort",()=>{this.removeListener(n,c),this.removeListener(i,a),o(new Error(`Want for ${e} aborted`))})})}unwantBlock(e){let t=vy(e);this._log(t),this.emit(t)}};var Dy=F(jr(),1);var Ay=F(jr(),1),c2=F(Iy(),1),gl=class extends Ay.EventEmitter{_options;_queue;_stats;_frequencyLastTime;_frequencyAccumulators;_movingAverages;_enabled;_timeout;constructor(e,t){super(),this._options=t,this._queue=[],this._stats={},this._frequencyLastTime=Date.now(),this._frequencyAccumulators={},this._movingAverages={},this._update=this._update.bind(this),e.forEach(n=>{this._stats[n]=BigInt(0),this._movingAverages[n]={},this._options.movingAverageIntervals.forEach(i=>{(this._movingAverages[n][i]=(0,c2.default)(i)).push(this._frequencyLastTime,0)})}),this._enabled=this._options.enabled}enable(){this._enabled=!0}disable(){this._enabled=!1}stop(){this._timeout!=null&&clearTimeout(this._timeout)}get snapshot(){return Object.assign({},this._stats)}get movingAverages(){return Object.assign({},this._movingAverages)}push(e,t){this._enabled&&(this._queue.push([e,t,Date.now()]),this._resetComputeTimeout())}_resetComputeTimeout(){this._timeout!=null&&clearTimeout(this._timeout),this._timeout=setTimeout(this._update,this._nextTimeout())}_nextTimeout(){let e=this._queue.length/this._options.computeThrottleMaxQueueSize;return Math.max(this._options.computeThrottleTimeout*(1-e),0)}_update(){if(this._timeout=void 0,this._queue.length>0){let e;for(;this._queue.length>0;){let t=e=this._queue.shift();t!=null&&this._applyOp(t)}e!=null&&this._updateFrequency(e[2]),this.emit("update",this._stats)}}_updateFrequency(e){let t=e-this._frequencyLastTime;t>0&&Object.keys(this._stats).forEach(n=>{this._updateFrequencyFor(n,t,e)}),this._frequencyLastTime=e}_updateFrequencyFor(e,t,n){let i=this._frequencyAccumulators[e]??0;this._frequencyAccumulators[e]=0;let s=i/t*1e3,o=this._movingAverages[e];o==null&&(o=this._movingAverages[e]={}),this._options.movingAverageIntervals.forEach(a=>{let c=o[a];c==null&&(c=o[a]=(0,c2.default)(a)),c.push(n,s)})}_applyOp(e){let t=e[0],n=e[1];if(typeof n!="number")throw new Error(`invalid increment number: ${n}`);Object.prototype.hasOwnProperty.call(this._stats,t)||(this._stats[t]=BigInt(0)),this._stats[t]=BigInt(this._stats[t])+BigInt(n),this._frequencyAccumulators[t]==null&&(this._frequencyAccumulators[t]=0),this._frequencyAccumulators[t]+=n}};var Ty={enabled:!1,computeThrottleTimeout:1e3,computeThrottleMaxQueueSize:1e3,movingAverageIntervals:[60*1e3,5*60*1e3,15*60*1e3]},qh=class extends Dy.EventEmitter{_initialCounters;_options;_enabled;_global;_peers;constructor(e,t=[],n=Ty){super();let i=Object.assign({},Ty,n);if(typeof i.computeThrottleTimeout!="number")throw new Error("need computeThrottleTimeout");if(typeof i.computeThrottleMaxQueueSize!="number")throw new Error("need computeThrottleMaxQueueSize");this._initialCounters=t,this._options=i,this._enabled=this._options.enabled,this._global=new gl(t,i),this._global.on("update",s=>this.emit("update",s)),this._peers=fi({name:"ipfs_bitswap_stats_peers",metrics:e.metrics})}enable(){this._enabled=!0,this._options.enabled=!0,this._global.enable()}disable(){this._enabled=!1,this._options.enabled=!1,this._global.disable()}stop(){this._enabled=!1,this._global.stop();for(let e of this._peers)e[1].stop()}get snapshot(){return this._global.snapshot}get movingAverages(){return this._global.movingAverages}forPeer(e){let t=e.toString();return this._peers.get(t)}push(e,t,n){if(this._enabled&&(this._global.push(t,n),e!=null)){let i=this._peers.get(e);i==null&&(i=new gl(this._initialCounters,this._options),this._peers.set(e,i)),i.push(t,n)}}disconnected(e){let t=e.toString(),n=this._peers.get(t);n!=null&&(n.stop(),this._peers.delete(t))}};var Cy=zk;function zk(r,e,t){var n=null,i=null,s=function(){n&&(clearTimeout(n),i=null,n=null)},o=function(){var c=i;s(),c&&c()},a=function(){if(!e)return r.apply(this,arguments);var c=this,l=arguments,u=t&&!n;if(s(),i=function(){r.apply(c,l)},n=setTimeout(function(){if(n=null,!u){var h=i;return i=null,h()}},e),u)return i()};return a.cancel=s,a.flush=o,a}var zh=class{peerId;refcnt;network;_entries;_log;constructor(e,t,n){this.peerId=t,this.network=n,this.refcnt=1,this._entries=[],this._log=bn(e,"msgqueue"),this.sendEntries=Cy(this.sendEntries.bind(this),ly)}addMessage(e,t={}){e.empty||this.send(e,t)}addEntries(e,t={}){this._entries=this._entries.concat(e),this.sendEntries(t)}sendEntries(e={}){if(this._entries.length===0)return;let t=new Lt(!1);this._entries.forEach(n=>{n.cancel===!0?t.cancel(n.cid):t.addEntry(n.cid,n.priority)}),this._entries=[],this.addMessage(t,e)}async send(e,t={}){try{await this.network.connectTo(this.peerId,t)}catch(n){this._log.error("cant connect to peer %p: %s",this.peerId,n.message);return}this._log("sending message to peer %p",this.peerId),this.network.sendMessage(this.peerId,e,t).catch(n=>{this._log.error("send error",n)})}};var Hh=class{peers;wantlist;network;_peerId;_log;constructor(e,t,n,i){this.peers=fi({name:"ipfs_bitswap_want_manager_peers",metrics:i.metrics}),this.wantlist=new Gi(n,i),this.network=t,this._peerId=e,this._log=bn(e,"want")}_addEntries(e,t,n,i={}){let s=e.map((o,a)=>new Lt.Entry(o,ay-a,Lt.WantType.Block,t));s.forEach(o=>{o.cancel?n===!0?this.wantlist.removeForce(o.cid.toString(me)):this.wantlist.remove(o.cid):(this._log("adding to wantlist"),this.wantlist.add(o.cid,o.priority))});for(let o of this.peers.values())o.addEntries(s,i)}_startPeerHandler(e){let t=this.peers.get(e.toString());if(t!=null){t.refcnt++;return}t=new zh(this._peerId,e,this.network);let n=new Lt(!0);for(let i of this.wantlist.entries())n.addEntry(i[1].cid,i[1].priority);return t.addMessage(n),this.peers.set(e.toString(),t),t}_stopPeerHandler(e){let t=this.peers.get(e.toString());t!=null&&(t.refcnt--,!(t.refcnt>0)&&this.peers.delete(e.toString()))}wantBlocks(e,t={}){this._addEntries(e,!1,!1,t),t.signal?.addEventListener("abort",()=>{this.cancelWants(e)})}unwantBlocks(e){this._log("unwant blocks: %s",e.length),this._addEntries(e,!0,!0)}cancelWants(e){this._log("cancel wants: %s",e.length),this._addEntries(e,!0)}connectedPeers(){return Array.from(this.peers.keys())}connected(e){this._startPeerHandler(e)}disconnected(e){this._stopPeerHandler(e)}start(){}stop(){this.peers.forEach(e=>{this.disconnected(e.peerId)})}};var Hk={async getHasher(){throw new Error("Not implemented")}},$k={maxInboundStreams:1024,maxOutboundStreams:1024,incomingStreamTimeout:3e4,hashLoader:Hk,statsEnabled:!1,statsComputeThrottleTimeout:1e3,statsComputeThrottleMaxQueueSize:1e3},Gk=["blocksReceived","dataReceived","dupBlksReceived","dupDataReceived","blocksSent","dataSent","providesBufferLength","wantListLength","peerCount"],$h=class{_libp2p;_log;stats;network;blockstore;engine;wm;notifications;started;constructor(e,t,n={}){this._libp2p=e,this._log=bn(this.peerId),n=Object.assign({},$k,n),this.stats=new qh(e,Gk,{enabled:n.statsEnabled,computeThrottleTimeout:n.statsComputeThrottleTimeout,computeThrottleMaxQueueSize:n.statsComputeThrottleMaxQueueSize}),this.network=new Uh(e,this,this.stats,{hashLoader:n.hashLoader,maxInboundStreams:n.maxInboundStreams,maxOutboundStreams:n.maxOutboundStreams,incomingStreamTimeout:n.incomingStreamTimeout}),this.blockstore=t,this.engine=new Ph(this.peerId,t,this.network,this.stats,e),this.wm=new Hh(this.peerId,this.network,this.stats,e),this.notifications=new Vh(this.peerId),this.started=!1}isStarted(){return this.started}get peerId(){return this._libp2p.peerId}async _receiveMessage(e,t){try{await this.engine.messageReceived(e,t)}catch{this._log("failed to receive message",t)}if(t.blocks.size===0)return;let n=[];for(let[i,s]of t.blocks.entries()){let o=ee.parse(i);n.push({wasWanted:this.wm.wantlist.contains(o),cid:o,data:s})}this.wm.cancelWants(n.filter(({wasWanted:i})=>i).map(({cid:i})=>i)),await Promise.all(n.map(async({cid:i,wasWanted:s,data:o})=>{await this._handleReceivedBlock(e,i,o,s)}))}async _handleReceivedBlock(e,t,n,i){this._log("received block");let s=await this.blockstore.has(t);this._updateReceiveCounters(e.toString(),t,n,s),i&&await this.put(t,n)}_updateReceiveCounters(e,t,n,i){this.stats.push(e,"blocksReceived",1),this.stats.push(e,"dataReceived",n.length),i&&(this.stats.push(e,"dupBlksReceived",1),this.stats.push(e,"dupDataReceived",n.length))}_receiveError(e){this._log.error("ReceiveError",e)}_onPeerConnected(e){this.wm.connected(e)}_onPeerDisconnected(e){this.wm.disconnected(e),this.engine.peerDisconnected(e),this.stats.disconnected(e)}enableStats(){this.stats.enable()}disableStats(){this.stats.disable()}wantlistForPeer(e,t){return this.engine.wantlistForPeer(e)}ledgerForPeer(e){return this.engine.ledgerForPeer(e)}async want(e,t={}){let n=async(c,l)=>(this.wm.wantBlocks([c],l),this.notifications.wantBlock(c,l)),i=!1,s=async(c,l)=>{try{return await this.blockstore.get(c,l)}catch(u){if(u.code!=="ERR_NOT_FOUND")throw u;return i||(i=!0,this.network.findAndConnect(c,l).catch(h=>{this._log.error(h)})),await n(c,l)}},o=new AbortController,a=st([o.signal,t.signal]);try{return await Promise.race([this.notifications.wantBlock(e,{...t,signal:a}),s(e,{...t,signal:a})])}finally{o.abort(),a.clear()}}unwant(e){let t=Array.isArray(e)?e:[e];this.wm.unwantBlocks(t),t.forEach(n=>{this.notifications.unwantBlock(n)})}cancelWants(e){this.wm.cancelWants(Array.isArray(e)?e:[e])}async put(e,t,n){await this.blockstore.put(e,t),this.notify(e,t)}async*putMany(e,t){yield*this.blockstore.putMany(ll(e,({cid:n,block:i})=>{this.notify(n,i)}),t)}notify(e,t,n={}){this.notifications.hasBlock(e,t),this.engine.receivedBlocks([{cid:e,block:t}]),this.network.provide(e,n).catch(i=>{this._log.error("Failed to provide: %s",i.message)})}getWantlist(){return this.wm.wantlist.entries()}get peers(){return this.engine.peers()}async start(){this.wm.start(),await this.network.start(),this.engine.start(),this.started=!0}async stop(){this.stats.stop(),this.wm.stop(),await this.network.stop(),this.engine.stop(),this.started=!1}};var Py=(r,e,t={})=>new $h(r,e,t);var Wk=["string","number","bigint","symbol"],Yk=["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 ky(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(Wk.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(Qk(r))return"Buffer";let t=Xk(r);return t||"Object"}function Qk(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function Xk(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(Yk.includes(e))return e}var S=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}};S.uint=new S(0,"uint",!0);S.negint=new S(1,"negint",!0);S.bytes=new S(2,"bytes",!0);S.string=new S(3,"string",!0);S.array=new S(4,"array",!1);S.map=new S(5,"map",!1);S.tag=new S(6,"tag",!1);S.float=new S(7,"float",!0);S.false=new S(7,"false",!0);S.true=new S(7,"true",!0);S.null=new S(7,"null",!0);S.undefined=new S(7,"undefined",!0);S.break=new S(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 _a=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",jk=new TextDecoder,Zk=new TextEncoder;function Gh(r){return _a&&globalThis.Buffer.isBuffer(r)}function yl(r){return r instanceof Uint8Array?Gh(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var By=_a?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):Ly(r,e,t):(r,e,t)=>t-e>64?jk.decode(r.subarray(e,t)):Ly(r,e,t),Wh=_a?r=>r.length>64?globalThis.Buffer.from(r):Ny(r):r=>r.length>64?Zk.encode(r):Ny(r),gi=r=>Uint8Array.from(r),Sa=_a?(r,e,t)=>Gh(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),My=_a?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),yl(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let i of r)n+i.length>t.length&&(i=i.subarray(0,t.length-n)),t.set(i,n),n+=i.length;return t},Uy=_a?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function Fy(r,e){if(Gh(r)&&Gh(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 Ny(r,e=1/0){let t,n=r.length,i=null,s=[];for(let o=0;o<n;++o){if(t=r.charCodeAt(o),t>55295&&t<57344){if(!i){if(t>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=t;continue}if(t<56320){(e-=3)>-1&&s.push(239,191,189),i=t;continue}t=(i-55296<<10|t-56320)+65536}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,t<128){if((e-=1)<0)break;s.push(t)}else if(t<2048){if((e-=2)<0)break;s.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;s.push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;s.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code point")}return s}function Ly(r,e,t){let n=[];for(;e<t;){let i=r[e],s=null,o=i>239?4:i>223?3:i>191?2:1;if(e+o<=t){let a,c,l,u;switch(o){case 1:i<128&&(s=i);break;case 2:a=r[e+1],(a&192)===128&&(u=(i&31)<<6|a&63,u>127&&(s=u));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(u=(i&15)<<12|(a&63)<<6|c&63,u>2047&&(u<55296||u>57343)&&(s=u));break;case 4:a=r[e+1],c=r[e+2],l=r[e+3],(a&192)===128&&(c&192)===128&&(l&192)===128&&(u=(i&15)<<18|(a&63)<<12|(c&63)<<6|l&63,u>65535&&u<1114112&&(s=u))}}s===null?(s=65533,o=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|s&1023),n.push(s),e+=o}return l2(n)}var Oy=4096;function l2(r){let e=r.length;if(e<=Oy)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Oy));return t}var Jk=256,wl=class{constructor(e=Jk){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 i=t.length-(this.maxCursor-this.cursor)-1;t.set(e,i)}else{if(t){let i=t.length-(this.maxCursor-this.cursor)-1;i<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,i),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=Uy(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=Sa(n,0,this.cursor)}else t=My(this.chunks,this.cursor);return e&&this.reset(),t}};var Y="CBOR decode error:",Ra="CBOR encode error:",bl=[];bl[23]=1;bl[24]=2;bl[25]=3;bl[26]=5;bl[27]=9;function Wi(r,e,t){if(r.length-e<t)throw new Error(`${Y} not enough data for type`)}var jt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Zr(r,e,t){Wi(r,e,1);let n=r[e];if(t.strict===!0&&n<jt[0])throw new Error(`${Y} integer encoded in more bytes than necessary (strict decode)`);return n}function Jr(r,e,t){Wi(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<jt[1])throw new Error(`${Y} integer encoded in more bytes than necessary (strict decode)`);return n}function en(r,e,t){Wi(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<jt[2])throw new Error(`${Y} integer encoded in more bytes than necessary (strict decode)`);return n}function tn(r,e,t){Wi(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],i=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],s=(BigInt(n)<<BigInt(32))+BigInt(i);if(t.strict===!0&&s<jt[3])throw new Error(`${Y} integer encoded in more bytes than necessary (strict decode)`);if(s<=Number.MAX_SAFE_INTEGER)return Number(s);if(t.allowBigInt===!0)return s;throw new Error(`${Y} integers outside of the safe integer range are not supported`)}function Ky(r,e,t,n){return new U(S.uint,Zr(r,e+1,n),2)}function Vy(r,e,t,n){return new U(S.uint,Jr(r,e+1,n),3)}function qy(r,e,t,n){return new U(S.uint,en(r,e+1,n),5)}function zy(r,e,t,n){return new U(S.uint,tn(r,e+1,n),9)}function vn(r,e){return ar(r,0,e.value)}function ar(r,e,t){if(t<jt[0]){let n=Number(t);r.push([e|n])}else if(t<jt[1]){let n=Number(t);r.push([e|24,n])}else if(t<jt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<jt[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<jt[4]){let i=[e|27,0,0,0,0,0,0,0],s=Number(n&BigInt(4294967295)),o=Number(n>>BigInt(32)&BigInt(4294967295));i[8]=s&255,s=s>>8,i[7]=s&255,s=s>>8,i[6]=s&255,s=s>>8,i[5]=s&255,i[4]=o&255,o=o>>8,i[3]=o&255,o=o>>8,i[2]=o&255,o=o>>8,i[1]=o&255,r.push(i)}else throw new Error(`${Y} encountered BigInt larger than allowable range`)}}vn.encodedSize=function(e){return ar.encodedSize(e.value)};ar.encodedSize=function(e){return e<jt[0]?1:e<jt[1]?2:e<jt[2]?3:e<jt[3]?5:9};vn.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function Hy(r,e,t,n){return new U(S.negint,-1-Zr(r,e+1,n),2)}function $y(r,e,t,n){return new U(S.negint,-1-Jr(r,e+1,n),3)}function Gy(r,e,t,n){return new U(S.negint,-1-en(r,e+1,n),5)}var u2=BigInt(-1),Wy=BigInt(1);function Yy(r,e,t,n){let i=tn(r,e+1,n);if(typeof i!="bigint"){let s=-1-i;if(s>=Number.MIN_SAFE_INTEGER)return new U(S.negint,s,9)}if(n.allowBigInt!==!0)throw new Error(`${Y} integers outside of the safe integer range are not supported`);return new U(S.negint,u2-BigInt(i),9)}function Yh(r,e){let t=e.value,n=typeof t=="bigint"?t*u2-Wy:t*-1-1;ar(r,e.type.majorEncoded,n)}Yh.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*u2-Wy:t*-1-1;return n<jt[0]?1:n<jt[1]?2:n<jt[2]?3:n<jt[3]?5:9};Yh.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function El(r,e,t,n){Wi(r,e,t+n);let i=Sa(r,e+t,e+t+n);return new U(S.bytes,i,t+n)}function Qy(r,e,t,n){return El(r,e,1,t)}function Xy(r,e,t,n){return El(r,e,2,Zr(r,e+1,n))}function jy(r,e,t,n){return El(r,e,3,Jr(r,e+1,n))}function Zy(r,e,t,n){return El(r,e,5,en(r,e+1,n))}function Jy(r,e,t,n){let i=tn(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Y} 64-bit integer bytes lengths not supported`);return El(r,e,9,i)}function Qh(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===S.string?Wh(r.value):r.value),r.encodedBytes}function Ia(r,e){let t=Qh(e);ar(r,e.type.majorEncoded,t.length),r.push(t)}Ia.encodedSize=function(e){let t=Qh(e);return ar.encodedSize(t.length)+t.length};Ia.compareTokens=function(e,t){return tN(Qh(e),Qh(t))};function tN(r,e){return r.length<e.length?-1:r.length>e.length?1:Fy(r,e)}function vl(r,e,t,n,i){let s=t+n;Wi(r,e,s);let o=new U(S.string,By(r,e+t,e+s),s);return i.retainStringBytes===!0&&(o.byteValue=Sa(r,e+t,e+s)),o}function e7(r,e,t,n){return vl(r,e,1,t,n)}function t7(r,e,t,n){return vl(r,e,2,Zr(r,e+1,n),n)}function r7(r,e,t,n){return vl(r,e,3,Jr(r,e+1,n),n)}function n7(r,e,t,n){return vl(r,e,5,en(r,e+1,n),n)}function i7(r,e,t,n){let i=tn(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Y} 64-bit integer string lengths not supported`);return vl(r,e,9,i,n)}var s7=Ia;function Aa(r,e,t,n){return new U(S.array,n,t)}function o7(r,e,t,n){return Aa(r,e,1,t)}function a7(r,e,t,n){return Aa(r,e,2,Zr(r,e+1,n))}function c7(r,e,t,n){return Aa(r,e,3,Jr(r,e+1,n))}function l7(r,e,t,n){return Aa(r,e,5,en(r,e+1,n))}function u7(r,e,t,n){let i=tn(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Y} 64-bit integer array lengths not supported`);return Aa(r,e,9,i)}function h7(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Y} indefinite length items not allowed`);return Aa(r,e,1,1/0)}function Xh(r,e){ar(r,S.array.majorEncoded,e.value)}Xh.compareTokens=vn.compareTokens;Xh.encodedSize=function(e){return ar.encodedSize(e.value)};function Ta(r,e,t,n){return new U(S.map,n,t)}function f7(r,e,t,n){return Ta(r,e,1,t)}function d7(r,e,t,n){return Ta(r,e,2,Zr(r,e+1,n))}function p7(r,e,t,n){return Ta(r,e,3,Jr(r,e+1,n))}function m7(r,e,t,n){return Ta(r,e,5,en(r,e+1,n))}function g7(r,e,t,n){let i=tn(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Y} 64-bit integer map lengths not supported`);return Ta(r,e,9,i)}function y7(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Y} indefinite length items not allowed`);return Ta(r,e,1,1/0)}function jh(r,e){ar(r,S.map.majorEncoded,e.value)}jh.compareTokens=vn.compareTokens;jh.encodedSize=function(e){return ar.encodedSize(e.value)};function w7(r,e,t,n){return new U(S.tag,t,1)}function b7(r,e,t,n){return new U(S.tag,Zr(r,e+1,n),2)}function E7(r,e,t,n){return new U(S.tag,Jr(r,e+1,n),3)}function v7(r,e,t,n){return new U(S.tag,en(r,e+1,n),5)}function x7(r,e,t,n){return new U(S.tag,tn(r,e+1,n),9)}function Zh(r,e){ar(r,S.tag.majorEncoded,e.value)}Zh.compareTokens=vn.compareTokens;Zh.encodedSize=function(e){return ar.encodedSize(e.value)};var aN=20,cN=21,lN=22,uN=23;function _7(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${Y} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new U(S.null,null,1):new U(S.undefined,void 0,1)}function S7(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Y} indefinite length items not allowed`);return new U(S.break,void 0,1)}function h2(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${Y} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${Y} Infinity values are not supported`)}return new U(S.float,r,e)}function R7(r,e,t,n){return h2(f2(r,e+1),3,n)}function I7(r,e,t,n){return h2(d2(r,e+1),5,n)}function A7(r,e,t,n){return h2(P7(r,e+1),9,n)}function Jh(r,e,t){let n=e.value;if(n===!1)r.push([S.float.majorEncoded|aN]);else if(n===!0)r.push([S.float.majorEncoded|cN]);else if(n===null)r.push([S.float.majorEncoded|lN]);else if(n===void 0)r.push([S.float.majorEncoded|uN]);else{let i,s=!1;(!t||t.float64!==!0)&&(D7(n),i=f2(Vn,1),n===i||Number.isNaN(n)?(Vn[0]=249,r.push(Vn.slice(0,3)),s=!0):(C7(n),i=d2(Vn,1),n===i&&(Vn[0]=250,r.push(Vn.slice(0,5)),s=!0))),s||(hN(n),i=P7(Vn,1),Vn[0]=251,r.push(Vn.slice(0,9)))}}Jh.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){D7(n);let i=f2(Vn,1);if(n===i||Number.isNaN(n))return 3;if(C7(n),i=d2(Vn,1),n===i)return 5}return 9};var T7=new ArrayBuffer(9),xn=new DataView(T7,1),Vn=new Uint8Array(T7,0);function D7(r){if(r===1/0)xn.setUint16(0,31744,!1);else if(r===-1/0)xn.setUint16(0,64512,!1);else if(Number.isNaN(r))xn.setUint16(0,32256,!1);else{xn.setFloat32(0,r);let e=xn.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)xn.setUint16(0,31744,!1);else if(t===0)xn.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?xn.setUint16(0,0):i<-14?xn.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):xn.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function f2(r,e){if(r.length-e<2)throw new Error(`${Y} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,i=t&1023,s;return n===0?s=i*2**-24:n!==31?s=(i+1024)*2**(n-25):s=i===0?1/0:NaN,t&32768?-s:s}function C7(r){xn.setFloat32(0,r,!1)}function d2(r,e){if(r.length-e<4)throw new Error(`${Y} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function hN(r){xn.setFloat64(0,r,!1)}function P7(r,e){if(r.length-e<8)throw new Error(`${Y} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}Jh.compareTokens=vn.compareTokens;function We(r,e,t){throw new Error(`${Y} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function ef(r){return()=>{throw new Error(`${Y} ${r}`)}}var V=[];for(let r=0;r<=23;r++)V[r]=We;V[24]=Ky;V[25]=Vy;V[26]=qy;V[27]=zy;V[28]=We;V[29]=We;V[30]=We;V[31]=We;for(let r=32;r<=55;r++)V[r]=We;V[56]=Hy;V[57]=$y;V[58]=Gy;V[59]=Yy;V[60]=We;V[61]=We;V[62]=We;V[63]=We;for(let r=64;r<=87;r++)V[r]=Qy;V[88]=Xy;V[89]=jy;V[90]=Zy;V[91]=Jy;V[92]=We;V[93]=We;V[94]=We;V[95]=ef("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)V[r]=e7;V[120]=t7;V[121]=r7;V[122]=n7;V[123]=i7;V[124]=We;V[125]=We;V[126]=We;V[127]=ef("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)V[r]=o7;V[152]=a7;V[153]=c7;V[154]=l7;V[155]=u7;V[156]=We;V[157]=We;V[158]=We;V[159]=h7;for(let r=160;r<=183;r++)V[r]=f7;V[184]=d7;V[185]=p7;V[186]=m7;V[187]=g7;V[188]=We;V[189]=We;V[190]=We;V[191]=y7;for(let r=192;r<=215;r++)V[r]=w7;V[216]=b7;V[217]=E7;V[218]=v7;V[219]=x7;V[220]=We;V[221]=We;V[222]=We;V[223]=We;for(let r=224;r<=243;r++)V[r]=ef("simple values are not supported");V[244]=We;V[245]=We;V[246]=We;V[247]=_7;V[248]=ef("simple values are not supported");V[249]=R7;V[250]=I7;V[251]=A7;V[252]=We;V[253]=We;V[254]=We;V[255]=S7;var qn=[];for(let r=0;r<24;r++)qn[r]=new U(S.uint,r,1);for(let r=-1;r>=-24;r--)qn[31-r]=new U(S.negint,r,1);qn[64]=new U(S.bytes,new Uint8Array(0),1);qn[96]=new U(S.string,"",1);qn[128]=new U(S.array,0,1);qn[160]=new U(S.map,0,1);qn[244]=new U(S.false,!1,1);qn[245]=new U(S.true,!0,1);qn[246]=new U(S.null,null,1);function k7(r){switch(r.type){case S.false:return gi([244]);case S.true:return gi([245]);case S.null:return gi([246]);case S.bytes:return r.value.length?void 0:gi([64]);case S.string:return r.value===""?gi([96]):void 0;case S.array:return r.value===0?gi([128]):void 0;case S.map:return r.value===0?gi([160]):void 0;case S.uint:return r.value<24?gi([Number(r.value)]):void 0;case S.negint:if(r.value>=-24)return gi([31-Number(r.value)])}}var dN={float64:!1,mapSorter:gN,quickEncodeToken:k7};function pN(){let r=[];return r[S.uint.major]=vn,r[S.negint.major]=Yh,r[S.bytes.major]=Ia,r[S.string.major]=s7,r[S.array.major]=Xh,r[S.map.major]=jh,r[S.tag.major]=Zh,r[S.float.major]=Jh,r}var N7=pN(),p2=new wl,Da=class{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(`${Ra} object contains circular references`);return new Da(t,e)}},xs={null:new U(S.null,null),undefined:new U(S.undefined,void 0),true:new U(S.true,!0),false:new U(S.false,!1),emptyArray:new U(S.array,0),emptyMap:new U(S.map,0)},_s={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new U(S.float,r):r>=0?new U(S.uint,r):new U(S.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new U(S.uint,r):new U(S.negint,r)},Uint8Array(r,e,t,n){return new U(S.bytes,r)},string(r,e,t,n){return new U(S.string,r)},boolean(r,e,t,n){return r?xs.true:xs.false},null(r,e,t,n){return xs.null},undefined(r,e,t,n){return xs.undefined},ArrayBuffer(r,e,t,n){return new U(S.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new U(S.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[xs.emptyArray,new U(S.break)]:xs.emptyArray;n=Da.createCheck(n,r);let i=[],s=0;for(let o of r)i[s++]=tf(o,t,n);return t.addBreakTokens?[new U(S.array,r.length),i,new U(S.break)]:[new U(S.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",s=i?r.keys():Object.keys(r),o=i?r.size:s.length;if(!o)return t.addBreakTokens===!0?[xs.emptyMap,new U(S.break)]:xs.emptyMap;n=Da.createCheck(n,r);let a=[],c=0;for(let l of s)a[c++]=[tf(l,t,n),tf(i?r.get(l):r[l],t,n)];return mN(a,t),t.addBreakTokens?[new U(S.map,o),a,new U(S.break)]:[new U(S.map,o),a]}};_s.Map=_s.Object;_s.Buffer=_s.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))_s[`${r}Array`]=_s.DataView;function tf(r,e={},t){let n=ky(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||_s[n];if(typeof i=="function"){let o=i(r,n,e,t);if(o!=null)return o}let s=_s[n];if(!s)throw new Error(`${Ra} unsupported type: ${n}`);return s(r,n,e,t)}function mN(r,e){e.mapSorter&&r.sort(e.mapSorter)}function gN(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let i=t.type.major,s=N7[i].compareTokens(t,n);return s===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),s}function L7(r,e,t,n){if(Array.isArray(e))for(let i of e)L7(r,i,t,n);else t[e.type.major](r,e,n)}function O7(r,e,t){let n=tf(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let i=t.quickEncodeToken(n);if(i)return i;let s=e[n.type.major];if(s.encodedSize){let o=s.encodedSize(n,t),a=new wl(o);if(s(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return yl(a.chunks[0])}}return p2.reset(),L7(p2,n,e,t),p2.toBytes(!0)}function xl(r,e){return e=Object.assign({},dN,e),O7(r,N7,e)}var yN={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},m2=class{constructor(e,t={}){this.pos=0,this.data=e,this.options=t}done(){return this.pos>=this.data.length}next(){let e=this.data[this.pos],t=qn[e];if(t===void 0){let n=V[e];if(!n)throw new Error(`${Y} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let i=e&31;t=n(this.data,this.pos,i,this.options)}return this.pos+=t.encodedLength,t}},_l=Symbol.for("DONE"),rf=Symbol.for("BREAK");function wN(r,e,t){let n=[];for(let i=0;i<r.value;i++){let s=Sl(e,t);if(s===rf){if(r.value===1/0)break;throw new Error(`${Y} got unexpected break to lengthed array`)}if(s===_l)throw new Error(`${Y} found array but not enough entries (got ${i}, expected ${r.value})`);n[i]=s}return n}function bN(r,e,t){let n=t.useMaps===!0,i=n?void 0:{},s=n?new Map:void 0;for(let o=0;o<r.value;o++){let a=Sl(e,t);if(a===rf){if(r.value===1/0)break;throw new Error(`${Y} got unexpected break to lengthed map`)}if(a===_l)throw new Error(`${Y} found map but not enough entries (got ${o} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${Y} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&s.has(a)||!n&&a in i))throw new Error(`${Y} found repeat map key "${a}"`);let c=Sl(e,t);if(c===_l)throw new Error(`${Y} found map but not enough entries (got ${o} [no value], expected ${r.value})`);n?s.set(a,c):i[a]=c}return n?s:i}function Sl(r,e){if(r.done())return _l;let t=r.next();if(t.type===S.break)return rf;if(t.type.terminal)return t.value;if(t.type===S.array)return wN(t,r,e);if(t.type===S.map)return bN(t,r,e);if(t.type===S.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=Sl(r,e);return e.tags[t.value](n)}throw new Error(`${Y} tag not supported (${t.value})`)}throw new Error("unsupported")}function zn(r,e){if(!(r instanceof Uint8Array))throw new Error(`${Y} data to decode must be a Uint8Array`);e=Object.assign({},yN,e);let t=e.tokenizer||new m2(r,e),n=Sl(t,e);if(n===_l)throw new Error(`${Y} did not find any content to decode`);if(n===rf)throw new Error(`${Y} got unexpected break`);if(!t.done())throw new Error(`${Y} too many terminals, data makes no sense`);return n}function Pe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var G7=F(M7(),1);var Il=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},w2=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},U7=r=>globalThis.DOMException===void 0?new w2(r):new DOMException(r),F7=r=>{let e=r.reason===void 0?U7("This operation was aborted."):r.reason;return e instanceof Error?e:U7(e)};function b2(r,e,t,n){let i,s=new Promise((o,a)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(e===Number.POSITIVE_INFINITY){o(r);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:c}=n;c.aborted&&a(F7(c)),c.addEventListener("abort",()=>{a(F7(c))})}i=n.customTimers.setTimeout.call(void 0,()=>{if(typeof t=="function"){try{o(t())}catch(u){a(u)}return}let c=typeof t=="string"?t:`Promise timed out after ${e} milliseconds`,l=t instanceof Error?t:new Il(c);typeof r.cancel=="function"&&r.cancel(),a(l)},e),(async()=>{try{o(await r)}catch(c){a(c)}finally{n.customTimers.clearTimeout.call(void 0,i)}})()});return s.clear=()=>{clearTimeout(i),i=void 0},s}function E2(r,e,t){let n=0,i=r.length;for(;i>0;){let s=Math.trunc(i/2),o=n+s;t(r[o],e)<=0?(n=++o,i-=s+1):i=s}return n}var Io=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Yi,Al=class{constructor(){Yi.set(this,[])}enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&Io(this,Yi,"f")[this.size-1].priority>=t.priority){Io(this,Yi,"f").push(n);return}let i=E2(Io(this,Yi,"f"),n,(s,o)=>o.priority-s.priority);Io(this,Yi,"f").splice(i,0,n)}dequeue(){let e=Io(this,Yi,"f").shift();return e?.run}filter(e){return Io(this,Yi,"f").filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return Io(this,Yi,"f").length}};Yi=new WeakMap;var St=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},Q=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Ot,Dl,Cl,Rs,uf,Pl,sf,Hn,Tl,rn,of,nn,kl,Ss,af,K7,V7,H7,q7,z7,cf,v2,x2,hf,$7,lf,ff=class extends Error{},wt=class extends G7.default{constructor(e){var t,n,i,s;if(super(),Ot.add(this),Dl.set(this,void 0),Cl.set(this,void 0),Rs.set(this,0),uf.set(this,void 0),Pl.set(this,void 0),sf.set(this,0),Hn.set(this,void 0),Tl.set(this,void 0),rn.set(this,void 0),of.set(this,void 0),nn.set(this,0),kl.set(this,void 0),Ss.set(this,void 0),af.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Al,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(s=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""}\` (${typeof e.interval})`);St(this,Dl,e.carryoverConcurrencyCount,"f"),St(this,Cl,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),St(this,uf,e.intervalCap,"f"),St(this,Pl,e.interval,"f"),St(this,rn,new e.queueClass,"f"),St(this,of,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,St(this,af,e.throwOnTimeout===!0,"f"),St(this,Ss,e.autoStart===!1,"f")}get concurrency(){return Q(this,kl,"f")}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);St(this,kl,e,"f"),Q(this,Ot,"m",hf).call(this)}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:Q(this,af,"f"),...t},new Promise((n,i)=>{Q(this,rn,"f").enqueue(async()=>{var s,o,a;St(this,nn,(o=Q(this,nn,"f"),o++,o),"f"),St(this,Rs,(a=Q(this,Rs,"f"),a++,a),"f");try{if(!((s=t.signal)===null||s===void 0)&&s.aborted)throw new ff("The task was aborted.");let c=e({signal:t.signal});t.timeout&&(c=b2(Promise.resolve(c),t.timeout)),t.signal&&(c=Promise.race([c,Q(this,Ot,"m",$7).call(this,t.signal)]));let l=await c;n(l),this.emit("completed",l)}catch(c){if(c instanceof Il&&!t.throwOnTimeout){n();return}i(c),this.emit("error",c)}finally{Q(this,Ot,"m",H7).call(this)}},t),this.emit("add"),Q(this,Ot,"m",cf).call(this)})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return Q(this,Ss,"f")?(St(this,Ss,!1,"f"),Q(this,Ot,"m",hf).call(this),this):this}pause(){St(this,Ss,!0,"f")}clear(){St(this,rn,new(Q(this,of,"f")),"f")}async onEmpty(){Q(this,rn,"f").size!==0&&await Q(this,Ot,"m",lf).call(this,"empty")}async onSizeLessThan(e){Q(this,rn,"f").size<e||await Q(this,Ot,"m",lf).call(this,"next",()=>Q(this,rn,"f").size<e)}async onIdle(){Q(this,nn,"f")===0&&Q(this,rn,"f").size===0||await Q(this,Ot,"m",lf).call(this,"idle")}get size(){return Q(this,rn,"f").size}sizeBy(e){return Q(this,rn,"f").filter(e).length}get pending(){return Q(this,nn,"f")}get isPaused(){return Q(this,Ss,"f")}};Dl=new WeakMap,Cl=new WeakMap,Rs=new WeakMap,uf=new WeakMap,Pl=new WeakMap,sf=new WeakMap,Hn=new WeakMap,Tl=new WeakMap,rn=new WeakMap,of=new WeakMap,nn=new WeakMap,kl=new WeakMap,Ss=new WeakMap,af=new WeakMap,Ot=new WeakSet,K7=function(){return Q(this,Cl,"f")||Q(this,Rs,"f")<Q(this,uf,"f")},V7=function(){return Q(this,nn,"f")<Q(this,kl,"f")},H7=function(){var e;St(this,nn,(e=Q(this,nn,"f"),e--,e),"f"),Q(this,Ot,"m",cf).call(this),this.emit("next")},q7=function(){Q(this,Ot,"m",x2).call(this),Q(this,Ot,"m",v2).call(this),St(this,Tl,void 0,"f")},z7=function(){let e=Date.now();if(Q(this,Hn,"f")===void 0){let t=Q(this,sf,"f")-e;if(t<0)St(this,Rs,Q(this,Dl,"f")?Q(this,nn,"f"):0,"f");else return Q(this,Tl,"f")===void 0&&St(this,Tl,setTimeout(()=>{Q(this,Ot,"m",q7).call(this)},t),"f"),!0}return!1},cf=function(){if(Q(this,rn,"f").size===0)return Q(this,Hn,"f")&&clearInterval(Q(this,Hn,"f")),St(this,Hn,void 0,"f"),this.emit("empty"),Q(this,nn,"f")===0&&this.emit("idle"),!1;if(!Q(this,Ss,"f")){let e=!Q(this,Ot,"a",z7);if(Q(this,Ot,"a",K7)&&Q(this,Ot,"a",V7)){let t=Q(this,rn,"f").dequeue();return t?(this.emit("active"),t(),e&&Q(this,Ot,"m",v2).call(this),!0):!1}}return!1},v2=function(){Q(this,Cl,"f")||Q(this,Hn,"f")!==void 0||(St(this,Hn,setInterval(()=>{Q(this,Ot,"m",x2).call(this)},Q(this,Pl,"f")),"f"),St(this,sf,Date.now()+Q(this,Pl,"f"),"f"))},x2=function(){Q(this,Rs,"f")===0&&Q(this,nn,"f")===0&&Q(this,Hn,"f")&&(clearInterval(Q(this,Hn,"f")),St(this,Hn,void 0,"f")),St(this,Rs,Q(this,Dl,"f")?Q(this,nn,"f"):0,"f"),Q(this,Ot,"m",hf).call(this)},hf=function(){for(;Q(this,Ot,"m",cf).call(this););},$7=async function(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(new ff("The task was aborted."))},{once:!0})})},lf=async function(e,t){return new Promise(n=>{let i=()=>{t&&!t()||(this.off(e,i),n())};this.on(e,i)})};var xN=new TextDecoder;function _2(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let i=r[e++];if(t+=n<28?(i&127)<<n:(i&127)*2**n,i<128)break}return[t,e]}function df(r,e){let t;[t,e]=_2(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 W7(r,e){let t;return[t,e]=_2(r,e),[t&7,t>>3,e]}function _N(r){let e={},t=r.length,n=0;for(;n<t;){let i,s;if([i,s,n]=W7(r,n),s===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) 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]=df(r,n)}else if(s===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let o;[o,n]=df(r,n),e.Name=xN.decode(o)}else if(s===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(i!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Tsize`);[e.Tsize,n]=_2(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${s}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function Y7(r){let e=r.length,t=0,n,i=!1,s;for(;t<e;){let a,c;if([a,c,t]=W7(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(s)throw new Error("protobuf: (PBNode) duplicate Data section");[s,t]=df(r,t),n&&(i=!0)}else if(c===2){if(i)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=df(r,t),n.push(_N(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 o={};return s&&(o.Data=s),o.Links=n||[],o}var bJ=new TextEncoder,EJ=2**32,vJ=2**31;var SJ=new TextEncoder;var Q7=112;function X7(r){let e=Y7(r),t={};return e.Data&&(t.Data=e.Data),e.Links&&(t.Links=e.Links.map(n=>{let i={};try{i.Hash=ee.decode(n.Hash)}catch{}if(!i.Hash)throw new Error("Invalid Hash field found in link, expected CID");return n.Name!==void 0&&(i.Name=n.Name),n.Tsize!==void 0&&(i.Tsize=n.Tsize),i})),t}var j7=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===S.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===S.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[S.uint.major](e,t){this.prefix(e);let n=String(t.value),i=[];for(let s=0;s<n.length;s++)i[s]=n.charCodeAt(s);e.push(i)}[S.negint.major](e,t){this[S.uint.major](e,t)}[S.bytes.major](e,t){throw new Error(`${Ra} unsupported type: Uint8Array`)}[S.string.major](e,t){this.prefix(e);let n=Wh(JSON.stringify(t.value));e.push(n.length>32?yl(n):n)}[S.array.major](e,t){this.prefix(e),this.inRecursive.push({type:S.array,elements:0}),e.push([91])}[S.map.major](e,t){this.prefix(e),this.inRecursive.push({type:S.map,elements:0}),e.push([123])}[S.tag.major](e,t){}[S.float.major](e,t){if(t.type.name==="break"){let o=this.inRecursive.pop();if(o){if(o.type===S.array)e.push([93]);else if(o.type===S.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(`${Ra} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),i=[],s=!1;for(let o=0;o<n.length;o++)i[o]=n.charCodeAt(o),!s&&(i[o]===46||i[o]===101||i[o]===69)&&(s=!0);s||(i.push(46),i.push(48)),e.push(i)}};var Ca=class{constructor(e,t={}){this.pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}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(`${Y} 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(`${Y} unexpected token at position ${this.pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this.pos,t=!1,n=!1,i=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(S.uint,0,this.pos-e);if(i([48,49,50,51,52,53,54,55,56,57]),t&&this.pos===e+1)throw new Error(`${Y} unexpected token at position ${this.pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${Y} unexpected token at position ${this.pos}`);n=!0,this.pos++,i([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this.pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this.pos++,i([48,49,50,51,52,53,54,55,56,57]));let s=String.fromCharCode.apply(null,this.data.subarray(e,this.pos)),o=parseFloat(s);return n?new U(S.float,o,this.pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(o)?new U(o>=0?S.uint:S.negint,o,this.pos-e):new U(o>=0?S.uint:S.negint,BigInt(s),this.pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${Y} unexpected character at position ${this.pos}; this shouldn't happen`);this.pos++;for(let s=this.pos,o=0;s<this.data.length&&o<65536;s++,o++){let a=this.data[s];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this.pos,s));return this.pos=s+1,new U(S.string,c,o)}}let e=this.pos,t=[],n=()=>{if(this.pos+4>=this.data.length)throw new Error(`${Y} unexpected end of unicode escape sequence at position ${this.pos}`);let s=0;for(let o=0;o<4;o++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${Y} unexpected unicode escape character at position ${this.pos}`);s=s*16+a,this.pos++}return s},i=()=>{let s=this.ch(),o=null,a=s>239?4:s>223?3:s>191?2:1;if(this.pos+a>this.data.length)throw new Error(`${Y} unexpected unicode sequence at position ${this.pos}`);let c,l,u,h;switch(a){case 1:s<128&&(o=s);break;case 2:c=this.data[this.pos+1],(c&192)===128&&(h=(s&31)<<6|c&63,h>127&&(o=h));break;case 3:c=this.data[this.pos+1],l=this.data[this.pos+2],(c&192)===128&&(l&192)===128&&(h=(s&15)<<12|(c&63)<<6|l&63,h>2047&&(h<55296||h>57343)&&(o=h));break;case 4:c=this.data[this.pos+1],l=this.data[this.pos+2],u=this.data[this.pos+3],(c&192)===128&&(l&192)===128&&(u&192)===128&&(h=(s&15)<<18|(c&63)<<12|(l&63)<<6|u&63,h>65535&&h<1114112&&(o=h))}o===null?(o=65533,a=1):o>65535&&(o-=65536,t.push(o>>>10&1023|55296),o=56320|o&1023),t.push(o),this.pos+=a};for(;!this.done();){let s=this.ch(),o;switch(s){case 92:if(this.pos++,this.done())throw new Error(`${Y} unexpected string termination at position ${this.pos}`);switch(o=this.ch(),this.pos++,o){case 34:case 39:case 92:case 47:t.push(o);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${Y} unexpected string escape character at position ${this.pos}`)}break;case 34:return this.pos++,new U(S.string,l2(t),this.pos-e);default:if(s<32)throw new Error(`${Y} invalid control character at position ${this.pos}`);s<128?(t.push(s),this.pos++):i()}}throw new Error(`${Y} unexpected end of string at position ${this.pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this.pos++,new U(S.map,1/0,1);case 91:return this.modeStack.push("array-start"),this.pos++,new U(S.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new U(S.null,null,4);case 102:return this.expect([102,97,108,115,101]),new U(S.false,!1,5);case 116:return this.expect([116,114,117,101]),new U(S.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(`${Y} 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(S.break,void 0,1);if(this.ch()!==44)throw new Error(`${Y} 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(S.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(S.break,void 0,1);if(this.ch()!==44)throw new Error(`${Y} 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(S.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${Y} 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(`${Y} unexpected parse state at position ${this.pos}; this shouldn't happen`)}}};function S2(r,e){return e=Object.assign({tokenizer:new Ca(r,e)},e),zn(r,e)}var Z7={codec:Q7,async*walk(r){yield*X7(r).Links.map(t=>t.Hash)}},J7={codec:mh,async*walk(){}},e9=42,t9={codec:113,async*walk(r){let e=[],t=[];t[e9]=n=>{if(n[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");let i=ee.decode(n.subarray(1));return e.push(i),i},zn(r,{tags:t}),yield*e}},R2=class extends Ca{tokenBuffer;constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===S.map){let t=this._next();if(t.type===S.string&&t.value==="/"){let n=this._next();if(n.type===S.string){if(this._next().type!==S.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new U(S.tag,42,0)}if(n.type===S.map){let i=this._next();if(i.type===S.string&&i.value==="bytes"){let s=this._next();if(s.type===S.string){for(let a=0;a<2;a++)if(this._next().type!==S.break)throw new Error("Invalid encoded Bytes form");let o=Ki.decode(`m${s.value}`);return new U(S.bytes,o,s.value.length)}this.tokenBuffer.push(s)}this.tokenBuffer.push(i)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},r9={codec:297,async*walk(r){let e=[],t=[];t[e9]=n=>{let i=ee.parse(n);return e.push(i),i},S2(r,{tags:t,tokenizer:new R2(r,{tags:t,allowIndefinite:!0,allowUndefined:!0,allowNaN:!0,allowInfinity:!0,allowBigInt:!0,strict:!1,rejectDuplicateMapKeys:!1})}),yield*e}};var IN=[J7,Z7,t9,r9],o9="/pin/",n9="/pinned-block/",I2=cl,i9=1;function s9(r){return r.version===0&&(r=r.toV1()),new ve(`${o9}${r.toString(I2)}`)}var pf=class{datastore;blockstore;dagWalkers;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.dagWalkers={},[...IN,...n].forEach(i=>{this.dagWalkers[i.codec]=i})}async add(e,t={}){let n=s9(e);if(await this.datastore.has(n))throw new Error("Already pinned");let i=Math.round(t.depth??1/0);if(i<0)throw new Error("Depth must be greater than or equal to 0");let s=new wt({concurrency:i9});s.add(async()=>{await this.#e(e,s,c=>{c.pinnedBy.find(l=>de(l,e.bytes))==null&&(c.pinCount++,c.pinnedBy.push(e.bytes))},{...t,depth:i})});let o=Pe();s.on("error",c=>{s.clear(),o.reject(c)}),await Promise.race([s.onIdle(),o.promise]);let a={depth:i,metadata:t.metadata??{}};return await this.datastore.put(n,xl(a),t),{cid:e,...a}}async#e(e,t,n,i){if(i.depth===-1)return;let s=this.dagWalkers[e.code];if(s==null)throw new Error(`No dag walker found for cid codec ${e.code}`);let o=await this.blockstore.get(e);await this.#t(e,n,i);for await(let a of s.walk(o))t.add(async()=>{await this.#e(a,t,n,{...i,depth:i.depth-1})})}async#t(e,t,n){let i=new ve(`${n9}${I2.encode(e.multihash.bytes)}`),s={pinCount:0,pinnedBy:[]};try{s=zn(await this.datastore.get(i,n))}catch(o){if(o.code!=="ERR_NOT_FOUND")throw o}if(t(s),s.pinCount===0&&await this.datastore.has(i)){await this.datastore.delete(i);return}await this.datastore.put(i,xl(s),n)}async rm(e,t={}){let n=s9(e),i=await this.datastore.get(n,t),s=zn(i);await this.datastore.delete(n,t);let o=new wt({concurrency:i9});return o.add(async()=>{await this.#e(e,o,a=>{a.pinCount--,a.pinnedBy=a.pinnedBy.filter(c=>de(c,e.bytes))},{...t,depth:s.depth})}),await o.onIdle(),{cid:e,...s}}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:o9+(e.cid!=null?`${e.cid.toString(cl)}`:"")},e)){let i=ee.parse(t.toString().substring(5),cl),s=zn(n);yield{cid:i,...s}}}async isPinned(e,t={}){let n=new ve(`${n9}${I2.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}};var A2=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},T2=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},a9=r=>globalThis.DOMException===void 0?new T2(r):new DOMException(r),c9=r=>{let e=r.reason===void 0?a9("This operation was aborted."):r.reason;return e instanceof Error?e:a9(e)};function D2(r,e){let{milliseconds:t,fallback:n,message:i,customTimers:s={setTimeout,clearTimeout}}=e,o,a=new Promise((c,l)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(t===Number.POSITIVE_INFINITY){c(r);return}if(e.signal){let{signal:h}=e;h.aborted&&l(c9(h)),h.addEventListener("abort",()=>{l(c9(h))})}let u=new A2;o=s.setTimeout.call(void 0,()=>{if(n){try{c(n())}catch(h){l(h)}return}typeof r.cancel=="function"&&r.cancel(),i===!1?c():i instanceof Error?l(i):(u.message=i??`Promise timed out after ${t} milliseconds`,l(u))},t),(async()=>{try{c(await r)}catch(h){l(h)}finally{s.clearTimeout.call(void 0,o)}})()});return a.clear=()=>{s.clearTimeout.call(void 0,o),o=void 0},a}var l9=(r=21)=>crypto.getRandomValues(new Uint8Array(r)).reduce((e,t)=>(t&=63,t<36?e+=t.toString(36):t<62?e+=(t-26).toString(36).toUpperCase():t>62?e+="-":e+="_",e),"");var C2="lock:worker:request-read",P2="lock:worker:release-read",k2="lock:master:grant-read",N2="lock:worker:request-write",L2="lock:worker:release-write",O2="lock:master:grant-write";var Is={},Pa=r=>{r.addEventListener("message",e=>{Pa.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{Pa.dispatchEvent("message",r,e)})};Pa.addEventListener=(r,e)=>{Is[r]==null&&(Is[r]=[]),Is[r].push(e)};Pa.removeEventListener=(r,e)=>{Is[r]!=null&&(Is[r]=Is[r].filter(t=>t===e))};Pa.dispatchEvent=function(r,e,t){Is[r]!=null&&Is[r].forEach(n=>n(e,t))};var B2=Pa;var u9=(r,e,t,n,i)=>(s,o)=>{if(o.data.type!==t)return;let a={type:o.data.type,name:o.data.name,identifier:o.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>(s.postMessage({type:i,name:a.name,identifier:a.identifier}),await new Promise(c=>{let l=u=>{if(u==null||u.data==null)return;let h={type:u.data.type,name:u.data.name,identifier:u.data.identifier};h.type===n&&h.identifier===a.identifier&&(s.removeEventListener("message",l),c())};s.addEventListener("message",l)}))}}))},h9=(r,e,t,n)=>async()=>{let i=l9();return globalThis.postMessage({type:e,identifier:i,name:r}),await new Promise(s=>{let o=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===i&&(globalThis.removeEventListener("message",o),s(()=>{globalThis.postMessage({type:n,identifier:i,name:r})}))};globalThis.addEventListener("message",o)})},AN={singleProcess:!1},f9=r=>{if(r=Object.assign({},AN,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return B2.addEventListener("message",u9(t,"requestReadLock",C2,P2,k2)),B2.addEventListener("message",u9(t,"requestWriteLock",N2,L2,O2)),t}return{isWorker:!0,readLock:t=>h9(t,C2,k2,P2),writeLock:t=>h9(t,N2,O2,L2)}};var Ao={},As;async function M2(r,e){let t,n=new Promise(i=>{t=i});return r.add(async()=>await D2((async()=>await new Promise(i=>{t(()=>{i()})}))(),{milliseconds:e.timeout})),await n}var TN=(r,e)=>{if(As.isWorker===!0)return{readLock:As.readLock(r,e),writeLock:As.writeLock(r,e)};let t=new wt({concurrency:1}),n;return{async readLock(){if(n!=null)return await M2(n,e);n=new wt({concurrency:e.concurrency,autoStart:!1});let i=n,s=M2(n,e);return t.add(async()=>(i.start(),await i.onIdle().then(()=>{n===i&&(n=null)}))),await s},async writeLock(){return n=null,await M2(t,e)}}},DN={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Nl(r){let e=Object.assign({},DN,r);return As==null&&(As=f9(e),As.isWorker!==!0&&(As.addEventListener("requestReadLock",t=>{Ao[t.data.name]!=null&&Ao[t.data.name].readLock().then(async n=>await t.data.handler().finally(()=>n()))}),As.addEventListener("requestWriteLock",async t=>{Ao[t.data.name]!=null&&Ao[t.data.name].writeLock().then(async n=>await t.data.handler().finally(()=>n()))}))),Ao[e.name]==null&&(Ao[e.name]=TN(e.name,e)),Ao[e.name]}var mf=class{lock;child;pins;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=Nl({singleProcess:n.holdGcLock})}unwrap(){return this.child}async put(e,t,n={}){let i=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{i()}}async*putMany(e,t={}){let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async get(e,t={}){let n=await this.lock.readLock();try{return await this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new Error("CID was pinned");await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){let n=await this.lock.writeLock();try{let i=this;yield*this.child.deleteMany(async function*(){for await(let s of e){if(await i.pins.isPinned(s))throw new Error("CID was pinned");yield s}}(),t)}finally{n()}}async has(e,t={}){let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}};var U2=new ve("/version"),d9=1;async function p9(r){if(!await r.has(U2)){await r.put(U2,K(`${d9}`));return}let e=await r.get(U2),t=O(e);if(parseInt(t,10)!==d9)throw new Error("Unknown datastore version, a datastore migration may be required")}var gf=class{child;bitswap;constructor(e,t={}){this.child=e,this.bitswap=t.bitswap}unwrap(){return this.child}async put(e,t,n={}){return await this.child.has(e)?(n.onProgress?.(new je("blocks:put:duplicate",e)),e):(this.bitswap?.isStarted()===!0&&(n.onProgress?.(new je("blocks:put:bitswap:notify",e)),this.bitswap.notify(e,t,n)),n.onProgress?.(new je("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=Or(e,async({cid:s})=>{let o=await this.child.has(s);return o&&t.onProgress?.(new je("blocks:put-many:duplicate",s)),!o}),i=ll(n,({cid:s,block:o})=>{t.onProgress?.(new je("blocks:put-many:bitswap:notify",s)),this.bitswap?.notify(s,o,t)});t.onProgress?.(new je("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(i,t)}async get(e,t={}){if(this.bitswap?.isStarted()!=null&&!await this.child.has(e)){t.onProgress?.(new je("blocks:get:bitswap:get",e));let n=await this.bitswap.want(e,t);return t.onProgress?.(new je("blocks:get:blockstore:put",e)),await this.child.put(e,n,t),n}return t.onProgress?.(new je("blocks:get:blockstore:get",e)),this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new je("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(ll(e,async n=>{if(this.bitswap?.isStarted()===!0&&!await this.child.has(n)){t.onProgress?.(new je("blocks:get-many:bitswap:get",n));let i=await this.bitswap.want(n,t);t.onProgress?.(new je("blocks:get-many:blockstore:put",n)),await this.child.put(n,i,t)}}))}async delete(e,t={}){t.onProgress?.(new je("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new je("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 je("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}};var F2=T("helia"),yf=class{libp2p;blockstore;datastore;pins;#e;constructor(e){let t=[Ce,Ep,hi,...e.hashers??[]];this.#e=Py(e.libp2p,e.blockstore,{hashLoader:{getHasher:async i=>{let s=t.find(o=>o.code===i||o.name===i);if(s!=null)return s;throw new Error(`Could not load hasher for code/name "${i}"`)}}});let n=new gf(e.blockstore,{bitswap:this.#e});this.pins=new pf(e.datastore,n,e.dagWalkers??[]),this.libp2p=e.libp2p,this.blockstore=new mf(n,this.pins,{holdGcLock:e.holdGcLock}),this.datastore=e.datastore}async start(){await p9(this.datastore),await this.#e?.start(),await this.libp2p.start()}async stop(){await this.libp2p.stop(),await this.#e?.stop()}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,i=this.blockstore.unwrap();F2("gc start"),await Yr(i.deleteMany(async function*(){for await(let{cid:s}of i.getAll())try{if(await n.pins.isPinned(s,e))continue;yield s,e.onProgress?.(new je("helia:gc:deleted",s))}catch(o){F2.error("Error during gc",o),e.onProgress?.(new je("helia:gc:error",o))}}()))}finally{t()}F2("gc finished")}};var lx=F(jr(),1);var jf={};Re(jf,{generateEphemeralKeyPair:()=>Xw,generateKeyPair:()=>eu,generateKeyPairFromSeed:()=>rM,importKey:()=>Ya,keyStretcher:()=>rb,keysPBM:()=>Ua,marshalPrivateKey:()=>B3,marshalPublicKey:()=>Wa,supportedKeys:()=>Ri,unmarshalPrivateKey:()=>an,unmarshalPublicKey:()=>rr});var Ire=F(Ml(),1),Are=F(Dw(),1);var Xf=F(tt(),1);var b3={};Re(b3,{Ed25519PrivateKey:()=>Lo,Ed25519PublicKey:()=>Hl,generateKeyPair:()=>EB,generateKeyPairFromSeed:()=>w3,unmarshalEd25519PrivateKey:()=>wB,unmarshalEd25519PublicKey:()=>bB});var eB=F(Cs(),1);var tr=BigInt(0),Ne=BigInt(1),Os=BigInt(2),tB=BigInt(8),Cw=BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),ht=Object.freeze({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),P:BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),l:Cw,n:Cw,h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960")});var Ow=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000"),Kl=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),ute=BigInt("6853475219497561581579357271197624642482790079785650197046958215289687604742"),rB=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),nB=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),iB=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),sB=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Ae=class{constructor(e,t,n,i){this.x=e,this.y=t,this.z=n,this.t=i}static fromAffine(e){if(!(e instanceof Et))throw new TypeError("ExtendedPoint#fromAffine: expected Point");return e.equals(Et.ZERO)?Ae.ZERO:new Ae(e.x,e.y,Ne,L(e.x*e.y))}static toAffineBatch(e){let t=cB(e.map(n=>n.z));return e.map((n,i)=>n.toAffine(t[i]))}static normalizeZ(e){return this.toAffineBatch(e).map(this.fromAffine)}equals(e){kw(e);let{x:t,y:n,z:i}=this,{x:s,y:o,z:a}=e,c=L(t*a),l=L(s*i),u=L(n*a),h=L(o*i);return c===l&&u===h}negate(){return new Ae(L(-this.x),this.y,this.z,L(-this.t))}double(){let{x:e,y:t,z:n}=this,{a:i}=ht,s=L(e*e),o=L(t*t),a=L(Os*L(n*n)),c=L(i*s),l=e+t,u=L(L(l*l)-s-o),h=c+o,f=h-a,d=c-o,p=L(u*f),m=L(h*d),g=L(u*d),y=L(f*h);return new Ae(p,m,y,g)}add(e){kw(e);let{x:t,y:n,z:i,t:s}=this,{x:o,y:a,z:c,t:l}=e,u=L((n-t)*(a+o)),h=L((n+t)*(a-o)),f=L(h-u);if(f===tr)return this.double();let d=L(i*Os*l),p=L(s*Os*c),m=p+d,g=h+u,y=p-d,b=L(m*f),E=L(g*y),I=L(m*y),v=L(f*g);return new Ae(b,E,v,I)}subtract(e){return this.add(e.negate())}precomputeWindow(e){let t=1+256/e,n=[],i=this,s=i;for(let o=0;o<t;o++){s=i,n.push(s);for(let a=1;a<2**(e-1);a++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,t){!t&&this.equals(Ae.BASE)&&(t=Et.BASE);let n=t&&t._WINDOW_SIZE||1;if(256%n)throw new Error("Point#wNAF: Invalid precomputation window, must be power of 2");let i=t&&f3.get(t);i||(i=this.precomputeWindow(n),t&&n!==1&&(i=Ae.normalizeZ(i),f3.set(t,i)));let s=Ae.ZERO,o=Ae.BASE,a=1+256/n,c=2**(n-1),l=BigInt(2**n-1),u=2**n,h=BigInt(n);for(let f=0;f<a;f++){let d=f*c,p=Number(e&l);e>>=h,p>c&&(p-=u,e+=Ne);let m=d,g=d+Math.abs(p)-1,y=f%2!==0,b=p<0;p===0?o=o.add(Pw(y,i[m])):s=s.add(Pw(b,i[g]))}return Ae.normalizeZ([s,o])[0]}multiply(e,t){return this.wNAF(Mf(e,ht.l),t)}multiplyUnsafe(e){let t=Mf(e,ht.l,!1),n=Ae.BASE,i=Ae.ZERO;if(t===tr)return i;if(this.equals(i)||t===Ne)return this;if(this.equals(n))return this.wNAF(t);let s=i,o=this;for(;t>tr;)t&Ne&&(s=s.add(o)),o=o.double(),t>>=Ne;return s}isSmallOrder(){return this.multiplyUnsafe(ht.h).equals(Ae.ZERO)}isTorsionFree(){let e=this.multiplyUnsafe(ht.l/Os).double();return ht.l%Os&&(e=e.add(this)),e.equals(Ae.ZERO)}toAffine(e){let{x:t,y:n,z:i}=this,s=this.equals(Ae.ZERO);e==null&&(e=s?tB:Uf(i));let o=L(t*e),a=L(n*e),c=L(i*e);if(s)return Et.ZERO;if(c!==Ne)throw new Error("invZ was invalid");return new Et(o,a)}fromRistrettoBytes(){l3()}toRistrettoBytes(){l3()}fromRistrettoHash(){l3()}};Ae.BASE=new Ae(ht.Gx,ht.Gy,Ne,L(ht.Gx*ht.Gy));Ae.ZERO=new Ae(tr,Ne,Ne,tr);function Pw(r,e){let t=e.negate();return r?t:e}function kw(r){if(!(r instanceof Ae))throw new TypeError("ExtendedPoint expected")}function c3(r){if(!(r instanceof Ur))throw new TypeError("RistrettoPoint expected")}function l3(){throw new Error("Legacy method: switch to RistrettoPoint")}var Ur=class{constructor(e){this.ep=e}static calcElligatorRistrettoMap(e){let{d:t}=ht,n=L(Kl*e*e),i=L((n+Ne)*iB),s=BigInt(-1),o=L((s-t*n)*L(n+t)),{isValid:a,value:c}=p3(i,o),l=L(c*e);Ls(l)||(l=L(-l)),a||(c=l),a||(s=n);let u=L(s*(n-Ne)*sB-o),h=c*c,f=L((c+c)*o),d=L(u*rB),p=L(Ne-h),m=L(Ne+h);return new Ae(L(f*m),L(p*d),L(d*m),L(f*p))}static hashToCurve(e){e=Bs(e,64);let t=u3(e.slice(0,32)),n=this.calcElligatorRistrettoMap(t),i=u3(e.slice(32,64)),s=this.calcElligatorRistrettoMap(i);return new Ur(n.add(s))}static fromHex(e){e=Bs(e,32);let{a:t,d:n}=ht,i="RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint",s=u3(e);if(!uB(Vl(s),e)||Ls(s))throw new Error(i);let o=L(s*s),a=L(Ne+t*o),c=L(Ne-t*o),l=L(a*a),u=L(c*c),h=L(t*n*l-u),{isValid:f,value:d}=Lw(L(h*u)),p=L(d*c),m=L(d*p*h),g=L((s+s)*p);Ls(g)&&(g=L(-g));let y=L(a*m),b=L(g*y);if(!f||Ls(b)||y===tr)throw new Error(i);return new Ur(new Ae(g,y,Ne,b))}toRawBytes(){let{x:e,y:t,z:n,t:i}=this.ep,s=L(L(n+t)*L(n-t)),o=L(e*t),a=L(o*o),{value:c}=Lw(L(s*a)),l=L(c*s),u=L(c*o),h=L(l*u*i),f;if(Ls(i*h)){let p=L(t*Kl),m=L(e*Kl);e=p,t=m,f=L(l*nB)}else f=u;Ls(e*h)&&(t=L(-t));let d=L((n-t)*f);return Ls(d)&&(d=L(-d)),Vl(d)}toHex(){return ql(this.toRawBytes())}toString(){return this.toHex()}equals(e){c3(e);let t=this.ep,n=e.ep,i=L(t.x*n.y)===L(t.y*n.x),s=L(t.y*n.y)===L(t.x*n.x);return i||s}add(e){return c3(e),new Ur(this.ep.add(e.ep))}subtract(e){return c3(e),new Ur(this.ep.subtract(e.ep))}multiply(e){return new Ur(this.ep.multiply(e))}multiplyUnsafe(e){return new Ur(this.ep.multiplyUnsafe(e))}};Ur.BASE=new Ur(Ae.BASE);Ur.ZERO=new Ur(Ae.ZERO);var f3=new WeakMap,Et=class{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,f3.delete(this)}static fromHex(e,t=!0){let{d:n,P:i}=ht;e=Bs(e,32);let s=e.slice();s[31]=e[31]&-129;let o=zl(s);if(t&&o>=i)throw new Error("Expected 0 < hex < P");if(!t&&o>=Ow)throw new Error("Expected 0 < hex < 2**256");let a=L(o*o),c=L(a-Ne),l=L(n*a+Ne),{isValid:u,value:h}=p3(c,l);if(!u)throw new Error("Point.fromHex: invalid y coordinate");let f=(h&Ne)===Ne;return(e[31]&128)!==0!==f&&(h=L(-h)),new Et(h,o)}static async fromPrivateKey(e){return(await Ff(e)).point}toRawBytes(){let e=Vl(this.y);return e[31]|=this.x&Ne?128:0,e}toHex(){return ql(this.toRawBytes())}toX25519(){let{y:e}=this,t=L((Ne+e)*Uf(Ne-e));return Vl(t)}isTorsionFree(){return Ae.fromAffine(this).isTorsionFree()}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new Et(L(-this.x),this.y)}add(e){return Ae.fromAffine(this).add(Ae.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return Ae.fromAffine(this).multiply(e,this).toAffine()}};Et.BASE=new Et(ht.Gx,ht.Gy);Et.ZERO=new Et(tr,Ne);var No=class{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromHex(e){let t=Bs(e,64),n=Et.fromHex(t.slice(0,32),!1),i=zl(t.slice(32,64));return new No(n,i)}assertValidity(){let{r:e,s:t}=this;if(!(e instanceof Et))throw new Error("Expected Point instance");return Mf(t,ht.l,!1),this}toRawBytes(){let e=new Uint8Array(64);return e.set(this.r.toRawBytes()),e.set(Vl(this.s),32),e}toHex(){return ql(this.toRawBytes())}};function Nw(...r){if(!r.every(n=>n instanceof Uint8Array))throw new Error("Expected Uint8Array list");if(r.length===1)return r[0];let e=r.reduce((n,i)=>n+i.length,0),t=new Uint8Array(e);for(let n=0,i=0;n<r.length;n++){let s=r[n];t.set(s,i),i+=s.length}return t}var oB=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function ql(r){if(!(r instanceof Uint8Array))throw new Error("Uint8Array expected");let e="";for(let t=0;t<r.length;t++)e+=oB[r[t]];return e}function d3(r){if(typeof r!="string")throw new TypeError("hexToBytes: expected string, got "+typeof r);if(r.length%2)throw new Error("hexToBytes: received invalid unpadded hex");let e=new Uint8Array(r.length/2);for(let t=0;t<e.length;t++){let n=t*2,i=r.slice(n,n+2),s=Number.parseInt(i,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");e[t]=s}return e}function Bw(r){let t=r.toString(16).padStart(64,"0");return d3(t)}function Vl(r){return Bw(r).reverse()}function Ls(r){return(L(r)&Ne)===Ne}function zl(r){if(!(r instanceof Uint8Array))throw new Error("Expected Uint8Array");return BigInt("0x"+ql(Uint8Array.from(r).reverse()))}var aB=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function u3(r){return L(zl(r)&aB)}function L(r,e=ht.P){let t=r%e;return t>=tr?t:e+t}function Uf(r,e=ht.P){if(r===tr||e<=tr)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=L(r,e),n=e,i=tr,s=Ne,o=Ne,a=tr;for(;t!==tr;){let l=n/t,u=n%t,h=i-o*l,f=s-a*l;n=t,t=u,i=o,s=a,o=h,a=f}if(n!==Ne)throw new Error("invert: does not exist");return L(i,e)}function cB(r,e=ht.P){let t=new Array(r.length),n=r.reduce((s,o,a)=>o===tr?s:(t[a]=s,L(s*o,e)),Ne),i=Uf(n,e);return r.reduceRight((s,o,a)=>o===tr?s:(t[a]=L(s*t[a],e),L(s*o,e)),i),t}function _i(r,e){let{P:t}=ht,n=r;for(;e-- >tr;)n*=n,n%=t;return n}function lB(r){let{P:e}=ht,t=BigInt(5),n=BigInt(10),i=BigInt(20),s=BigInt(40),o=BigInt(80),c=r*r%e*r%e,l=_i(c,Os)*c%e,u=_i(l,Ne)*r%e,h=_i(u,t)*u%e,f=_i(h,n)*h%e,d=_i(f,i)*f%e,p=_i(d,s)*d%e,m=_i(p,o)*p%e,g=_i(m,o)*p%e,y=_i(g,n)*h%e;return{pow_p_5_8:_i(y,Os)*r%e,b2:c}}function p3(r,e){let t=L(e*e*e),n=L(t*t*e),i=lB(r*n).pow_p_5_8,s=L(r*t*i),o=L(e*s*s),a=s,c=L(s*Kl),l=o===r,u=o===L(-r),h=o===L(-r*Kl);return l&&(s=a),(u||h)&&(s=c),Ls(s)&&(s=L(-s)),{isValid:l||u,value:s}}function Lw(r){return p3(Ne,r)}function Bf(r){return L(zl(r),ht.l)}function uB(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}function Bs(r,e){let t=r instanceof Uint8Array?Uint8Array.from(r):d3(r);if(typeof e=="number"&&t.length!==e)throw new Error(`Expected ${e} bytes`);return t}function Mf(r,e,t=!0){if(!e)throw new TypeError("Specify max value");if(typeof r=="number"&&Number.isSafeInteger(r)&&(r=BigInt(r)),typeof r=="bigint"&&r<e){if(t){if(tr<r)return r}else if(tr<=r)return r}throw new TypeError("Expected valid scalar: 0 < scalar < max")}function hB(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function fB(r){if(r=typeof r=="bigint"||typeof r=="number"?Bw(Mf(r,Ow)):Bs(r),r.length!==32)throw new Error("Expected 32 bytes");return r}function dB(r){let e=hB(r.slice(0,32)),t=r.slice(32,64),n=Bf(e),i=Et.BASE.multiply(n),s=i.toRawBytes();return{head:e,prefix:t,scalar:n,point:i,pointBytes:s}}var h3;async function Ff(r){return dB(await Ms.sha512(fB(r)))}async function m3(r){return(await Ff(r)).pointBytes}async function Mw(r,e){r=Bs(r);let{prefix:t,scalar:n,pointBytes:i}=await Ff(e),s=Bf(await Ms.sha512(t,r)),o=Et.BASE.multiply(s),a=Bf(await Ms.sha512(o.toRawBytes(),i,r)),c=L(s+a*n,ht.l);return new No(o,c).toRawBytes()}function pB(r,e,t){e=Bs(e),t instanceof Et||(t=Et.fromHex(t,!1));let{r:n,s:i}=r instanceof No?r.assertValidity():No.fromHex(r),s=Ae.BASE.multiplyUnsafe(i);return{r:n,s:i,SB:s,pub:t,msg:e}}function mB(r,e,t,n){let i=Bf(n),s=Ae.fromAffine(r).multiplyUnsafe(i);return Ae.fromAffine(e).add(s).subtract(t).multiplyUnsafe(ht.h).equals(Ae.ZERO)}async function Uw(r,e,t){let{r:n,SB:i,msg:s,pub:o}=pB(r,e,t),a=await Ms.sha512(n.toRawBytes(),o.toRawBytes(),s);return mB(o,n,i,a)}Et.BASE._setWindowSize(8);var Ns={node:eB,web:typeof self=="object"&&"crypto"in self?self.crypto:void 0},Ms={bytesToHex:ql,hexToBytes:d3,concatBytes:Nw,getExtendedPublicKey:Ff,mod:L,invert:Uf,TORSION_SUBGROUP:["0100000000000000000000000000000000000000000000000000000000000000","c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a","0000000000000000000000000000000000000000000000000000000000000080","26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05","ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f","26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85","0000000000000000000000000000000000000000000000000000000000000000","c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa"],hashToPrivateScalar:r=>{if(r=Bs(r),r.length<40||r.length>1024)throw new Error("Expected 40-1024 bytes of private key as per FIPS 186");return L(zl(r),ht.l-Ne)+Ne},randomBytes:(r=32)=>{if(Ns.web)return Ns.web.getRandomValues(new Uint8Array(r));if(Ns.node){let{randomBytes:e}=Ns.node;return new Uint8Array(e(r).buffer)}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>Ms.randomBytes(32),sha512:async(...r)=>{let e=Nw(...r);if(Ns.web){let t=await Ns.web.subtle.digest("SHA-512",e.buffer);return new Uint8Array(t)}else{if(Ns.node)return Uint8Array.from(Ns.node.createHash("sha512").update(e).digest());throw new Error("The environment doesn't have sha512 function")}},precompute(r=8,e=Et.BASE){let t=e.equals(Et.BASE)?e:new Et(e.x,e.y);return t._setWindowSize(r),t.multiply(Os),t},sha512Sync:void 0};Object.defineProperties(Ms,{sha512Sync:{configurable:!1,get(){return h3},set(r){h3||(h3=r)}}});var Ba=32,Zi=64,Kf=32;async function Fw(){let r=Ms.randomPrivateKey(),e=await m3(r);return{privateKey:zw(r,e),publicKey:e}}async function Kw(r){if(r.length!==Kf)throw new TypeError('"seed" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=r,t=await m3(e);return{privateKey:zw(e,t),publicKey:t}}async function Vw(r,e){let t=r.subarray(0,Kf);return Mw(e,t)}async function qw(r,e,t){return Uw(e,t,r)}function zw(r,e){let t=new Uint8Array(Zi);for(let n=0;n<Kf;n++)t[n]=r[n],t[Kf+n]=e[n];return t}var Mt={get(r=globalThis){let e=r.crypto;if(e==null||e.subtle==null)throw Object.assign(new Error("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p-crypto/blob/master/README.md#web-crypto-api"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var g3={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function Vf(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,i=r?.digest??"SHA-256",s=r?.saltLength??16,o=r?.iterations??32767,a=Mt.get();t*=8;async function c(h,f){let d=a.getRandomValues(new Uint8Array(s)),p=a.getRandomValues(new Uint8Array(n)),m={name:e,iv:p};typeof f=="string"&&(f=K(f));let g;if(f.length===0){g=await a.subtle.importKey("jwk",g3,{name:"AES-GCM"},!0,["encrypt"]);try{let b={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},E=await a.subtle.importKey("raw",f,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,E,{name:e,length:t},!0,["encrypt"])}catch{g=await a.subtle.importKey("jwk",g3,{name:"AES-GCM"},!0,["encrypt"])}}else{let b={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},E=await a.subtle.importKey("raw",f,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,E,{name:e,length:t},!0,["encrypt"])}let y=await a.subtle.encrypt(m,g,h);return le([d,m.iv,new Uint8Array(y)])}async function l(h,f){let d=h.subarray(0,s),p=h.subarray(s,s+n),m=h.subarray(s+n),g={name:e,iv:p};typeof f=="string"&&(f=K(f));let y;if(f.length===0)try{let E={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},I=await a.subtle.importKey("raw",f,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(E,I,{name:e,length:t},!0,["decrypt"])}catch{y=await a.subtle.importKey("jwk",g3,{name:"AES-GCM"},!0,["decrypt"])}else{let E={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},I=await a.subtle.importKey("raw",f,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(E,I,{name:e,length:t},!0,["decrypt"])}let b=await a.subtle.decrypt(g,y,m);return new Uint8Array(b)}return{encrypt:c,decrypt:l}}async function Ma(r,e){let n=await Vf().encrypt(r,e);return Ki.encode(n)}var Ua={};Re(Ua,{KeyType:()=>ft,PrivateKey:()=>Yn,PublicKey:()=>Wn});var ft;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(ft||(ft={}));var y3;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(y3||(y3={}));(function(r){r.codec=()=>At(y3)})(ft||(ft={}));var Wn;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ft.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.Type=ft.codec().decode(t);break;case 2:i.Data=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(Wn||(Wn={}));var Yn;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ft.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.Type=ft.codec().decode(t);break;case 2:i.Data=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(Yn||(Yn={}));var Hl=class{_key;constructor(e){this._key=Fa(e,Ba)}async verify(e,t){return qw(this._key,t,e)}marshal(){return this._key}get bytes(){return Wn.encode({Type:ft.Ed25519,Data:this.marshal()}).subarray()}equals(e){return de(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ce.digest(this.bytes);return e}},Lo=class{_key;_publicKey;constructor(e,t){this._key=Fa(e,Zi),this._publicKey=Fa(t,Ba)}async sign(e){return Vw(this._key,e)}get public(){return new Hl(this._publicKey)}marshal(){return this._key}get bytes(){return Yn.encode({Type:ft.Ed25519,Data:this.marshal()}).subarray()}equals(e){return de(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ce.digest(this.bytes);return e}async id(){let e=hi.digest(this.public.bytes);return me.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return Ma(this.bytes,e);throw new w(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function wB(r){if(r.length>Zi){r=Fa(r,Zi+Ba);let n=r.subarray(0,Zi),i=r.subarray(Zi,r.length);return new Lo(n,i)}r=Fa(r,Zi);let e=r.subarray(0,Zi),t=r.subarray(Ba);return new Lo(e,t)}function bB(r){return r=Fa(r,Ba),new Hl(r)}async function EB(){let{privateKey:r,publicKey:e}=await Fw();return new Lo(r,e)}async function w3(r){let{privateKey:e,publicKey:t}=await Kw(r);return new Lo(e,t)}function Fa(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new w(`Key must be a Uint8Array of length ${e}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}var Ste=F(Bt(),1),Rte=F(kf(),1),$w=F(tt(),1);function Qn(r,e){let t=Uint8Array.from(r.abs().toByteArray());if(t=t[0]===0?t.subarray(1):t,e!=null){if(t.length>e)throw new Error("byte array longer than desired length");t=le([new Uint8Array(e-t.length),t])}return O(t,"base64url")}function sn(r){let e=qf(r);return new $w.default.jsbn.BigInteger(O(e,"base16"),16)}function qf(r,e){let t=K(r,"base64urlpad");if(e!=null){if(t.length>e)throw new Error("byte array longer than desired length");t=le([new Uint8Array(e-t.length),t])}return t}var Gw={"P-256":256,"P-384":384,"P-521":521},vB=Object.keys(Gw),E3=vB.join(" / ");async function Ww(r){if(r!=="P-256"&&r!=="P-384"&&r!=="P-521")throw new w(`Unknown curve: ${r}. Must be ${E3}`,"ERR_INVALID_CURVE");let e=await Mt.get().subtle.generateKey({name:"ECDH",namedCurve:r},!0,["deriveBits"]),t=async(s,o)=>{let a;o!=null?a=await Mt.get().subtle.importKey("jwk",_B(r,o),{name:"ECDH",namedCurve:r},!1,["deriveBits"]):a=e.privateKey;let c=await Mt.get().subtle.importKey("jwk",Qw(r,s),{name:"ECDH",namedCurve:r},!1,[]),l=await Mt.get().subtle.deriveBits({name:"ECDH",namedCurve:r,public:c},a,Gw[r]);return new Uint8Array(l,0,l.byteLength)},n=await Mt.get().subtle.exportKey("jwk",e.publicKey);return{key:xB(n),genSharedKey:t}}var Yw={"P-256":32,"P-384":48,"P-521":66};function xB(r){if(r.crv==null||r.x==null||r.y==null)throw new w("JWK was missing components","ERR_INVALID_PARAMETERS");if(r.crv!=="P-256"&&r.crv!=="P-384"&&r.crv!=="P-521")throw new w(`Unknown curve: ${r.crv}. Must be ${E3}`,"ERR_INVALID_CURVE");let e=Yw[r.crv];return le([Uint8Array.from([4]),qf(r.x,e),qf(r.y,e)],1+e*2)}function Qw(r,e){if(r!=="P-256"&&r!=="P-384"&&r!=="P-521")throw new w(`Unknown curve: ${r}. Must be ${E3}`,"ERR_INVALID_CURVE");let t=Yw[r];if(!de(e.subarray(0,1),Uint8Array.from([4])))throw new w("Cannot unmarshal public key - invalid key format","ERR_INVALID_KEY_FORMAT");return{kty:"EC",crv:r,x:O(e.subarray(1,t+1),"base64url"),y:O(e.subarray(1+t),"base64url"),ext:!0}}var _B=(r,e)=>({...Qw(r,e.public),d:O(e.private,"base64url")});var Xw=Ww;async function jw(r,e){let t=Ki.decode(r);return Vf().decrypt(t,e)}var Zw={SHA1:20,SHA256:32,SHA512:64};var SB={SHA1:"SHA-1",SHA256:"SHA-256",SHA512:"SHA-512"},RB=async(r,e)=>{let t=await Mt.get().subtle.sign({name:"HMAC"},r,e);return new Uint8Array(t,0,t.byteLength)};async function Jw(r,e){let t=SB[r],n=await Mt.get().subtle.importKey("raw",e,{name:"HMAC",hash:{name:t}},!1,["sign"]);return{async digest(i){return RB(n,i)},length:Zw[r]}}var tb={"AES-128":{ivSize:16,keySize:16},"AES-256":{ivSize:16,keySize:32},Blowfish:{ivSize:8,keySize:32}};async function rb(r,e,t){let n=tb[r];if(n==null){let b=Object.keys(tb).join(" / ");throw new w(`unknown cipher type '${r}'. Must be ${b}`,"ERR_INVALID_CIPHER_TYPE")}if(e==null)throw new w("missing hash type","ERR_MISSING_HASH_TYPE");let i=n.keySize,s=n.ivSize,o=20,a=K("key expansion"),c=2*(s+i+o),l=await Jw(e,t),u=await l.digest(a),h=[],f=0;for(;f<c;){let b=await l.digest(le([u,a])),E=b.length;f+E>c&&(E=c-f),h.push(b),f+=E,u=await l.digest(u)}let d=c/2,p=le(h),m=p.subarray(0,d),g=p.subarray(d,c),y=b=>({iv:b.subarray(0,s),cipherKey:b.subarray(s,s+i),macKey:b.subarray(s+i)});return{k1:y(m),k2:y(g)}}var P3={};Re(P3,{RsaPrivateKey:()=>Ga,RsaPublicKey:()=>jl,fromJwk:()=>XB,generateKeyPair:()=>jB,unmarshalRsaPrivateKey:()=>YB,unmarshalRsaPublicKey:()=>QB});var Xl=F(tt(),1);var gre=F(ab(),1);var AB=F(Cs(),1);var Le=BigInt(0),pt=BigInt(1),Fs=BigInt(2),Wl=BigInt(3),cb=BigInt(8),Dt=Object.freeze({a:Le,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:pt,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),lb=(r,e)=>(r+e/Fs)/e,zf={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(r){let{n:e}=Dt,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-pt*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,o=BigInt("0x100000000000000000000000000000000"),a=lb(s*r,e),c=lb(-n*r,e),l=G(r-a*t-c*i,e),u=G(-a*n-c*s,e),h=l>o,f=u>o;if(h&&(l=e-l),f&&(u=e-u),l>o||u>o)throw new Error("splitScalarEndo: Endomorphism failed, k="+r);return{k1neg:h,k1:l,k2neg:f,k2:u}}},Xn=32,qa=32,TB=32,ub=Xn+1,hb=2*Xn+1;function fb(r){let{a:e,b:t}=Dt,n=G(r*r),i=G(n*r);return G(i+e*r+t)}var Hf=Dt.a===Le,Wf=class extends Error{constructor(e){super(e)}};function db(r){if(!(r instanceof Ue))throw new TypeError("JacobianPoint expected")}var Ue=class{constructor(e,t,n){this.x=e,this.y=t,this.z=n}static fromAffine(e){if(!(e instanceof Qe))throw new TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(Qe.ZERO)?Ue.ZERO:new Ue(e.x,e.y,pt)}static toAffineBatch(e){let t=NB(e.map(n=>n.z));return e.map((n,i)=>n.toAffine(t[i]))}static normalizeZ(e){return Ue.toAffineBatch(e).map(Ue.fromAffine)}equals(e){db(e);let{x:t,y:n,z:i}=this,{x:s,y:o,z:a}=e,c=G(i*i),l=G(a*a),u=G(t*l),h=G(s*c),f=G(G(n*a)*l),d=G(G(o*i)*c);return u===h&&f===d}negate(){return new Ue(this.x,G(-this.y),this.z)}double(){let{x:e,y:t,z:n}=this,i=G(e*e),s=G(t*t),o=G(s*s),a=e+s,c=G(Fs*(G(a*a)-i-o)),l=G(Wl*i),u=G(l*l),h=G(u-Fs*c),f=G(l*(c-h)-cb*o),d=G(Fs*t*n);return new Ue(h,f,d)}add(e){db(e);let{x:t,y:n,z:i}=this,{x:s,y:o,z:a}=e;if(s===Le||o===Le)return this;if(t===Le||n===Le)return e;let c=G(i*i),l=G(a*a),u=G(t*l),h=G(s*c),f=G(G(n*a)*l),d=G(G(o*i)*c),p=G(h-u),m=G(d-f);if(p===Le)return m===Le?this.double():Ue.ZERO;let g=G(p*p),y=G(p*g),b=G(u*g),E=G(m*m-y-Fs*b),I=G(m*(b-E)-f*y),v=G(i*a*p);return new Ue(E,I,v)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){let t=Ue.ZERO;if(typeof e=="bigint"&&e===Le)return t;let n=gb(e);if(n===pt)return this;if(!Hf){let h=t,f=this;for(;n>Le;)n&pt&&(h=h.add(f)),f=f.double(),n>>=pt;return h}let{k1neg:i,k1:s,k2neg:o,k2:a}=zf.splitScalar(n),c=t,l=t,u=this;for(;s>Le||a>Le;)s&pt&&(c=c.add(u)),a&pt&&(l=l.add(u)),u=u.double(),s>>=pt,a>>=pt;return i&&(c=c.negate()),o&&(l=l.negate()),l=new Ue(G(l.x*zf.beta),l.y,l.z),c.add(l)}precomputeWindow(e){let t=Hf?128/e+1:256/e+1,n=[],i=this,s=i;for(let o=0;o<t;o++){s=i,n.push(s);for(let a=1;a<2**(e-1);a++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,t){!t&&this.equals(Ue.BASE)&&(t=Qe.BASE);let n=t&&t._WINDOW_SIZE||1;if(256%n)throw new Error("Point#wNAF: Invalid precomputation window, must be power of 2");let i=t&&S3.get(t);i||(i=this.precomputeWindow(n),t&&n!==1&&(i=Ue.normalizeZ(i),S3.set(t,i)));let s=Ue.ZERO,o=Ue.BASE,a=1+(Hf?128/n:256/n),c=2**(n-1),l=BigInt(2**n-1),u=2**n,h=BigInt(n);for(let f=0;f<a;f++){let d=f*c,p=Number(e&l);e>>=h,p>c&&(p-=u,e+=pt);let m=d,g=d+Math.abs(p)-1,y=f%2!==0,b=p<0;p===0?o=o.add($f(y,i[m])):s=s.add($f(b,i[g]))}return{p:s,f:o}}multiply(e,t){let n=gb(e),i,s;if(Hf){let{k1neg:o,k1:a,k2neg:c,k2:l}=zf.splitScalar(n),{p:u,f:h}=this.wNAF(a,t),{p:f,f:d}=this.wNAF(l,t);u=$f(o,u),f=$f(c,f),f=new Ue(G(f.x*zf.beta),f.y,f.z),i=u.add(f),s=h.add(d)}else{let{p:o,f:a}=this.wNAF(n,t);i=o,s=a}return Ue.normalizeZ([i,s])[0]}toAffine(e){let{x:t,y:n,z:i}=this,s=this.equals(Ue.ZERO);e==null&&(e=s?cb:$a(i));let o=e,a=G(o*o),c=G(a*o),l=G(t*a),u=G(n*c),h=G(i*o);if(s)return Qe.ZERO;if(h!==pt)throw new Error("invZ was invalid");return new Qe(l,u)}};Ue.BASE=new Ue(Dt.Gx,Dt.Gy,pt);Ue.ZERO=new Ue(Le,pt,Le);function $f(r,e){let t=e.negate();return r?t:e}var S3=new WeakMap,Qe=class{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,S3.delete(this)}hasEvenY(){return this.y%Fs===Le}static fromCompressedHex(e){let t=e.length===32,n=Ks(t?e:e.subarray(1));if(!_3(n))throw new Error("Point is not on curve");let i=fb(n),s=kB(i),o=(s&pt)===pt;t?o&&(s=G(-s)):(e[0]&1)===1!==o&&(s=G(-s));let a=new Qe(n,s);return a.assertValidity(),a}static fromUncompressedHex(e){let t=Ks(e.subarray(1,Xn+1)),n=Ks(e.subarray(Xn+1,Xn*2+1)),i=new Qe(t,n);return i.assertValidity(),i}static fromHex(e){let t=Ha(e),n=t.length,i=t[0];if(n===Xn)return this.fromCompressedHex(t);if(n===ub&&(i===2||i===3))return this.fromCompressedHex(t);if(n===hb&&i===4)return this.fromUncompressedHex(t);throw new Error(`Point.fromHex: received invalid point. Expected 32-${ub} compressed bytes or ${hb} uncompressed bytes, not ${n}`)}static fromPrivateKey(e){return Qe.BASE.multiply(Qf(e))}static fromSignature(e,t,n){let{r:i,s}=yb(t);if(![0,1,2,3].includes(n))throw new Error("Cannot recover: invalid recovery bit");let o=A3(Ha(e)),{n:a}=Dt,c=n===2||n===3?i+a:i,l=$a(c,a),u=G(-o*l,a),h=G(s*l,a),f=n&1?"03":"02",d=Qe.fromHex(f+Ka(c)),p=Qe.BASE.multiplyAndAddUnsafe(d,u,h);if(!p)throw new Error("Cannot recover signature: point at infinify");return p.assertValidity(),p}toRawBytes(e=!1){return Bo(this.toHex(e))}toHex(e=!1){let t=Ka(this.x);return e?`${this.hasEvenY()?"02":"03"}${t}`:`04${t}${Ka(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){let e="Point is not on elliptic curve",{x:t,y:n}=this;if(!_3(t)||!_3(n))throw new Error(e);let i=G(n*n),s=fb(t);if(G(i-s)!==Le)throw new Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new Qe(this.x,G(-this.y))}double(){return Ue.fromAffine(this).double().toAffine()}add(e){return Ue.fromAffine(this).add(Ue.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return Ue.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,t,n){let i=Ue.fromAffine(this),s=t===Le||t===pt||this!==Qe.BASE?i.multiplyUnsafe(t):i.multiply(t),o=Ue.fromAffine(e).multiplyUnsafe(n),a=s.add(o);return a.equals(Ue.ZERO)?void 0:a.toAffine()}};Qe.BASE=new Qe(Dt.Gx,Dt.Gy);Qe.ZERO=new Qe(Le,Le);function pb(r){return Number.parseInt(r[0],16)>=8?"00"+r:r}function mb(r){if(r.length<2||r[0]!==2)throw new Error(`Invalid signature integer tag: ${za(r)}`);let e=r[1],t=r.subarray(2,e+2);if(!e||t.length!==e)throw new Error("Invalid signature integer: wrong length");if(t[0]===0&&t[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:Ks(t),left:r.subarray(e+2)}}function DB(r){if(r.length<2||r[0]!=48)throw new Error(`Invalid signature tag: ${za(r)}`);if(r[1]!==r.length-2)throw new Error("Invalid signature: incorrect length");let{data:e,left:t}=mb(r.subarray(2)),{data:n,left:i}=mb(t);if(i.length)throw new Error(`Invalid signature: left bytes after parsing: ${za(i)}`);return{r:e,s:n}}var Si=class{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromCompact(e){let t=e instanceof Uint8Array,n="Signature.fromCompact";if(typeof e!="string"&&!t)throw new TypeError(`${n}: Expected string or Uint8Array`);let i=t?za(e):e;if(i.length!==128)throw new Error(`${n}: Expected 64-byte hex`);return new Si(Yf(i.slice(0,64)),Yf(i.slice(64,128)))}static fromDER(e){let t=e instanceof Uint8Array;if(typeof e!="string"&&!t)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");let{r:n,s:i}=DB(t?e:Bo(e));return new Si(n,i)}static fromHex(e){return this.fromDER(e)}assertValidity(){let{r:e,s:t}=this;if(!Ql(e))throw new Error("Invalid Signature: r must be 0 < r < n");if(!Ql(t))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){let e=Dt.n>>pt;return this.s>e}normalizeS(){return this.hasHighS()?new Si(this.r,G(-this.s,Dt.n)):this}toDERRawBytes(){return Bo(this.toDERHex())}toDERHex(){let e=pb(Gl(this.s)),t=pb(Gl(this.r)),n=e.length/2,i=t.length/2,s=Gl(n),o=Gl(i);return`30${Gl(i+n+4)}02${o}${t}02${s}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return Bo(this.toCompactHex())}toCompactHex(){return Ka(this.r)+Ka(this.s)}};function Us(...r){if(!r.every(n=>n instanceof Uint8Array))throw new Error("Uint8Array list expected");if(r.length===1)return r[0];let e=r.reduce((n,i)=>n+i.length,0),t=new Uint8Array(e);for(let n=0,i=0;n<r.length;n++){let s=r[n];t.set(s,i),i+=s.length}return t}var CB=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function za(r){if(!(r instanceof Uint8Array))throw new Error("Expected Uint8Array");let e="";for(let t=0;t<r.length;t++)e+=CB[r[t]];return e}var PB=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000");function Ka(r){if(typeof r!="bigint")throw new Error("Expected bigint");if(!(Le<=r&&r<PB))throw new Error("Expected number 0 <= n < 2^256");return r.toString(16).padStart(64,"0")}function R3(r){let e=Bo(Ka(r));if(e.length!==32)throw new Error("Error: expected 32 bytes");return e}function Gl(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function Yf(r){if(typeof r!="string")throw new TypeError("hexToNumber: expected string, got "+typeof r);return BigInt(`0x${r}`)}function Bo(r){if(typeof r!="string")throw new TypeError("hexToBytes: expected string, got "+typeof r);if(r.length%2)throw new Error("hexToBytes: received invalid unpadded hex"+r.length);let e=new Uint8Array(r.length/2);for(let t=0;t<e.length;t++){let n=t*2,i=r.slice(n,n+2),s=Number.parseInt(i,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");e[t]=s}return e}function Ks(r){return Yf(za(r))}function Ha(r){return r instanceof Uint8Array?Uint8Array.from(r):Bo(r)}function gb(r){if(typeof r=="number"&&Number.isSafeInteger(r)&&r>0)return BigInt(r);if(typeof r=="bigint"&&Ql(r))return r;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function G(r,e=Dt.P){let t=r%e;return t>=Le?t:e+t}function Rn(r,e){let{P:t}=Dt,n=r;for(;e-- >Le;)n*=n,n%=t;return n}function kB(r){let{P:e}=Dt,t=BigInt(6),n=BigInt(11),i=BigInt(22),s=BigInt(23),o=BigInt(44),a=BigInt(88),c=r*r*r%e,l=c*c*r%e,u=Rn(l,Wl)*l%e,h=Rn(u,Wl)*l%e,f=Rn(h,Fs)*c%e,d=Rn(f,n)*f%e,p=Rn(d,i)*d%e,m=Rn(p,o)*p%e,g=Rn(m,a)*m%e,y=Rn(g,o)*p%e,b=Rn(y,Wl)*l%e,E=Rn(b,s)*d%e,I=Rn(E,t)*c%e,v=Rn(I,Fs);if(v*v%e!==r)throw new Error("Cannot find square root");return v}function $a(r,e=Dt.P){if(r===Le||e<=Le)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=G(r,e),n=e,i=Le,s=pt,o=pt,a=Le;for(;t!==Le;){let l=n/t,u=n%t,h=i-o*l,f=s-a*l;n=t,t=u,i=o,s=a,o=h,a=f}if(n!==pt)throw new Error("invert: does not exist");return G(i,e)}function NB(r,e=Dt.P){let t=new Array(r.length),n=r.reduce((s,o,a)=>o===Le?s:(t[a]=s,G(s*o,e)),pt),i=$a(n,e);return r.reduceRight((s,o,a)=>o===Le?s:(t[a]=G(s*t[a],e),G(s*o,e)),i),t}function LB(r){let e=r.length*8-qa*8,t=Ks(r);return e>0?t>>BigInt(e):t}function A3(r,e=!1){let t=LB(r);if(e)return t;let{n}=Dt;return t>=n?t-n:t}var Va,Yl,I3=class{constructor(e,t){if(this.hashLen=e,this.qByteLen=t,typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");this.v=new Uint8Array(e).fill(1),this.k=new Uint8Array(e).fill(0),this.counter=0}hmac(...e){return jn.hmacSha256(this.k,...e)}hmacSync(...e){return Yl(this.k,...e)}checkSync(){if(typeof Yl!="function")throw new Wf("hmacSha256Sync needs to be set")}incr(){if(this.counter>=1e3)throw new Error("Tried 1,000 k values for sign(), all were invalid");this.counter+=1}async reseed(e=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),e),this.v=await this.hmac(this.v),e.length!==0&&(this.k=await this.hmac(this.v,Uint8Array.from([1]),e),this.v=await this.hmac(this.v))}reseedSync(e=new Uint8Array){this.checkSync(),this.k=this.hmacSync(this.v,Uint8Array.from([0]),e),this.v=this.hmacSync(this.v),e.length!==0&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),e),this.v=this.hmacSync(this.v))}async generate(){this.incr();let e=0,t=[];for(;e<this.qByteLen;){this.v=await this.hmac(this.v);let n=this.v.slice();t.push(n),e+=this.v.length}return Us(...t)}generateSync(){this.checkSync(),this.incr();let e=0,t=[];for(;e<this.qByteLen;){this.v=this.hmacSync(this.v);let n=this.v.slice();t.push(n),e+=this.v.length}return Us(...t)}};function Ql(r){return Le<r&&r<Dt.n}function _3(r){return Le<r&&r<Dt.P}function OB(r,e,t,n=!0){let{n:i}=Dt,s=A3(r,!0);if(!Ql(s))return;let o=$a(s,i),a=Qe.BASE.multiply(s),c=G(a.x,i);if(c===Le)return;let l=G(o*G(e+t*c,i),i);if(l===Le)return;let u=new Si(c,l),h=(a.x===u.r?0:2)|Number(a.y&pt);return n&&u.hasHighS()&&(u=u.normalizeS(),h^=1),{sig:u,recovery:h}}function Qf(r){let e;if(typeof r=="bigint")e=r;else if(typeof r=="number"&&Number.isSafeInteger(r)&&r>0)e=BigInt(r);else if(typeof r=="string"){if(r.length!==2*qa)throw new Error("Expected 32 bytes of private key");e=Yf(r)}else if(r instanceof Uint8Array){if(r.length!==qa)throw new Error("Expected 32 bytes of private key");e=Ks(r)}else throw new TypeError("Expected valid private key");if(!Ql(e))throw new Error("Expected private key: 0 < key < n");return e}function BB(r){return r instanceof Qe?(r.assertValidity(),r):Qe.fromHex(r)}function yb(r){if(r instanceof Si)return r.assertValidity(),r;try{return Si.fromDER(r)}catch{return Si.fromCompact(r)}}function T3(r,e=!1){return Qe.fromPrivateKey(r).toRawBytes(e)}function wb(r){let e=r.length>Xn?r.slice(0,Xn):r;return Ks(e)}function MB(r){let e=wb(r),t=G(e,Dt.n);return bb(t<Le?e:t)}function bb(r){return R3(r)}function UB(r,e,t){if(r==null)throw new Error(`sign: expected valid message hash, not "${r}"`);let n=Ha(r),i=Qf(e),s=[bb(i),MB(n)];if(t!=null){t===!0&&(t=jn.randomBytes(Xn));let c=Ha(t);if(c.length!==Xn)throw new Error(`sign: Expected ${Xn} bytes of extra data`);s.push(c)}let o=Us(...s),a=wb(n);return{seed:o,m:a,d:i}}function FB(r,e){let{sig:t,recovery:n}=r,{der:i,recovered:s}=Object.assign({canonical:!0,der:!0},e),o=i?t.toDERRawBytes():t.toCompactRawBytes();return s?[o,n]:o}async function Eb(r,e,t={}){let{seed:n,m:i,d:s}=UB(r,e,t.extraEntropy),o=new I3(TB,qa);await o.reseed(n);let a;for(;!(a=OB(await o.generate(),i,s,t.canonical));)await o.reseed();return FB(a,t)}var KB={strict:!0};function vb(r,e,t,n=KB){let i;try{i=yb(r),e=Ha(e)}catch{return!1}let{r:s,s:o}=i;if(n.strict&&i.hasHighS())return!1;let a=A3(e),c;try{c=BB(t)}catch{return!1}let{n:l}=Dt,u=$a(o,l),h=G(a*u,l),f=G(s*u,l),d=Qe.BASE.multiplyAndAddUnsafe(c,h,f);return d?G(d.x,l)===s:!1}Qe.BASE._setWindowSize(8);var on={node:AB,web:typeof self=="object"&&"crypto"in self?self.crypto:void 0};var Gf={},jn={bytesToHex:za,hexToBytes:Bo,concatBytes:Us,mod:G,invert:$a,isValidPrivateKey(r){try{return Qf(r),!0}catch{return!1}},_bigintTo32Bytes:R3,_normalizePrivateKey:Qf,hashToPrivateKey:r=>{r=Ha(r);let e=qa+8;if(r.length<e||r.length>1024)throw new Error("Expected valid bytes of private key as per FIPS 186");let t=G(Ks(r),Dt.n-pt)+pt;return R3(t)},randomBytes:(r=32)=>{if(on.web)return on.web.getRandomValues(new Uint8Array(r));if(on.node){let{randomBytes:e}=on.node;return Uint8Array.from(e(r))}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>jn.hashToPrivateKey(jn.randomBytes(qa+8)),precompute(r=8,e=Qe.BASE){let t=e===Qe.BASE?e:new Qe(e.x,e.y);return t._setWindowSize(r),t.multiply(Wl),t},sha256:async(...r)=>{if(on.web){let e=await on.web.subtle.digest("SHA-256",Us(...r));return new Uint8Array(e)}else if(on.node){let{createHash:e}=on.node,t=e("sha256");return r.forEach(n=>t.update(n)),Uint8Array.from(t.digest())}else throw new Error("The environment doesn't have sha256 function")},hmacSha256:async(r,...e)=>{if(on.web){let t=await on.web.subtle.importKey("raw",r,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=Us(...e),i=await on.web.subtle.sign("HMAC",t,n);return new Uint8Array(i)}else if(on.node){let{createHmac:t}=on.node,n=t("sha256",r);return e.forEach(i=>n.update(i)),Uint8Array.from(n.digest())}else throw new Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:async(r,...e)=>{let t=Gf[r];if(t===void 0){let n=await jn.sha256(Uint8Array.from(r,i=>i.charCodeAt(0)));t=Us(n,n),Gf[r]=t}return jn.sha256(t,...e)},taggedHashSync:(r,...e)=>{if(typeof Va!="function")throw new Wf("sha256Sync is undefined, you need to set it");let t=Gf[r];if(t===void 0){let n=Va(Uint8Array.from(r,i=>i.charCodeAt(0)));t=Us(n,n),Gf[r]=t}return Va(t,...e)},_JacobianPoint:Ue};Object.defineProperties(jn,{sha256Sync:{configurable:!1,get(){return Va},set(r){Va||(Va=r)}},hmacSha256Sync:{configurable:!1,get(){return Yl},set(r){Yl||(Yl=r)}}});function In(r){if(isNaN(r)||r<=0)throw new w("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return jn.randomBytes(r)}var Zte=F(Of(),1),D3=F(tt(),1);function xb(r,e){return e.map(t=>sn(r[t]))}function _b(r){return D3.default.pki.setRsaPrivateKey(...xb(r,["n","e","d","p","q","dp","dq","qi"]))}function Sb(r){return D3.default.pki.setRsaPublicKey(...xb(r,["n","e"]))}var Mo={};Re(Mo,{jwkToPkcs1:()=>zB,jwkToPkix:()=>$B,pkcs1ToJwk:()=>qB,pkixToJwk:()=>HB});var tre=F(Ml(),1),rre=F(Of(),1);var Ji=F(tt(),1);function qB(r){let e=Ji.default.asn1.fromDer(O(r,"ascii")),t=Ji.default.pki.privateKeyFromAsn1(e);return{kty:"RSA",n:Qn(t.n),e:Qn(t.e),d:Qn(t.d),p:Qn(t.p),q:Qn(t.q),dp:Qn(t.dP),dq:Qn(t.dQ),qi:Qn(t.qInv),alg:"RS256"}}function zB(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new w("JWK was missing components","ERR_INVALID_PARAMETERS");let e=Ji.default.pki.privateKeyToAsn1({n:sn(r.n),e:sn(r.e),d:sn(r.d),p:sn(r.p),q:sn(r.q),dP:sn(r.dp),dQ:sn(r.dq),qInv:sn(r.qi)});return K(Ji.default.asn1.toDer(e).getBytes(),"ascii")}function HB(r){let e=Ji.default.asn1.fromDer(O(r,"ascii")),t=Ji.default.pki.publicKeyFromAsn1(e);return{kty:"RSA",n:Qn(t.n),e:Qn(t.e)}}function $B(r){if(r.n==null||r.e==null)throw new w("JWK was missing components","ERR_INVALID_PARAMETERS");let e=Ji.default.pki.publicKeyToAsn1({n:sn(r.n),e:sn(r.e)});return K(Ji.default.asn1.toDer(e).getBytes(),"ascii")}async function Rb(r){let e=await Mt.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 Tb(e);return{privateKey:t[0],publicKey:t[1]}}async function C3(r){let t=[await Mt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await GB(r)],n=await Tb({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function Ib(r,e){let t=await Mt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Mt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,Uint8Array.from(e));return new Uint8Array(n,0,n.byteLength)}async function Ab(r,e,t){let n=await Mt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Mt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t)}async function Tb(r){if(r.privateKey==null||r.publicKey==null)throw new w("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Mt.get().subtle.exportKey("jwk",r.privateKey),Mt.get().subtle.exportKey("jwk",r.publicKey)])}async function GB(r){return Mt.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function Db(r,e,t,n){let i=e?Sb(r):_b(r),s=O(Uint8Array.from(t),"ascii"),o=n(s,i);return K(o,"ascii")}function Cb(r,e){return Db(r,!0,e,(t,n)=>n.encrypt(t))}function Pb(r,e){return Db(r,!1,e,(t,n)=>n.decrypt(t))}var jl=class{_key;constructor(e){this._key=e}async verify(e,t){return Ab(this._key,t,e)}marshal(){return Mo.jwkToPkix(this._key)}get bytes(){return Wn.encode({Type:ft.RSA,Data:this.marshal()}).subarray()}encrypt(e){return Cb(this._key,e)}equals(e){return de(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ce.digest(this.bytes);return e}},Ga=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return In(16)}async sign(e){return Ib(this._key,e)}get public(){if(this._publicKey==null)throw new w("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new jl(this._publicKey)}decrypt(e){return Pb(this._key,e)}marshal(){return Mo.jwkToPkcs1(this._key)}get bytes(){return Yn.encode({Type:ft.RSA,Data:this.marshal()}).subarray()}equals(e){return de(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ce.digest(this.bytes);return e}async id(){let e=await this.public.hash();return O(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8"){let n=new Xl.default.util.ByteBuffer(this.marshal()),i=Xl.default.asn1.fromDer(n),s=Xl.default.pki.privateKeyFromAsn1(i),o={algorithm:"aes256",count:1e4,saltSize:128/8,prfAlgorithm:"sha512"};return Xl.default.pki.encryptRsaPrivateKey(s,e,o)}else{if(t==="libp2p-key")return Ma(this.bytes,e);throw new w(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}};async function YB(r){let e=Mo.pkcs1ToJwk(r),t=await C3(e);return new Ga(t.privateKey,t.publicKey)}function QB(r){let e=Mo.pkixToJwk(r);return new jl(e)}async function XB(r){let e=await C3(r);return new Ga(e.privateKey,e.publicKey)}async function jB(r){let e=await Rb(r);return new Ga(e.privateKey,e.publicKey)}var N3={};Re(N3,{Secp256k1PrivateKey:()=>Jl,Secp256k1PublicKey:()=>Zl,generateKeyPair:()=>tM,unmarshalSecp256k1PrivateKey:()=>JB,unmarshalSecp256k1PublicKey:()=>eM});function kb(){return jn.randomPrivateKey()}async function Nb(r,e){let{digest:t}=await Ce.digest(e);try{return await Eb(t,r)}catch(n){throw new w(String(n),"ERR_INVALID_INPUT")}}async function Lb(r,e,t){try{let{digest:n}=await Ce.digest(t);return vb(e,n,r)}catch(n){throw new w(String(n),"ERR_INVALID_INPUT")}}function Ob(r){return Qe.fromHex(r).toRawBytes(!0)}function Bb(r){try{T3(r,!0)}catch(e){throw new w(String(e),"ERR_INVALID_PRIVATE_KEY")}}function k3(r){try{Qe.fromHex(r)}catch(e){throw new w(String(e),"ERR_INVALID_PUBLIC_KEY")}}function Mb(r){try{return T3(r,!0)}catch(e){throw new w(String(e),"ERR_INVALID_PRIVATE_KEY")}}var Zl=class{_key;constructor(e){k3(e),this._key=e}async verify(e,t){return Lb(this._key,t,e)}marshal(){return Ob(this._key)}get bytes(){return Wn.encode({Type:ft.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return de(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ce.digest(this.bytes);return e}},Jl=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??Mb(e),Bb(this._key),k3(this._publicKey)}async sign(e){return Nb(this._key,e)}get public(){return new Zl(this._publicKey)}marshal(){return this._key}get bytes(){return Yn.encode({Type:ft.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return de(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ce.digest(this.bytes);return e}async id(){let e=await this.public.hash();return O(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return Ma(this.bytes,e);throw new w(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function JB(r){return new Jl(r)}function eM(r){return new Zl(r)}async function tM(){let r=kb();return new Jl(r)}var Ri={rsa:P3,ed25519:b3,secp256k1:N3};function L3(r){let e=Object.keys(Ri).join(" / ");return new w(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function O3(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return Ri[r];throw L3(r)}async function eu(r,e){return O3(r).generateKeyPair(e??2048)}async function rM(r,e,t){if(r.toLowerCase()!=="ed25519")throw new w("Seed key derivation is unimplemented for RSA or secp256k1","ERR_UNSUPPORTED_KEY_DERIVATION_TYPE");return w3(e)}function rr(r){let e=Wn.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case ft.RSA:return Ri.rsa.unmarshalRsaPublicKey(t);case ft.Ed25519:return Ri.ed25519.unmarshalEd25519PublicKey(t);case ft.Secp256k1:return Ri.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw L3(e.Type??"RSA")}}function Wa(r,e){return e=(e??"rsa").toLowerCase(),O3(e),r.bytes}async function an(r){let e=Yn.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case ft.RSA:return Ri.rsa.unmarshalRsaPrivateKey(t);case ft.Ed25519:return Ri.ed25519.unmarshalEd25519PrivateKey(t);case ft.Secp256k1:return Ri.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw L3(e.Type??"RSA")}}function B3(r,e){return e=(e??"rsa").toLowerCase(),O3(e),r.bytes}async function Ya(r,e){try{let i=await jw(r,e);return await an(i)}catch{}let t=Xf.default.pki.decryptRsaPrivateKey(r,e);if(t===null)throw new w("Cannot read the key, most likely the password is wrong or not a RSA key","ERR_CANNOT_DECRYPT_PEM");let n=Xf.default.asn1.toDer(Xf.default.pki.privateKeyToAsn1(t));return n=K(n.getBytes(),"ascii"),Ri.rsa.unmarshalRsaPrivateKey(n)}var tu=Symbol.for("@libp2p/content-routing");var Uo=Symbol.for("@libp2p/peer-discovery");var ru=Symbol.for("@libp2p/peer-routing");var Fe=class extends EventTarget{#e=new Map;listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let i=this.#e.get(e);i==null&&(i=[],this.#e.set(e,i)),i.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let i=this.#e.get(e);i!=null&&(i=i.filter(({callback:s})=>s!==t),this.#e.set(e,i))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:i})=>!i),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t){return this.dispatchEvent(new Je(e,t))}},M3=class extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}},Je=globalThis.CustomEvent??M3;var aE=F(Gb(),1);var tE=F(eE(),1),Vs=tE.default;var Oe;(function(r){r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",r.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",r.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",r.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",r.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",r.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",r.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",r.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",r.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",r.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",r.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",r.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",r.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",r.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH"})(Oe||(Oe={}));var Gre=F(Sf(),1),EM=F(tt(),1);var nE=F(Z2(),1),iE=F(Bt(),1),rE={sha1:"sha1","sha2-256":"sha256","sha2-512":"sha512"};function nu(r,e,t,n,i){if(i!=="sha1"&&i!=="sha2-256"&&i!=="sha2-512"){let a=Object.keys(rE).join(" / ");throw new w(`Hash '${i}' is unknown or not supported. Must be ${a}`,"ERR_UNSUPPORTED_HASH_TYPE")}let s=rE[i],o=(0,nE.default)(r,e,t,n,s);return iE.default.encode64(o,null)}var F3=Symbol.for("@libp2p/peer-id");function e0(r){return r!=null&&!!r[F3]}var _M=Symbol.for("nodejs.util.inspect.custom"),sE=Object.values(wn).map(r=>r.decoder).reduce((r,e)=>r.or(e),wn.identity.decoder),oE=114,K3=36,V3=37,iu=class{constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}get[F3](){return!0}toString(){return this.string==null&&(this.string=me.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return ee.createV1(oE,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e instanceof Uint8Array)return de(this.multihash.bytes,e);if(typeof e=="string")return oe(e).equals(this);if(e?.multihash?.bytes!=null)return de(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[_M](){return`PeerId(${this.toString()})`}},ja=class extends iu{constructor(e){super({...e,type:"RSA"}),this.type="RSA",this.publicKey=e.publicKey}},Za=class extends iu{constructor(e){super({...e,type:"Ed25519"}),this.type="Ed25519",this.publicKey=e.multihash.digest}},Ja=class extends iu{constructor(e){super({...e,type:"secp256k1"}),this.type="secp256k1",this.publicKey=e.multihash.digest}};function oe(r,e){if(e=e??sE,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=ui(me.decode(`z${r}`));return r.startsWith("12D")?new Za({multihash:t}):r.startsWith("16U")?new Ja({multihash:t}):new ja({multihash:t})}return vt(sE.decode(r))}function vt(r){try{let e=ui(r);if(e.code===hi.code){if(e.digest.length===K3)return new Za({multihash:e});if(e.digest.length===V3)return new Ja({multihash:e})}if(e.code===Ce.code)return new ja({multihash:e})}catch{return SM(ee.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function SM(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==oE)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===Ce.code)return new ja({multihash:r.multihash});if(e.code===hi.code){if(e.digest.length===K3)return new Za({multihash:r.multihash});if(e.digest.length===V3)return new Ja({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function zt(r,e){return r.length===K3?new Za({multihash:Bn(hi.code,r),privateKey:e}):r.length===V3?new Ja({multihash:Bn(hi.code,r),privateKey:e}):new ja({multihash:await Ce.digest(r),publicKey:r,privateKey:e})}var t0=T("libp2p:keychain"),IM="/pkcs8/",cE="/info/",Fo=new WeakMap,Ko={minKeyLength:112/8,minSaltLength:128/8,minIterationCount:1e3},q3={dek:{keyLength:512/8,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"}};function es(r){return r==null||typeof r!="string"?!1:r===(0,aE.default)(r.trim())&&r.length>0}async function nt(){let t=Math.random()*800+200;await new Promise(n=>setTimeout(n,t))}function Ii(r){return new ve(IM+r)}function qs(r){return new ve(cE+r)}var Vo=class{constructor(e,t){if(this.components=e,this.init=Vs(q3,t),this.init.pass!=null&&this.init.pass?.length<20)throw new Error("pass must be least 20 characters");if(this.init.dek?.keyLength!=null&&this.init.dek.keyLength<Ko.minKeyLength)throw new Error(`dek.keyLength must be least ${Ko.minKeyLength} bytes`);if(this.init.dek?.salt?.length!=null&&this.init.dek.salt.length<Ko.minSaltLength)throw new Error(`dek.saltLength must be least ${Ko.minSaltLength} bytes`);if(this.init.dek?.iterationCount!=null&&this.init.dek.iterationCount<Ko.minIterationCount)throw new Error(`dek.iterationCount must be least ${Ko.minIterationCount}`);let n=this.init.pass!=null&&this.init.dek?.salt!=null?nu(this.init.pass,this.init.dek?.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";Fo.set(this,{dek:n})}static generateOptions(){let e=Object.assign({},q3),t=Math.ceil(Ko.minSaltLength/3)*3;return e.dek.salt=O(In(t),"base64"),e}static get options(){return q3}async createKey(e,t,n=2048){if(!es(e)||e==="self")throw await nt(),new w("Invalid key name",Oe.ERR_INVALID_KEY_NAME);if(typeof t!="string")throw await nt(),new w("Invalid key type",Oe.ERR_INVALID_KEY_TYPE);let i=Ii(e);if(await this.components.datastore.has(i))throw await nt(),new w("Key name already exists",Oe.ERR_KEY_ALREADY_EXISTS);switch(t.toLowerCase()){case"rsa":if(!Number.isSafeInteger(n)||n<2048)throw await nt(),new w("Invalid RSA key size",Oe.ERR_INVALID_KEY_SIZE);break;default:break}let o;try{let a=await eu(t,n),c=await a.id(),l=Fo.get(this);if(l==null)throw new w("dek missing",Oe.ERR_INVALID_PARAMETERS);let u=l.dek,h=await a.export(u);o={name:e,id:c};let f=this.components.datastore.batch();f.put(i,K(h)),f.put(qs(e),K(JSON.stringify(o))),await f.commit()}catch(a){throw await nt(),a}return o}async listKeys(){let e={prefix:cE},t=[];for await(let n of this.components.datastore.query(e))t.push(JSON.parse(O(n.value)));return t}async findKeyById(e){try{let n=(await this.listKeys()).find(i=>i.id===e);if(n==null)throw new w(`Key with id '${e}' does not exist.`,Oe.ERR_KEY_NOT_FOUND);return n}catch(t){throw await nt(),t}}async findKeyByName(e){if(!es(e))throw await nt(),new w(`Invalid key name '${e}'`,Oe.ERR_INVALID_KEY_NAME);let t=qs(e);try{let n=await this.components.datastore.get(t);return JSON.parse(O(n))}catch(n){throw await nt(),t0.error(n),new w(`Key '${e}' does not exist.`,Oe.ERR_KEY_NOT_FOUND)}}async removeKey(e){if(!es(e)||e==="self")throw await nt(),new w(`Invalid key name '${e}'`,Oe.ERR_INVALID_KEY_NAME);let t=Ii(e),n=await this.findKeyByName(e),i=this.components.datastore.batch();return i.delete(t),i.delete(qs(e)),await i.commit(),n}async renameKey(e,t){if(!es(e)||e==="self")throw await nt(),new w(`Invalid old key name '${e}'`,Oe.ERR_OLD_KEY_NAME_INVALID);if(!es(t)||t==="self")throw await nt(),new w(`Invalid new key name '${t}'`,Oe.ERR_NEW_KEY_NAME_INVALID);let n=Ii(e),i=Ii(t),s=qs(e),o=qs(t);if(await this.components.datastore.has(i))throw await nt(),new w(`Key '${t}' already exists`,Oe.ERR_KEY_ALREADY_EXISTS);try{let c=await this.components.datastore.get(n),l=await this.components.datastore.get(s),u=JSON.parse(O(l));u.name=t;let h=this.components.datastore.batch();return h.put(i,c),h.put(o,K(JSON.stringify(u))),h.delete(n),h.delete(s),await h.commit(),u}catch(c){throw await nt(),c}}async exportKey(e,t){if(!es(e))throw await nt(),new w(`Invalid key name '${e}'`,Oe.ERR_INVALID_KEY_NAME);if(t==null)throw await nt(),new w("Password is required",Oe.ERR_PASSWORD_REQUIRED);let n=Ii(e);try{let i=await this.components.datastore.get(n),s=O(i),o=Fo.get(this);if(o==null)throw new w("dek missing",Oe.ERR_INVALID_PARAMETERS);let a=o.dek;return await(await Ya(s,a)).export(t)}catch(i){throw await nt(),i}}async exportPeerId(e){let t="temporary-password",n=await this.exportKey(e,t),i=await Ya(n,t);return await zt(i.public.bytes,i.bytes)}async importKey(e,t,n){if(!es(e)||e==="self")throw await nt(),new w(`Invalid key name '${e}'`,Oe.ERR_INVALID_KEY_NAME);if(t==null)throw await nt(),new w("PEM encoded key is required",Oe.ERR_PEM_REQUIRED);let i=Ii(e);if(await this.components.datastore.has(i))throw await nt(),new w(`Key '${e}' already exists`,Oe.ERR_KEY_ALREADY_EXISTS);let o;try{o=await Ya(t,n)}catch{throw await nt(),new w("Cannot read the key, most likely the password is wrong",Oe.ERR_CANNOT_READ_KEY)}let a;try{a=await o.id();let u=Fo.get(this);if(u==null)throw new w("dek missing",Oe.ERR_INVALID_PARAMETERS);let h=u.dek;t=await o.export(h)}catch(u){throw await nt(),u}let c={name:e,id:a},l=this.components.datastore.batch();return l.put(i,K(t)),l.put(qs(e),K(JSON.stringify(c))),await l.commit(),c}async importPeer(e,t){try{if(!es(e))throw new w(`Invalid key name '${e}'`,Oe.ERR_INVALID_KEY_NAME);if(t==null)throw new w("PeerId is required",Oe.ERR_MISSING_PRIVATE_KEY);if(t.privateKey==null)throw new w("PeerId.privKey is required",Oe.ERR_MISSING_PRIVATE_KEY);let n=await an(t.privateKey),i=Ii(e);if(await this.components.datastore.has(i))throw await nt(),new w(`Key '${e}' already exists`,Oe.ERR_KEY_ALREADY_EXISTS);let o=Fo.get(this);if(o==null)throw new w("dek missing",Oe.ERR_INVALID_PARAMETERS);let a=o.dek,c=await n.export(a),l={name:e,id:t.toString()},u=this.components.datastore.batch();return u.put(i,K(c)),u.put(qs(e),K(JSON.stringify(l))),await u.commit(),l}catch(n){throw await nt(),n}}async getPrivateKey(e){if(!es(e))throw await nt(),new w(`Invalid key name '${e}'`,Oe.ERR_INVALID_KEY_NAME);try{let t=Ii(e),n=await this.components.datastore.get(t);return O(n)}catch(t){throw await nt(),t0.error(t),new w(`Key '${e}' does not exist.`,Oe.ERR_KEY_NOT_FOUND)}}async rotateKeychainPass(e,t){if(typeof e!="string")throw await nt(),new w(`Invalid old pass type '${typeof e}'`,Oe.ERR_INVALID_OLD_PASS_TYPE);if(typeof t!="string")throw await nt(),new w(`Invalid new pass type '${typeof t}'`,Oe.ERR_INVALID_NEW_PASS_TYPE);if(t.length<20)throw await nt(),new w(`Invalid pass length ${t.length}`,Oe.ERR_INVALID_PASS_LENGTH);t0("recreating keychain");let n=Fo.get(this);if(n==null)throw new w("dek missing",Oe.ERR_INVALID_PARAMETERS);let i=n.dek;this.init.pass=t;let s=t!=null&&this.init.dek?.salt!=null?nu(t,this.init.dek.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";Fo.set(this,{dek:s});let o=await this.listKeys();for(let a of o){let c=await this.components.datastore.get(Ii(a.name)),l=O(c),u=await Ya(l,i),h=s.toString(),f=await u.export(h),d=this.components.datastore.batch(),p={name:a.name,id:a.id};d.put(Ii(a.name),K(f)),d.put(qs(a.name),K(JSON.stringify(p))),await d.commit()}t0("keychain reconstructed")}};function ts(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),i=n.value;return n.done===!0||i==null?{done:!0,value:void 0}:{done:!1,value:e(i)}}};return t}var Fr=class{constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){this.map.delete(e.toString())}entries(){return ts(this.map.entries(),e=>[oe(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,oe(n),this)})}get(e){return this.map.get(e.toString())}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),t)}keys(){return ts(this.map.keys(),e=>oe(e))}values(){return this.map.values()}get size(){return this.map.size}};var vr=class{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 ts(this.set.entries(),e=>{let t=oe(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=oe(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return ts(this.set.values(),e=>oe(e))}intersection(e){let t=new vr;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new vr;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new vr;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var ec=class{constructor(e){if(this.list=[],e!=null)for(let t of e)this.list.push(t.toString())}[Symbol.iterator](){return ts(this.list.entries(),e=>oe(e[1]))}concat(e){let t=new ec(this);for(let n of e)t.push(n);return t}entries(){return ts(this.list.entries(),e=>[e[0],oe(e[1])])}every(e){return this.list.every((t,n)=>e(oe(t),n,this))}filter(e){let t=new ec;return this.list.forEach((n,i)=>{let s=oe(n);e(s,i,this)&&t.push(s)}),t}find(e){let t=this.list.find((n,i)=>e(oe(n),i,this));if(t!=null)return oe(t)}findIndex(e){return this.list.findIndex((t,n)=>e(oe(t),n,this))}forEach(e){this.list.forEach((t,n)=>{e(oe(t),n,this)})}includes(e){return this.list.includes(e.toString())}indexOf(e){return this.list.indexOf(e.toString())}pop(){let e=this.list.pop();if(e!=null)return oe(e)}push(...e){for(let t of e)this.list.push(t.toString())}shift(){let e=this.list.shift();if(e!=null)return oe(e)}unshift(...e){let t=this.list.length;for(let n=e.length-1;n>-1;n--)t=this.list.unshift(e[n].toString());return t}get length(){return this.list.length}};var z3;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.id!=null&&(n.uint32(10),n.bytes(t.id)),t.pubKey!=null&&(n.uint32(18),n.bytes(t.pubKey)),t.privKey!=null&&(n.uint32(26),n.bytes(t.privKey)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.id=t.bytes();break;case 2:i.pubKey=t.bytes();break;case 3:i.privKey=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(z3||(z3={}));var r0=async()=>{let r=await eu("Ed25519"),e=await AM(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function lE(r){return await zt(Wa(r))}async function AM(r){return await zt(Wa(r.public),B3(r))}var uE={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var su;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.publicKey=t.bytes();break;case 2:i.payloadType=t.bytes();break;case 3:i.payload=t.bytes();break;case 5:i.signature=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(su||(su={}));var TM,Wt=class{constructor(e){let{peerId:t,payloadType:n,payload:i,signature:s}=e;this.peerId=t,this.payloadType=n,this.payload=i,this.signature=s}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=su.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return de(this.marshal(),e.marshal())}async validate(e){let t=hE(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return await rr(this.peerId.publicKey).verify(t.subarray(),this.signature)}};TM=Wt;Wt.createFromProtobuf=async r=>{let e=su.decode(r),t=await zt(e.publicKey);return new Wt({peerId:t,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};Wt.seal=async(r,e)=>{if(e.privateKey==null)throw new Error("Missing private key");let t=r.domain,n=r.codec,i=r.marshal(),s=hE(t,n,i),a=await(await an(e.privateKey)).sign(s.subarray());return new Wt({peerId:e,payloadType:n,payload:i,signature:a})};Wt.openAndCertify=async(r,e)=>{let t=await Wt.createFromProtobuf(r);if(!await t.validate(e))throw new w("envelope signature is not valid for the given domain",uE.ERR_SIGNATURE_NOT_VALID);return t};var hE=(r,e,t)=>{let n=K(r),i=ot.encode(n.byteLength),s=ot.encode(e.length),o=ot.encode(t.length);return new j(i,n,s,e,o,t)};var tm=F(Eo(),1);var nc=F(Eo(),1);var n0=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,i){return this.readAtomically(()=>{let s=0,o=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*i)-1;for(;;){let u=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let f=Number.parseInt(h,e);if(!Number.isNaN(f))return f});if(u===void 0)break;if(s*=e,s+=u,s>l||(o+=1,t!==void 0&&o>t))return}if(o!==0)return!n&&c&&o>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;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 i=n*2;if(n<t.length-3){let o=this.readSeparator(":",n,()=>this.readIPv4Addr());if(o!==void 0)return t[i]=o[0],t[i+1]=o[1],t[i+2]=o[2],t[i+3]=o[3],[i+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[i,!1];t[i]=s>>8,t[i+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,i]=e(t);if(n===16)return t;if(i||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),o=16-(n+2),[a]=e(s.subarray(0,o));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var fE=45,DM=15,tc=new n0;function H3(r){if(!(r.length>DM))return tc.new(r).parseWith(()=>tc.readIPv4Addr())}function $3(r){if(!(r.length>fE))return tc.new(r).parseWith(()=>tc.readIPv6Addr())}function i0(r){if(!(r.length>fE))return tc.new(r).parseWith(()=>tc.readIPAddr())}var die=parseInt("0xFFFF",16),pie=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var Ai=F(Eo(),1);function mE(r){return!!H3(r)}function gE(r){return!!$3(r)}function rc(r){return!!i0(r)}var yE=mE,LM=gE,G3=function(r){let e=0;if(r=r.toString().trim(),yE(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(LM(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=yE(t[n]),o;s&&(o=G3(t[n]),t[n]=O(o.slice(0,2),"base16")),o!=null&&++n<8&&t.splice(n,0,O(o.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 s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let i=new Uint8Array(e+16);for(n=0;n<t.length;n++){let s=parseInt(t[n],16);i[e++]=s>>8&255,i[e++]=s&255}return i}throw new Error("invalid ip address")},wE=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let i=[];for(let s=0;s<t;s++)i.push(r[e+s]);return i.join(".")}if(t===16){let i=[];for(let s=0;s<t;s+=2)i.push(n.getUint16(e+s).toString(16));return i.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var ou={},W3={},BM=[[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"],[777,-1,"memory"]];BM.forEach(r=>{let e=MM(...r);W3[e.code]=e,ou[e.name]=e});function MM(r,e,t,n,i){return{code:r,size:e,name:t,resolvable:!!n,path:!!i}}function X(r){if(typeof r=="number"){if(W3[r]!=null)return W3[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(ou[r]!=null)return ou[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var jie=X("ip4"),Zie=X("ip6"),Jie=X("ipcidr");function s0(r,e){switch(X(r).code){case 4:case 41:return FM(e);case 42:return vE(e);case 6:case 273:case 33:case 132:return SE(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return vE(e);case 421:return zM(e);case 444:return xE(e);case 445:return xE(e);case 466:return qM(e);default:return O(e,"base16")}}function _E(r,e){switch(X(r).code){case 4:return bE(e);case 41:return bE(e);case 42:return EE(e);case 6:case 273:case 33:case 132:return Q3(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return EE(e);case 421:return KM(e);case 444:return HM(e);case 445:return $M(e);case 466:return VM(e);default:return K(e,"base16")}}var Y3=Object.values(wn).map(r=>r.decoder),UM=function(){let r=Y3[0].or(Y3[1]);return Y3.slice(2).forEach(e=>r=r.or(e)),r}();function bE(r){if(!rc(r))throw new Error("invalid ip address");return G3(r)}function FM(r){let e=wE(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!rc(e))throw new Error("invalid ip address");return e}function Q3(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function SE(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function EE(r){let e=K(r),t=Uint8Array.from(Ai.default.encode(e.length));return le([t,e],t.length+e.length)}function vE(r){let e=Ai.default.decode(r);if(r=r.slice(Ai.default.decode.bytes),r.length!==e)throw new Error("inconsistent lengths");return O(r)}function KM(r){let e;r[0]==="Q"||r[0]==="1"?e=ui(me.decode(`z${r}`)).bytes:e=ee.parse(r).multihash.bytes;let t=Uint8Array.from(Ai.default.encode(e.length));return le([t,e],t.length+e.length)}function VM(r){let e=UM.decode(r),t=Uint8Array.from(Ai.default.encode(e.length));return le([t,e],t.length+e.length)}function qM(r){let e=Ai.default.decode(r),t=r.slice(Ai.default.decode.bytes);if(t.length!==e)throw new Error("inconsistent lengths");return"u"+O(t,"base64url")}function zM(r){let e=Ai.default.decode(r),t=r.slice(Ai.default.decode.bytes);if(t.length!==e)throw new Error("inconsistent lengths");return O(t,"base58btc")}function HM(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=Gt.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=Q3(n);return le([t,i],t.length+i.length)}function $M(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=Gt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=Q3(n);return le([t,i],t.length+i.length)}function xE(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=O(e,"base32"),i=SE(t);return`${n}:${i}`}function GM(r){let e=[],t=r.split("/").slice(1);if(t.length===1&&t[0]==="")return[];for(let n=0;n<t.length;n++){let i=t[n],s=X(i);if(s.size===0){e.push([i]);continue}if(n++,n>=t.length)throw IE("invalid address: "+r);if(s.path===!0){e.push([i,em(t.slice(n).join("/"))]);break}e.push([i,t[n]])}return e}function WM(r){let e=[];return r.map(t=>{let n=c0(t);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),em(e.join("/"))}function YM(r){return r.map(e=>{Array.isArray(e)||(e=[e]);let t=c0(e);return e.length>1?[t.code,_E(t.code,e[1])]:[t.code]})}function X3(r){return r.map(e=>{let t=c0(e);return e[1]!=null?[t.code,s0(t.code,e[1])]:[t.code]})}function j3(r){return a0(le(r.map(e=>{let t=c0(e),n=Uint8Array.from(nc.default.encode(t.code));return e.length>1&&e[1]!=null&&(n=le([n,e[1]])),n})))}function Z3(r,e){return r.size>0?r.size/8:r.size===0?0:nc.default.decode(e)+(nc.default.decode.bytes??0)}function o0(r){let e=[],t=0;for(;t<r.length;){let n=nc.default.decode(r,t),i=nc.default.decode.bytes??0,s=X(n),o=Z3(s,r.slice(t+i));if(o===0){e.push([n]),t+=i;continue}let a=r.slice(t+i,t+i+o);if(t+=o+i,t>r.length)throw IE("Invalid address Uint8Array: "+O(r,"base16"));e.push([n,a])}return e}function J3(r){let e=o0(r),t=X3(e);return WM(t)}function QM(r){r=em(r);let e=GM(r),t=YM(e);return j3(t)}function RE(r){return QM(r)}function a0(r){let e=XM(r);if(e!=null)throw e;return Uint8Array.from(r)}function XM(r){try{o0(r)}catch(e){return e}}function em(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function IE(r){return new Error("Error parsing address: "+r)}function c0(r){return X(r[0])}var ZM=Symbol.for("nodejs.util.inspect.custom"),JM=[X("dns").code,X("dns4").code,X("dns6").code,X("dnsaddr").code],rm=new Map,AE=Symbol.for("@multiformats/js-multiaddr/multiaddr");function qo(r){return!!r?.[AE]}var rs=class{bytes;#e;#t;#n;#r;[AE]=!0;constructor(e){if(e==null&&(e=""),e instanceof Uint8Array)this.bytes=a0(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);this.bytes=RE(e)}else if(qo(e))this.bytes=a0(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr")}toString(){return this.#e==null&&(this.#e=J3(this.bytes)),this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,i,s="",o=X("tcp"),a=X("udp"),c=X("ip4"),l=X("ip6"),u=X("dns6"),h=X("ip6zone");for(let[d,p]of this.stringTuples())d===h.code&&(s=`%${p??""}`),JM.includes(d)&&(t=o.name,i=443,n=`${p??""}${s}`,e=d===u.code?6:4),(d===o.code||d===a.code)&&(t=X(d).name,i=parseInt(p??"")),(d===c.code||d===l.code)&&(t=X(d).name,n=`${p??""}${s}`,e=d===l.code?6:4);if(e==null||t==null||n==null||i==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:i}}protos(){return this.protoCodes().map(e=>Object.assign({},X(e)))}protoCodes(){let e=[],t=this.bytes,n=0;for(;n<t.length;){let i=tm.default.decode(t,n),s=tm.default.decode.bytes??0,o=X(i),a=Z3(o,t.slice(n+s));n+=a+s,e.push(i)}return e}protoNames(){return this.protos().map(e=>e.name)}tuples(){return this.#t==null&&(this.#t=o0(this.bytes)),this.#t}stringTuples(){return this.#n==null&&(this.#n=X3(this.tuples())),this.#n}encapsulate(e){return e=new rs(e),new rs(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),i=n.lastIndexOf(t);if(i<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new rs(n.slice(0,i))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new rs(j3(t.slice(0,n)));return this}getPeerId(){try{let t=this.stringTuples().filter(n=>n[0]===ou.ipfs.code).pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?O(me.decode(`z${n}`),"base58btc"):O(ee.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){if(this.#r===void 0)try{this.#r=this.stringTuples().filter(e=>X(e[0]).path===!0)[0][1],this.#r==null&&(this.#r=null)}catch{this.#r=null}return this.#r}equals(e){return de(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=rm.get(t.name);if(n==null)throw new w(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(s=>new rs(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[ZM](){return`Multiaddr(${J3(this.bytes)})`}};function se(r){return new rs(r)}function TE(r,e){let t=(n,i)=>n.toString().localeCompare(i.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,i)=>e[i].equals(n)))}var au;(function(r){let e;(function(n){let i;n.codec=()=>(i==null&&(i=ne((s,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(o.uint32(10),o.bytes(s.multiaddr)),a.lengthDelimited!==!1&&o.ldelim()},(s,o)=>{let a={multiaddr:new Uint8Array(0)},c=o==null?s.len:s.pos+o;for(;s.pos<c;){let l=s.uint32();switch(l>>>3){case 1:a.multiaddr=s.bytes();break;default:s.skipType(l&7);break}}return a})),i),n.encode=s=>re(s,n.codec()),n.decode=s=>te(s,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=ne((n,i,s={})=>{if(s.lengthDelimited!==!1&&i.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(i.uint32(10),i.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(i.uint32(16),i.uint64(n.seq)),n.addresses!=null)for(let o of n.addresses)i.uint32(26),r.AddressInfo.codec().encode(o,i);s.lengthDelimited!==!1&&i.ldelim()},(n,i)=>{let s={peerId:new Uint8Array(0),seq:0n,addresses:[]},o=i==null?n.len:n.pos+i;for(;n.pos<o;){let a=n.uint32();switch(a>>>3){case 1:s.peerId=n.bytes();break;case 2:s.seq=n.uint64();break;case 3:s.addresses.push(r.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return s})),t),r.encode=n=>re(n,r.codec()),r.decode=n=>te(n,r.codec())})(au||(au={}));var DE="libp2p-peer-record",CE=Uint8Array.from([3,1]);var Ut=class{constructor(e){this.domain=Ut.DOMAIN,this.codec=Ut.CODEC;let{peerId:t,multiaddrs:n,seqNumber:i}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=i??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=au.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof Ut)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!TE(this.multiaddrs,e.multiaddrs))}};Ut.createFromProtobuf=r=>{let e=au.decode(r),t=vt(e.peerId),n=(e.addresses??[]).map(s=>se(s.multiaddr)),i=e.seq;return new Ut({peerId:t,multiaddrs:n,seqNumber:i})};Ut.DOMAIN=DE;Ut.CODEC=CE;var cr={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var ic;(function(r){let e;(function(i){let s;i.codec=()=>(s==null&&(s=ne((o,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),o.key!=null&&o.key!==""&&(a.uint32(10),a.string(o.key)),o.value!=null&&o.value.byteLength>0&&(a.uint32(18),a.bytes(o.value)),c.lengthDelimited!==!1&&a.ldelim()},(o,a)=>{let c={key:"",value:new Uint8Array(0)},l=a==null?o.len:o.pos+a;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:c.key=o.string();break;case 2:c.value=o.bytes();break;default:o.skipType(u&7);break}}return c})),s),i.encode=o=>re(o,i.codec()),i.decode=o=>te(o,i.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(i){let s;i.codec=()=>(s==null&&(s=ne((o,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),o.key!=null&&o.key!==""&&(a.uint32(10),a.string(o.key)),o.value!=null&&(a.uint32(18),u0.codec().encode(o.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(o,a)=>{let c={key:""},l=a==null?o.len:o.pos+a;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:c.key=o.string();break;case 2:c.value=u0.codec().decode(o,o.uint32());break;default:o.skipType(u&7);break}}return c})),s),i.encode=o=>re(o,i.codec()),i.decode=o=>te(o,i.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=ne((i,s,o={})=>{if(o.lengthDelimited!==!1&&s.fork(),i.addresses!=null)for(let a of i.addresses)s.uint32(10),l0.codec().encode(a,s);if(i.protocols!=null)for(let a of i.protocols)s.uint32(18),s.string(a);if(i.publicKey!=null&&(s.uint32(34),s.bytes(i.publicKey)),i.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(i.peerRecordEnvelope)),i.metadata!=null&&i.metadata.size!==0)for(let[a,c]of i.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(i.tags!=null&&i.tags.size!==0)for(let[a,c]of i.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.addresses.push(l0.codec().decode(i,i.uint32()));break;case 2:o.protocols.push(i.string());break;case 4:o.publicKey=i.bytes();break;case 5:o.peerRecordEnvelope=i.bytes();break;case 6:{let l=r.Peer$metadataEntry.codec().decode(i,i.uint32());o.metadata.set(l.key,l.value);break}case 7:{let l=r.Peer$tagsEntry.codec().decode(i,i.uint32());o.tags.set(l.key,l.value);break}default:i.skipType(c&7);break}}return o})),n),r.encode=i=>re(i,r.codec()),r.decode=i=>te(i,r.codec())})(ic||(ic={}));var l0;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={multiaddr:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.multiaddr=t.bytes();break;case 2:i.isCertified=t.bool();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(l0||(l0={}));var u0;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.value=t.uint32();break;case 2:i.expiry=t.uint64();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(u0||(u0={}));async function sc(r,e){let t=ic.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=await lE(rr(t.publicKey)));let n=new Map,i=BigInt(Date.now());for(let[s,o]of t.tags.entries())o.expiry!=null&&o.expiry<i||n.set(s,o);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:o})=>({multiaddr:se(s),isCertified:o??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var nm="/peers/";function oc(r){if(!e0(r)||r.type==null)throw new w("Invalid PeerId",cr.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new ve(`${nm}${e}`)}async function PE(r,e,t){let n=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=se(i.multiaddr)),!qo(i.multiaddr))throw new w("Multiaddr was invalid",cr.ERR_INVALID_PARAMETERS);if(!await e(r,i.multiaddr))continue;let s=i.isCertified??!1,o=i.multiaddr.toString(),a=n.get(o);a!=null?i.isCertified=a.isCertified||s:n.set(o,{multiaddr:i.multiaddr,isCertified:s})}return[...n.values()].sort((i,s)=>i.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:i,multiaddr:s})=>({isCertified:i,multiaddr:s.bytes}))}async function f0(r,e,t,n){if(e==null)throw new w("Invalid PeerData",cr.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!de(e.publicKey,r.publicKey))throw new w("publicKey bytes do not match peer id publicKey bytes",cr.ERR_INVALID_PARAMETERS);let i=n.existingPeer;if(i!=null&&!r.equals(i.id))throw new w("peer id did not match existing peer id",cr.ERR_INVALID_PARAMETERS);let s=i?.addresses??[],o=new Set(i?.protocols??[]),a=i?.metadata??new Map,c=i?.tags??new Map,l=i?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(h=>({isCertified:!1,multiaddr:h}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(o=new Set(e.protocols)),e.metadata!=null){let h=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=h0(h,{validate:kE})}if(e.tags!=null){let h=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=h0(h,{validate:NE,map:LE})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(h=>({isCertified:!1,multiaddr:h}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(o=new Set([...o,...e.protocols])),e.metadata!=null){let h=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[f,d]of h)d==null?a.delete(f):a.set(f,d);a=h0([...a.entries()],{validate:kE})}if(e.tags!=null){let h=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),f=new Map(c);for(let[d,p]of h)p==null?f.delete(d):f.set(d,p);c=h0([...f.entries()],{validate:NE,map:LE})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u={addresses:await PE(r,n.addressFilter??(async()=>!0),s),protocols:[...o.values()].sort((h,f)=>h.localeCompare(f)),metadata:a,tags:c,publicKey:i?.id.publicKey??e.publicKey??r.publicKey,peerRecordEnvelope:l};return r.type!=="RSA"&&delete u.publicKey,u}function h0(r,e){let t=new Map;for(let[n,i]of r)i!=null&&e.validate(n,i);for(let[n,i]of r.sort(([s],[o])=>s.localeCompare(o)))i!=null&&t.set(n,e.map?.(n,i)??i);return t}function kE(r,e){if(typeof r!="string")throw new w("Metadata key must be a string",cr.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new w("Metadata value must be a Uint8Array",cr.ERR_INVALID_PARAMETERS)}function NE(r,e){if(typeof r!="string")throw new w("Tag name must be a string",cr.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new w("Tag value must be an integer",cr.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new w("Tag value must be between 0-100",cr.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new w("Tag ttl must be an integer",cr.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new w("Tag ttl must be between greater than 0",cr.ERR_INVALID_PARAMETERS)}}function LE(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}}var d0=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=Nl({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(oc(e))}async delete(e){if(this.peerId.equals(e))throw new w("Cannot delete self peer",cr.ERR_INVALID_PARAMETERS);await this.datastore.delete(oc(e))}async load(e){let t=await this.datastore.get(oc(e));return sc(e,t)}async save(e,t){let{existingBuf:n,existingPeer:i}=await this.#e(e),s=await f0(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,i)}async patch(e,t){let{existingBuf:n,existingPeer:i}=await this.#e(e),s=await f0(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:i});return this.#t(e,s,n,i)}async merge(e,t){let{existingBuf:n,existingPeer:i}=await this.#e(e),s=await f0(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:i});return this.#t(e,s,n,i)}async*all(){for await(let{key:e,value:t}of this.datastore.query({prefix:nm})){let n=e.toString().split("/")[2],i=Gt.decode(n),s=vt(i);s.equals(this.peerId)||(yield sc(s,t))}}async#e(e){try{let t=await this.datastore.get(oc(e)),n=await sc(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}return{}}async#t(e,t,n,i){let s=ic.encode(t);return n!=null&&de(s,n)?{peer:await sc(e,s),previous:i,updated:!1}:(await this.datastore.put(oc(e),s),{peer:await sc(e,s),previous:i,updated:!0})}};var lt=T("libp2p:peer-store"),p0=class{store;events;peerId;constructor(e,t={}){this.events=e.events,this.peerId=e.peerId,this.store=new d0(e,t)}async forEach(e){lt.trace("forEach await read lock");let t=await this.store.lock.readLock();lt.trace("forEach got read lock");try{for await(let n of this.store.all())e(n)}finally{lt.trace("forEach release read lock"),t()}}async all(){lt.trace("all await read lock");let e=await this.store.lock.readLock();lt.trace("all got read lock");try{let t=[];for await(let n of this.store.all())t.push(n);return t}finally{lt.trace("all release read lock"),e()}}async delete(e){lt.trace("delete await write lock");let t=await this.store.lock.writeLock();lt.trace("delete got write lock");try{await this.store.delete(e)}finally{lt.trace("delete release write lock"),t()}}async has(e){lt.trace("has await read lock");let t=await this.store.lock.readLock();lt.trace("has got read lock");try{return await this.store.has(e)}finally{lt.trace("has release read lock"),t()}}async get(e){lt.trace("get await read lock");let t=await this.store.lock.readLock();lt.trace("get got read lock");try{return await this.store.load(e)}finally{lt.trace("get release read lock"),t()}}async save(e,t){lt.trace("save await write lock");let n=await this.store.lock.writeLock();lt.trace("save got write lock");try{let i=await this.store.save(e,t);return this.#e(e,i),i.peer}finally{lt.trace("save release write lock"),n()}}async patch(e,t){lt.trace("patch await write lock");let n=await this.store.lock.writeLock();lt.trace("patch got write lock");try{let i=await this.store.patch(e,t);return this.#e(e,i),i.peer}finally{lt.trace("patch release write lock"),n()}}async merge(e,t){lt.trace("merge await write lock");let n=await this.store.lock.writeLock();lt.trace("merge got write lock");try{let i=await this.store.merge(e,t);return this.#e(e,i),i.peer}finally{lt.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await Wt.openAndCertify(e,Ut.DOMAIN);if(t?.equals(n.peerId)===!1)return lt("envelope peer id was not the expected peer id - expected: %p received: %p",t,n.peerId),!1;let i=Ut.createFromProtobuf(n.payload),s;try{s=await this.get(n.peerId)}catch(o){if(o.code!=="ERR_NOT_FOUND")throw o}if(s?.peerRecordEnvelope!=null){let o=await Wt.createFromProtobuf(s.peerRecordEnvelope),a=Ut.createFromProtobuf(o.payload);if(a.seqNumber>=i.seqNumber)return lt("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,i.seqNumber),!1}return await this.patch(i.peerId,{peerRecordEnvelope:e,addresses:i.multiaddrs.map(o=>({isCertified:!0,multiaddr:o}))}),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function OE(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var eU=T("libp2p:address-manager"),tU=r=>r;function im(r,e){let t=r.getPeerId();return t!=null&&oe(t).equals(e)&&(r=r.decapsulate(se(`/p2p/${e.toString()}`))),r}var m0=class{components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:i=[]}=t;this.components=e,this.listen=n.map(s=>s.toString()),this.announce=new Set(i.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??tU,this._updatePeerStoreAddresses=OE(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>se(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=>{eU.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>se(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>se(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>se(e))}addObservedAddr(e){e=im(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=im(e,this.components.peerId);let t=e.toString(),i=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),i||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=im(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,i])=>i.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>se(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};function BE(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}var sm=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>BE(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")}},rU=["metrics","connectionProtector"],nU=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function ME(r={}){let e=new sm(r);return new Proxy(e,{get(n,i,s){if(typeof i=="string"&&!nU.includes(i)){let o=e.components[i];if(o==null&&!rU.includes(i))throw new w(`${i} not set`,"ERR_SERVICE_MISSING");return o}return Reflect.get(n,i,s)},set(n,i,s){return typeof i=="string"?e.components[i]=s:Reflect.set(n,i,s),!0}})}var HE=F(UE(),1);var FE="[a-fA-F\\d:]",zs=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${FE})|(?<=${FE})(?=\\s|$))`:"",Zn="(?: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}",Ht="[a-fA-F\\d]{1,4}",g0=`
|
|
52
|
+
`});var JI=Xe(()=>{ZI();pd();ao();r5();Yu()});var s5,E5e,eA=Xe(()=>{AI();TI();DI();CI();PI();W8();kI();X8();NI();OI();HI();WI();YI();QI();JI();s5={...V8,...q8,...z8,...H8,...$8,...G8,...Y8,...Q8,...j8,...Z8},E5e={...n5,...i5}});function Wc(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}var yd=Xe(()=>{});function wd(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Wc(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}var o5=Xe(()=>{yd()});function rA(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var tA,a5,r$,bd,c5=Xe(()=>{eA();o5();tA=rA("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),a5=rA("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=wd(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),r$={utf8:tA,"utf-8":tA,hex:s5.base16,latin1:a5,ascii:a5,binary:a5,...s5},bd=r$});var nA={};Re(nA,{toString:()=>n$});function n$(r,e="utf8"){let t=bd[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}var iA=Xe(()=>{c5()});var sA={};Re(sA,{fromString:()=>i$});function i$(r,e="utf8"){let t=bd[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Wc(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}var oA=Xe(()=>{c5();yd()});var aA={};Re(aA,{concat:()=>s$});function s$(r,e){e||(e=r.reduce((i,s)=>i+s.length,0));let t=wd(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return Wc(t)}var cA=Xe(()=>{o5();yd()});var u5=D((N5e,pA)=>{"use strict";var lA=oI(),Yc=yI(),{names:Xu}=bI(),{toString:Ed}=(iA(),uh(nA)),{fromString:o$}=(oA(),uh(sA)),{concat:a$}=(cA(),uh(aA)),Qc={};for(let r in Xu){let e=r;Qc[Xu[e]]=e}Object.freeze(Qc);function c$(r){if(!(r instanceof Uint8Array))throw new Error("must be passed a Uint8Array");return Ed(r,"base16")}function l$(r){return o$(r,"base16")}function u$(r){if(!(r instanceof Uint8Array))throw new Error("must be passed a Uint8Array");return Ed(lA.encode("base58btc",r)).slice(1)}function h$(r){let e=r instanceof Uint8Array?Ed(r):r;return lA.decode("z"+e)}function uA(r){if(!(r instanceof Uint8Array))throw new Error("multihash must be a Uint8Array");if(r.length<2)throw new Error("multihash too short. must be > 2 bytes.");let e=Yc.decode(r);if(!fA(e))throw new Error(`multihash unknown function code: 0x${e.toString(16)}`);r=r.slice(Yc.decode.bytes);let t=Yc.decode(r);if(t<0)throw new Error(`multihash invalid length: ${t}`);if(r=r.slice(Yc.decode.bytes),r.length!==t)throw new Error(`multihash length inconsistent: 0x${Ed(r,"base16")}`);return{code:e,name:Qc[e],length:t,digest:r}}function f$(r,e,t){if(!r||e===void 0)throw new Error("multihash encode requires at least two args: digest, code");let n=hA(e);if(!(r instanceof Uint8Array))throw new Error("digest should be a Uint8Array");if(t==null&&(t=r.length),t&&r.length!==t)throw new Error("digest length should be equal to specified length.");let i=Yc.encode(n),s=Yc.encode(t);return a$([i,s,r],i.length+s.length+r.length)}function hA(r){let e=r;if(typeof r=="string"){if(Xu[r]===void 0)throw new Error(`Unrecognized hash function named: ${r}`);e=Xu[r]}if(typeof e!="number")throw new Error(`Hash function code should be a number. Got: ${e}`);if(Qc[e]===void 0&&!l5(e))throw new Error(`Unrecognized function code: ${e}`);return e}function l5(r){return r>0&&r<16}function fA(r){return!!(l5(r)||Qc[r])}function dA(r){uA(r)}function d$(r){return dA(r),r.subarray(0,2)}pA.exports={names:Xu,codes:Qc,toHexString:c$,fromHexString:l$,toB58String:u$,fromB58String:h$,decode:uA,encode:f$,coerceCode:hA,isAppCode:l5,validate:dA,prefix:d$,isValidCode:fA}});var DA=D(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});var g5=class{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;let t={value:e,done:!1};if(this.pullQueue.length){let n=this.pullQueue.shift();n&&n.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),this.highWaterMark!==void 0&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn(`EventIterator queue reached ${this.pushQueue.length} items`))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(let e of this.pullQueue)e.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(e){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(let t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{let t=Promise.reject(e);t.catch(()=>{}),this.pushQueue.push(t)}}remove(){Promise.resolve().then(()=>{this.removeCallback&&this.removeCallback()})}[Symbol.asyncIterator](){return{next:e=>{let t=this.pushQueue.shift();return t?(this.lowWaterMark!==void 0&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),t):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise((n,i)=>{this.pullQueue.push({resolve:n,reject:i})})},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}},Sd=class{constructor(e,{highWaterMark:t=100,lowWaterMark:n=1}={}){let i=new g5;i.highWaterMark=t,i.lowWaterMark=n,i.removeCallback=e({push:s=>i.push(s),stop:()=>i.stop(),fail:s=>i.fail(s),on:(s,o)=>{i.eventHandlers[s]=o}})||(()=>{}),this[Symbol.asyncIterator]=()=>i[Symbol.asyncIterator](),Object.freeze(this)}};Rd.EventIterator=Sd;Rd.default=Sd});var CA=D(ju=>{"use strict";Object.defineProperty(ju,"__esModule",{value:!0});var y5=DA();ju.EventIterator=y5.EventIterator;function _$(r,e,t){return new y5.EventIterator(({push:n})=>(this.addEventListener(r,n,e),()=>this.removeEventListener(r,n,e)),t)}ju.subscribe=_$;ju.default=y5.EventIterator});var b5=D((p6e,UA)=>{"use strict";var S$=typeof navigator<"u"&&navigator.product==="ReactNative";function R$(){return S$?"http://localhost":self.location?self.location.protocol+"//"+self.location.host:""}var Zu=self.URL,MA=R$(),w5=class{constructor(e="",t=MA){this.super=new Zu(e,t),this.path=this.pathname+this.search,this.auth=this.username&&this.password?this.username+":"+this.password:null,this.query=this.search&&this.search.startsWith("?")?this.search.slice(1):null}get hash(){return this.super.hash}get host(){return this.super.host}get hostname(){return this.super.hostname}get href(){return this.super.href}get origin(){return this.super.origin}get password(){return this.super.password}get pathname(){return this.super.pathname}get port(){return this.super.port}get protocol(){return this.super.protocol}get search(){return this.super.search}get searchParams(){return this.super.searchParams}get username(){return this.super.username}set hash(e){this.super.hash=e}set host(e){this.super.host=e}set hostname(e){this.super.hostname=e}set href(e){this.super.href=e}set password(e){this.super.password=e}set pathname(e){this.super.pathname=e}set port(e){this.super.port=e}set protocol(e){this.super.protocol=e}set search(e){this.super.search=e}set username(e){this.super.username=e}static createObjectURL(e){return Zu.createObjectURL(e)}static revokeObjectURL(e){Zu.revokeObjectURL(e)}toJSON(){return this.super.toJSON()}toString(){return this.super.toString()}format(){return this.toString()}};function I$(r){if(typeof r=="string")return new Zu(r).toString();if(!(r instanceof Zu)){let e=r.username&&r.password?`${r.username}:${r.password}@`:"",t=r.auth?r.auth+"@":"",n=r.port?":"+r.port:"",i=r.protocol?r.protocol+"//":"",s=r.host||"",o=r.hostname||"",a=r.search||(r.query?"?"+r.query:""),c=r.hash||"",l=r.pathname||"",u=r.path||l+a;return`${i}${e||t}${s||o+n}${u}${c}`}}UA.exports={URLWithLegacySupport:w5,URLSearchParams:self.URLSearchParams,defaultBase:MA,format:I$}});var VA=D((m6e,KA)=>{"use strict";var{URLWithLegacySupport:FA,format:A$}=b5();KA.exports=(r,e={},t={},n)=>{let i=e.protocol?e.protocol.replace(":",""):"http";i=(t[i]||n||i)+":";let s;try{s=new FA(r)}catch{s={}}let o=Object.assign({},e,{protocol:i||s.protocol,host:e.host||s.host});return new FA(r,A$(o)).toString()}});var zA=D((g6e,qA)=>{"use strict";var{URLWithLegacySupport:T$,format:D$,URLSearchParams:C$,defaultBase:P$}=b5(),k$=VA();qA.exports={URL:T$,URLSearchParams:C$,format:D$,relative:k$,defaultBase:P$}});var YA=D((x6e,WA)=>{function O$(){return!!(typeof window<"u"&&typeof window.process=="object"&&window.process.type==="renderer"||typeof process<"u"&&typeof process.versions=="object"&&process.versions.electron||typeof navigator=="object"&&typeof navigator.userAgent=="string"&&navigator.userAgent.indexOf("Electron")>=0)}WA.exports=O$});var gT=D(P5=>{"use strict";Object.defineProperty(P5,"__esModule",{value:!0});function $$(r){return typeof r.saveState<"u"&&typeof r.restoreState<"u"&&typeof r.cleanSavedState<"u"}P5.isSerializableHash=$$});var wT=D(th=>{"use strict";Object.defineProperty(th,"__esModule",{value:!0});var Mi=gT(),G$=i1(),W$=Li(),yT=function(){function r(e,t){this._finished=!1,this._inner=new e,this._outer=new e,this.blockSize=this._outer.blockSize,this.digestLength=this._outer.digestLength;var n=new Uint8Array(this.blockSize);t.length>this.blockSize?this._inner.update(t).finish(n).clean():n.set(t);for(var i=0;i<n.length;i++)n[i]^=54;this._inner.update(n);for(var i=0;i<n.length;i++)n[i]^=106;this._outer.update(n),Mi.isSerializableHash(this._inner)&&Mi.isSerializableHash(this._outer)&&(this._innerKeyedState=this._inner.saveState(),this._outerKeyedState=this._outer.saveState()),W$.wipe(n)}return r.prototype.reset=function(){if(!Mi.isSerializableHash(this._inner)||!Mi.isSerializableHash(this._outer))throw new Error("hmac: can't reset() because hash doesn't implement restoreState()");return this._inner.restoreState(this._innerKeyedState),this._outer.restoreState(this._outerKeyedState),this._finished=!1,this},r.prototype.clean=function(){Mi.isSerializableHash(this._inner)&&this._inner.cleanSavedState(this._innerKeyedState),Mi.isSerializableHash(this._outer)&&this._outer.cleanSavedState(this._outerKeyedState),this._inner.clean(),this._outer.clean()},r.prototype.update=function(e){return this._inner.update(e),this},r.prototype.finish=function(e){return this._finished?(this._outer.finish(e),this):(this._inner.finish(e),this._outer.update(e.subarray(0,this.digestLength)).finish(e),this._finished=!0,this)},r.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},r.prototype.saveState=function(){if(!Mi.isSerializableHash(this._inner))throw new Error("hmac: can't saveState() because hash doesn't implement it");return this._inner.saveState()},r.prototype.restoreState=function(e){if(!Mi.isSerializableHash(this._inner)||!Mi.isSerializableHash(this._outer))throw new Error("hmac: can't restoreState() because hash doesn't implement it");return this._inner.restoreState(e),this._outer.restoreState(this._outerKeyedState),this._finished=!1,this},r.prototype.cleanSavedState=function(e){if(!Mi.isSerializableHash(this._inner))throw new Error("hmac: can't cleanSavedState() because hash doesn't implement it");this._inner.cleanSavedState(e)},r}();th.HMAC=yT;function Y$(r,e,t){var n=new yT(r,e);n.update(t);var i=n.digest();return n.clean(),i}th.hmac=Y$;th.equal=G$.equal});var vT=D(k5=>{"use strict";Object.defineProperty(k5,"__esModule",{value:!0});var bT=wT(),ET=Li(),Q$=function(){function r(e,t,n,i){n===void 0&&(n=new Uint8Array(0)),this._counter=new Uint8Array(1),this._hash=e,this._info=i;var s=bT.hmac(this._hash,n,t);this._hmac=new bT.HMAC(e,s),this._buffer=new Uint8Array(this._hmac.digestLength),this._bufpos=this._buffer.length}return r.prototype._fillBuffer=function(){this._counter[0]++;var e=this._counter[0];if(e===0)throw new Error("hkdf: cannot expand more");this._hmac.reset(),e>1&&this._hmac.update(this._buffer),this._info&&this._hmac.update(this._info),this._hmac.update(this._counter),this._hmac.finish(this._buffer),this._bufpos=0},r.prototype.expand=function(e){for(var t=new Uint8Array(e),n=0;n<t.length;n++)this._bufpos===this._buffer.length&&this._fillBuffer(),t[n]=this._buffer[this._bufpos++];return t},r.prototype.clean=function(){this._hmac.clean(),ET.wipe(this._buffer),ET.wipe(this._counter),this._bufpos=0},r}();k5.HKDF=Q$});var _T=D(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});var Od=_u(),Ld=Li();uo.DIGEST_LENGTH=32;uo.BLOCK_SIZE=64;var xT=function(){function r(){this.digestLength=uo.DIGEST_LENGTH,this.blockSize=uo.BLOCK_SIZE,this._state=new Int32Array(8),this._temp=new Int32Array(64),this._buffer=new Uint8Array(128),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return r.prototype._initState=function(){this._state[0]=1779033703,this._state[1]=3144134277,this._state[2]=1013904242,this._state[3]=2773480762,this._state[4]=1359893119,this._state[5]=2600822924,this._state[6]=528734635,this._state[7]=1541459225},r.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},r.prototype.clean=function(){Ld.wipe(this._buffer),Ld.wipe(this._temp),this.reset()},r.prototype.update=function(e,t){if(t===void 0&&(t=e.length),this._finished)throw new Error("SHA256: can't update because hash was finished.");var n=0;if(this._bytesHashed+=t,this._bufferLength>0){for(;this._bufferLength<this.blockSize&&t>0;)this._buffer[this._bufferLength++]=e[n++],t--;this._bufferLength===this.blockSize&&(N5(this._temp,this._state,this._buffer,0,this.blockSize),this._bufferLength=0)}for(t>=this.blockSize&&(n=N5(this._temp,this._state,e,n,t),t%=this.blockSize);t>0;)this._buffer[this._bufferLength++]=e[n++],t--;return this},r.prototype.finish=function(e){if(!this._finished){var t=this._bytesHashed,n=this._bufferLength,i=t/536870912|0,s=t<<3,o=t%64<56?64:128;this._buffer[n]=128;for(var a=n+1;a<o-8;a++)this._buffer[a]=0;Od.writeUint32BE(i,this._buffer,o-8),Od.writeUint32BE(s,this._buffer,o-4),N5(this._temp,this._state,this._buffer,0,o),this._finished=!0}for(var a=0;a<this.digestLength/4;a++)Od.writeUint32BE(this._state[a],e,a*4);return this},r.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},r.prototype.saveState=function(){if(this._finished)throw new Error("SHA256: cannot save finished state");return{state:new Int32Array(this._state),buffer:this._bufferLength>0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},r.prototype.restoreState=function(e){return this._state.set(e.state),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},r.prototype.cleanSavedState=function(e){Ld.wipe(e.state),e.buffer&&Ld.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},r}();uo.SHA256=xT;var X$=new Int32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function N5(r,e,t,n,i){for(;i>=64;){for(var s=e[0],o=e[1],a=e[2],c=e[3],l=e[4],u=e[5],h=e[6],f=e[7],d=0;d<16;d++){var p=n+d*4;r[d]=Od.readUint32BE(t,p)}for(var d=16;d<64;d++){var m=r[d-2],g=(m>>>17|m<<32-17)^(m>>>19|m<<32-19)^m>>>10;m=r[d-15];var y=(m>>>7|m<<32-7)^(m>>>18|m<<32-18)^m>>>3;r[d]=(g+r[d-7]|0)+(y+r[d-16]|0)}for(var d=0;d<64;d++){var g=(((l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7))+(l&u^~l&h)|0)+(f+(X$[d]+r[d]|0)|0)|0,y=((s>>>2|s<<32-2)^(s>>>13|s<<32-13)^(s>>>22|s<<32-22))+(s&o^s&a^o&a)|0;f=h,h=u,u=l,l=c+g|0,c=a,a=o,o=s,s=g+y|0}e[0]+=s,e[1]+=o,e[2]+=a,e[3]+=c,e[4]+=l,e[5]+=u,e[6]+=h,e[7]+=f,n+=64,i-=64}return n}function j$(r){var e=new xT;e.update(r);var t=e.digest();return e.clean(),t}uo.hash=j$});var hD=D((D7e,uD)=>{function On(r,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}uD.exports=On;On.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};On.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};On.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var e=new Date().getTime();if(r&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},t),this._options.unref&&this._timer.unref(),!0};On.prototype.attempt=function(r,e){this._fn=r,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};On.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};On.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};On.prototype.start=On.prototype.try;On.prototype.errors=function(){return this._errors};On.prototype.attempts=function(){return this._attempts};On.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},e=null,t=0,n=0;n<this._errors.length;n++){var i=this._errors[n],s=i.message,o=(r[s]||0)+1;r[s]=o,o>=t&&(e=i,t=o)}return e}});var fD=D(ua=>{var yG=hD();ua.operation=function(r){var e=ua.timeouts(r);return new yG(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};ua.timeouts=function(r){if(r instanceof Array)return[].concat(r);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in r)e[t]=r[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],i=0;i<e.retries;i++)n.push(this.createTimeout(i,e));return r&&r.forever&&!n.length&&n.push(this.createTimeout(i,e)),n.sort(function(s,o){return s-o}),n};ua.createTimeout=function(r,e){var t=e.randomize?Math.random()+1:1,n=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,r));return n=Math.min(n,e.maxTimeout),n};ua.wrap=function(r,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var n in r)typeof r[n]=="function"&&t.push(n)}for(var i=0;i<t.length;i++){var s=t[i],o=r[s];r[s]=function(c){var l=ua.operation(e),u=Array.prototype.slice.call(arguments,1),h=u.pop();u.push(function(f){l.retry(f)||(f&&(arguments[0]=l.mainError()),h.apply(this,arguments))}),l.attempt(function(){c.apply(r,u)})}.bind(r,o),r[s].options=e}}});var pD=D((P7e,dD)=>{dD.exports=fD()});var CG={};Re(CG,{createHelia:()=>TG});var Wr=F(Zd(),1);var np={};Re(np,{base58btc:()=>me,base58flickr:()=>JD});function YD(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var i=0;i<r.length;i++){var s=r.charAt(i),o=s.charCodeAt(0);if(t[o]!==255)throw new TypeError(s+" is ambiguous");t[o]=i}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,g=0,y=0,b=p.length;y!==b&&p[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,I=new Uint8Array(E);y!==b;){for(var v=p[y],_=0,A=E-1;(v!==0||_<g)&&A!==-1;A--,_++)v+=256*I[A]>>>0,I[A]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=_,y++}for(var P=E-g;P!==E&&I[P]===0;)P++;for(var M=c.repeat(m);P<E;++P)M+=r.charAt(I[P]);return M}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var g=0,y=0;p[m]===c;)g++,m++;for(var b=(p.length-m)*l+1>>>0,E=new Uint8Array(b);p[m];){var I=t[p.charCodeAt(m)];if(I===255)return;for(var v=0,_=b-1;(I!==0||v<y)&&_!==-1;_--,v++)I+=a*E[_]>>>0,E[_]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");y=v,m++}if(p[m]!==" "){for(var A=b-y;A!==b&&E[A]===0;)A++;for(var P=new Uint8Array(g+(b-A)),M=g;A!==b;)P[M++]=E[A++];return P}}}function d(p){var m=f(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:d}}var QD=YD,XD=QD,a6=XD;var OG=new Uint8Array(0);var c6=(r,e)=>{if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0},Fi=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")};var l6=r=>new TextEncoder().encode(r),u6=r=>new TextDecoder().decode(r);var Jd=class{constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},ep=class{constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return f6(this,e)}},tp=class{constructor(e){this.decoders=e}or(e){return f6(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},f6=(r,e)=>new tp({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),rp=class{constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new Jd(e,t,n),this.decoder=new ep(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},pa=({name:r,prefix:e,encode:t,decode:n})=>new rp(r,e,t,n),ms=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:i}=a6(t,e);return pa({prefix:r,name:e,encode:n,decode:s=>Fi(i(s))})},jD=(r,e,t,n)=>{let i={};for(let u=0;u<e.length;++u)i[e[u]]=u;let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),a=0,c=0,l=0;for(let u=0;u<s;++u){let h=i[r[u]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|h,a+=t,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},ZD=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<<t)-1,s="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,s+=e[i&a>>o];if(o&&(s+=e[i&a<<t-o]),n)for(;s.length*t&7;)s+="=";return s},It=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>pa({prefix:e,name:r,encode(i){return ZD(i,n,t)},decode(i){return jD(i,n,t,r)}});var me=ms({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),JD=ms({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ip={};Re(ip,{base32:()=>Gt,base32hex:()=>nC,base32hexpad:()=>sC,base32hexpadupper:()=>oC,base32hexupper:()=>iC,base32pad:()=>tC,base32padupper:()=>rC,base32upper:()=>eC,base32z:()=>aC});var Gt=It({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),eC=It({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),tC=It({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),rC=It({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),nC=It({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),iC=It({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),sC=It({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),oC=It({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),aC=It({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var sp={};Re(sp,{base64:()=>Ki,base64pad:()=>cC,base64url:()=>lC,base64urlpad:()=>uC});var Ki=It({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),cC=It({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),lC=It({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),uC=It({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});Wr.default.formatters.b=r=>r==null?"undefined":me.baseEncode(r);Wr.default.formatters.t=r=>r==null?"undefined":Gt.baseEncode(r);Wr.default.formatters.m=r=>r==null?"undefined":Ki.baseEncode(r);Wr.default.formatters.p=r=>r==null?"undefined":r.toString();Wr.default.formatters.c=r=>r==null?"undefined":r.toString();Wr.default.formatters.k=r=>r==null?"undefined":r.toString();Wr.default.formatters.a=r=>r==null?"undefined":r.toString();function hC(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 T(r){let e=hC(`${r}:trace`);return Wr.default.enabled(`${r}:trace`)&&Wr.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,Wr.default)(`${r}:trace`)),Object.assign((0,Wr.default)(r),{error:(0,Wr.default)(`${r}:error`),trace:e})}var dh={};Re(dh,{abortedError:()=>bC,closeFailedError:()=>pC,deleteFailedError:()=>yC,getFailedError:()=>gC,hasFailedError:()=>wC,notFoundError:()=>op,openFailedError:()=>dC,putFailedError:()=>mC});var Vi=F(li(),1);function dC(r){return r=r??new Error("Open failed"),(0,Vi.default)(r,"ERR_OPEN_FAILED")}function pC(r){return r=r??new Error("Close failed"),(0,Vi.default)(r,"ERR_CLOSE_FAILED")}function mC(r){return r=r??new Error("Put failed"),(0,Vi.default)(r,"ERR_PUT_FAILED")}function gC(r){return r=r??new Error("Get failed"),(0,Vi.default)(r,"ERR_GET_FAILED")}function yC(r){return r=r??new Error("Delete failed"),(0,Vi.default)(r,"ERR_DELETE_FAILED")}function wC(r){return r=r??new Error("Has failed"),(0,Vi.default)(r,"ERR_HAS_FAILED")}function op(r){return r=r??new Error("Not Found"),(0,Vi.default)(r,"ERR_NOT_FOUND")}function bC(r){return r=r??new Error("Aborted"),(0,Vi.default)(r,"ERR_ABORTED")}var rl=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,block:i}of e)await this.put(n,i,t),yield n}get(e,t){return Promise.reject(new Error(".get is not implemented"))}async*getMany(e,t){for await(let n of e)yield{cid:n,block:await this.get(n,t)}}async delete(e,t){await Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var EC=y6,m6=128,vC=127,xC=~vC,_C=Math.pow(2,31);function y6(r,e,t){e=e||[],t=t||0;for(var n=t;r>=_C;)e[t++]=r&255|m6,r/=128;for(;r&xC;)e[t++]=r&255|m6,r>>>=7;return e[t]=r|0,y6.bytes=t-n+1,e}var SC=ap,RC=128,g6=127;function ap(r,n){var t=0,n=n||0,i=0,s=n,o,a=r.length;do{if(s>=a)throw ap.bytes=0,new RangeError("Could not decode varint");o=r[s++],t+=i<28?(o&g6)<<i:(o&g6)*Math.pow(2,i),i+=7}while(o>=RC);return ap.bytes=s-n,t}var IC=Math.pow(2,7),AC=Math.pow(2,14),TC=Math.pow(2,21),DC=Math.pow(2,28),CC=Math.pow(2,35),PC=Math.pow(2,42),kC=Math.pow(2,49),NC=Math.pow(2,56),LC=Math.pow(2,63),OC=function(r){return r<IC?1:r<AC?2:r<TC?3:r<DC?4:r<CC?5:r<PC?6:r<kC?7:r<NC?8:r<LC?9:10},BC={encode:EC,decode:SC,encodingLength:OC},MC=BC,nl=MC;var il=(r,e=0)=>[nl.decode(r,e),nl.decode.bytes],ma=(r,e,t=0)=>(nl.encode(r,e,t),e),ga=r=>nl.encodingLength(r);var Mn={};Re(Mn,{Digest:()=>yo,create:()=>Bn,decode:()=>ui,equals:()=>cp});var Bn=(r,e)=>{let t=e.byteLength,n=ga(r),i=n+ga(t),s=new Uint8Array(i+t);return ma(r,s,0),ma(t,s,n),s.set(e,i),new yo(r,t,e,s)},ui=r=>{let e=Fi(r),[t,n]=il(e),[i,s]=il(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new yo(t,i,o,e)},cp=(r,e)=>{if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&c6(r.bytes,t.bytes)}},yo=class{constructor(e,t,n,i){this.code=e,this.size=t,this.digest=n,this.bytes=i}};var w6=(r,e)=>{let{bytes:t,version:n}=r;switch(n){case 0:return FC(t,lp(r),e||me.encoder);default:return KC(t,lp(r),e||Gt.encoder)}};var b6=new WeakMap,lp=r=>{let e=b6.get(r);if(e==null){let t=new Map;return b6.set(r,t),t}return e},ee=class{constructor(e,t,n,i){this.code=t,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==sl)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==VC)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return ee.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Bn(e,t);return ee.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return ee.equals(this,e)}static equals(e,t){let n=t;return n&&e.code===n.code&&e.version===n.version&&cp(e.multihash,n.multihash)}toString(e){return w6(this,e)}toJSON(){return{"/":w6(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof ee)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:i,multihash:s,bytes:o}=t;return new ee(n,i,s,o||E6(n,i,s.bytes))}else if(t[qC]===!0){let{version:n,multihash:i,code:s}=t,o=ui(i);return ee.create(n,s,o)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==sl)throw new Error(`Version 0 CID must use dag-pb (code: ${sl}) block encoding`);return new ee(e,t,n,n.bytes)}case 1:{let i=E6(e,t,n.bytes);return new ee(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return ee.create(0,sl,e)}static createV1(e,t){return ee.create(1,e,t)}static decode(e){let[t,n]=ee.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=ee.inspectBytes(e),n=t.size-t.multihashSize,i=Fi(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=i.subarray(t.multihashSize-t.digestSize),o=new yo(t.multihashCode,t.digestSize,s,i);return[t.version===0?ee.createV0(o):ee.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,f]=il(e.subarray(t));return t+=f,h},i=n(),s=sl;if(i===18?(i=0,t=0):s=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=t,a=n(),c=n(),l=t+c,u=l-o;return{version:i,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,i]=UC(e,t),s=ee.decode(i);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return lp(s).set(n,e),s}},UC=(r,e)=>{switch(r[0]){case"Q":{let t=e||me;return[me.prefix,t.decode(`${me.prefix}${r}`)]}case me.prefix:{let t=e||me;return[me.prefix,t.decode(r)]}case Gt.prefix:{let t=e||Gt;return[Gt.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}},FC=(r,e,t)=>{let{prefix:n}=t;if(n!==me.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return i},KC=(r,e,t)=>{let{prefix:n}=t,i=e.get(n);if(i==null){let s=t.encode(r);return e.set(n,s),s}else return i},sl=112,VC=18,E6=(r,e,t)=>{let n=ga(r),i=n+ga(e),s=new Uint8Array(i+t.byteLength);return ma(r,s,0),ma(e,s,n),s.set(t,i),s},qC=Symbol.for("@ipld/js-cid/CID");var mh=85;var ol=class extends rl{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(Gt.encode(e.multihash.bytes),t),e}get(e){let t=this.data.get(Gt.encode(e.multihash.bytes));if(t==null)throw op();return t}has(e){return this.data.has(Gt.encode(e.multihash.bytes))}async delete(e){this.data.delete(Gt.encode(e.multihash.bytes))}async*getAll(){for(let[e,t]of this.data.entries())yield{cid:ee.createV1(mh,ui(Gt.decode(e))),block:t}}};var aW={...dh};var v6=F(li(),1);function gh(r){return r=r??new Error("Not Found"),(0,v6.default)(r,"ERR_NOT_FOUND")}var x6=(r=21)=>crypto.getRandomValues(new Uint8Array(r)).reduce((e,t)=>(t&=63,t<36?e+=t.toString(36):t<62?e+=(t-26).toString(36).toUpperCase():t>62?e+="-":e+="_",e),"");var hp={};Re(hp,{identity:()=>zC});var zC=pa({prefix:"\0",name:"identity",encode:r=>u6(r),decode:r=>l6(r)});var fp={};Re(fp,{base2:()=>HC});var HC=It({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var dp={};Re(dp,{base8:()=>$C});var $C=It({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var pp={};Re(pp,{base10:()=>GC});var GC=ms({prefix:"9",name:"base10",alphabet:"0123456789"});var mp={};Re(mp,{base16:()=>WC,base16upper:()=>YC});var WC=It({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),YC=It({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var gp={};Re(gp,{base36:()=>cl,base36upper:()=>QC});var cl=ms({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),QC=ms({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var yp={};Re(yp,{base256emoji:()=>eP});var _6=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),XC=_6.reduce((r,e,t)=>(r[t]=e,r),[]),jC=_6.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function ZC(r){return r.reduce((e,t)=>(e+=XC[t],e),"")}function JC(r){let e=[];for(let t of r){let n=jC[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var eP=pa({prefix:"\u{1F680}",name:"base256emoji",encode:ZC,decode:JC});var vp={};Re(vp,{sha256:()=>Ce,sha512:()=>Ep});var bp=({name:r,code:e,encode:t})=>new wp(r,e,t),wp=class{constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?Bn(this.code,t):t.then(n=>Bn(this.code,n))}else throw Error("Unknown type, must be binary type")}};var R6=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),Ce=bp({name:"sha2-256",code:18,encode:R6("SHA-256")}),Ep=bp({name:"sha2-512",code:19,encode:R6("SHA-512")});var xp={};Re(xp,{identity:()=>hi});var I6=0,tP="identity",A6=Fi,rP=r=>Bn(I6,A6(r)),hi={code:I6,name:tP,encode:A6,digest:rP};var xW=new TextEncoder,_W=new TextDecoder;var wn={...hp,...fp,...dp,...pp,...mp,...ip,...gp,...np,...sp,...yp},TW={...vp,...xp};function qi(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function zi(r=0){return globalThis.Buffer?.alloc!=null?qi(globalThis.Buffer.alloc(r)):new Uint8Array(r)}function Ir(r=0){return globalThis.Buffer?.allocUnsafe!=null?qi(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function D6(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var T6=D6("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),_p=D6("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Ir(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),iP={utf8:T6,"utf-8":T6,hex:wn.base16,latin1:_p,ascii:_p,binary:_p,...wn},yh=iP;function K(r,e="utf8"){let t=yh[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?qi(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}function O(r,e="utf8"){let t=yh[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}var Hi="/",C6=new TextEncoder().encode(Hi),wh=C6[0],ve=class{_buf;constructor(e,t){if(typeof e=="string")this._buf=K(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]!==wh)throw new Error("Invalid key")}toString(e="utf8"){return O(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new ve(e.join(Hi))}static random(){return new ve(x6().replace(/-/g,""))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new ve(e):typeof e.uint8Array=="function"?new ve(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=C6),this._buf[0]!==wh){let e=new Uint8Array(this._buf.byteLength+1);e.fill(wh,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===wh;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let i=0;i<t.length;i++){if(n.length<i+1)return!1;let s=t[i],o=n[i];if(s<o)return!0;if(s>o)return!1}return t.length<n.length}reverse(){return ve.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Hi).slice(1)}type(){return sP(this.baseNamespace())}name(){return oP(this.baseNamespace())}instance(e){return new ve(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Hi)||(e+=Hi),e+=this.type(),new ve(e)}parent(){let e=this.list();return e.length===1?new ve(Hi):new ve(e.slice(0,-1).join(Hi))}child(e){return this.toString()===Hi?e:e.toString()===Hi?this:new ve(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 ve.withNamespaces([...this.namespaces(),...aP(e.map(t=>t.namespaces()))])}};function sP(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function oP(r){let e=r.split(":");return e[e.length-1]}function aP(r){return[].concat(...r)}var P6="SHARDING";function lP(r){return r[Symbol.asyncIterator]!=null}function uP(r){if(lP(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Yr=uP;function hP(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:i=>{n.push(i)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var ya=hP;function fP(r){return r[Symbol.asyncIterator]!=null}function dP(r,e){if(fP(r))return async function*(){for await(let a of r)await e(a)&&(yield a)}();let t=ya(r),{value:n,done:i}=t.next();if(i===!0)return function*(){}();let s=e(n);if(typeof s.then=="function")return async function*(){await s&&(yield n);for await(let a of t)await e(a)&&(yield a)}();let o=e;return function*(){s===!0&&(yield n);for(let a of t)o(a)&&(yield a)}()}var Or=dP;function pP(r){return r[Symbol.asyncIterator]!=null}function mP(r){if(pP(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var Sp=mP;function gP(r){return r[Symbol.asyncIterator]!=null}function yP(r,e){return gP(r)?async function*(){yield*(await Sp(r)).sort(e)}():function*(){yield*Sp(r).sort(e)}()}var bh=yP;function wP(r){return r[Symbol.asyncIterator]!=null}function bP(r,e){return wP(r)?async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}():function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}}()}var gs=bP;var $i=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:i}of e)await this.put(n,i,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,i){e.push({key:n,value:i})},delete(n){t.push(n)},commit:async n=>{await Yr(this.putMany(e,n)),e=[],await Yr(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let i=e.prefix;n=Or(n,s=>s.key.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,s)=>Or(i,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,s)=>bh(i,s),n)),e.offset!=null){let i=0,s=e.offset;n=Or(n,()=>i++>=s)}return e.limit!=null&&(n=gs(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let i=e.prefix;n=Or(n,s=>s.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,s)=>Or(i,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,s)=>bh(i,s),n)),e.offset!=null){let i=e.offset,s=0;n=Or(n,()=>s++>=i)}return e.limit!=null&&(n=gs(n,e.limit)),n}};var wo=class extends $i{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){let t=this.data.get(e.toString());if(t==null)throw gh();return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,t]of this.data.entries())yield{key:new ve(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new ve(e)}};function EP(r){return r[Symbol.asyncIterator]!=null}function vP(r,e){if(EP(r))return async function*(){for await(let a of r)yield e(a)}();let t=ya(r),{value:n,done:i}=t.next();if(i===!0)return function*(){}();let s=e(n);if(typeof s.then=="function")return async function*(){yield await s;for await(let a of t)yield e(a)}();let o=e;return function*(){yield s;for(let a of t)yield o(a)}()}var Un=vP;var Eh=class{constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},wa=class{constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Eh(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Eh(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};function et(r={}){return N6(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function k6(r={}){return N6(t=>{let n,i=[];for(;!t.isEmpty()&&(n=t.shift(),n!=null);){if(n.error!=null)throw n.error;n.done===!1&&i.push(n.value)}return n==null?{done:!0}:{done:n.done===!0,value:i}},r)}function N6(r,e){e=e??{};let t=e.onEnd,n=new wa,i,s,o,a=async()=>n.isEmpty()?o?{done:!0}:await new Promise((m,g)=>{s=y=>{s=null,n.push(y);try{m(r(n))}catch(b){g(b)}return i}}):r(n),c=m=>s!=null?s(m):(n.push(m),i),l=m=>(n=new wa,s!=null?s({error:m}):(n.push({error:m}),i)),u=m=>{if(o)return i;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:m})},h=m=>o?i:(o=!0,m!=null?l(m):c({done:!0})),f=()=>(n=new wa,h(),{done:!0}),d=m=>(h(m),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:a,return:f,throw:d,push:u,end:h,get readableLength(){return n.size}},t==null)return i;let p=i;return i={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(m){return p.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return p.return(),t!=null&&(t(),t=void 0),{done:!0}},push:u,end(m){return p.end(m),t!=null&&(t(m),t=void 0),i},get readableLength(){return p.readableLength}},i}function xP(r){return r[Symbol.asyncIterator]!=null}function _P(...r){let e=[];for(let t of r)xP(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=et({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let i of n)t.push(i)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var Qt=_P;function be(r,...e){if(r==null)throw new Error("Empty pipeline");if(Rp(r)){let n=r;r=()=>n.source}else if(O6(r)||L6(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&Rp(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)Rp(t[n])&&(t[n]=RP(t[n]));return SP(...t)}var SP=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},L6=r=>r?.[Symbol.asyncIterator]!=null,O6=r=>r?.[Symbol.iterator]!=null,Rp=r=>r==null?!1:r.sink!=null&&r.source!=null,RP=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=et({objectMode:!0});t.then(()=>{n.end()},o=>{n.end(o)});let i,s=r.source;if(L6(s))i=async function*(){yield*s,n.end()};else if(O6(s))i=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Qt(n,i())}return r.source};var CY=new ve(P6);var qY=T("datastore:core:tiered");function st(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let i=e.signal;return i.clear=n,i}function TP(r){return r[Symbol.asyncIterator]!=null}function DP(r,e){if(TP(r))return async function*(){for await(let a of r)await e(a),yield a}();let t=ya(r),{value:n,done:i}=t.next();if(i===!0)return function*(){}();if(typeof e(n)?.then=="function")return async function*(){yield n;for await(let a of t)await e(a),yield a}();let o=e;return function*(){yield n;for(let a of t)o(a),yield a}()}var ll=DP;var Ip=class extends Map{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 fi(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Ip({name:e,metrics:t}):n=new Map,n}var vh=class extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.code=vh.code,this.type=vh.type}},Qr=vh;wr(Qr,"code","ABORT_ERR"),wr(Qr,"type","aborted");var w=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}};var Hg=F(X6(),1);function de(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var bo=class{_refCounter;cid;priority;wantType;constructor(e,t,n){this._refCounter=1,this.cid=e,this.priority=t??1,this.wantType=n}inc(){this._refCounter+=1}dec(){this._refCounter=Math.max(0,this._refCounter-1)}hasRefs(){return this._refCounter>0}get[Symbol.toStringTag](){return`WantlistEntry <key: ${this.cid.toString(me)}, priority: ${this.priority}, refs: ${this._refCounter}>`}equals(e){return this._refCounter===e._refCounter&&this.cid.equals(e.cid)&&this.priority===e.priority&&this.wantType===e.wantType}};var ys=class{entry;cancel;sendDontHave;constructor(e,t,n,i,s){this.entry=new bo(e,t,n),this.cancel=!!i,this.sendDontHave=!!s}get cid(){return this.entry.cid}set cid(e){this.entry.cid=e}get priority(){return this.entry.priority}set priority(e){this.entry.priority=e}get wantType(){return this.entry.wantType}set wantType(e){this.entry.wantType=e}get[Symbol.toStringTag](){return`BitswapMessageEntry ${this.cid.toString(me)} <cancel: ${this.cancel}, priority: ${this.priority}>`}equals(e){return this.cancel===e.cancel&&this.sendDontHave===e.sendDontHave&&this.wantType===e.wantType&&this.entry.equals(e.entry)}};var bn=(r,e)=>{let t=["bitswap"];return e!=null&&t.push(e),r!=null&&t.push(`${r.toString().slice(0,8)}`),T(t.join(":"))};var xh=(r,e)=>{if(r.size!==e.size)return!1;for(let[t,n]of r){let i=e.get(t);if(i===void 0||n instanceof Uint8Array&&i instanceof Uint8Array&&!de(n,i)||n instanceof ys&&i instanceof ys&&!n.equals(i))return!1}return!0};var ul=F(Eo(),1);function rk(r){let e=new Uint8Array(r.reduce((n,i)=>n+ul.default.encodingLength(i),0)),t=0;for(let n of r)e=ul.encode(n,e,t),t+=ul.default.encodingLength(n);return e}var og=rk;var Qp=F(Vp(),1),Kg=F(kg(),1),Vg=F(xo(),1),Xp=F(Yp(),1),qg=F(Fg(),1);function hk(){Vg.default._configure(),Qp.default._configure(Kg.default),Xp.default._configure(qg.default)}hk();var zg=["uint64","int64","sint64","fixed64","sfixed64"];function fk(r){for(let e of zg){if(r[e]==null)continue;let t=r[e];r[e]=function(){return BigInt(t.call(this).toString())}}return r}function jp(r){return fk(new Qp.default(r))}function dk(r){for(let e of zg){if(r[e]==null)continue;let t=r[e];r[e]=function(n){return t.call(this,n.toString())}}return r}function Zp(){return dk(Xp.default.create())}function te(r,e){let t=jp(r instanceof Uint8Array?r:r.subarray());return e.decode(t)}function re(r,e){let t=Zp();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Ea;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Ea||(Ea={}));function Ah(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function At(r){function e(i){if(r[i.toString()]==null)throw new Error("Invalid enum value");return r[i]}let t=function(s,o){let a=e(s);o.int32(a)},n=function(s){let o=s.int32();return e(o)};return Ah("enum",Ea.VARINT,t,n)}function ne(r,e){return Ah("message",Ea.LENGTH_DELIMITED,r,e)}var Br;(function(r){let e;(function(a){let c;(function(f){f.Block="Block",f.Have="Have"})(c=a.WantType||(a.WantType={}));let l;(function(f){f[f.Block=0]="Block",f[f.Have=1]="Have"})(l||(l={})),function(f){f.codec=()=>At(l)}(c=a.WantType||(a.WantType={}));let u;(function(f){let d;f.codec=()=>(d==null&&(d=ne((p,m,g={})=>{g.lengthDelimited!==!1&&m.fork(),p.block!=null&&p.block.byteLength>0&&(m.uint32(10),m.bytes(p.block)),p.priority!=null&&p.priority!==0&&(m.uint32(16),m.int32(p.priority)),p.cancel!=null&&p.cancel!==!1&&(m.uint32(24),m.bool(p.cancel)),p.wantType!=null&&l[p.wantType]!==0&&(m.uint32(32),r.Wantlist.WantType.codec().encode(p.wantType,m)),p.sendDontHave!=null&&p.sendDontHave!==!1&&(m.uint32(40),m.bool(p.sendDontHave)),g.lengthDelimited!==!1&&m.ldelim()},(p,m)=>{let g={block:new Uint8Array(0),priority:0,cancel:!1,wantType:c.Block,sendDontHave:!1},y=m==null?p.len:p.pos+m;for(;p.pos<y;){let b=p.uint32();switch(b>>>3){case 1:g.block=p.bytes();break;case 2:g.priority=p.int32();break;case 3:g.cancel=p.bool();break;case 4:g.wantType=r.Wantlist.WantType.codec().decode(p);break;case 5:g.sendDontHave=p.bool();break;default:p.skipType(b&7);break}}return g})),d),f.encode=p=>re(p,f.codec()),f.decode=p=>te(p,f.codec())})(u=a.Entry||(a.Entry={}));let h;a.codec=()=>(h==null&&(h=ne((f,d,p={})=>{if(p.lengthDelimited!==!1&&d.fork(),f.entries!=null)for(let m of f.entries)d.uint32(10),r.Wantlist.Entry.codec().encode(m,d);f.full!=null&&f.full!==!1&&(d.uint32(16),d.bool(f.full)),p.lengthDelimited!==!1&&d.ldelim()},(f,d)=>{let p={entries:[],full:!1},m=d==null?f.len:f.pos+d;for(;f.pos<m;){let g=f.uint32();switch(g>>>3){case 1:p.entries.push(r.Wantlist.Entry.codec().decode(f,f.uint32()));break;case 2:p.full=f.bool();break;default:f.skipType(g&7);break}}return p})),h),a.encode=f=>re(f,a.codec()),a.decode=f=>te(f,a.codec())})(e=r.Wantlist||(r.Wantlist={}));let t;(function(a){let c;a.codec=()=>(c==null&&(c=ne((l,u,h={})=>{h.lengthDelimited!==!1&&u.fork(),l.prefix!=null&&l.prefix.byteLength>0&&(u.uint32(10),u.bytes(l.prefix)),l.data!=null&&l.data.byteLength>0&&(u.uint32(18),u.bytes(l.data)),h.lengthDelimited!==!1&&u.ldelim()},(l,u)=>{let h={prefix:new Uint8Array(0),data:new Uint8Array(0)},f=u==null?l.len:l.pos+u;for(;l.pos<f;){let d=l.uint32();switch(d>>>3){case 1:h.prefix=l.bytes();break;case 2:h.data=l.bytes();break;default:l.skipType(d&7);break}}return h})),c),a.encode=l=>re(l,a.codec()),a.decode=l=>te(l,a.codec())})(t=r.Block||(r.Block={}));let n;(function(a){a.Have="Have",a.DontHave="DontHave"})(n=r.BlockPresenceType||(r.BlockPresenceType={}));let i;(function(a){a[a.Have=0]="Have",a[a.DontHave=1]="DontHave"})(i||(i={})),function(a){a.codec=()=>At(i)}(n=r.BlockPresenceType||(r.BlockPresenceType={}));let s;(function(a){let c;a.codec=()=>(c==null&&(c=ne((l,u,h={})=>{h.lengthDelimited!==!1&&u.fork(),l.cid!=null&&l.cid.byteLength>0&&(u.uint32(10),u.bytes(l.cid)),l.type!=null&&i[l.type]!==0&&(u.uint32(16),r.BlockPresenceType.codec().encode(l.type,u)),h.lengthDelimited!==!1&&u.ldelim()},(l,u)=>{let h={cid:new Uint8Array(0),type:n.Have},f=u==null?l.len:l.pos+u;for(;l.pos<f;){let d=l.uint32();switch(d>>>3){case 1:h.cid=l.bytes();break;case 2:h.type=r.BlockPresenceType.codec().decode(l);break;default:l.skipType(d&7);break}}return h})),c),a.encode=l=>re(l,a.codec()),a.decode=l=>te(l,a.codec())})(s=r.BlockPresence||(r.BlockPresence={}));let o;r.codec=()=>(o==null&&(o=ne((a,c,l={})=>{if(l.lengthDelimited!==!1&&c.fork(),a.wantlist!=null&&(c.uint32(10),r.Wantlist.codec().encode(a.wantlist,c)),a.blocks!=null)for(let u of a.blocks)c.uint32(18),c.bytes(u);if(a.payload!=null)for(let u of a.payload)c.uint32(26),r.Block.codec().encode(u,c);if(a.blockPresences!=null)for(let u of a.blockPresences)c.uint32(34),r.BlockPresence.codec().encode(u,c);a.pendingBytes!=null&&a.pendingBytes!==0&&(c.uint32(40),c.int32(a.pendingBytes)),l.lengthDelimited!==!1&&c.ldelim()},(a,c)=>{let l={blocks:[],payload:[],blockPresences:[],pendingBytes:0},u=c==null?a.len:a.pos+c;for(;a.pos<u;){let h=a.uint32();switch(h>>>3){case 1:l.wantlist=r.Wantlist.codec().decode(a,a.uint32());break;case 2:l.blocks.push(a.bytes());break;case 3:l.payload.push(r.Block.codec().decode(a,a.uint32()));break;case 4:l.blockPresences.push(r.BlockPresence.codec().decode(a,a.uint32()));break;case 5:l.pendingBytes=a.int32();break;default:a.skipType(h&7);break}}return l})),o),r.encode=a=>re(a,r.codec()),r.decode=a=>te(a,r.codec())})(Br||(Br={}));var mi=class{full;wantlist;blocks;blockPresences;pendingBytes;constructor(e){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}get empty(){return this.blocks.size===0&&this.wantlist.size===0&&this.blockPresences.size===0}addEntry(e,t,n,i,s){n==null&&(n=mi.WantType.Block);let o=e.toString(me),a=this.wantlist.get(o);a!=null?(a.wantType===n&&(a.priority=t),i===!0&&(a.cancel=!!i),s===!0&&(a.sendDontHave=!!s),n===mi.WantType.Block&&a.wantType===mi.WantType.Have&&(a.wantType=n)):this.wantlist.set(o,new ys(e,t,n,i,s))}addBlock(e,t){let n=e.toString(me);this.blocks.set(n,t)}addHave(e){let t=e.toString(me);this.blockPresences.has(t)||this.blockPresences.set(t,mi.BlockPresenceType.Have)}addDontHave(e){let t=e.toString(me);this.blockPresences.has(t)||this.blockPresences.set(t,mi.BlockPresenceType.DontHave)}cancel(e){let t=e.toString(me);this.wantlist.delete(t),this.addEntry(e,0,mi.WantType.Block,!0,!1)}setPendingBytes(e){this.pendingBytes=e}serializeToBitswap100(){return Br.encode({wantlist:{entries:Array.from(this.wantlist.values()).map(e=>({block:e.cid.bytes,priority:Number(e.priority),cancel:!!e.cancel,wantType:Br.Wantlist.WantType.Block,sendDontHave:!1})),full:!!this.full},blocks:Array.from(this.blocks.values())})}serializeToBitswap110(){let e={wantlist:{entries:Array.from(this.wantlist.values()).map(t=>({block:t.cid.bytes,priority:Number(t.priority),wantType:t.wantType,cancel:!!t.cancel,sendDontHave:!!t.sendDontHave})),full:!!this.full},blockPresences:[],payload:[],pendingBytes:this.pendingBytes,blocks:[]};for(let[t,n]of this.blocks.entries()){let i=ee.parse(t),s=i.version,o=i.code,a=i.multihash.code,c=i.multihash.digest.length,l=og([s,o,a,c]);e.payload.push({prefix:l,data:n})}for(let[t,n]of this.blockPresences)e.blockPresences.push({cid:ee.parse(t).bytes,type:n});return this.pendingBytes>0&&(e.pendingBytes=this.pendingBytes),Br.encode(e)}equals(e){return!(this.full!==e.full||this.pendingBytes!==e.pendingBytes||!xh(this.wantlist,e.wantlist)||!xh(this.blocks,e.blocks)||!xh(this.blockPresences,e.blockPresences))}get[Symbol.toStringTag](){let e=Array.from(this.wantlist.keys()),t=Array.from(this.blocks.keys());return`BitswapMessage <full: ${this.full}, list: ${e}, blocks: ${t}>`}},Lt=mi;wr(Lt,"Entry",ys),wr(Lt,"WantType",{Block:Br.Wantlist.WantType.Block,Have:Br.Wantlist.WantType.Have}),wr(Lt,"BlockPresenceType",{Have:Br.BlockPresenceType.Have,DontHave:Br.BlockPresenceType.DontHave}),wr(Lt,"deserialize",async(e,t)=>{let n=Br.decode(e),i=n.wantlist?.full===!0,s=new mi(i);return n.wantlist?.entries.forEach(o=>{if(o.block==null)return;let a=ee.decode(o.block);s.addEntry(a,o.priority??0,o.wantType,!!o.cancel,!!o.sendDontHave)}),n.blockPresences.forEach(o=>{if(o.cid==null)return;let a=ee.decode(o.cid);o.type===mi.BlockPresenceType.Have?s.addHave(a):s.addDontHave(a)}),n.blocks.length>0?(await Promise.all(n.blocks.map(async o=>{let a=await Ce.digest(o),c=ee.createV0(a);s.addBlock(c,o)})),s):(n.payload.length>0&&(await Promise.all(n.payload.map(async o=>{if(o.prefix==null||o.data==null)return;let a=(0,Hg.default)(o.prefix),c=a[0],l=a[1],u=a[2],h=u===Ce.code?Ce:await t?.getHasher(u);if(h==null)throw new w("Unknown hash algorithm","ERR_UNKNOWN_HASH_ALG");let f=await h.digest(o.data),d=ee.create(c,l,f);s.addBlock(d,o.data)})),s.setPendingBytes(n.pendingBytes)),s)}),wr(Lt,"blockPresenceSize",e=>e.bytes.length+1);var $g={Block:Br.Wantlist.WantType.Block,Have:Br.Wantlist.WantType.Have},pk=(r,e)=>Array.prototype.slice.call(e,0).sort((t,n)=>{let i=r(t),s=r(n);return i<s?-1:i>s?1:0}),Gi=class{set;_stats;constructor(e,t){this.set=t!=null?fi({name:"ipfs_bitswap_wantlist",metrics:t.metrics}):new Map,this._stats=e}get length(){return this.set.size}add(e,t,n){let i=e.toString(me),s=this.set.get(i);s!=null?(s.inc(),s.priority=t,s.wantType===$g.Have&&n===$g.Block&&(s.wantType=n)):(this.set.set(i,new bo(e,t,n)),this._stats!=null&&this._stats.push(void 0,"wantListSize",1))}remove(e){let t=e.toString(me),n=this.set.get(t);n!=null&&(n.dec(),!n.hasRefs()&&(this.set.delete(t),this._stats!=null&&this._stats.push(void 0,"wantListSize",-1)))}removeForce(e){this.set.has(e)&&this.set.delete(e)}forEach(e){this.set.forEach(e)}entries(){return this.set.entries()}sortedEntries(){return new Map(pk(e=>e[1].key,Array.from(this.set.entries())))}contains(e){let t=e.toString(me);return this.set.has(t)}get(e){let t=e.toString(me);return this.set.get(t)}};wr(Gi,"Entry",bo);var Th=class{partner;wantlist;exchangeCount;accounting;lastExchange;constructor(e){this.partner=e,this.wantlist=new Gi,this.exchangeCount=0,this.accounting={bytesSent:0,bytesRecv:0}}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.accounting.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.accounting.bytesRecv+=e}wants(e,t,n){this.wantlist.add(e,t,n)}cancelWant(e){this.wantlist.remove(e)}wantlistContains(e){return this.wantlist.get(e)}debtRatio(){return this.accounting.bytesSent/(this.accounting.bytesRecv+1)}};var dl=class extends Map{_cmp;_keys;constructor(e,t){super(),this._cmp=t??this._defaultSort,this._keys=[];for(let[n,i]of e??[])this.set(n,i)}update(e){if(e<0||e>=this._keys.length)return;let t=this._keys[e];this._keys.splice(e,1);let n=this._find(t);this._keys.splice(n,0,t)}set(e,t){if(this.has(e)){let i=this.indexOf(e);this._keys.splice(i,1)}super.set(e,t);let n=this._find(e);return this._keys.splice(n,0,e),this}clear(){super.clear(),this._keys=[]}delete(e){if(!this.has(e))return!1;let t=this.indexOf(e);return this._keys.splice(t,1),super.delete(e)}indexOf(e){if(!this.has(e))return-1;let t=this._find(e);if(this._keys[t]===e)return t;for(let n=1;n<this._keys.length;n++){if(this._keys[t+n]===e)return t+n;if(this._keys[t-n]===e)return t-n}return-1}_find(e){let t=0,n=this._keys.length;for(;t<n;){let i=t+n>>>1,s=this._kCmp(this._keys[i],e);if(s<0)t=i+1;else if(s>0)n=i;else return i}return t}*keys(){for(let e of this._keys)yield e}*values(){for(let e of this._keys)yield this.get(e)}*entries(){for(let e of this._keys)yield[e,this.get(e)]}*[Symbol.iterator](){yield*this.entries()}forEach(e,t=this){if(e!=null)for(let n of this._keys){let i=this.get(n);if(i==null)throw new Error("Value cannot be undefined");e.apply(t,[[n,i]])}}_defaultSort(e,t){return e[0]<t[0]?-1:t[0]<e[0]?1:0}_kCmp(e,t){return this._cmp([e,this.get(e)],[t,this.get(t)])}};var mk={hasNewInfo(){return!1},merge(){}},Dh=class{_taskMerger;_byPeer;constructor(e=mk){this._taskMerger=e,this._byPeer=new dl([],Ch.compare)}pushTasks(e,t){let n=this._byPeer.get(e.toString());n==null&&(n=new Ch(e,this._taskMerger)),n.pushTasks(t),this._byPeer.set(e.toString(),n)}popTasks(e){let t=this._head();if(t===void 0)return{tasks:[],pendingSize:0};let{tasks:n,pendingSize:i}=t.popTasks(e);if(n.length===0)return{tasks:n,pendingSize:i};let s=t.peerId;return t.isIdle()?this._byPeer.delete(s.toString()):this._byPeer.update(0),{peerId:s,tasks:n,pendingSize:i}}_head(){if(this._byPeer.size!==0)for(let[,e]of this._byPeer)return e}remove(e,t){this._byPeer.get(t.toString())?.remove(e)}tasksDone(e,t){let n=this._byPeer.get(e.toString());if(n==null)return;let i=this._byPeer.indexOf(e.toString());for(let s of t)n.taskDone(s);this._byPeer.update(i)}},Ch=class{peerId;_taskMerger;_activeTotalSize;_pending;_active;constructor(e,t){this.peerId=e,this._taskMerger=t,this._activeTotalSize=0,this._pending=new Jp,this._active=new Set}pushTasks(e){for(let t of e)this._pushTask(t)}_pushTask(e){if(!this._taskHasMoreInfoThanActiveTasks(e))return;let t=this._pending.get(e.topic);if(t!=null){e.priority>t.priority&&this._pending.updatePriority(e.topic,e.priority),this._taskMerger.merge(e,t);return}this._pending.add(e)}_taskHasMoreInfoThanActiveTasks(e){let t=[];for(let n of this._active)n.topic===e.topic&&t.push(n);return t.length===0?!0:this._taskMerger.hasNewInfo(e,t)}popTasks(e){let t=0,n=[],i=this._pending.tasks();for(let s=0;s<i.length&&t<e;s++){let o=i[s];n.push(o),t+=o.size,this._pending.delete(o.topic),this._activeTotalSize+=o.size,this._active.add(o)}return{tasks:n,pendingSize:this._pending.totalSize}}taskDone(e){this._active.has(e)&&(this._activeTotalSize-=e.size,this._active.delete(e))}remove(e){this._pending.delete(e)}isIdle(){return this._pending.length===0&&this._active.size===0}static compare(e,t){return e[1]._pending.length===0?1:t[1]._pending.length===0?-1:e[1]._activeTotalSize===t[1]._activeTotalSize?t[1]._pending.length-e[1]._pending.length:e[1]._activeTotalSize-t[1]._activeTotalSize}},Jp=class{_tasks;constructor(){this._tasks=new dl([],this._compare)}get length(){return this._tasks.size}get totalSize(){return[...this._tasks.values()].reduce((e,t)=>e+t.task.size,0)}get(e){return this._tasks?.get(e)?.task}add(e){this._tasks.set(e.topic,{created:Date.now(),task:e})}delete(e){this._tasks.delete(e)}tasks(){return[...this._tasks.values()].map(e=>e.task)}updatePriority(e,t){let n=this._tasks.get(e);if(n==null)return;let i=this._tasks.indexOf(e);n.task.priority=t,this._tasks.update(i)}_compare(e,t){return e[1].task.priority===t[1].task.priority?e[1].created-t[1].created:t[1].task.priority-e[1].task.priority}};var Gg={hasNewInfo(r,e){let t=!1,n=!1;for(let i of e)i.data.haveBlock&&(t=!0),i.data.isWantBlock&&(n=!0);return!!(!n&&r.data.isWantBlock||!t&&r.data.haveBlock)},merge(r,e){let t=r.data,n=e.data;!n.haveBlock&&t.haveBlock&&(n.haveBlock=t.haveBlock,n.blockSize=t.blockSize),!n.isWantBlock&&t.isWantBlock&&(n.isWantBlock=!0,(!n.haveBlock||t.haveBlock)&&(n.haveBlock=t.haveBlock,e.size=r.size)),n.isWantBlock&&n.haveBlock&&(e.size=n.blockSize)}};var Wg=Lt.WantType,gk=16*1024,yk=1024,Ph=class{_log;blockstore;network;_stats;_opts;ledgerMap;_running;_requestQueue;constructor(e,t,n,i,s,o={}){this._log=bn(e,"engine"),this.blockstore=t,this.network=n,this._stats=i,this._opts=this._processOpts(o),this.ledgerMap=fi({name:"ipfs_bitswap_ledger_map",metrics:s.metrics}),this._running=!1,this._requestQueue=new Dh(Gg)}_processOpts(e){return{maxSizeReplaceHasWithBlock:yk,targetMessageSize:gk,...e}}_scheduleProcessTasks(){setTimeout(()=>{this._processTasks().catch(e=>{this._log.error("error processing stats",e)})})}async _processTasks(){if(!this._running)return;let{peerId:e,tasks:t,pendingSize:n}=this._requestQueue.popTasks(this._opts.targetMessageSize);if(t.length===0)return;let i=new Lt(!1);i.setPendingBytes(n);let s=[],o=new Map;for(let c of t){let l=ee.parse(c.topic);c.data.haveBlock?c.data.isWantBlock?(s.push(l),o.set(c.topic,c.data)):i.addHave(l):i.addDontHave(l)}let a=await this._getBlocks(s);for(let[c,l]of o){let u=ee.parse(c),h=a.get(c);h!=null?i.addBlock(u,h):l.sendDontHave&&i.addDontHave(u)}if(i.empty){e!=null&&this._requestQueue.tasksDone(e,t),this._scheduleProcessTasks();return}try{e!=null&&await this.network.sendMessage(e,i);for(let[c,l]of a.entries())e!=null&&this.messageSent(e,ee.parse(c),l)}catch(c){this._log.error(c)}e!=null&&this._requestQueue.tasksDone(e,t),this._scheduleProcessTasks()}wantlistForPeer(e){let t=e.toString(),n=this.ledgerMap.get(t);return n!=null?n.wantlist.sortedEntries():new Map}ledgerForPeer(e){let t=e.toString(),n=this.ledgerMap.get(t);if(n!=null)return{peer:n.partner,value:n.debtRatio(),sent:n.accounting.bytesSent,recv:n.accounting.bytesRecv,exchanged:n.exchangeCount}}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.partner)}receivedBlocks(e){if(e.length!==0){for(let t of this.ledgerMap.values())for(let{cid:n,block:i}of e){let s=t.wantlistContains(n);if(s==null)continue;let o=i.length,a=this._sendAsBlock(s.wantType,o),c=o;a||(c=Lt.blockPresenceSize(s.cid)),this._requestQueue.pushTasks(t.partner,[{topic:s.cid.toString(me),priority:s.priority,size:c,data:{blockSize:o,isWantBlock:a,haveBlock:!0,sendDontHave:!1}}])}this._scheduleProcessTasks()}}async messageReceived(e,t){let n=this._findOrCreate(e);if(t.empty)return;if(t.full&&(n.wantlist=new Gi),this._updateBlockAccounting(t.blocks,n),t.wantlist.size===0){this._scheduleProcessTasks();return}let i=[],s=[];t.wantlist.forEach(o=>{o.cancel?(n.cancelWant(o.cid),i.push(o.cid)):(n.wants(o.cid,o.priority,o.wantType),s.push(o))}),this._cancelWants(e,i),await this._addWants(e,s),this._scheduleProcessTasks()}_cancelWants(e,t){for(let n of t)this._requestQueue.remove(n.toString(me),e)}async _addWants(e,t){let n=await this._getBlockSizes(t.map(s=>s.cid)),i=[];for(let s of t){let o=s.cid.toString(me),a=n.get(o);if(a==null)s.sendDontHave&&i.push({topic:o,priority:s.priority,size:Lt.blockPresenceSize(s.cid),data:{isWantBlock:s.wantType===Wg.Block,blockSize:0,haveBlock:!1,sendDontHave:s.sendDontHave}});else{let c=this._sendAsBlock(s.wantType,a),l=a;c||(l=Lt.blockPresenceSize(s.cid)),i.push({topic:o,priority:s.priority,size:l,data:{isWantBlock:c,blockSize:a,haveBlock:!0,sendDontHave:s.sendDontHave}})}this._requestQueue.pushTasks(e,i)}}_sendAsBlock(e,t){return e===Wg.Block||t<=this._opts.maxSizeReplaceHasWithBlock}async _getBlockSizes(e){let t=await this._getBlocks(e);return new Map([...t].map(([n,i])=>[n,i.length]))}async _getBlocks(e){let t=new Map;return await Promise.all(e.map(async n=>{try{let i=await this.blockstore.get(n);t.set(n.toString(me),i)}catch(i){i.code!=="ERR_NOT_FOUND"&&this._log.error("failed to query blockstore for %s: %s",n,i)}})),t}_updateBlockAccounting(e,t){for(let n of e.values())this._log("got block (%s bytes)",n.length),t.receivedBytes(n.length)}messageSent(e,t,n){let i=this._findOrCreate(e);i.sentBytes(n.length),i.wantlist.remove(t)}numBytesSentTo(e){return this._findOrCreate(e).accounting.bytesSent}numBytesReceivedFrom(e){return this._findOrCreate(e).accounting.bytesRecv}peerDisconnected(e){this.ledgerMap.delete(e.toString())}_findOrCreate(e){let t=e.toString(),n=this.ledgerMap.get(t);if(n!=null)return n;let i=new Th(e);return this.ledgerMap.set(t,i),this._stats!=null&&this._stats.push(t,"peerCount",1),i}start(){this._running=!0}stop(){this._running=!1}};var kh=Symbol.for("@libp2p/topology");function Yg(r){return r!=null&&!!r[kh]}var Qg=()=>{},e2=class{constructor(e){this.min=e.min??0,this.max=e.max??1/0,this.peers=new Set,this.onConnect=e.onConnect??Qg,this.onDisconnect=e.onDisconnect??Qg}get[Symbol.toStringTag](){return kh.toString()}get[kh](){return!0}async setRegistrar(e){this.registrar=e}disconnect(e){this.onDisconnect(e)}};function Es(r){return new e2(r)}var pl=class extends Error{constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Xg(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function gt(r,e,t){let n=t??{},i=Xg(r);async function*s(){let o,a=()=>{o?.()};for(e.addEventListener("abort",a);;){let c;try{if(e.aborted){let{abortMessage:u,abortCode:h}=n;throw new pl(u,h)}let l=new Promise((u,h)=>{o=()=>{let{abortMessage:f,abortCode:d}=n;h(new pl(f,d))}});c=await Promise.race([l,i.next()]),o=null}catch(l){e.removeEventListener("abort",a);let u=l.type==="aborted"&&e.aborted;if(u&&n.onAbort!=null&&n.onAbort(r),typeof i.return=="function")try{let h=i.return();h instanceof Promise&&h.catch(f=>{n.onReturnError!=null&&n.onReturnError(f)})}catch(h){n.onReturnError!=null&&n.onReturnError(h)}if(u&&n.returnOnAbort===!0)return;throw l}if(c.done===!0)break;yield c.value}e.removeEventListener("abort",a)}return s()}function wk(r,e,t){return n=>r(gt(n,e,t))}function br(r,e,t){return{sink:wk(r.sink,e,{...t,onAbort:void 0}),source:gt(r.source,e,t)}}function le(r,e){e==null&&(e=r.reduce((i,s)=>i+s.length,0));let t=Ir(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return qi(t)}var Zg=Symbol.for("@achingbrain/uint8arraylist");function jg(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let i=t+n.byteLength;if(e<i)return{buf:n,index:e-t};t=i}throw new RangeError("index is out of bounds")}function Nh(r){return!!r?.[Zg]}var j=class{constructor(...e){Object.defineProperty(this,Zg,{value:!0}),this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Nh(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Nh(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=jg(this.bufs,e);return t.buf[t.index]}set(e,t){let n=jg(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Nh(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:i}=this._subList(e,t);return le(n,i)}subarray(e,t){let{bufs:n,length:i}=this._subList(e,t);return n.length===1?n[0]:le(n,i)}sublist(e,t){let{bufs:n,length:i}=this._subList(e,t),s=new j;return s.length=i,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],i=0;for(let s=0;s<this.bufs.length;s++){let o=this.bufs[s],a=i,c=a+o.byteLength;if(i=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(o);break}let h=e-a;n.push(o.subarray(h,h+(t-e)));break}if(l){if(e===0){n.push(o);continue}n.push(o.subarray(e-a));continue}if(u){if(t===c){n.push(o);break}n.push(o.subarray(0,t-a));break}n.push(o)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Nh(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let s=256,o=new Int32Array(s);for(let h=0;h<s;h++)o[h]=-1;for(let h=0;h<i;h++)o[n[h]]=h;let a=o,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let h=t;h<=c;h+=u){u=0;for(let f=l;f>=0;f--){let d=this.get(h+f);if(n[f]!==d){u=Math.max(1,f-a[d]);break}}if(u===0)return h}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Ir(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let i=zi(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,t,n),this.write(i,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let i=zi(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,t,n),this.write(i,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let i=zi(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,t,n),this.write(i,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Ir(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let i=zi(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,t,n),this.write(i,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let i=zi(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,t,n),this.write(i,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let i=zi(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,t,n),this.write(i,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let i=zi(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,t,n),this.write(i,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let i=zi(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,t,n),this.write(i,e)}equals(e){if(e==null||!(e instanceof j)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!de(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new j;return n.bufs=e,t==null&&(t=e.reduce((i,s)=>i+s.byteLength,0)),n.length=t,n}};function Lh(r){return r instanceof Uint8Array?{get(e){return r[e]},set(e,t){r[e]=t}}:{get(e){return r.get(e)},set(e,t){r.set(e,t)}}}var Jg=4294967296,Xr=class{constructor(e=0,t=0){this.hi=e,this.lo=t}toBigInt(e){if(e===!0)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toNumber(e){return Number(this.toBigInt(e))}zzDecode(){let e=-(this.lo&1),t=((this.lo>>>1|this.hi<<31)^e)>>>0,n=(this.hi>>>1^e)>>>0;return new Xr(n,t)}zzEncode(){let e=this.hi>>31,t=((this.hi<<1|this.lo>>>31)^e)>>>0,n=(this.lo<<1^e)>>>0;return new Xr(t,n)}toBytes(e,t=0){let n=Lh(e);for(;this.hi>0;)n.set(t++,this.lo&127|128),this.lo=(this.lo>>>7|this.hi<<25)>>>0,this.hi>>>=7;for(;this.lo>127;)n.set(t++,this.lo&127|128),this.lo=this.lo>>>7;n.set(t++,this.lo)}static fromBigInt(e){if(e===0n)return new Xr;let t=e<0;t&&(e=-e);let n=Number(e>>32n)|0,i=Number(e-(BigInt(n)<<32n))|0;return t&&(n=~n>>>0,i=~i>>>0,++i>Jg&&(i=0,++n>Jg&&(n=0))),new Xr(n,i)}static fromNumber(e){if(e===0)return new Xr;let t=e<0;t&&(e=-e);let n=e>>>0,i=(e-n)/4294967296>>>0;return t&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new Xr(i,n)}static fromBytes(e,t=0){let n=Lh(e),i=new Xr,s=0;if(e.length-t>4){for(;s<4;++s)if(i.lo=(i.lo|(n.get(t)&127)<<s*7)>>>0,n.get(t++)<128)return i;if(i.lo=(i.lo|(n.get(t)&127)<<28)>>>0,i.hi=(i.hi|(n.get(t)&127)>>4)>>>0,n.get(t++)<128)return i;s=0}else for(;s<4;++s){if(t>=e.length)throw RangeError(`index out of range: ${t} > ${e.length}`);if(i.lo=(i.lo|(n.get(t)&127)<<s*7)>>>0,n.get(t++)<128)return i}if(e.length-t>4){for(;s<5;++s)if(i.hi=(i.hi|(n.get(t)&127)<<s*7+3)>>>0,n.get(t++)<128)return i}else if(t<e.byteLength)for(;s<5;++s){if(t>=e.length)throw RangeError(`index out of range: ${t} > ${e.length}`);if(i.hi=(i.hi|(n.get(t)&127)<<s*7+3)>>>0,n.get(t++)<128)return i}throw RangeError("invalid varint encoding")}};var bk=Math.pow(2,7),Ek=Math.pow(2,14),vk=Math.pow(2,21),xk=Math.pow(2,28),_k=Math.pow(2,35),Sk=Math.pow(2,42),Rk=Math.pow(2,49),Ik=Math.pow(2,56),Ak=Math.pow(2,63),ot={encodingLength(r){return r<bk?1:r<Ek?2:r<vk?3:r<xk?4:r<_k?5:r<Sk?6:r<Rk?7:r<Ik?8:r<Ak?9:10},encode(r,e,t=0){if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return e==null&&(e=Ir(ot.encodingLength(r))),Xr.fromNumber(r).toBytes(e,t),e},decode(r,e=0){return Xr.fromBytes(r,e).toNumber(!0)}};function Oh(r){return r[Symbol.asyncIterator]!=null}var Bh=r=>{let e=ot.encodingLength(r),t=Ir(e);return ot.encode(r,t),Bh.bytes=e,t};Bh.bytes=0;function yt(r,e){e=e??{};let t=e.lengthEncoder??Bh;function*n(i){let s=t(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return Oh(r)?async function*(){for await(let i of r)yield*n(i)}():function*(){for(let i of r)yield*n(i)}()}yt.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Bh;return new j(t(r.byteLength),r)};var va=F(li(),1);var Tk=8,Dk=1024*1024*4,So;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(So||(So={}));var t2=r=>{let e=ot.decode(r);return t2.bytes=ot.encodingLength(e),e};t2.bytes=0;function Tt(r,e){let t=new j,n=So.LENGTH,i=-1,s=e?.lengthDecoder??t2,o=e?.maxLengthLength??Tk,a=e?.maxDataLength??Dk;function*c(){for(;t.byteLength>0;){if(n===So.LENGTH)try{if(i=s(t),i<0)throw(0,va.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,va.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(i),n=So.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>o)throw(0,va.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw l}if(n===So.DATA){if(t.byteLength<i)break;let l=t.sublist(0,i);t.consume(i),e?.onData!=null&&e.onData(l),yield l,n=So.LENGTH}}}return Oh(r)?async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw(0,va.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw(0,va.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Tt.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:s,value:o}=await r.next(t);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}}();return Tt(n,{...e??{},onLength:s=>{t=s}})};var je=class extends Event{constructor(e,t){super(e),this.detail=t}};var uy=F(oy(),1);var ay=Math.pow(2,31)-1,cy=1e3,ly=1;var i2="/ipfs/bitswap/1.0.0",s2="/ipfs/bitswap/1.1.0",o2="/ipfs/bitswap/1.2.0",Nk=1024,Lk=1024,Ok=3e4,Uh=class{_log;_libp2p;_bitswap;_protocols;_stats;_running;_hashLoader;_maxInboundStreams;_maxOutboundStreams;_incomingStreamTimeout;_registrarIds;constructor(e,t,n,i={}){this._log=bn(e.peerId,"network"),this._libp2p=e,this._bitswap=t,this._protocols=[i2],i.b100Only!==!0&&(this._protocols.unshift(s2),this._protocols.unshift(o2)),this._stats=n,this._running=!1,this._onPeerConnect=this._onPeerConnect.bind(this),this._onPeerDisconnect=this._onPeerDisconnect.bind(this),this._onConnection=this._onConnection.bind(this),this._hashLoader=i.hashLoader??{async getHasher(){throw new Error("Not implemented")}},this._maxInboundStreams=i.maxInboundStreams??Nk,this._maxOutboundStreams=i.maxOutboundStreams??Lk,this._incomingStreamTimeout=i.incomingStreamTimeout??Ok}async start(){this._running=!0,await this._libp2p.handle(this._protocols,this._onConnection,{maxInboundStreams:this._maxInboundStreams,maxOutboundStreams:this._maxOutboundStreams});let e=Es({onConnect:this._onPeerConnect,onDisconnect:this._onPeerDisconnect});this._registrarIds=[];for(let t of this._protocols)this._registrarIds.push(await this._libp2p.register(t,e));this._libp2p.getConnections().forEach(t=>{this._onPeerConnect(t.remotePeer)})}async stop(){if(this._running=!1,await this._libp2p.unhandle(this._protocols),this._registrarIds!=null){for(let e of this._registrarIds)this._libp2p.unregister(e);this._registrarIds=[]}}_onConnection(e){if(!this._running)return;let{stream:t,connection:n}=e,i=new uy.TimeoutController(this._incomingStreamTimeout);Promise.resolve().then(async()=>{this._log("incoming new bitswap %s connection from %p",t.stat.protocol,n.remotePeer),await be(gt(t.source,i.signal),s=>Tt(s),async s=>{for await(let o of s){try{let a=await Lt.deserialize(o.subarray(),this._hashLoader);await this._bitswap._receiveMessage(n.remotePeer,a)}catch(a){this._bitswap._receiveError(a);break}i.reset()}})}).catch(s=>{this._log(s),t.abort(s)}).finally(()=>{i.clear(),t.close()})}_onPeerConnect(e){this._bitswap._onPeerConnected(e)}_onPeerDisconnect(e){this._bitswap._onPeerDisconnected(e)}findProviders(e,t={}){return t.onProgress?.(new je("bitswap:network:find-providers",e)),this._libp2p.contentRouting.findProviders(e,t)}async findAndConnect(e,t){await Yr(gs(Un(this.findProviders(e,t),async n=>this.connectTo(n.id,t).catch(i=>{this._log.error(i)})),3)).catch(n=>{this._log.error(n)})}async provide(e,t={}){t.onProgress?.(new je("bitswap:network:provide",e)),await this._libp2p.contentRouting.provide(e,t)}async sendMessage(e,t,n={}){if(!this._running)throw new Error("network isn't running");let i=e.toString();this._log("sendMessage to %s",i,t),n.onProgress?.(new je("bitswap:network:send-wantlist",e)),await this._writeMessage(e,t,n),this._updateSentStats(e,t.blocks)}async connectTo(e,t={}){if(!this._running)throw new Error("network isn't running");return t.onProgress?.(new je("bitswap:network:dial",e)),this._libp2p.dial(e,t)}_updateSentStats(e,t){let n=e.toString();if(this._stats!=null){for(let i of t.values())this._stats.push(n,"dataSent",i.length);this._stats.push(n,"blocksSent",t.size)}}async _writeMessage(e,t,n={}){let i=await this._libp2p.dialProtocol(e,[o2,s2,i2]);try{let s;switch(i.stat.protocol){case i2:s=t.serializeToBitswap100();break;case s2:case o2:s=t.serializeToBitswap110();break;default:throw new Error(`Unknown protocol: ${i.stat.protocol}`)}await be([s],o=>yt(o),i)}catch(s){n.onProgress?.(new je("bitswap:network:send-wantlist:error",{peer:e,error:s})),this._log(s)}finally{i.close()}}};var _y=F(jr(),1);var vy=r=>`unwant:${O(r.multihash.bytes,"base64")}`,xy=r=>`block:${O(r.multihash.bytes,"base64")}`,Vh=class extends _y.EventEmitter{_log;constructor(e){super(),this.setMaxListeners(cy),this._log=bn(e,"notif")}hasBlock(e,t){let n=xy(e);this._log(n),this.emit(n,t)}async wantBlock(e,t={}){if(e==null)throw new Error("Not a valid cid");let n=xy(e),i=vy(e);return this._log(`wantBlock:${e}`),new Promise((s,o)=>{let a=()=>{this.removeListener(n,c),t.onProgress?.(new je("bitswap:want-block:unwant",e)),o(new Error(`Block for ${e} unwanted`))},c=l=>{this.removeListener(i,a),t.onProgress?.(new je("bitswap:want-block:block",e)),s(l)};this.once(i,a),this.once(n,c),t.signal?.addEventListener("abort",()=>{this.removeListener(n,c),this.removeListener(i,a),o(new Error(`Want for ${e} aborted`))})})}unwantBlock(e){let t=vy(e);this._log(t),this.emit(t)}};var Dy=F(jr(),1);var Ay=F(jr(),1),c2=F(Iy(),1),gl=class extends Ay.EventEmitter{_options;_queue;_stats;_frequencyLastTime;_frequencyAccumulators;_movingAverages;_enabled;_timeout;constructor(e,t){super(),this._options=t,this._queue=[],this._stats={},this._frequencyLastTime=Date.now(),this._frequencyAccumulators={},this._movingAverages={},this._update=this._update.bind(this),e.forEach(n=>{this._stats[n]=BigInt(0),this._movingAverages[n]={},this._options.movingAverageIntervals.forEach(i=>{(this._movingAverages[n][i]=(0,c2.default)(i)).push(this._frequencyLastTime,0)})}),this._enabled=this._options.enabled}enable(){this._enabled=!0}disable(){this._enabled=!1}stop(){this._timeout!=null&&clearTimeout(this._timeout)}get snapshot(){return Object.assign({},this._stats)}get movingAverages(){return Object.assign({},this._movingAverages)}push(e,t){this._enabled&&(this._queue.push([e,t,Date.now()]),this._resetComputeTimeout())}_resetComputeTimeout(){this._timeout!=null&&clearTimeout(this._timeout),this._timeout=setTimeout(this._update,this._nextTimeout())}_nextTimeout(){let e=this._queue.length/this._options.computeThrottleMaxQueueSize;return Math.max(this._options.computeThrottleTimeout*(1-e),0)}_update(){if(this._timeout=void 0,this._queue.length>0){let e;for(;this._queue.length>0;){let t=e=this._queue.shift();t!=null&&this._applyOp(t)}e!=null&&this._updateFrequency(e[2]),this.emit("update",this._stats)}}_updateFrequency(e){let t=e-this._frequencyLastTime;t>0&&Object.keys(this._stats).forEach(n=>{this._updateFrequencyFor(n,t,e)}),this._frequencyLastTime=e}_updateFrequencyFor(e,t,n){let i=this._frequencyAccumulators[e]??0;this._frequencyAccumulators[e]=0;let s=i/t*1e3,o=this._movingAverages[e];o==null&&(o=this._movingAverages[e]={}),this._options.movingAverageIntervals.forEach(a=>{let c=o[a];c==null&&(c=o[a]=(0,c2.default)(a)),c.push(n,s)})}_applyOp(e){let t=e[0],n=e[1];if(typeof n!="number")throw new Error(`invalid increment number: ${n}`);Object.prototype.hasOwnProperty.call(this._stats,t)||(this._stats[t]=BigInt(0)),this._stats[t]=BigInt(this._stats[t])+BigInt(n),this._frequencyAccumulators[t]==null&&(this._frequencyAccumulators[t]=0),this._frequencyAccumulators[t]+=n}};var Ty={enabled:!1,computeThrottleTimeout:1e3,computeThrottleMaxQueueSize:1e3,movingAverageIntervals:[60*1e3,5*60*1e3,15*60*1e3]},qh=class extends Dy.EventEmitter{_initialCounters;_options;_enabled;_global;_peers;constructor(e,t=[],n=Ty){super();let i=Object.assign({},Ty,n);if(typeof i.computeThrottleTimeout!="number")throw new Error("need computeThrottleTimeout");if(typeof i.computeThrottleMaxQueueSize!="number")throw new Error("need computeThrottleMaxQueueSize");this._initialCounters=t,this._options=i,this._enabled=this._options.enabled,this._global=new gl(t,i),this._global.on("update",s=>this.emit("update",s)),this._peers=fi({name:"ipfs_bitswap_stats_peers",metrics:e.metrics})}enable(){this._enabled=!0,this._options.enabled=!0,this._global.enable()}disable(){this._enabled=!1,this._options.enabled=!1,this._global.disable()}stop(){this._enabled=!1,this._global.stop();for(let e of this._peers)e[1].stop()}get snapshot(){return this._global.snapshot}get movingAverages(){return this._global.movingAverages}forPeer(e){let t=e.toString();return this._peers.get(t)}push(e,t,n){if(this._enabled&&(this._global.push(t,n),e!=null)){let i=this._peers.get(e);i==null&&(i=new gl(this._initialCounters,this._options),this._peers.set(e,i)),i.push(t,n)}}disconnected(e){let t=e.toString(),n=this._peers.get(t);n!=null&&(n.stop(),this._peers.delete(t))}};var Cy=zk;function zk(r,e,t){var n=null,i=null,s=function(){n&&(clearTimeout(n),i=null,n=null)},o=function(){var c=i;s(),c&&c()},a=function(){if(!e)return r.apply(this,arguments);var c=this,l=arguments,u=t&&!n;if(s(),i=function(){r.apply(c,l)},n=setTimeout(function(){if(n=null,!u){var h=i;return i=null,h()}},e),u)return i()};return a.cancel=s,a.flush=o,a}var zh=class{peerId;refcnt;network;_entries;_log;constructor(e,t,n){this.peerId=t,this.network=n,this.refcnt=1,this._entries=[],this._log=bn(e,"msgqueue"),this.sendEntries=Cy(this.sendEntries.bind(this),ly)}addMessage(e,t={}){e.empty||this.send(e,t)}addEntries(e,t={}){this._entries=this._entries.concat(e),this.sendEntries(t)}sendEntries(e={}){if(this._entries.length===0)return;let t=new Lt(!1);this._entries.forEach(n=>{n.cancel===!0?t.cancel(n.cid):t.addEntry(n.cid,n.priority)}),this._entries=[],this.addMessage(t,e)}async send(e,t={}){try{await this.network.connectTo(this.peerId,t)}catch(n){this._log.error("cant connect to peer %p: %s",this.peerId,n.message);return}this._log("sending message to peer %p",this.peerId),this.network.sendMessage(this.peerId,e,t).catch(n=>{this._log.error("send error",n)})}};var Hh=class{peers;wantlist;network;_peerId;_log;constructor(e,t,n,i){this.peers=fi({name:"ipfs_bitswap_want_manager_peers",metrics:i.metrics}),this.wantlist=new Gi(n,i),this.network=t,this._peerId=e,this._log=bn(e,"want")}_addEntries(e,t,n,i={}){let s=e.map((o,a)=>new Lt.Entry(o,ay-a,Lt.WantType.Block,t));s.forEach(o=>{o.cancel?n===!0?this.wantlist.removeForce(o.cid.toString(me)):this.wantlist.remove(o.cid):(this._log("adding to wantlist"),this.wantlist.add(o.cid,o.priority))});for(let o of this.peers.values())o.addEntries(s,i)}_startPeerHandler(e){let t=this.peers.get(e.toString());if(t!=null){t.refcnt++;return}t=new zh(this._peerId,e,this.network);let n=new Lt(!0);for(let i of this.wantlist.entries())n.addEntry(i[1].cid,i[1].priority);return t.addMessage(n),this.peers.set(e.toString(),t),t}_stopPeerHandler(e){let t=this.peers.get(e.toString());t!=null&&(t.refcnt--,!(t.refcnt>0)&&this.peers.delete(e.toString()))}wantBlocks(e,t={}){this._addEntries(e,!1,!1,t),t.signal?.addEventListener("abort",()=>{this.cancelWants(e)})}unwantBlocks(e){this._log("unwant blocks: %s",e.length),this._addEntries(e,!0,!0)}cancelWants(e){this._log("cancel wants: %s",e.length),this._addEntries(e,!0)}connectedPeers(){return Array.from(this.peers.keys())}connected(e){this._startPeerHandler(e)}disconnected(e){this._stopPeerHandler(e)}start(){}stop(){this.peers.forEach(e=>{this.disconnected(e.peerId)})}};var Hk={async getHasher(){throw new Error("Not implemented")}},$k={maxInboundStreams:1024,maxOutboundStreams:1024,incomingStreamTimeout:3e4,hashLoader:Hk,statsEnabled:!1,statsComputeThrottleTimeout:1e3,statsComputeThrottleMaxQueueSize:1e3},Gk=["blocksReceived","dataReceived","dupBlksReceived","dupDataReceived","blocksSent","dataSent","providesBufferLength","wantListLength","peerCount"],$h=class{_libp2p;_log;stats;network;blockstore;engine;wm;notifications;started;constructor(e,t,n={}){this._libp2p=e,this._log=bn(this.peerId),n=Object.assign({},$k,n),this.stats=new qh(e,Gk,{enabled:n.statsEnabled,computeThrottleTimeout:n.statsComputeThrottleTimeout,computeThrottleMaxQueueSize:n.statsComputeThrottleMaxQueueSize}),this.network=new Uh(e,this,this.stats,{hashLoader:n.hashLoader,maxInboundStreams:n.maxInboundStreams,maxOutboundStreams:n.maxOutboundStreams,incomingStreamTimeout:n.incomingStreamTimeout}),this.blockstore=t,this.engine=new Ph(this.peerId,t,this.network,this.stats,e),this.wm=new Hh(this.peerId,this.network,this.stats,e),this.notifications=new Vh(this.peerId),this.started=!1}isStarted(){return this.started}get peerId(){return this._libp2p.peerId}async _receiveMessage(e,t){try{await this.engine.messageReceived(e,t)}catch{this._log("failed to receive message",t)}if(t.blocks.size===0)return;let n=[];for(let[i,s]of t.blocks.entries()){let o=ee.parse(i);n.push({wasWanted:this.wm.wantlist.contains(o),cid:o,data:s})}this.wm.cancelWants(n.filter(({wasWanted:i})=>i).map(({cid:i})=>i)),await Promise.all(n.map(async({cid:i,wasWanted:s,data:o})=>{await this._handleReceivedBlock(e,i,o,s)}))}async _handleReceivedBlock(e,t,n,i){this._log("received block");let s=await this.blockstore.has(t);this._updateReceiveCounters(e.toString(),t,n,s),i&&await this.put(t,n)}_updateReceiveCounters(e,t,n,i){this.stats.push(e,"blocksReceived",1),this.stats.push(e,"dataReceived",n.length),i&&(this.stats.push(e,"dupBlksReceived",1),this.stats.push(e,"dupDataReceived",n.length))}_receiveError(e){this._log.error("ReceiveError",e)}_onPeerConnected(e){this.wm.connected(e)}_onPeerDisconnected(e){this.wm.disconnected(e),this.engine.peerDisconnected(e),this.stats.disconnected(e)}enableStats(){this.stats.enable()}disableStats(){this.stats.disable()}wantlistForPeer(e,t){return this.engine.wantlistForPeer(e)}ledgerForPeer(e){return this.engine.ledgerForPeer(e)}async want(e,t={}){let n=async(c,l)=>(this.wm.wantBlocks([c],l),this.notifications.wantBlock(c,l)),i=!1,s=async(c,l)=>{try{return await this.blockstore.get(c,l)}catch(u){if(u.code!=="ERR_NOT_FOUND")throw u;return i||(i=!0,this.network.findAndConnect(c,l).catch(h=>{this._log.error(h)})),await n(c,l)}},o=new AbortController,a=st([o.signal,t.signal]);try{return await Promise.race([this.notifications.wantBlock(e,{...t,signal:a}),s(e,{...t,signal:a})])}finally{o.abort(),a.clear()}}unwant(e){let t=Array.isArray(e)?e:[e];this.wm.unwantBlocks(t),t.forEach(n=>{this.notifications.unwantBlock(n)})}cancelWants(e){this.wm.cancelWants(Array.isArray(e)?e:[e])}async put(e,t,n){await this.blockstore.put(e,t),this.notify(e,t)}async*putMany(e,t){yield*this.blockstore.putMany(ll(e,({cid:n,block:i})=>{this.notify(n,i)}),t)}notify(e,t,n={}){this.notifications.hasBlock(e,t),this.engine.receivedBlocks([{cid:e,block:t}]),this.network.provide(e,n).catch(i=>{this._log.error("Failed to provide: %s",i.message)})}getWantlist(){return this.wm.wantlist.entries()}get peers(){return this.engine.peers()}async start(){this.wm.start(),await this.network.start(),this.engine.start(),this.started=!0}async stop(){this.stats.stop(),this.wm.stop(),await this.network.stop(),this.engine.stop(),this.started=!1}};var Py=(r,e,t={})=>new $h(r,e,t);var Wk=["string","number","bigint","symbol"],Yk=["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 ky(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(Wk.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(Qk(r))return"Buffer";let t=Xk(r);return t||"Object"}function Qk(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function Xk(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(Yk.includes(e))return e}var S=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}};S.uint=new S(0,"uint",!0);S.negint=new S(1,"negint",!0);S.bytes=new S(2,"bytes",!0);S.string=new S(3,"string",!0);S.array=new S(4,"array",!1);S.map=new S(5,"map",!1);S.tag=new S(6,"tag",!1);S.float=new S(7,"float",!0);S.false=new S(7,"false",!0);S.true=new S(7,"true",!0);S.null=new S(7,"null",!0);S.undefined=new S(7,"undefined",!0);S.break=new S(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 _a=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",jk=new TextDecoder,Zk=new TextEncoder;function Gh(r){return _a&&globalThis.Buffer.isBuffer(r)}function yl(r){return r instanceof Uint8Array?Gh(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var By=_a?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):Ly(r,e,t):(r,e,t)=>t-e>64?jk.decode(r.subarray(e,t)):Ly(r,e,t),Wh=_a?r=>r.length>64?globalThis.Buffer.from(r):Ny(r):r=>r.length>64?Zk.encode(r):Ny(r),gi=r=>Uint8Array.from(r),Sa=_a?(r,e,t)=>Gh(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),My=_a?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),yl(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let i of r)n+i.length>t.length&&(i=i.subarray(0,t.length-n)),t.set(i,n),n+=i.length;return t},Uy=_a?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function Fy(r,e){if(Gh(r)&&Gh(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 Ny(r,e=1/0){let t,n=r.length,i=null,s=[];for(let o=0;o<n;++o){if(t=r.charCodeAt(o),t>55295&&t<57344){if(!i){if(t>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=t;continue}if(t<56320){(e-=3)>-1&&s.push(239,191,189),i=t;continue}t=(i-55296<<10|t-56320)+65536}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,t<128){if((e-=1)<0)break;s.push(t)}else if(t<2048){if((e-=2)<0)break;s.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;s.push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;s.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code point")}return s}function Ly(r,e,t){let n=[];for(;e<t;){let i=r[e],s=null,o=i>239?4:i>223?3:i>191?2:1;if(e+o<=t){let a,c,l,u;switch(o){case 1:i<128&&(s=i);break;case 2:a=r[e+1],(a&192)===128&&(u=(i&31)<<6|a&63,u>127&&(s=u));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(u=(i&15)<<12|(a&63)<<6|c&63,u>2047&&(u<55296||u>57343)&&(s=u));break;case 4:a=r[e+1],c=r[e+2],l=r[e+3],(a&192)===128&&(c&192)===128&&(l&192)===128&&(u=(i&15)<<18|(a&63)<<12|(c&63)<<6|l&63,u>65535&&u<1114112&&(s=u))}}s===null?(s=65533,o=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|s&1023),n.push(s),e+=o}return l2(n)}var Oy=4096;function l2(r){let e=r.length;if(e<=Oy)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Oy));return t}var Jk=256,wl=class{constructor(e=Jk){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 i=t.length-(this.maxCursor-this.cursor)-1;t.set(e,i)}else{if(t){let i=t.length-(this.maxCursor-this.cursor)-1;i<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,i),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=Uy(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=Sa(n,0,this.cursor)}else t=My(this.chunks,this.cursor);return e&&this.reset(),t}};var Y="CBOR decode error:",Ra="CBOR encode error:",bl=[];bl[23]=1;bl[24]=2;bl[25]=3;bl[26]=5;bl[27]=9;function Wi(r,e,t){if(r.length-e<t)throw new Error(`${Y} not enough data for type`)}var jt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Zr(r,e,t){Wi(r,e,1);let n=r[e];if(t.strict===!0&&n<jt[0])throw new Error(`${Y} integer encoded in more bytes than necessary (strict decode)`);return n}function Jr(r,e,t){Wi(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<jt[1])throw new Error(`${Y} integer encoded in more bytes than necessary (strict decode)`);return n}function en(r,e,t){Wi(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<jt[2])throw new Error(`${Y} integer encoded in more bytes than necessary (strict decode)`);return n}function tn(r,e,t){Wi(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],i=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],s=(BigInt(n)<<BigInt(32))+BigInt(i);if(t.strict===!0&&s<jt[3])throw new Error(`${Y} integer encoded in more bytes than necessary (strict decode)`);if(s<=Number.MAX_SAFE_INTEGER)return Number(s);if(t.allowBigInt===!0)return s;throw new Error(`${Y} integers outside of the safe integer range are not supported`)}function Ky(r,e,t,n){return new U(S.uint,Zr(r,e+1,n),2)}function Vy(r,e,t,n){return new U(S.uint,Jr(r,e+1,n),3)}function qy(r,e,t,n){return new U(S.uint,en(r,e+1,n),5)}function zy(r,e,t,n){return new U(S.uint,tn(r,e+1,n),9)}function vn(r,e){return ar(r,0,e.value)}function ar(r,e,t){if(t<jt[0]){let n=Number(t);r.push([e|n])}else if(t<jt[1]){let n=Number(t);r.push([e|24,n])}else if(t<jt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<jt[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<jt[4]){let i=[e|27,0,0,0,0,0,0,0],s=Number(n&BigInt(4294967295)),o=Number(n>>BigInt(32)&BigInt(4294967295));i[8]=s&255,s=s>>8,i[7]=s&255,s=s>>8,i[6]=s&255,s=s>>8,i[5]=s&255,i[4]=o&255,o=o>>8,i[3]=o&255,o=o>>8,i[2]=o&255,o=o>>8,i[1]=o&255,r.push(i)}else throw new Error(`${Y} encountered BigInt larger than allowable range`)}}vn.encodedSize=function(e){return ar.encodedSize(e.value)};ar.encodedSize=function(e){return e<jt[0]?1:e<jt[1]?2:e<jt[2]?3:e<jt[3]?5:9};vn.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function Hy(r,e,t,n){return new U(S.negint,-1-Zr(r,e+1,n),2)}function $y(r,e,t,n){return new U(S.negint,-1-Jr(r,e+1,n),3)}function Gy(r,e,t,n){return new U(S.negint,-1-en(r,e+1,n),5)}var u2=BigInt(-1),Wy=BigInt(1);function Yy(r,e,t,n){let i=tn(r,e+1,n);if(typeof i!="bigint"){let s=-1-i;if(s>=Number.MIN_SAFE_INTEGER)return new U(S.negint,s,9)}if(n.allowBigInt!==!0)throw new Error(`${Y} integers outside of the safe integer range are not supported`);return new U(S.negint,u2-BigInt(i),9)}function Yh(r,e){let t=e.value,n=typeof t=="bigint"?t*u2-Wy:t*-1-1;ar(r,e.type.majorEncoded,n)}Yh.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*u2-Wy:t*-1-1;return n<jt[0]?1:n<jt[1]?2:n<jt[2]?3:n<jt[3]?5:9};Yh.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function El(r,e,t,n){Wi(r,e,t+n);let i=Sa(r,e+t,e+t+n);return new U(S.bytes,i,t+n)}function Qy(r,e,t,n){return El(r,e,1,t)}function Xy(r,e,t,n){return El(r,e,2,Zr(r,e+1,n))}function jy(r,e,t,n){return El(r,e,3,Jr(r,e+1,n))}function Zy(r,e,t,n){return El(r,e,5,en(r,e+1,n))}function Jy(r,e,t,n){let i=tn(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Y} 64-bit integer bytes lengths not supported`);return El(r,e,9,i)}function Qh(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===S.string?Wh(r.value):r.value),r.encodedBytes}function Ia(r,e){let t=Qh(e);ar(r,e.type.majorEncoded,t.length),r.push(t)}Ia.encodedSize=function(e){let t=Qh(e);return ar.encodedSize(t.length)+t.length};Ia.compareTokens=function(e,t){return tN(Qh(e),Qh(t))};function tN(r,e){return r.length<e.length?-1:r.length>e.length?1:Fy(r,e)}function vl(r,e,t,n,i){let s=t+n;Wi(r,e,s);let o=new U(S.string,By(r,e+t,e+s),s);return i.retainStringBytes===!0&&(o.byteValue=Sa(r,e+t,e+s)),o}function e7(r,e,t,n){return vl(r,e,1,t,n)}function t7(r,e,t,n){return vl(r,e,2,Zr(r,e+1,n),n)}function r7(r,e,t,n){return vl(r,e,3,Jr(r,e+1,n),n)}function n7(r,e,t,n){return vl(r,e,5,en(r,e+1,n),n)}function i7(r,e,t,n){let i=tn(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Y} 64-bit integer string lengths not supported`);return vl(r,e,9,i,n)}var s7=Ia;function Aa(r,e,t,n){return new U(S.array,n,t)}function o7(r,e,t,n){return Aa(r,e,1,t)}function a7(r,e,t,n){return Aa(r,e,2,Zr(r,e+1,n))}function c7(r,e,t,n){return Aa(r,e,3,Jr(r,e+1,n))}function l7(r,e,t,n){return Aa(r,e,5,en(r,e+1,n))}function u7(r,e,t,n){let i=tn(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Y} 64-bit integer array lengths not supported`);return Aa(r,e,9,i)}function h7(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Y} indefinite length items not allowed`);return Aa(r,e,1,1/0)}function Xh(r,e){ar(r,S.array.majorEncoded,e.value)}Xh.compareTokens=vn.compareTokens;Xh.encodedSize=function(e){return ar.encodedSize(e.value)};function Ta(r,e,t,n){return new U(S.map,n,t)}function f7(r,e,t,n){return Ta(r,e,1,t)}function d7(r,e,t,n){return Ta(r,e,2,Zr(r,e+1,n))}function p7(r,e,t,n){return Ta(r,e,3,Jr(r,e+1,n))}function m7(r,e,t,n){return Ta(r,e,5,en(r,e+1,n))}function g7(r,e,t,n){let i=tn(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Y} 64-bit integer map lengths not supported`);return Ta(r,e,9,i)}function y7(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Y} indefinite length items not allowed`);return Ta(r,e,1,1/0)}function jh(r,e){ar(r,S.map.majorEncoded,e.value)}jh.compareTokens=vn.compareTokens;jh.encodedSize=function(e){return ar.encodedSize(e.value)};function w7(r,e,t,n){return new U(S.tag,t,1)}function b7(r,e,t,n){return new U(S.tag,Zr(r,e+1,n),2)}function E7(r,e,t,n){return new U(S.tag,Jr(r,e+1,n),3)}function v7(r,e,t,n){return new U(S.tag,en(r,e+1,n),5)}function x7(r,e,t,n){return new U(S.tag,tn(r,e+1,n),9)}function Zh(r,e){ar(r,S.tag.majorEncoded,e.value)}Zh.compareTokens=vn.compareTokens;Zh.encodedSize=function(e){return ar.encodedSize(e.value)};var aN=20,cN=21,lN=22,uN=23;function _7(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${Y} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new U(S.null,null,1):new U(S.undefined,void 0,1)}function S7(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Y} indefinite length items not allowed`);return new U(S.break,void 0,1)}function h2(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${Y} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${Y} Infinity values are not supported`)}return new U(S.float,r,e)}function R7(r,e,t,n){return h2(f2(r,e+1),3,n)}function I7(r,e,t,n){return h2(d2(r,e+1),5,n)}function A7(r,e,t,n){return h2(P7(r,e+1),9,n)}function Jh(r,e,t){let n=e.value;if(n===!1)r.push([S.float.majorEncoded|aN]);else if(n===!0)r.push([S.float.majorEncoded|cN]);else if(n===null)r.push([S.float.majorEncoded|lN]);else if(n===void 0)r.push([S.float.majorEncoded|uN]);else{let i,s=!1;(!t||t.float64!==!0)&&(D7(n),i=f2(Vn,1),n===i||Number.isNaN(n)?(Vn[0]=249,r.push(Vn.slice(0,3)),s=!0):(C7(n),i=d2(Vn,1),n===i&&(Vn[0]=250,r.push(Vn.slice(0,5)),s=!0))),s||(hN(n),i=P7(Vn,1),Vn[0]=251,r.push(Vn.slice(0,9)))}}Jh.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){D7(n);let i=f2(Vn,1);if(n===i||Number.isNaN(n))return 3;if(C7(n),i=d2(Vn,1),n===i)return 5}return 9};var T7=new ArrayBuffer(9),xn=new DataView(T7,1),Vn=new Uint8Array(T7,0);function D7(r){if(r===1/0)xn.setUint16(0,31744,!1);else if(r===-1/0)xn.setUint16(0,64512,!1);else if(Number.isNaN(r))xn.setUint16(0,32256,!1);else{xn.setFloat32(0,r);let e=xn.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)xn.setUint16(0,31744,!1);else if(t===0)xn.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?xn.setUint16(0,0):i<-14?xn.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):xn.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function f2(r,e){if(r.length-e<2)throw new Error(`${Y} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,i=t&1023,s;return n===0?s=i*2**-24:n!==31?s=(i+1024)*2**(n-25):s=i===0?1/0:NaN,t&32768?-s:s}function C7(r){xn.setFloat32(0,r,!1)}function d2(r,e){if(r.length-e<4)throw new Error(`${Y} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function hN(r){xn.setFloat64(0,r,!1)}function P7(r,e){if(r.length-e<8)throw new Error(`${Y} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}Jh.compareTokens=vn.compareTokens;function We(r,e,t){throw new Error(`${Y} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function ef(r){return()=>{throw new Error(`${Y} ${r}`)}}var V=[];for(let r=0;r<=23;r++)V[r]=We;V[24]=Ky;V[25]=Vy;V[26]=qy;V[27]=zy;V[28]=We;V[29]=We;V[30]=We;V[31]=We;for(let r=32;r<=55;r++)V[r]=We;V[56]=Hy;V[57]=$y;V[58]=Gy;V[59]=Yy;V[60]=We;V[61]=We;V[62]=We;V[63]=We;for(let r=64;r<=87;r++)V[r]=Qy;V[88]=Xy;V[89]=jy;V[90]=Zy;V[91]=Jy;V[92]=We;V[93]=We;V[94]=We;V[95]=ef("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)V[r]=e7;V[120]=t7;V[121]=r7;V[122]=n7;V[123]=i7;V[124]=We;V[125]=We;V[126]=We;V[127]=ef("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)V[r]=o7;V[152]=a7;V[153]=c7;V[154]=l7;V[155]=u7;V[156]=We;V[157]=We;V[158]=We;V[159]=h7;for(let r=160;r<=183;r++)V[r]=f7;V[184]=d7;V[185]=p7;V[186]=m7;V[187]=g7;V[188]=We;V[189]=We;V[190]=We;V[191]=y7;for(let r=192;r<=215;r++)V[r]=w7;V[216]=b7;V[217]=E7;V[218]=v7;V[219]=x7;V[220]=We;V[221]=We;V[222]=We;V[223]=We;for(let r=224;r<=243;r++)V[r]=ef("simple values are not supported");V[244]=We;V[245]=We;V[246]=We;V[247]=_7;V[248]=ef("simple values are not supported");V[249]=R7;V[250]=I7;V[251]=A7;V[252]=We;V[253]=We;V[254]=We;V[255]=S7;var qn=[];for(let r=0;r<24;r++)qn[r]=new U(S.uint,r,1);for(let r=-1;r>=-24;r--)qn[31-r]=new U(S.negint,r,1);qn[64]=new U(S.bytes,new Uint8Array(0),1);qn[96]=new U(S.string,"",1);qn[128]=new U(S.array,0,1);qn[160]=new U(S.map,0,1);qn[244]=new U(S.false,!1,1);qn[245]=new U(S.true,!0,1);qn[246]=new U(S.null,null,1);function k7(r){switch(r.type){case S.false:return gi([244]);case S.true:return gi([245]);case S.null:return gi([246]);case S.bytes:return r.value.length?void 0:gi([64]);case S.string:return r.value===""?gi([96]):void 0;case S.array:return r.value===0?gi([128]):void 0;case S.map:return r.value===0?gi([160]):void 0;case S.uint:return r.value<24?gi([Number(r.value)]):void 0;case S.negint:if(r.value>=-24)return gi([31-Number(r.value)])}}var dN={float64:!1,mapSorter:gN,quickEncodeToken:k7};function pN(){let r=[];return r[S.uint.major]=vn,r[S.negint.major]=Yh,r[S.bytes.major]=Ia,r[S.string.major]=s7,r[S.array.major]=Xh,r[S.map.major]=jh,r[S.tag.major]=Zh,r[S.float.major]=Jh,r}var N7=pN(),p2=new wl,Da=class{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(`${Ra} object contains circular references`);return new Da(t,e)}},xs={null:new U(S.null,null),undefined:new U(S.undefined,void 0),true:new U(S.true,!0),false:new U(S.false,!1),emptyArray:new U(S.array,0),emptyMap:new U(S.map,0)},_s={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new U(S.float,r):r>=0?new U(S.uint,r):new U(S.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new U(S.uint,r):new U(S.negint,r)},Uint8Array(r,e,t,n){return new U(S.bytes,r)},string(r,e,t,n){return new U(S.string,r)},boolean(r,e,t,n){return r?xs.true:xs.false},null(r,e,t,n){return xs.null},undefined(r,e,t,n){return xs.undefined},ArrayBuffer(r,e,t,n){return new U(S.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new U(S.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[xs.emptyArray,new U(S.break)]:xs.emptyArray;n=Da.createCheck(n,r);let i=[],s=0;for(let o of r)i[s++]=tf(o,t,n);return t.addBreakTokens?[new U(S.array,r.length),i,new U(S.break)]:[new U(S.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",s=i?r.keys():Object.keys(r),o=i?r.size:s.length;if(!o)return t.addBreakTokens===!0?[xs.emptyMap,new U(S.break)]:xs.emptyMap;n=Da.createCheck(n,r);let a=[],c=0;for(let l of s)a[c++]=[tf(l,t,n),tf(i?r.get(l):r[l],t,n)];return mN(a,t),t.addBreakTokens?[new U(S.map,o),a,new U(S.break)]:[new U(S.map,o),a]}};_s.Map=_s.Object;_s.Buffer=_s.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))_s[`${r}Array`]=_s.DataView;function tf(r,e={},t){let n=ky(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||_s[n];if(typeof i=="function"){let o=i(r,n,e,t);if(o!=null)return o}let s=_s[n];if(!s)throw new Error(`${Ra} unsupported type: ${n}`);return s(r,n,e,t)}function mN(r,e){e.mapSorter&&r.sort(e.mapSorter)}function gN(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let i=t.type.major,s=N7[i].compareTokens(t,n);return s===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),s}function L7(r,e,t,n){if(Array.isArray(e))for(let i of e)L7(r,i,t,n);else t[e.type.major](r,e,n)}function O7(r,e,t){let n=tf(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let i=t.quickEncodeToken(n);if(i)return i;let s=e[n.type.major];if(s.encodedSize){let o=s.encodedSize(n,t),a=new wl(o);if(s(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return yl(a.chunks[0])}}return p2.reset(),L7(p2,n,e,t),p2.toBytes(!0)}function xl(r,e){return e=Object.assign({},dN,e),O7(r,N7,e)}var yN={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},m2=class{constructor(e,t={}){this.pos=0,this.data=e,this.options=t}done(){return this.pos>=this.data.length}next(){let e=this.data[this.pos],t=qn[e];if(t===void 0){let n=V[e];if(!n)throw new Error(`${Y} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let i=e&31;t=n(this.data,this.pos,i,this.options)}return this.pos+=t.encodedLength,t}},_l=Symbol.for("DONE"),rf=Symbol.for("BREAK");function wN(r,e,t){let n=[];for(let i=0;i<r.value;i++){let s=Sl(e,t);if(s===rf){if(r.value===1/0)break;throw new Error(`${Y} got unexpected break to lengthed array`)}if(s===_l)throw new Error(`${Y} found array but not enough entries (got ${i}, expected ${r.value})`);n[i]=s}return n}function bN(r,e,t){let n=t.useMaps===!0,i=n?void 0:{},s=n?new Map:void 0;for(let o=0;o<r.value;o++){let a=Sl(e,t);if(a===rf){if(r.value===1/0)break;throw new Error(`${Y} got unexpected break to lengthed map`)}if(a===_l)throw new Error(`${Y} found map but not enough entries (got ${o} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${Y} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&s.has(a)||!n&&a in i))throw new Error(`${Y} found repeat map key "${a}"`);let c=Sl(e,t);if(c===_l)throw new Error(`${Y} found map but not enough entries (got ${o} [no value], expected ${r.value})`);n?s.set(a,c):i[a]=c}return n?s:i}function Sl(r,e){if(r.done())return _l;let t=r.next();if(t.type===S.break)return rf;if(t.type.terminal)return t.value;if(t.type===S.array)return wN(t,r,e);if(t.type===S.map)return bN(t,r,e);if(t.type===S.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=Sl(r,e);return e.tags[t.value](n)}throw new Error(`${Y} tag not supported (${t.value})`)}throw new Error("unsupported")}function zn(r,e){if(!(r instanceof Uint8Array))throw new Error(`${Y} data to decode must be a Uint8Array`);e=Object.assign({},yN,e);let t=e.tokenizer||new m2(r,e),n=Sl(t,e);if(n===_l)throw new Error(`${Y} did not find any content to decode`);if(n===rf)throw new Error(`${Y} got unexpected break`);if(!t.done())throw new Error(`${Y} too many terminals, data makes no sense`);return n}function Pe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var G7=F(M7(),1);var Il=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},w2=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},U7=r=>globalThis.DOMException===void 0?new w2(r):new DOMException(r),F7=r=>{let e=r.reason===void 0?U7("This operation was aborted."):r.reason;return e instanceof Error?e:U7(e)};function b2(r,e,t,n){let i,s=new Promise((o,a)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(e===Number.POSITIVE_INFINITY){o(r);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:c}=n;c.aborted&&a(F7(c)),c.addEventListener("abort",()=>{a(F7(c))})}i=n.customTimers.setTimeout.call(void 0,()=>{if(typeof t=="function"){try{o(t())}catch(u){a(u)}return}let c=typeof t=="string"?t:`Promise timed out after ${e} milliseconds`,l=t instanceof Error?t:new Il(c);typeof r.cancel=="function"&&r.cancel(),a(l)},e),(async()=>{try{o(await r)}catch(c){a(c)}finally{n.customTimers.clearTimeout.call(void 0,i)}})()});return s.clear=()=>{clearTimeout(i),i=void 0},s}function E2(r,e,t){let n=0,i=r.length;for(;i>0;){let s=Math.trunc(i/2),o=n+s;t(r[o],e)<=0?(n=++o,i-=s+1):i=s}return n}var Io=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Yi,Al=class{constructor(){Yi.set(this,[])}enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&Io(this,Yi,"f")[this.size-1].priority>=t.priority){Io(this,Yi,"f").push(n);return}let i=E2(Io(this,Yi,"f"),n,(s,o)=>o.priority-s.priority);Io(this,Yi,"f").splice(i,0,n)}dequeue(){let e=Io(this,Yi,"f").shift();return e?.run}filter(e){return Io(this,Yi,"f").filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return Io(this,Yi,"f").length}};Yi=new WeakMap;var St=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},Q=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Ot,Dl,Cl,Rs,uf,Pl,sf,Hn,Tl,rn,of,nn,kl,Ss,af,K7,V7,H7,q7,z7,cf,v2,x2,hf,$7,lf,ff=class extends Error{},wt=class extends G7.default{constructor(e){var t,n,i,s;if(super(),Ot.add(this),Dl.set(this,void 0),Cl.set(this,void 0),Rs.set(this,0),uf.set(this,void 0),Pl.set(this,void 0),sf.set(this,0),Hn.set(this,void 0),Tl.set(this,void 0),rn.set(this,void 0),of.set(this,void 0),nn.set(this,0),kl.set(this,void 0),Ss.set(this,void 0),af.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Al,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(s=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""}\` (${typeof e.interval})`);St(this,Dl,e.carryoverConcurrencyCount,"f"),St(this,Cl,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),St(this,uf,e.intervalCap,"f"),St(this,Pl,e.interval,"f"),St(this,rn,new e.queueClass,"f"),St(this,of,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,St(this,af,e.throwOnTimeout===!0,"f"),St(this,Ss,e.autoStart===!1,"f")}get concurrency(){return Q(this,kl,"f")}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);St(this,kl,e,"f"),Q(this,Ot,"m",hf).call(this)}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:Q(this,af,"f"),...t},new Promise((n,i)=>{Q(this,rn,"f").enqueue(async()=>{var s,o,a;St(this,nn,(o=Q(this,nn,"f"),o++,o),"f"),St(this,Rs,(a=Q(this,Rs,"f"),a++,a),"f");try{if(!((s=t.signal)===null||s===void 0)&&s.aborted)throw new ff("The task was aborted.");let c=e({signal:t.signal});t.timeout&&(c=b2(Promise.resolve(c),t.timeout)),t.signal&&(c=Promise.race([c,Q(this,Ot,"m",$7).call(this,t.signal)]));let l=await c;n(l),this.emit("completed",l)}catch(c){if(c instanceof Il&&!t.throwOnTimeout){n();return}i(c),this.emit("error",c)}finally{Q(this,Ot,"m",H7).call(this)}},t),this.emit("add"),Q(this,Ot,"m",cf).call(this)})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return Q(this,Ss,"f")?(St(this,Ss,!1,"f"),Q(this,Ot,"m",hf).call(this),this):this}pause(){St(this,Ss,!0,"f")}clear(){St(this,rn,new(Q(this,of,"f")),"f")}async onEmpty(){Q(this,rn,"f").size!==0&&await Q(this,Ot,"m",lf).call(this,"empty")}async onSizeLessThan(e){Q(this,rn,"f").size<e||await Q(this,Ot,"m",lf).call(this,"next",()=>Q(this,rn,"f").size<e)}async onIdle(){Q(this,nn,"f")===0&&Q(this,rn,"f").size===0||await Q(this,Ot,"m",lf).call(this,"idle")}get size(){return Q(this,rn,"f").size}sizeBy(e){return Q(this,rn,"f").filter(e).length}get pending(){return Q(this,nn,"f")}get isPaused(){return Q(this,Ss,"f")}};Dl=new WeakMap,Cl=new WeakMap,Rs=new WeakMap,uf=new WeakMap,Pl=new WeakMap,sf=new WeakMap,Hn=new WeakMap,Tl=new WeakMap,rn=new WeakMap,of=new WeakMap,nn=new WeakMap,kl=new WeakMap,Ss=new WeakMap,af=new WeakMap,Ot=new WeakSet,K7=function(){return Q(this,Cl,"f")||Q(this,Rs,"f")<Q(this,uf,"f")},V7=function(){return Q(this,nn,"f")<Q(this,kl,"f")},H7=function(){var e;St(this,nn,(e=Q(this,nn,"f"),e--,e),"f"),Q(this,Ot,"m",cf).call(this),this.emit("next")},q7=function(){Q(this,Ot,"m",x2).call(this),Q(this,Ot,"m",v2).call(this),St(this,Tl,void 0,"f")},z7=function(){let e=Date.now();if(Q(this,Hn,"f")===void 0){let t=Q(this,sf,"f")-e;if(t<0)St(this,Rs,Q(this,Dl,"f")?Q(this,nn,"f"):0,"f");else return Q(this,Tl,"f")===void 0&&St(this,Tl,setTimeout(()=>{Q(this,Ot,"m",q7).call(this)},t),"f"),!0}return!1},cf=function(){if(Q(this,rn,"f").size===0)return Q(this,Hn,"f")&&clearInterval(Q(this,Hn,"f")),St(this,Hn,void 0,"f"),this.emit("empty"),Q(this,nn,"f")===0&&this.emit("idle"),!1;if(!Q(this,Ss,"f")){let e=!Q(this,Ot,"a",z7);if(Q(this,Ot,"a",K7)&&Q(this,Ot,"a",V7)){let t=Q(this,rn,"f").dequeue();return t?(this.emit("active"),t(),e&&Q(this,Ot,"m",v2).call(this),!0):!1}}return!1},v2=function(){Q(this,Cl,"f")||Q(this,Hn,"f")!==void 0||(St(this,Hn,setInterval(()=>{Q(this,Ot,"m",x2).call(this)},Q(this,Pl,"f")),"f"),St(this,sf,Date.now()+Q(this,Pl,"f"),"f"))},x2=function(){Q(this,Rs,"f")===0&&Q(this,nn,"f")===0&&Q(this,Hn,"f")&&(clearInterval(Q(this,Hn,"f")),St(this,Hn,void 0,"f")),St(this,Rs,Q(this,Dl,"f")?Q(this,nn,"f"):0,"f"),Q(this,Ot,"m",hf).call(this)},hf=function(){for(;Q(this,Ot,"m",cf).call(this););},$7=async function(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(new ff("The task was aborted."))},{once:!0})})},lf=async function(e,t){return new Promise(n=>{let i=()=>{t&&!t()||(this.off(e,i),n())};this.on(e,i)})};var xN=new TextDecoder;function _2(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let i=r[e++];if(t+=n<28?(i&127)<<n:(i&127)*2**n,i<128)break}return[t,e]}function df(r,e){let t;[t,e]=_2(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 W7(r,e){let t;return[t,e]=_2(r,e),[t&7,t>>3,e]}function _N(r){let e={},t=r.length,n=0;for(;n<t;){let i,s;if([i,s,n]=W7(r,n),s===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) 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]=df(r,n)}else if(s===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let o;[o,n]=df(r,n),e.Name=xN.decode(o)}else if(s===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(i!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Tsize`);[e.Tsize,n]=_2(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${s}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function Y7(r){let e=r.length,t=0,n,i=!1,s;for(;t<e;){let a,c;if([a,c,t]=W7(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(s)throw new Error("protobuf: (PBNode) duplicate Data section");[s,t]=df(r,t),n&&(i=!0)}else if(c===2){if(i)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=df(r,t),n.push(_N(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 o={};return s&&(o.Data=s),o.Links=n||[],o}var bJ=new TextEncoder,EJ=2**32,vJ=2**31;var SJ=new TextEncoder;var Q7=112;function X7(r){let e=Y7(r),t={};return e.Data&&(t.Data=e.Data),e.Links&&(t.Links=e.Links.map(n=>{let i={};try{i.Hash=ee.decode(n.Hash)}catch{}if(!i.Hash)throw new Error("Invalid Hash field found in link, expected CID");return n.Name!==void 0&&(i.Name=n.Name),n.Tsize!==void 0&&(i.Tsize=n.Tsize),i})),t}var j7=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===S.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===S.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[S.uint.major](e,t){this.prefix(e);let n=String(t.value),i=[];for(let s=0;s<n.length;s++)i[s]=n.charCodeAt(s);e.push(i)}[S.negint.major](e,t){this[S.uint.major](e,t)}[S.bytes.major](e,t){throw new Error(`${Ra} unsupported type: Uint8Array`)}[S.string.major](e,t){this.prefix(e);let n=Wh(JSON.stringify(t.value));e.push(n.length>32?yl(n):n)}[S.array.major](e,t){this.prefix(e),this.inRecursive.push({type:S.array,elements:0}),e.push([91])}[S.map.major](e,t){this.prefix(e),this.inRecursive.push({type:S.map,elements:0}),e.push([123])}[S.tag.major](e,t){}[S.float.major](e,t){if(t.type.name==="break"){let o=this.inRecursive.pop();if(o){if(o.type===S.array)e.push([93]);else if(o.type===S.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(`${Ra} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),i=[],s=!1;for(let o=0;o<n.length;o++)i[o]=n.charCodeAt(o),!s&&(i[o]===46||i[o]===101||i[o]===69)&&(s=!0);s||(i.push(46),i.push(48)),e.push(i)}};var Ca=class{constructor(e,t={}){this.pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}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(`${Y} 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(`${Y} unexpected token at position ${this.pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this.pos,t=!1,n=!1,i=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(S.uint,0,this.pos-e);if(i([48,49,50,51,52,53,54,55,56,57]),t&&this.pos===e+1)throw new Error(`${Y} unexpected token at position ${this.pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${Y} unexpected token at position ${this.pos}`);n=!0,this.pos++,i([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this.pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this.pos++,i([48,49,50,51,52,53,54,55,56,57]));let s=String.fromCharCode.apply(null,this.data.subarray(e,this.pos)),o=parseFloat(s);return n?new U(S.float,o,this.pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(o)?new U(o>=0?S.uint:S.negint,o,this.pos-e):new U(o>=0?S.uint:S.negint,BigInt(s),this.pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${Y} unexpected character at position ${this.pos}; this shouldn't happen`);this.pos++;for(let s=this.pos,o=0;s<this.data.length&&o<65536;s++,o++){let a=this.data[s];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this.pos,s));return this.pos=s+1,new U(S.string,c,o)}}let e=this.pos,t=[],n=()=>{if(this.pos+4>=this.data.length)throw new Error(`${Y} unexpected end of unicode escape sequence at position ${this.pos}`);let s=0;for(let o=0;o<4;o++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${Y} unexpected unicode escape character at position ${this.pos}`);s=s*16+a,this.pos++}return s},i=()=>{let s=this.ch(),o=null,a=s>239?4:s>223?3:s>191?2:1;if(this.pos+a>this.data.length)throw new Error(`${Y} unexpected unicode sequence at position ${this.pos}`);let c,l,u,h;switch(a){case 1:s<128&&(o=s);break;case 2:c=this.data[this.pos+1],(c&192)===128&&(h=(s&31)<<6|c&63,h>127&&(o=h));break;case 3:c=this.data[this.pos+1],l=this.data[this.pos+2],(c&192)===128&&(l&192)===128&&(h=(s&15)<<12|(c&63)<<6|l&63,h>2047&&(h<55296||h>57343)&&(o=h));break;case 4:c=this.data[this.pos+1],l=this.data[this.pos+2],u=this.data[this.pos+3],(c&192)===128&&(l&192)===128&&(u&192)===128&&(h=(s&15)<<18|(c&63)<<12|(l&63)<<6|u&63,h>65535&&h<1114112&&(o=h))}o===null?(o=65533,a=1):o>65535&&(o-=65536,t.push(o>>>10&1023|55296),o=56320|o&1023),t.push(o),this.pos+=a};for(;!this.done();){let s=this.ch(),o;switch(s){case 92:if(this.pos++,this.done())throw new Error(`${Y} unexpected string termination at position ${this.pos}`);switch(o=this.ch(),this.pos++,o){case 34:case 39:case 92:case 47:t.push(o);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${Y} unexpected string escape character at position ${this.pos}`)}break;case 34:return this.pos++,new U(S.string,l2(t),this.pos-e);default:if(s<32)throw new Error(`${Y} invalid control character at position ${this.pos}`);s<128?(t.push(s),this.pos++):i()}}throw new Error(`${Y} unexpected end of string at position ${this.pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this.pos++,new U(S.map,1/0,1);case 91:return this.modeStack.push("array-start"),this.pos++,new U(S.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new U(S.null,null,4);case 102:return this.expect([102,97,108,115,101]),new U(S.false,!1,5);case 116:return this.expect([116,114,117,101]),new U(S.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(`${Y} 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(S.break,void 0,1);if(this.ch()!==44)throw new Error(`${Y} 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(S.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(S.break,void 0,1);if(this.ch()!==44)throw new Error(`${Y} 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(S.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${Y} 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(`${Y} unexpected parse state at position ${this.pos}; this shouldn't happen`)}}};function S2(r,e){return e=Object.assign({tokenizer:new Ca(r,e)},e),zn(r,e)}var Z7={codec:Q7,async*walk(r){yield*X7(r).Links.map(t=>t.Hash)}},J7={codec:mh,async*walk(){}},e9=42,t9={codec:113,async*walk(r){let e=[],t=[];t[e9]=n=>{if(n[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");let i=ee.decode(n.subarray(1));return e.push(i),i},zn(r,{tags:t}),yield*e}},R2=class extends Ca{tokenBuffer;constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===S.map){let t=this._next();if(t.type===S.string&&t.value==="/"){let n=this._next();if(n.type===S.string){if(this._next().type!==S.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new U(S.tag,42,0)}if(n.type===S.map){let i=this._next();if(i.type===S.string&&i.value==="bytes"){let s=this._next();if(s.type===S.string){for(let a=0;a<2;a++)if(this._next().type!==S.break)throw new Error("Invalid encoded Bytes form");let o=Ki.decode(`m${s.value}`);return new U(S.bytes,o,s.value.length)}this.tokenBuffer.push(s)}this.tokenBuffer.push(i)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},r9={codec:297,async*walk(r){let e=[],t=[];t[e9]=n=>{let i=ee.parse(n);return e.push(i),i},S2(r,{tags:t,tokenizer:new R2(r,{tags:t,allowIndefinite:!0,allowUndefined:!0,allowNaN:!0,allowInfinity:!0,allowBigInt:!0,strict:!1,rejectDuplicateMapKeys:!1})}),yield*e}};var IN=[J7,Z7,t9,r9],o9="/pin/",n9="/pinned-block/",I2=cl,i9=1;function s9(r){return r.version===0&&(r=r.toV1()),new ve(`${o9}${r.toString(I2)}`)}var pf=class{datastore;blockstore;dagWalkers;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.dagWalkers={},[...IN,...n].forEach(i=>{this.dagWalkers[i.codec]=i})}async add(e,t={}){let n=s9(e);if(await this.datastore.has(n))throw new Error("Already pinned");let i=Math.round(t.depth??1/0);if(i<0)throw new Error("Depth must be greater than or equal to 0");let s=new wt({concurrency:i9});s.add(async()=>{await this.#e(e,s,c=>{c.pinnedBy.find(l=>de(l,e.bytes))==null&&(c.pinCount++,c.pinnedBy.push(e.bytes))},{...t,depth:i})});let o=Pe();s.on("error",c=>{s.clear(),o.reject(c)}),await Promise.race([s.onIdle(),o.promise]);let a={depth:i,metadata:t.metadata??{}};return await this.datastore.put(n,xl(a),t),{cid:e,...a}}async#e(e,t,n,i){if(i.depth===-1)return;let s=this.dagWalkers[e.code];if(s==null)throw new Error(`No dag walker found for cid codec ${e.code}`);let o=await this.blockstore.get(e);await this.#t(e,n,i);for await(let a of s.walk(o))t.add(async()=>{await this.#e(a,t,n,{...i,depth:i.depth-1})})}async#t(e,t,n){let i=new ve(`${n9}${I2.encode(e.multihash.bytes)}`),s={pinCount:0,pinnedBy:[]};try{s=zn(await this.datastore.get(i,n))}catch(o){if(o.code!=="ERR_NOT_FOUND")throw o}if(t(s),s.pinCount===0&&await this.datastore.has(i)){await this.datastore.delete(i);return}await this.datastore.put(i,xl(s),n)}async rm(e,t={}){let n=s9(e),i=await this.datastore.get(n,t),s=zn(i);await this.datastore.delete(n,t);let o=new wt({concurrency:i9});return o.add(async()=>{await this.#e(e,o,a=>{a.pinCount--,a.pinnedBy=a.pinnedBy.filter(c=>de(c,e.bytes))},{...t,depth:s.depth})}),await o.onIdle(),{cid:e,...s}}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:o9+(e.cid!=null?`${e.cid.toString(cl)}`:"")},e)){let i=ee.parse(t.toString().substring(5),cl),s=zn(n);yield{cid:i,...s}}}async isPinned(e,t={}){let n=new ve(`${n9}${I2.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}};var A2=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},T2=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},a9=r=>globalThis.DOMException===void 0?new T2(r):new DOMException(r),c9=r=>{let e=r.reason===void 0?a9("This operation was aborted."):r.reason;return e instanceof Error?e:a9(e)};function D2(r,e){let{milliseconds:t,fallback:n,message:i,customTimers:s={setTimeout,clearTimeout}}=e,o,a=new Promise((c,l)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(t===Number.POSITIVE_INFINITY){c(r);return}if(e.signal){let{signal:h}=e;h.aborted&&l(c9(h)),h.addEventListener("abort",()=>{l(c9(h))})}let u=new A2;o=s.setTimeout.call(void 0,()=>{if(n){try{c(n())}catch(h){l(h)}return}typeof r.cancel=="function"&&r.cancel(),i===!1?c():i instanceof Error?l(i):(u.message=i??`Promise timed out after ${t} milliseconds`,l(u))},t),(async()=>{try{c(await r)}catch(h){l(h)}finally{s.clearTimeout.call(void 0,o)}})()});return a.clear=()=>{s.clearTimeout.call(void 0,o),o=void 0},a}var l9=(r=21)=>crypto.getRandomValues(new Uint8Array(r)).reduce((e,t)=>(t&=63,t<36?e+=t.toString(36):t<62?e+=(t-26).toString(36).toUpperCase():t>62?e+="-":e+="_",e),"");var C2="lock:worker:request-read",P2="lock:worker:release-read",k2="lock:master:grant-read",N2="lock:worker:request-write",L2="lock:worker:release-write",O2="lock:master:grant-write";var Is={},Pa=r=>{r.addEventListener("message",e=>{Pa.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{Pa.dispatchEvent("message",r,e)})};Pa.addEventListener=(r,e)=>{Is[r]==null&&(Is[r]=[]),Is[r].push(e)};Pa.removeEventListener=(r,e)=>{Is[r]!=null&&(Is[r]=Is[r].filter(t=>t===e))};Pa.dispatchEvent=function(r,e,t){Is[r]!=null&&Is[r].forEach(n=>n(e,t))};var B2=Pa;var u9=(r,e,t,n,i)=>(s,o)=>{if(o.data.type!==t)return;let a={type:o.data.type,name:o.data.name,identifier:o.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>(s.postMessage({type:i,name:a.name,identifier:a.identifier}),await new Promise(c=>{let l=u=>{if(u==null||u.data==null)return;let h={type:u.data.type,name:u.data.name,identifier:u.data.identifier};h.type===n&&h.identifier===a.identifier&&(s.removeEventListener("message",l),c())};s.addEventListener("message",l)}))}}))},h9=(r,e,t,n)=>async()=>{let i=l9();return globalThis.postMessage({type:e,identifier:i,name:r}),await new Promise(s=>{let o=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===i&&(globalThis.removeEventListener("message",o),s(()=>{globalThis.postMessage({type:n,identifier:i,name:r})}))};globalThis.addEventListener("message",o)})},AN={singleProcess:!1},f9=r=>{if(r=Object.assign({},AN,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return B2.addEventListener("message",u9(t,"requestReadLock",C2,P2,k2)),B2.addEventListener("message",u9(t,"requestWriteLock",N2,L2,O2)),t}return{isWorker:!0,readLock:t=>h9(t,C2,k2,P2),writeLock:t=>h9(t,N2,O2,L2)}};var Ao={},As;async function M2(r,e){let t,n=new Promise(i=>{t=i});return r.add(async()=>await D2((async()=>await new Promise(i=>{t(()=>{i()})}))(),{milliseconds:e.timeout})),await n}var TN=(r,e)=>{if(As.isWorker===!0)return{readLock:As.readLock(r,e),writeLock:As.writeLock(r,e)};let t=new wt({concurrency:1}),n;return{async readLock(){if(n!=null)return await M2(n,e);n=new wt({concurrency:e.concurrency,autoStart:!1});let i=n,s=M2(n,e);return t.add(async()=>(i.start(),await i.onIdle().then(()=>{n===i&&(n=null)}))),await s},async writeLock(){return n=null,await M2(t,e)}}},DN={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Nl(r){let e=Object.assign({},DN,r);return As==null&&(As=f9(e),As.isWorker!==!0&&(As.addEventListener("requestReadLock",t=>{Ao[t.data.name]!=null&&Ao[t.data.name].readLock().then(async n=>await t.data.handler().finally(()=>n()))}),As.addEventListener("requestWriteLock",async t=>{Ao[t.data.name]!=null&&Ao[t.data.name].writeLock().then(async n=>await t.data.handler().finally(()=>n()))}))),Ao[e.name]==null&&(Ao[e.name]=TN(e.name,e)),Ao[e.name]}var mf=class{lock;child;pins;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=Nl({singleProcess:n.holdGcLock})}unwrap(){return this.child}async put(e,t,n={}){let i=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{i()}}async*putMany(e,t={}){let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async get(e,t={}){let n=await this.lock.readLock();try{return await this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new Error("CID was pinned");await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){let n=await this.lock.writeLock();try{let i=this;yield*this.child.deleteMany(async function*(){for await(let s of e){if(await i.pins.isPinned(s))throw new Error("CID was pinned");yield s}}(),t)}finally{n()}}async has(e,t={}){let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}};var U2=new ve("/version"),d9=1;async function p9(r){if(!await r.has(U2)){await r.put(U2,K(`${d9}`));return}let e=await r.get(U2),t=O(e);if(parseInt(t,10)!==d9)throw new Error("Unknown datastore version, a datastore migration may be required")}var gf=class{child;bitswap;constructor(e,t={}){this.child=e,this.bitswap=t.bitswap}unwrap(){return this.child}async put(e,t,n={}){return await this.child.has(e)?(n.onProgress?.(new je("blocks:put:duplicate",e)),e):(this.bitswap?.isStarted()===!0&&(n.onProgress?.(new je("blocks:put:bitswap:notify",e)),this.bitswap.notify(e,t,n)),n.onProgress?.(new je("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=Or(e,async({cid:s})=>{let o=await this.child.has(s);return o&&t.onProgress?.(new je("blocks:put-many:duplicate",s)),!o}),i=ll(n,({cid:s,block:o})=>{t.onProgress?.(new je("blocks:put-many:bitswap:notify",s)),this.bitswap?.notify(s,o,t)});t.onProgress?.(new je("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(i,t)}async get(e,t={}){if(t.offline!==!0&&this.bitswap?.isStarted()!=null&&!await this.child.has(e)){t.onProgress?.(new je("blocks:get:bitswap:get",e));let n=await this.bitswap.want(e,t);return t.onProgress?.(new je("blocks:get:blockstore:put",e)),await this.child.put(e,n,t),n}return t.onProgress?.(new je("blocks:get:blockstore:get",e)),this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new je("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(ll(e,async n=>{if(t.offline!==!0&&this.bitswap?.isStarted()===!0&&!await this.child.has(n)){t.onProgress?.(new je("blocks:get-many:bitswap:get",n));let i=await this.bitswap.want(n,t);t.onProgress?.(new je("blocks:get-many:blockstore:put",n)),await this.child.put(n,i,t)}}))}async delete(e,t={}){t.onProgress?.(new je("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new je("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 je("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}};var F2=T("helia"),yf=class{libp2p;blockstore;datastore;pins;#e;constructor(e){let t=[Ce,Ep,hi,...e.hashers??[]];this.#e=Py(e.libp2p,e.blockstore,{hashLoader:{getHasher:async i=>{let s=t.find(o=>o.code===i||o.name===i);if(s!=null)return s;throw new Error(`Could not load hasher for code/name "${i}"`)}}});let n=new gf(e.blockstore,{bitswap:this.#e});this.pins=new pf(e.datastore,n,e.dagWalkers??[]),this.libp2p=e.libp2p,this.blockstore=new mf(n,this.pins,{holdGcLock:e.holdGcLock}),this.datastore=e.datastore}async start(){await p9(this.datastore),await this.#e?.start(),await this.libp2p.start()}async stop(){await this.libp2p.stop(),await this.#e?.stop()}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,i=this.blockstore.unwrap();F2("gc start"),await Yr(i.deleteMany(async function*(){for await(let{cid:s}of i.getAll())try{if(await n.pins.isPinned(s,e))continue;yield s,e.onProgress?.(new je("helia:gc:deleted",s))}catch(o){F2.error("Error during gc",o),e.onProgress?.(new je("helia:gc:error",o))}}()))}finally{t()}F2("gc finished")}};var lx=F(jr(),1);var jf={};Re(jf,{generateEphemeralKeyPair:()=>Xw,generateKeyPair:()=>eu,generateKeyPairFromSeed:()=>rM,importKey:()=>Ya,keyStretcher:()=>rb,keysPBM:()=>Ua,marshalPrivateKey:()=>B3,marshalPublicKey:()=>Wa,supportedKeys:()=>Ri,unmarshalPrivateKey:()=>an,unmarshalPublicKey:()=>rr});var Ire=F(Ml(),1),Are=F(Dw(),1);var Xf=F(tt(),1);var b3={};Re(b3,{Ed25519PrivateKey:()=>Lo,Ed25519PublicKey:()=>Hl,generateKeyPair:()=>EB,generateKeyPairFromSeed:()=>w3,unmarshalEd25519PrivateKey:()=>wB,unmarshalEd25519PublicKey:()=>bB});var eB=F(Cs(),1);var tr=BigInt(0),Ne=BigInt(1),Os=BigInt(2),tB=BigInt(8),Cw=BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),ht=Object.freeze({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),P:BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),l:Cw,n:Cw,h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960")});var Ow=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000"),Kl=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),ute=BigInt("6853475219497561581579357271197624642482790079785650197046958215289687604742"),rB=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),nB=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),iB=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),sB=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Ae=class{constructor(e,t,n,i){this.x=e,this.y=t,this.z=n,this.t=i}static fromAffine(e){if(!(e instanceof Et))throw new TypeError("ExtendedPoint#fromAffine: expected Point");return e.equals(Et.ZERO)?Ae.ZERO:new Ae(e.x,e.y,Ne,L(e.x*e.y))}static toAffineBatch(e){let t=cB(e.map(n=>n.z));return e.map((n,i)=>n.toAffine(t[i]))}static normalizeZ(e){return this.toAffineBatch(e).map(this.fromAffine)}equals(e){kw(e);let{x:t,y:n,z:i}=this,{x:s,y:o,z:a}=e,c=L(t*a),l=L(s*i),u=L(n*a),h=L(o*i);return c===l&&u===h}negate(){return new Ae(L(-this.x),this.y,this.z,L(-this.t))}double(){let{x:e,y:t,z:n}=this,{a:i}=ht,s=L(e*e),o=L(t*t),a=L(Os*L(n*n)),c=L(i*s),l=e+t,u=L(L(l*l)-s-o),h=c+o,f=h-a,d=c-o,p=L(u*f),m=L(h*d),g=L(u*d),y=L(f*h);return new Ae(p,m,y,g)}add(e){kw(e);let{x:t,y:n,z:i,t:s}=this,{x:o,y:a,z:c,t:l}=e,u=L((n-t)*(a+o)),h=L((n+t)*(a-o)),f=L(h-u);if(f===tr)return this.double();let d=L(i*Os*l),p=L(s*Os*c),m=p+d,g=h+u,y=p-d,b=L(m*f),E=L(g*y),I=L(m*y),v=L(f*g);return new Ae(b,E,v,I)}subtract(e){return this.add(e.negate())}precomputeWindow(e){let t=1+256/e,n=[],i=this,s=i;for(let o=0;o<t;o++){s=i,n.push(s);for(let a=1;a<2**(e-1);a++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,t){!t&&this.equals(Ae.BASE)&&(t=Et.BASE);let n=t&&t._WINDOW_SIZE||1;if(256%n)throw new Error("Point#wNAF: Invalid precomputation window, must be power of 2");let i=t&&f3.get(t);i||(i=this.precomputeWindow(n),t&&n!==1&&(i=Ae.normalizeZ(i),f3.set(t,i)));let s=Ae.ZERO,o=Ae.BASE,a=1+256/n,c=2**(n-1),l=BigInt(2**n-1),u=2**n,h=BigInt(n);for(let f=0;f<a;f++){let d=f*c,p=Number(e&l);e>>=h,p>c&&(p-=u,e+=Ne);let m=d,g=d+Math.abs(p)-1,y=f%2!==0,b=p<0;p===0?o=o.add(Pw(y,i[m])):s=s.add(Pw(b,i[g]))}return Ae.normalizeZ([s,o])[0]}multiply(e,t){return this.wNAF(Mf(e,ht.l),t)}multiplyUnsafe(e){let t=Mf(e,ht.l,!1),n=Ae.BASE,i=Ae.ZERO;if(t===tr)return i;if(this.equals(i)||t===Ne)return this;if(this.equals(n))return this.wNAF(t);let s=i,o=this;for(;t>tr;)t&Ne&&(s=s.add(o)),o=o.double(),t>>=Ne;return s}isSmallOrder(){return this.multiplyUnsafe(ht.h).equals(Ae.ZERO)}isTorsionFree(){let e=this.multiplyUnsafe(ht.l/Os).double();return ht.l%Os&&(e=e.add(this)),e.equals(Ae.ZERO)}toAffine(e){let{x:t,y:n,z:i}=this,s=this.equals(Ae.ZERO);e==null&&(e=s?tB:Uf(i));let o=L(t*e),a=L(n*e),c=L(i*e);if(s)return Et.ZERO;if(c!==Ne)throw new Error("invZ was invalid");return new Et(o,a)}fromRistrettoBytes(){l3()}toRistrettoBytes(){l3()}fromRistrettoHash(){l3()}};Ae.BASE=new Ae(ht.Gx,ht.Gy,Ne,L(ht.Gx*ht.Gy));Ae.ZERO=new Ae(tr,Ne,Ne,tr);function Pw(r,e){let t=e.negate();return r?t:e}function kw(r){if(!(r instanceof Ae))throw new TypeError("ExtendedPoint expected")}function c3(r){if(!(r instanceof Ur))throw new TypeError("RistrettoPoint expected")}function l3(){throw new Error("Legacy method: switch to RistrettoPoint")}var Ur=class{constructor(e){this.ep=e}static calcElligatorRistrettoMap(e){let{d:t}=ht,n=L(Kl*e*e),i=L((n+Ne)*iB),s=BigInt(-1),o=L((s-t*n)*L(n+t)),{isValid:a,value:c}=p3(i,o),l=L(c*e);Ls(l)||(l=L(-l)),a||(c=l),a||(s=n);let u=L(s*(n-Ne)*sB-o),h=c*c,f=L((c+c)*o),d=L(u*rB),p=L(Ne-h),m=L(Ne+h);return new Ae(L(f*m),L(p*d),L(d*m),L(f*p))}static hashToCurve(e){e=Bs(e,64);let t=u3(e.slice(0,32)),n=this.calcElligatorRistrettoMap(t),i=u3(e.slice(32,64)),s=this.calcElligatorRistrettoMap(i);return new Ur(n.add(s))}static fromHex(e){e=Bs(e,32);let{a:t,d:n}=ht,i="RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint",s=u3(e);if(!uB(Vl(s),e)||Ls(s))throw new Error(i);let o=L(s*s),a=L(Ne+t*o),c=L(Ne-t*o),l=L(a*a),u=L(c*c),h=L(t*n*l-u),{isValid:f,value:d}=Lw(L(h*u)),p=L(d*c),m=L(d*p*h),g=L((s+s)*p);Ls(g)&&(g=L(-g));let y=L(a*m),b=L(g*y);if(!f||Ls(b)||y===tr)throw new Error(i);return new Ur(new Ae(g,y,Ne,b))}toRawBytes(){let{x:e,y:t,z:n,t:i}=this.ep,s=L(L(n+t)*L(n-t)),o=L(e*t),a=L(o*o),{value:c}=Lw(L(s*a)),l=L(c*s),u=L(c*o),h=L(l*u*i),f;if(Ls(i*h)){let p=L(t*Kl),m=L(e*Kl);e=p,t=m,f=L(l*nB)}else f=u;Ls(e*h)&&(t=L(-t));let d=L((n-t)*f);return Ls(d)&&(d=L(-d)),Vl(d)}toHex(){return ql(this.toRawBytes())}toString(){return this.toHex()}equals(e){c3(e);let t=this.ep,n=e.ep,i=L(t.x*n.y)===L(t.y*n.x),s=L(t.y*n.y)===L(t.x*n.x);return i||s}add(e){return c3(e),new Ur(this.ep.add(e.ep))}subtract(e){return c3(e),new Ur(this.ep.subtract(e.ep))}multiply(e){return new Ur(this.ep.multiply(e))}multiplyUnsafe(e){return new Ur(this.ep.multiplyUnsafe(e))}};Ur.BASE=new Ur(Ae.BASE);Ur.ZERO=new Ur(Ae.ZERO);var f3=new WeakMap,Et=class{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,f3.delete(this)}static fromHex(e,t=!0){let{d:n,P:i}=ht;e=Bs(e,32);let s=e.slice();s[31]=e[31]&-129;let o=zl(s);if(t&&o>=i)throw new Error("Expected 0 < hex < P");if(!t&&o>=Ow)throw new Error("Expected 0 < hex < 2**256");let a=L(o*o),c=L(a-Ne),l=L(n*a+Ne),{isValid:u,value:h}=p3(c,l);if(!u)throw new Error("Point.fromHex: invalid y coordinate");let f=(h&Ne)===Ne;return(e[31]&128)!==0!==f&&(h=L(-h)),new Et(h,o)}static async fromPrivateKey(e){return(await Ff(e)).point}toRawBytes(){let e=Vl(this.y);return e[31]|=this.x&Ne?128:0,e}toHex(){return ql(this.toRawBytes())}toX25519(){let{y:e}=this,t=L((Ne+e)*Uf(Ne-e));return Vl(t)}isTorsionFree(){return Ae.fromAffine(this).isTorsionFree()}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new Et(L(-this.x),this.y)}add(e){return Ae.fromAffine(this).add(Ae.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return Ae.fromAffine(this).multiply(e,this).toAffine()}};Et.BASE=new Et(ht.Gx,ht.Gy);Et.ZERO=new Et(tr,Ne);var No=class{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromHex(e){let t=Bs(e,64),n=Et.fromHex(t.slice(0,32),!1),i=zl(t.slice(32,64));return new No(n,i)}assertValidity(){let{r:e,s:t}=this;if(!(e instanceof Et))throw new Error("Expected Point instance");return Mf(t,ht.l,!1),this}toRawBytes(){let e=new Uint8Array(64);return e.set(this.r.toRawBytes()),e.set(Vl(this.s),32),e}toHex(){return ql(this.toRawBytes())}};function Nw(...r){if(!r.every(n=>n instanceof Uint8Array))throw new Error("Expected Uint8Array list");if(r.length===1)return r[0];let e=r.reduce((n,i)=>n+i.length,0),t=new Uint8Array(e);for(let n=0,i=0;n<r.length;n++){let s=r[n];t.set(s,i),i+=s.length}return t}var oB=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function ql(r){if(!(r instanceof Uint8Array))throw new Error("Uint8Array expected");let e="";for(let t=0;t<r.length;t++)e+=oB[r[t]];return e}function d3(r){if(typeof r!="string")throw new TypeError("hexToBytes: expected string, got "+typeof r);if(r.length%2)throw new Error("hexToBytes: received invalid unpadded hex");let e=new Uint8Array(r.length/2);for(let t=0;t<e.length;t++){let n=t*2,i=r.slice(n,n+2),s=Number.parseInt(i,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");e[t]=s}return e}function Bw(r){let t=r.toString(16).padStart(64,"0");return d3(t)}function Vl(r){return Bw(r).reverse()}function Ls(r){return(L(r)&Ne)===Ne}function zl(r){if(!(r instanceof Uint8Array))throw new Error("Expected Uint8Array");return BigInt("0x"+ql(Uint8Array.from(r).reverse()))}var aB=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function u3(r){return L(zl(r)&aB)}function L(r,e=ht.P){let t=r%e;return t>=tr?t:e+t}function Uf(r,e=ht.P){if(r===tr||e<=tr)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=L(r,e),n=e,i=tr,s=Ne,o=Ne,a=tr;for(;t!==tr;){let l=n/t,u=n%t,h=i-o*l,f=s-a*l;n=t,t=u,i=o,s=a,o=h,a=f}if(n!==Ne)throw new Error("invert: does not exist");return L(i,e)}function cB(r,e=ht.P){let t=new Array(r.length),n=r.reduce((s,o,a)=>o===tr?s:(t[a]=s,L(s*o,e)),Ne),i=Uf(n,e);return r.reduceRight((s,o,a)=>o===tr?s:(t[a]=L(s*t[a],e),L(s*o,e)),i),t}function _i(r,e){let{P:t}=ht,n=r;for(;e-- >tr;)n*=n,n%=t;return n}function lB(r){let{P:e}=ht,t=BigInt(5),n=BigInt(10),i=BigInt(20),s=BigInt(40),o=BigInt(80),c=r*r%e*r%e,l=_i(c,Os)*c%e,u=_i(l,Ne)*r%e,h=_i(u,t)*u%e,f=_i(h,n)*h%e,d=_i(f,i)*f%e,p=_i(d,s)*d%e,m=_i(p,o)*p%e,g=_i(m,o)*p%e,y=_i(g,n)*h%e;return{pow_p_5_8:_i(y,Os)*r%e,b2:c}}function p3(r,e){let t=L(e*e*e),n=L(t*t*e),i=lB(r*n).pow_p_5_8,s=L(r*t*i),o=L(e*s*s),a=s,c=L(s*Kl),l=o===r,u=o===L(-r),h=o===L(-r*Kl);return l&&(s=a),(u||h)&&(s=c),Ls(s)&&(s=L(-s)),{isValid:l||u,value:s}}function Lw(r){return p3(Ne,r)}function Bf(r){return L(zl(r),ht.l)}function uB(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}function Bs(r,e){let t=r instanceof Uint8Array?Uint8Array.from(r):d3(r);if(typeof e=="number"&&t.length!==e)throw new Error(`Expected ${e} bytes`);return t}function Mf(r,e,t=!0){if(!e)throw new TypeError("Specify max value");if(typeof r=="number"&&Number.isSafeInteger(r)&&(r=BigInt(r)),typeof r=="bigint"&&r<e){if(t){if(tr<r)return r}else if(tr<=r)return r}throw new TypeError("Expected valid scalar: 0 < scalar < max")}function hB(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function fB(r){if(r=typeof r=="bigint"||typeof r=="number"?Bw(Mf(r,Ow)):Bs(r),r.length!==32)throw new Error("Expected 32 bytes");return r}function dB(r){let e=hB(r.slice(0,32)),t=r.slice(32,64),n=Bf(e),i=Et.BASE.multiply(n),s=i.toRawBytes();return{head:e,prefix:t,scalar:n,point:i,pointBytes:s}}var h3;async function Ff(r){return dB(await Ms.sha512(fB(r)))}async function m3(r){return(await Ff(r)).pointBytes}async function Mw(r,e){r=Bs(r);let{prefix:t,scalar:n,pointBytes:i}=await Ff(e),s=Bf(await Ms.sha512(t,r)),o=Et.BASE.multiply(s),a=Bf(await Ms.sha512(o.toRawBytes(),i,r)),c=L(s+a*n,ht.l);return new No(o,c).toRawBytes()}function pB(r,e,t){e=Bs(e),t instanceof Et||(t=Et.fromHex(t,!1));let{r:n,s:i}=r instanceof No?r.assertValidity():No.fromHex(r),s=Ae.BASE.multiplyUnsafe(i);return{r:n,s:i,SB:s,pub:t,msg:e}}function mB(r,e,t,n){let i=Bf(n),s=Ae.fromAffine(r).multiplyUnsafe(i);return Ae.fromAffine(e).add(s).subtract(t).multiplyUnsafe(ht.h).equals(Ae.ZERO)}async function Uw(r,e,t){let{r:n,SB:i,msg:s,pub:o}=pB(r,e,t),a=await Ms.sha512(n.toRawBytes(),o.toRawBytes(),s);return mB(o,n,i,a)}Et.BASE._setWindowSize(8);var Ns={node:eB,web:typeof self=="object"&&"crypto"in self?self.crypto:void 0},Ms={bytesToHex:ql,hexToBytes:d3,concatBytes:Nw,getExtendedPublicKey:Ff,mod:L,invert:Uf,TORSION_SUBGROUP:["0100000000000000000000000000000000000000000000000000000000000000","c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a","0000000000000000000000000000000000000000000000000000000000000080","26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05","ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f","26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85","0000000000000000000000000000000000000000000000000000000000000000","c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa"],hashToPrivateScalar:r=>{if(r=Bs(r),r.length<40||r.length>1024)throw new Error("Expected 40-1024 bytes of private key as per FIPS 186");return L(zl(r),ht.l-Ne)+Ne},randomBytes:(r=32)=>{if(Ns.web)return Ns.web.getRandomValues(new Uint8Array(r));if(Ns.node){let{randomBytes:e}=Ns.node;return new Uint8Array(e(r).buffer)}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>Ms.randomBytes(32),sha512:async(...r)=>{let e=Nw(...r);if(Ns.web){let t=await Ns.web.subtle.digest("SHA-512",e.buffer);return new Uint8Array(t)}else{if(Ns.node)return Uint8Array.from(Ns.node.createHash("sha512").update(e).digest());throw new Error("The environment doesn't have sha512 function")}},precompute(r=8,e=Et.BASE){let t=e.equals(Et.BASE)?e:new Et(e.x,e.y);return t._setWindowSize(r),t.multiply(Os),t},sha512Sync:void 0};Object.defineProperties(Ms,{sha512Sync:{configurable:!1,get(){return h3},set(r){h3||(h3=r)}}});var Ba=32,Zi=64,Kf=32;async function Fw(){let r=Ms.randomPrivateKey(),e=await m3(r);return{privateKey:zw(r,e),publicKey:e}}async function Kw(r){if(r.length!==Kf)throw new TypeError('"seed" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=r,t=await m3(e);return{privateKey:zw(e,t),publicKey:t}}async function Vw(r,e){let t=r.subarray(0,Kf);return Mw(e,t)}async function qw(r,e,t){return Uw(e,t,r)}function zw(r,e){let t=new Uint8Array(Zi);for(let n=0;n<Kf;n++)t[n]=r[n],t[Kf+n]=e[n];return t}var Mt={get(r=globalThis){let e=r.crypto;if(e==null||e.subtle==null)throw Object.assign(new Error("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p-crypto/blob/master/README.md#web-crypto-api"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var g3={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function Vf(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,i=r?.digest??"SHA-256",s=r?.saltLength??16,o=r?.iterations??32767,a=Mt.get();t*=8;async function c(h,f){let d=a.getRandomValues(new Uint8Array(s)),p=a.getRandomValues(new Uint8Array(n)),m={name:e,iv:p};typeof f=="string"&&(f=K(f));let g;if(f.length===0){g=await a.subtle.importKey("jwk",g3,{name:"AES-GCM"},!0,["encrypt"]);try{let b={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},E=await a.subtle.importKey("raw",f,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,E,{name:e,length:t},!0,["encrypt"])}catch{g=await a.subtle.importKey("jwk",g3,{name:"AES-GCM"},!0,["encrypt"])}}else{let b={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},E=await a.subtle.importKey("raw",f,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,E,{name:e,length:t},!0,["encrypt"])}let y=await a.subtle.encrypt(m,g,h);return le([d,m.iv,new Uint8Array(y)])}async function l(h,f){let d=h.subarray(0,s),p=h.subarray(s,s+n),m=h.subarray(s+n),g={name:e,iv:p};typeof f=="string"&&(f=K(f));let y;if(f.length===0)try{let E={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},I=await a.subtle.importKey("raw",f,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(E,I,{name:e,length:t},!0,["decrypt"])}catch{y=await a.subtle.importKey("jwk",g3,{name:"AES-GCM"},!0,["decrypt"])}else{let E={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},I=await a.subtle.importKey("raw",f,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(E,I,{name:e,length:t},!0,["decrypt"])}let b=await a.subtle.decrypt(g,y,m);return new Uint8Array(b)}return{encrypt:c,decrypt:l}}async function Ma(r,e){let n=await Vf().encrypt(r,e);return Ki.encode(n)}var Ua={};Re(Ua,{KeyType:()=>ft,PrivateKey:()=>Yn,PublicKey:()=>Wn});var ft;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(ft||(ft={}));var y3;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(y3||(y3={}));(function(r){r.codec=()=>At(y3)})(ft||(ft={}));var Wn;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ft.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.Type=ft.codec().decode(t);break;case 2:i.Data=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(Wn||(Wn={}));var Yn;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ft.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.Type=ft.codec().decode(t);break;case 2:i.Data=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(Yn||(Yn={}));var Hl=class{_key;constructor(e){this._key=Fa(e,Ba)}async verify(e,t){return qw(this._key,t,e)}marshal(){return this._key}get bytes(){return Wn.encode({Type:ft.Ed25519,Data:this.marshal()}).subarray()}equals(e){return de(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ce.digest(this.bytes);return e}},Lo=class{_key;_publicKey;constructor(e,t){this._key=Fa(e,Zi),this._publicKey=Fa(t,Ba)}async sign(e){return Vw(this._key,e)}get public(){return new Hl(this._publicKey)}marshal(){return this._key}get bytes(){return Yn.encode({Type:ft.Ed25519,Data:this.marshal()}).subarray()}equals(e){return de(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ce.digest(this.bytes);return e}async id(){let e=hi.digest(this.public.bytes);return me.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return Ma(this.bytes,e);throw new w(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function wB(r){if(r.length>Zi){r=Fa(r,Zi+Ba);let n=r.subarray(0,Zi),i=r.subarray(Zi,r.length);return new Lo(n,i)}r=Fa(r,Zi);let e=r.subarray(0,Zi),t=r.subarray(Ba);return new Lo(e,t)}function bB(r){return r=Fa(r,Ba),new Hl(r)}async function EB(){let{privateKey:r,publicKey:e}=await Fw();return new Lo(r,e)}async function w3(r){let{privateKey:e,publicKey:t}=await Kw(r);return new Lo(e,t)}function Fa(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new w(`Key must be a Uint8Array of length ${e}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}var Ste=F(Bt(),1),Rte=F(kf(),1),$w=F(tt(),1);function Qn(r,e){let t=Uint8Array.from(r.abs().toByteArray());if(t=t[0]===0?t.subarray(1):t,e!=null){if(t.length>e)throw new Error("byte array longer than desired length");t=le([new Uint8Array(e-t.length),t])}return O(t,"base64url")}function sn(r){let e=qf(r);return new $w.default.jsbn.BigInteger(O(e,"base16"),16)}function qf(r,e){let t=K(r,"base64urlpad");if(e!=null){if(t.length>e)throw new Error("byte array longer than desired length");t=le([new Uint8Array(e-t.length),t])}return t}var Gw={"P-256":256,"P-384":384,"P-521":521},vB=Object.keys(Gw),E3=vB.join(" / ");async function Ww(r){if(r!=="P-256"&&r!=="P-384"&&r!=="P-521")throw new w(`Unknown curve: ${r}. Must be ${E3}`,"ERR_INVALID_CURVE");let e=await Mt.get().subtle.generateKey({name:"ECDH",namedCurve:r},!0,["deriveBits"]),t=async(s,o)=>{let a;o!=null?a=await Mt.get().subtle.importKey("jwk",_B(r,o),{name:"ECDH",namedCurve:r},!1,["deriveBits"]):a=e.privateKey;let c=await Mt.get().subtle.importKey("jwk",Qw(r,s),{name:"ECDH",namedCurve:r},!1,[]),l=await Mt.get().subtle.deriveBits({name:"ECDH",namedCurve:r,public:c},a,Gw[r]);return new Uint8Array(l,0,l.byteLength)},n=await Mt.get().subtle.exportKey("jwk",e.publicKey);return{key:xB(n),genSharedKey:t}}var Yw={"P-256":32,"P-384":48,"P-521":66};function xB(r){if(r.crv==null||r.x==null||r.y==null)throw new w("JWK was missing components","ERR_INVALID_PARAMETERS");if(r.crv!=="P-256"&&r.crv!=="P-384"&&r.crv!=="P-521")throw new w(`Unknown curve: ${r.crv}. Must be ${E3}`,"ERR_INVALID_CURVE");let e=Yw[r.crv];return le([Uint8Array.from([4]),qf(r.x,e),qf(r.y,e)],1+e*2)}function Qw(r,e){if(r!=="P-256"&&r!=="P-384"&&r!=="P-521")throw new w(`Unknown curve: ${r}. Must be ${E3}`,"ERR_INVALID_CURVE");let t=Yw[r];if(!de(e.subarray(0,1),Uint8Array.from([4])))throw new w("Cannot unmarshal public key - invalid key format","ERR_INVALID_KEY_FORMAT");return{kty:"EC",crv:r,x:O(e.subarray(1,t+1),"base64url"),y:O(e.subarray(1+t),"base64url"),ext:!0}}var _B=(r,e)=>({...Qw(r,e.public),d:O(e.private,"base64url")});var Xw=Ww;async function jw(r,e){let t=Ki.decode(r);return Vf().decrypt(t,e)}var Zw={SHA1:20,SHA256:32,SHA512:64};var SB={SHA1:"SHA-1",SHA256:"SHA-256",SHA512:"SHA-512"},RB=async(r,e)=>{let t=await Mt.get().subtle.sign({name:"HMAC"},r,e);return new Uint8Array(t,0,t.byteLength)};async function Jw(r,e){let t=SB[r],n=await Mt.get().subtle.importKey("raw",e,{name:"HMAC",hash:{name:t}},!1,["sign"]);return{async digest(i){return RB(n,i)},length:Zw[r]}}var tb={"AES-128":{ivSize:16,keySize:16},"AES-256":{ivSize:16,keySize:32},Blowfish:{ivSize:8,keySize:32}};async function rb(r,e,t){let n=tb[r];if(n==null){let b=Object.keys(tb).join(" / ");throw new w(`unknown cipher type '${r}'. Must be ${b}`,"ERR_INVALID_CIPHER_TYPE")}if(e==null)throw new w("missing hash type","ERR_MISSING_HASH_TYPE");let i=n.keySize,s=n.ivSize,o=20,a=K("key expansion"),c=2*(s+i+o),l=await Jw(e,t),u=await l.digest(a),h=[],f=0;for(;f<c;){let b=await l.digest(le([u,a])),E=b.length;f+E>c&&(E=c-f),h.push(b),f+=E,u=await l.digest(u)}let d=c/2,p=le(h),m=p.subarray(0,d),g=p.subarray(d,c),y=b=>({iv:b.subarray(0,s),cipherKey:b.subarray(s,s+i),macKey:b.subarray(s+i)});return{k1:y(m),k2:y(g)}}var P3={};Re(P3,{RsaPrivateKey:()=>Ga,RsaPublicKey:()=>jl,fromJwk:()=>XB,generateKeyPair:()=>jB,unmarshalRsaPrivateKey:()=>YB,unmarshalRsaPublicKey:()=>QB});var Xl=F(tt(),1);var gre=F(ab(),1);var AB=F(Cs(),1);var Le=BigInt(0),pt=BigInt(1),Fs=BigInt(2),Wl=BigInt(3),cb=BigInt(8),Dt=Object.freeze({a:Le,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:pt,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),lb=(r,e)=>(r+e/Fs)/e,zf={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(r){let{n:e}=Dt,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-pt*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,o=BigInt("0x100000000000000000000000000000000"),a=lb(s*r,e),c=lb(-n*r,e),l=G(r-a*t-c*i,e),u=G(-a*n-c*s,e),h=l>o,f=u>o;if(h&&(l=e-l),f&&(u=e-u),l>o||u>o)throw new Error("splitScalarEndo: Endomorphism failed, k="+r);return{k1neg:h,k1:l,k2neg:f,k2:u}}},Xn=32,qa=32,TB=32,ub=Xn+1,hb=2*Xn+1;function fb(r){let{a:e,b:t}=Dt,n=G(r*r),i=G(n*r);return G(i+e*r+t)}var Hf=Dt.a===Le,Wf=class extends Error{constructor(e){super(e)}};function db(r){if(!(r instanceof Ue))throw new TypeError("JacobianPoint expected")}var Ue=class{constructor(e,t,n){this.x=e,this.y=t,this.z=n}static fromAffine(e){if(!(e instanceof Qe))throw new TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(Qe.ZERO)?Ue.ZERO:new Ue(e.x,e.y,pt)}static toAffineBatch(e){let t=NB(e.map(n=>n.z));return e.map((n,i)=>n.toAffine(t[i]))}static normalizeZ(e){return Ue.toAffineBatch(e).map(Ue.fromAffine)}equals(e){db(e);let{x:t,y:n,z:i}=this,{x:s,y:o,z:a}=e,c=G(i*i),l=G(a*a),u=G(t*l),h=G(s*c),f=G(G(n*a)*l),d=G(G(o*i)*c);return u===h&&f===d}negate(){return new Ue(this.x,G(-this.y),this.z)}double(){let{x:e,y:t,z:n}=this,i=G(e*e),s=G(t*t),o=G(s*s),a=e+s,c=G(Fs*(G(a*a)-i-o)),l=G(Wl*i),u=G(l*l),h=G(u-Fs*c),f=G(l*(c-h)-cb*o),d=G(Fs*t*n);return new Ue(h,f,d)}add(e){db(e);let{x:t,y:n,z:i}=this,{x:s,y:o,z:a}=e;if(s===Le||o===Le)return this;if(t===Le||n===Le)return e;let c=G(i*i),l=G(a*a),u=G(t*l),h=G(s*c),f=G(G(n*a)*l),d=G(G(o*i)*c),p=G(h-u),m=G(d-f);if(p===Le)return m===Le?this.double():Ue.ZERO;let g=G(p*p),y=G(p*g),b=G(u*g),E=G(m*m-y-Fs*b),I=G(m*(b-E)-f*y),v=G(i*a*p);return new Ue(E,I,v)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){let t=Ue.ZERO;if(typeof e=="bigint"&&e===Le)return t;let n=gb(e);if(n===pt)return this;if(!Hf){let h=t,f=this;for(;n>Le;)n&pt&&(h=h.add(f)),f=f.double(),n>>=pt;return h}let{k1neg:i,k1:s,k2neg:o,k2:a}=zf.splitScalar(n),c=t,l=t,u=this;for(;s>Le||a>Le;)s&pt&&(c=c.add(u)),a&pt&&(l=l.add(u)),u=u.double(),s>>=pt,a>>=pt;return i&&(c=c.negate()),o&&(l=l.negate()),l=new Ue(G(l.x*zf.beta),l.y,l.z),c.add(l)}precomputeWindow(e){let t=Hf?128/e+1:256/e+1,n=[],i=this,s=i;for(let o=0;o<t;o++){s=i,n.push(s);for(let a=1;a<2**(e-1);a++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,t){!t&&this.equals(Ue.BASE)&&(t=Qe.BASE);let n=t&&t._WINDOW_SIZE||1;if(256%n)throw new Error("Point#wNAF: Invalid precomputation window, must be power of 2");let i=t&&S3.get(t);i||(i=this.precomputeWindow(n),t&&n!==1&&(i=Ue.normalizeZ(i),S3.set(t,i)));let s=Ue.ZERO,o=Ue.BASE,a=1+(Hf?128/n:256/n),c=2**(n-1),l=BigInt(2**n-1),u=2**n,h=BigInt(n);for(let f=0;f<a;f++){let d=f*c,p=Number(e&l);e>>=h,p>c&&(p-=u,e+=pt);let m=d,g=d+Math.abs(p)-1,y=f%2!==0,b=p<0;p===0?o=o.add($f(y,i[m])):s=s.add($f(b,i[g]))}return{p:s,f:o}}multiply(e,t){let n=gb(e),i,s;if(Hf){let{k1neg:o,k1:a,k2neg:c,k2:l}=zf.splitScalar(n),{p:u,f:h}=this.wNAF(a,t),{p:f,f:d}=this.wNAF(l,t);u=$f(o,u),f=$f(c,f),f=new Ue(G(f.x*zf.beta),f.y,f.z),i=u.add(f),s=h.add(d)}else{let{p:o,f:a}=this.wNAF(n,t);i=o,s=a}return Ue.normalizeZ([i,s])[0]}toAffine(e){let{x:t,y:n,z:i}=this,s=this.equals(Ue.ZERO);e==null&&(e=s?cb:$a(i));let o=e,a=G(o*o),c=G(a*o),l=G(t*a),u=G(n*c),h=G(i*o);if(s)return Qe.ZERO;if(h!==pt)throw new Error("invZ was invalid");return new Qe(l,u)}};Ue.BASE=new Ue(Dt.Gx,Dt.Gy,pt);Ue.ZERO=new Ue(Le,pt,Le);function $f(r,e){let t=e.negate();return r?t:e}var S3=new WeakMap,Qe=class{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,S3.delete(this)}hasEvenY(){return this.y%Fs===Le}static fromCompressedHex(e){let t=e.length===32,n=Ks(t?e:e.subarray(1));if(!_3(n))throw new Error("Point is not on curve");let i=fb(n),s=kB(i),o=(s&pt)===pt;t?o&&(s=G(-s)):(e[0]&1)===1!==o&&(s=G(-s));let a=new Qe(n,s);return a.assertValidity(),a}static fromUncompressedHex(e){let t=Ks(e.subarray(1,Xn+1)),n=Ks(e.subarray(Xn+1,Xn*2+1)),i=new Qe(t,n);return i.assertValidity(),i}static fromHex(e){let t=Ha(e),n=t.length,i=t[0];if(n===Xn)return this.fromCompressedHex(t);if(n===ub&&(i===2||i===3))return this.fromCompressedHex(t);if(n===hb&&i===4)return this.fromUncompressedHex(t);throw new Error(`Point.fromHex: received invalid point. Expected 32-${ub} compressed bytes or ${hb} uncompressed bytes, not ${n}`)}static fromPrivateKey(e){return Qe.BASE.multiply(Qf(e))}static fromSignature(e,t,n){let{r:i,s}=yb(t);if(![0,1,2,3].includes(n))throw new Error("Cannot recover: invalid recovery bit");let o=A3(Ha(e)),{n:a}=Dt,c=n===2||n===3?i+a:i,l=$a(c,a),u=G(-o*l,a),h=G(s*l,a),f=n&1?"03":"02",d=Qe.fromHex(f+Ka(c)),p=Qe.BASE.multiplyAndAddUnsafe(d,u,h);if(!p)throw new Error("Cannot recover signature: point at infinify");return p.assertValidity(),p}toRawBytes(e=!1){return Bo(this.toHex(e))}toHex(e=!1){let t=Ka(this.x);return e?`${this.hasEvenY()?"02":"03"}${t}`:`04${t}${Ka(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){let e="Point is not on elliptic curve",{x:t,y:n}=this;if(!_3(t)||!_3(n))throw new Error(e);let i=G(n*n),s=fb(t);if(G(i-s)!==Le)throw new Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new Qe(this.x,G(-this.y))}double(){return Ue.fromAffine(this).double().toAffine()}add(e){return Ue.fromAffine(this).add(Ue.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return Ue.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,t,n){let i=Ue.fromAffine(this),s=t===Le||t===pt||this!==Qe.BASE?i.multiplyUnsafe(t):i.multiply(t),o=Ue.fromAffine(e).multiplyUnsafe(n),a=s.add(o);return a.equals(Ue.ZERO)?void 0:a.toAffine()}};Qe.BASE=new Qe(Dt.Gx,Dt.Gy);Qe.ZERO=new Qe(Le,Le);function pb(r){return Number.parseInt(r[0],16)>=8?"00"+r:r}function mb(r){if(r.length<2||r[0]!==2)throw new Error(`Invalid signature integer tag: ${za(r)}`);let e=r[1],t=r.subarray(2,e+2);if(!e||t.length!==e)throw new Error("Invalid signature integer: wrong length");if(t[0]===0&&t[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:Ks(t),left:r.subarray(e+2)}}function DB(r){if(r.length<2||r[0]!=48)throw new Error(`Invalid signature tag: ${za(r)}`);if(r[1]!==r.length-2)throw new Error("Invalid signature: incorrect length");let{data:e,left:t}=mb(r.subarray(2)),{data:n,left:i}=mb(t);if(i.length)throw new Error(`Invalid signature: left bytes after parsing: ${za(i)}`);return{r:e,s:n}}var Si=class{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromCompact(e){let t=e instanceof Uint8Array,n="Signature.fromCompact";if(typeof e!="string"&&!t)throw new TypeError(`${n}: Expected string or Uint8Array`);let i=t?za(e):e;if(i.length!==128)throw new Error(`${n}: Expected 64-byte hex`);return new Si(Yf(i.slice(0,64)),Yf(i.slice(64,128)))}static fromDER(e){let t=e instanceof Uint8Array;if(typeof e!="string"&&!t)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");let{r:n,s:i}=DB(t?e:Bo(e));return new Si(n,i)}static fromHex(e){return this.fromDER(e)}assertValidity(){let{r:e,s:t}=this;if(!Ql(e))throw new Error("Invalid Signature: r must be 0 < r < n");if(!Ql(t))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){let e=Dt.n>>pt;return this.s>e}normalizeS(){return this.hasHighS()?new Si(this.r,G(-this.s,Dt.n)):this}toDERRawBytes(){return Bo(this.toDERHex())}toDERHex(){let e=pb(Gl(this.s)),t=pb(Gl(this.r)),n=e.length/2,i=t.length/2,s=Gl(n),o=Gl(i);return`30${Gl(i+n+4)}02${o}${t}02${s}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return Bo(this.toCompactHex())}toCompactHex(){return Ka(this.r)+Ka(this.s)}};function Us(...r){if(!r.every(n=>n instanceof Uint8Array))throw new Error("Uint8Array list expected");if(r.length===1)return r[0];let e=r.reduce((n,i)=>n+i.length,0),t=new Uint8Array(e);for(let n=0,i=0;n<r.length;n++){let s=r[n];t.set(s,i),i+=s.length}return t}var CB=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function za(r){if(!(r instanceof Uint8Array))throw new Error("Expected Uint8Array");let e="";for(let t=0;t<r.length;t++)e+=CB[r[t]];return e}var PB=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000");function Ka(r){if(typeof r!="bigint")throw new Error("Expected bigint");if(!(Le<=r&&r<PB))throw new Error("Expected number 0 <= n < 2^256");return r.toString(16).padStart(64,"0")}function R3(r){let e=Bo(Ka(r));if(e.length!==32)throw new Error("Error: expected 32 bytes");return e}function Gl(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function Yf(r){if(typeof r!="string")throw new TypeError("hexToNumber: expected string, got "+typeof r);return BigInt(`0x${r}`)}function Bo(r){if(typeof r!="string")throw new TypeError("hexToBytes: expected string, got "+typeof r);if(r.length%2)throw new Error("hexToBytes: received invalid unpadded hex"+r.length);let e=new Uint8Array(r.length/2);for(let t=0;t<e.length;t++){let n=t*2,i=r.slice(n,n+2),s=Number.parseInt(i,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");e[t]=s}return e}function Ks(r){return Yf(za(r))}function Ha(r){return r instanceof Uint8Array?Uint8Array.from(r):Bo(r)}function gb(r){if(typeof r=="number"&&Number.isSafeInteger(r)&&r>0)return BigInt(r);if(typeof r=="bigint"&&Ql(r))return r;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function G(r,e=Dt.P){let t=r%e;return t>=Le?t:e+t}function Rn(r,e){let{P:t}=Dt,n=r;for(;e-- >Le;)n*=n,n%=t;return n}function kB(r){let{P:e}=Dt,t=BigInt(6),n=BigInt(11),i=BigInt(22),s=BigInt(23),o=BigInt(44),a=BigInt(88),c=r*r*r%e,l=c*c*r%e,u=Rn(l,Wl)*l%e,h=Rn(u,Wl)*l%e,f=Rn(h,Fs)*c%e,d=Rn(f,n)*f%e,p=Rn(d,i)*d%e,m=Rn(p,o)*p%e,g=Rn(m,a)*m%e,y=Rn(g,o)*p%e,b=Rn(y,Wl)*l%e,E=Rn(b,s)*d%e,I=Rn(E,t)*c%e,v=Rn(I,Fs);if(v*v%e!==r)throw new Error("Cannot find square root");return v}function $a(r,e=Dt.P){if(r===Le||e<=Le)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=G(r,e),n=e,i=Le,s=pt,o=pt,a=Le;for(;t!==Le;){let l=n/t,u=n%t,h=i-o*l,f=s-a*l;n=t,t=u,i=o,s=a,o=h,a=f}if(n!==pt)throw new Error("invert: does not exist");return G(i,e)}function NB(r,e=Dt.P){let t=new Array(r.length),n=r.reduce((s,o,a)=>o===Le?s:(t[a]=s,G(s*o,e)),pt),i=$a(n,e);return r.reduceRight((s,o,a)=>o===Le?s:(t[a]=G(s*t[a],e),G(s*o,e)),i),t}function LB(r){let e=r.length*8-qa*8,t=Ks(r);return e>0?t>>BigInt(e):t}function A3(r,e=!1){let t=LB(r);if(e)return t;let{n}=Dt;return t>=n?t-n:t}var Va,Yl,I3=class{constructor(e,t){if(this.hashLen=e,this.qByteLen=t,typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");this.v=new Uint8Array(e).fill(1),this.k=new Uint8Array(e).fill(0),this.counter=0}hmac(...e){return jn.hmacSha256(this.k,...e)}hmacSync(...e){return Yl(this.k,...e)}checkSync(){if(typeof Yl!="function")throw new Wf("hmacSha256Sync needs to be set")}incr(){if(this.counter>=1e3)throw new Error("Tried 1,000 k values for sign(), all were invalid");this.counter+=1}async reseed(e=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),e),this.v=await this.hmac(this.v),e.length!==0&&(this.k=await this.hmac(this.v,Uint8Array.from([1]),e),this.v=await this.hmac(this.v))}reseedSync(e=new Uint8Array){this.checkSync(),this.k=this.hmacSync(this.v,Uint8Array.from([0]),e),this.v=this.hmacSync(this.v),e.length!==0&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),e),this.v=this.hmacSync(this.v))}async generate(){this.incr();let e=0,t=[];for(;e<this.qByteLen;){this.v=await this.hmac(this.v);let n=this.v.slice();t.push(n),e+=this.v.length}return Us(...t)}generateSync(){this.checkSync(),this.incr();let e=0,t=[];for(;e<this.qByteLen;){this.v=this.hmacSync(this.v);let n=this.v.slice();t.push(n),e+=this.v.length}return Us(...t)}};function Ql(r){return Le<r&&r<Dt.n}function _3(r){return Le<r&&r<Dt.P}function OB(r,e,t,n=!0){let{n:i}=Dt,s=A3(r,!0);if(!Ql(s))return;let o=$a(s,i),a=Qe.BASE.multiply(s),c=G(a.x,i);if(c===Le)return;let l=G(o*G(e+t*c,i),i);if(l===Le)return;let u=new Si(c,l),h=(a.x===u.r?0:2)|Number(a.y&pt);return n&&u.hasHighS()&&(u=u.normalizeS(),h^=1),{sig:u,recovery:h}}function Qf(r){let e;if(typeof r=="bigint")e=r;else if(typeof r=="number"&&Number.isSafeInteger(r)&&r>0)e=BigInt(r);else if(typeof r=="string"){if(r.length!==2*qa)throw new Error("Expected 32 bytes of private key");e=Yf(r)}else if(r instanceof Uint8Array){if(r.length!==qa)throw new Error("Expected 32 bytes of private key");e=Ks(r)}else throw new TypeError("Expected valid private key");if(!Ql(e))throw new Error("Expected private key: 0 < key < n");return e}function BB(r){return r instanceof Qe?(r.assertValidity(),r):Qe.fromHex(r)}function yb(r){if(r instanceof Si)return r.assertValidity(),r;try{return Si.fromDER(r)}catch{return Si.fromCompact(r)}}function T3(r,e=!1){return Qe.fromPrivateKey(r).toRawBytes(e)}function wb(r){let e=r.length>Xn?r.slice(0,Xn):r;return Ks(e)}function MB(r){let e=wb(r),t=G(e,Dt.n);return bb(t<Le?e:t)}function bb(r){return R3(r)}function UB(r,e,t){if(r==null)throw new Error(`sign: expected valid message hash, not "${r}"`);let n=Ha(r),i=Qf(e),s=[bb(i),MB(n)];if(t!=null){t===!0&&(t=jn.randomBytes(Xn));let c=Ha(t);if(c.length!==Xn)throw new Error(`sign: Expected ${Xn} bytes of extra data`);s.push(c)}let o=Us(...s),a=wb(n);return{seed:o,m:a,d:i}}function FB(r,e){let{sig:t,recovery:n}=r,{der:i,recovered:s}=Object.assign({canonical:!0,der:!0},e),o=i?t.toDERRawBytes():t.toCompactRawBytes();return s?[o,n]:o}async function Eb(r,e,t={}){let{seed:n,m:i,d:s}=UB(r,e,t.extraEntropy),o=new I3(TB,qa);await o.reseed(n);let a;for(;!(a=OB(await o.generate(),i,s,t.canonical));)await o.reseed();return FB(a,t)}var KB={strict:!0};function vb(r,e,t,n=KB){let i;try{i=yb(r),e=Ha(e)}catch{return!1}let{r:s,s:o}=i;if(n.strict&&i.hasHighS())return!1;let a=A3(e),c;try{c=BB(t)}catch{return!1}let{n:l}=Dt,u=$a(o,l),h=G(a*u,l),f=G(s*u,l),d=Qe.BASE.multiplyAndAddUnsafe(c,h,f);return d?G(d.x,l)===s:!1}Qe.BASE._setWindowSize(8);var on={node:AB,web:typeof self=="object"&&"crypto"in self?self.crypto:void 0};var Gf={},jn={bytesToHex:za,hexToBytes:Bo,concatBytes:Us,mod:G,invert:$a,isValidPrivateKey(r){try{return Qf(r),!0}catch{return!1}},_bigintTo32Bytes:R3,_normalizePrivateKey:Qf,hashToPrivateKey:r=>{r=Ha(r);let e=qa+8;if(r.length<e||r.length>1024)throw new Error("Expected valid bytes of private key as per FIPS 186");let t=G(Ks(r),Dt.n-pt)+pt;return R3(t)},randomBytes:(r=32)=>{if(on.web)return on.web.getRandomValues(new Uint8Array(r));if(on.node){let{randomBytes:e}=on.node;return Uint8Array.from(e(r))}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>jn.hashToPrivateKey(jn.randomBytes(qa+8)),precompute(r=8,e=Qe.BASE){let t=e===Qe.BASE?e:new Qe(e.x,e.y);return t._setWindowSize(r),t.multiply(Wl),t},sha256:async(...r)=>{if(on.web){let e=await on.web.subtle.digest("SHA-256",Us(...r));return new Uint8Array(e)}else if(on.node){let{createHash:e}=on.node,t=e("sha256");return r.forEach(n=>t.update(n)),Uint8Array.from(t.digest())}else throw new Error("The environment doesn't have sha256 function")},hmacSha256:async(r,...e)=>{if(on.web){let t=await on.web.subtle.importKey("raw",r,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=Us(...e),i=await on.web.subtle.sign("HMAC",t,n);return new Uint8Array(i)}else if(on.node){let{createHmac:t}=on.node,n=t("sha256",r);return e.forEach(i=>n.update(i)),Uint8Array.from(n.digest())}else throw new Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:async(r,...e)=>{let t=Gf[r];if(t===void 0){let n=await jn.sha256(Uint8Array.from(r,i=>i.charCodeAt(0)));t=Us(n,n),Gf[r]=t}return jn.sha256(t,...e)},taggedHashSync:(r,...e)=>{if(typeof Va!="function")throw new Wf("sha256Sync is undefined, you need to set it");let t=Gf[r];if(t===void 0){let n=Va(Uint8Array.from(r,i=>i.charCodeAt(0)));t=Us(n,n),Gf[r]=t}return Va(t,...e)},_JacobianPoint:Ue};Object.defineProperties(jn,{sha256Sync:{configurable:!1,get(){return Va},set(r){Va||(Va=r)}},hmacSha256Sync:{configurable:!1,get(){return Yl},set(r){Yl||(Yl=r)}}});function In(r){if(isNaN(r)||r<=0)throw new w("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return jn.randomBytes(r)}var Zte=F(Of(),1),D3=F(tt(),1);function xb(r,e){return e.map(t=>sn(r[t]))}function _b(r){return D3.default.pki.setRsaPrivateKey(...xb(r,["n","e","d","p","q","dp","dq","qi"]))}function Sb(r){return D3.default.pki.setRsaPublicKey(...xb(r,["n","e"]))}var Mo={};Re(Mo,{jwkToPkcs1:()=>zB,jwkToPkix:()=>$B,pkcs1ToJwk:()=>qB,pkixToJwk:()=>HB});var tre=F(Ml(),1),rre=F(Of(),1);var Ji=F(tt(),1);function qB(r){let e=Ji.default.asn1.fromDer(O(r,"ascii")),t=Ji.default.pki.privateKeyFromAsn1(e);return{kty:"RSA",n:Qn(t.n),e:Qn(t.e),d:Qn(t.d),p:Qn(t.p),q:Qn(t.q),dp:Qn(t.dP),dq:Qn(t.dQ),qi:Qn(t.qInv),alg:"RS256"}}function zB(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new w("JWK was missing components","ERR_INVALID_PARAMETERS");let e=Ji.default.pki.privateKeyToAsn1({n:sn(r.n),e:sn(r.e),d:sn(r.d),p:sn(r.p),q:sn(r.q),dP:sn(r.dp),dQ:sn(r.dq),qInv:sn(r.qi)});return K(Ji.default.asn1.toDer(e).getBytes(),"ascii")}function HB(r){let e=Ji.default.asn1.fromDer(O(r,"ascii")),t=Ji.default.pki.publicKeyFromAsn1(e);return{kty:"RSA",n:Qn(t.n),e:Qn(t.e)}}function $B(r){if(r.n==null||r.e==null)throw new w("JWK was missing components","ERR_INVALID_PARAMETERS");let e=Ji.default.pki.publicKeyToAsn1({n:sn(r.n),e:sn(r.e)});return K(Ji.default.asn1.toDer(e).getBytes(),"ascii")}async function Rb(r){let e=await Mt.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 Tb(e);return{privateKey:t[0],publicKey:t[1]}}async function C3(r){let t=[await Mt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await GB(r)],n=await Tb({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function Ib(r,e){let t=await Mt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Mt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,Uint8Array.from(e));return new Uint8Array(n,0,n.byteLength)}async function Ab(r,e,t){let n=await Mt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Mt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t)}async function Tb(r){if(r.privateKey==null||r.publicKey==null)throw new w("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Mt.get().subtle.exportKey("jwk",r.privateKey),Mt.get().subtle.exportKey("jwk",r.publicKey)])}async function GB(r){return Mt.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function Db(r,e,t,n){let i=e?Sb(r):_b(r),s=O(Uint8Array.from(t),"ascii"),o=n(s,i);return K(o,"ascii")}function Cb(r,e){return Db(r,!0,e,(t,n)=>n.encrypt(t))}function Pb(r,e){return Db(r,!1,e,(t,n)=>n.decrypt(t))}var jl=class{_key;constructor(e){this._key=e}async verify(e,t){return Ab(this._key,t,e)}marshal(){return Mo.jwkToPkix(this._key)}get bytes(){return Wn.encode({Type:ft.RSA,Data:this.marshal()}).subarray()}encrypt(e){return Cb(this._key,e)}equals(e){return de(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ce.digest(this.bytes);return e}},Ga=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return In(16)}async sign(e){return Ib(this._key,e)}get public(){if(this._publicKey==null)throw new w("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new jl(this._publicKey)}decrypt(e){return Pb(this._key,e)}marshal(){return Mo.jwkToPkcs1(this._key)}get bytes(){return Yn.encode({Type:ft.RSA,Data:this.marshal()}).subarray()}equals(e){return de(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ce.digest(this.bytes);return e}async id(){let e=await this.public.hash();return O(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8"){let n=new Xl.default.util.ByteBuffer(this.marshal()),i=Xl.default.asn1.fromDer(n),s=Xl.default.pki.privateKeyFromAsn1(i),o={algorithm:"aes256",count:1e4,saltSize:128/8,prfAlgorithm:"sha512"};return Xl.default.pki.encryptRsaPrivateKey(s,e,o)}else{if(t==="libp2p-key")return Ma(this.bytes,e);throw new w(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}};async function YB(r){let e=Mo.pkcs1ToJwk(r),t=await C3(e);return new Ga(t.privateKey,t.publicKey)}function QB(r){let e=Mo.pkixToJwk(r);return new jl(e)}async function XB(r){let e=await C3(r);return new Ga(e.privateKey,e.publicKey)}async function jB(r){let e=await Rb(r);return new Ga(e.privateKey,e.publicKey)}var N3={};Re(N3,{Secp256k1PrivateKey:()=>Jl,Secp256k1PublicKey:()=>Zl,generateKeyPair:()=>tM,unmarshalSecp256k1PrivateKey:()=>JB,unmarshalSecp256k1PublicKey:()=>eM});function kb(){return jn.randomPrivateKey()}async function Nb(r,e){let{digest:t}=await Ce.digest(e);try{return await Eb(t,r)}catch(n){throw new w(String(n),"ERR_INVALID_INPUT")}}async function Lb(r,e,t){try{let{digest:n}=await Ce.digest(t);return vb(e,n,r)}catch(n){throw new w(String(n),"ERR_INVALID_INPUT")}}function Ob(r){return Qe.fromHex(r).toRawBytes(!0)}function Bb(r){try{T3(r,!0)}catch(e){throw new w(String(e),"ERR_INVALID_PRIVATE_KEY")}}function k3(r){try{Qe.fromHex(r)}catch(e){throw new w(String(e),"ERR_INVALID_PUBLIC_KEY")}}function Mb(r){try{return T3(r,!0)}catch(e){throw new w(String(e),"ERR_INVALID_PRIVATE_KEY")}}var Zl=class{_key;constructor(e){k3(e),this._key=e}async verify(e,t){return Lb(this._key,t,e)}marshal(){return Ob(this._key)}get bytes(){return Wn.encode({Type:ft.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return de(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ce.digest(this.bytes);return e}},Jl=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??Mb(e),Bb(this._key),k3(this._publicKey)}async sign(e){return Nb(this._key,e)}get public(){return new Zl(this._publicKey)}marshal(){return this._key}get bytes(){return Yn.encode({Type:ft.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return de(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ce.digest(this.bytes);return e}async id(){let e=await this.public.hash();return O(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return Ma(this.bytes,e);throw new w(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function JB(r){return new Jl(r)}function eM(r){return new Zl(r)}async function tM(){let r=kb();return new Jl(r)}var Ri={rsa:P3,ed25519:b3,secp256k1:N3};function L3(r){let e=Object.keys(Ri).join(" / ");return new w(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function O3(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return Ri[r];throw L3(r)}async function eu(r,e){return O3(r).generateKeyPair(e??2048)}async function rM(r,e,t){if(r.toLowerCase()!=="ed25519")throw new w("Seed key derivation is unimplemented for RSA or secp256k1","ERR_UNSUPPORTED_KEY_DERIVATION_TYPE");return w3(e)}function rr(r){let e=Wn.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case ft.RSA:return Ri.rsa.unmarshalRsaPublicKey(t);case ft.Ed25519:return Ri.ed25519.unmarshalEd25519PublicKey(t);case ft.Secp256k1:return Ri.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw L3(e.Type??"RSA")}}function Wa(r,e){return e=(e??"rsa").toLowerCase(),O3(e),r.bytes}async function an(r){let e=Yn.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case ft.RSA:return Ri.rsa.unmarshalRsaPrivateKey(t);case ft.Ed25519:return Ri.ed25519.unmarshalEd25519PrivateKey(t);case ft.Secp256k1:return Ri.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw L3(e.Type??"RSA")}}function B3(r,e){return e=(e??"rsa").toLowerCase(),O3(e),r.bytes}async function Ya(r,e){try{let i=await jw(r,e);return await an(i)}catch{}let t=Xf.default.pki.decryptRsaPrivateKey(r,e);if(t===null)throw new w("Cannot read the key, most likely the password is wrong or not a RSA key","ERR_CANNOT_DECRYPT_PEM");let n=Xf.default.asn1.toDer(Xf.default.pki.privateKeyToAsn1(t));return n=K(n.getBytes(),"ascii"),Ri.rsa.unmarshalRsaPrivateKey(n)}var tu=Symbol.for("@libp2p/content-routing");var Uo=Symbol.for("@libp2p/peer-discovery");var ru=Symbol.for("@libp2p/peer-routing");var Fe=class extends EventTarget{#e=new Map;listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let i=this.#e.get(e);i==null&&(i=[],this.#e.set(e,i)),i.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let i=this.#e.get(e);i!=null&&(i=i.filter(({callback:s})=>s!==t),this.#e.set(e,i))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:i})=>!i),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t){return this.dispatchEvent(new Je(e,t))}},M3=class extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}},Je=globalThis.CustomEvent??M3;var aE=F(Gb(),1);var tE=F(eE(),1),Vs=tE.default;var Oe;(function(r){r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",r.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",r.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",r.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",r.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",r.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",r.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",r.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",r.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",r.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",r.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",r.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",r.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",r.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH"})(Oe||(Oe={}));var Gre=F(Sf(),1),EM=F(tt(),1);var nE=F(Z2(),1),iE=F(Bt(),1),rE={sha1:"sha1","sha2-256":"sha256","sha2-512":"sha512"};function nu(r,e,t,n,i){if(i!=="sha1"&&i!=="sha2-256"&&i!=="sha2-512"){let a=Object.keys(rE).join(" / ");throw new w(`Hash '${i}' is unknown or not supported. Must be ${a}`,"ERR_UNSUPPORTED_HASH_TYPE")}let s=rE[i],o=(0,nE.default)(r,e,t,n,s);return iE.default.encode64(o,null)}var F3=Symbol.for("@libp2p/peer-id");function e0(r){return r!=null&&!!r[F3]}var _M=Symbol.for("nodejs.util.inspect.custom"),sE=Object.values(wn).map(r=>r.decoder).reduce((r,e)=>r.or(e),wn.identity.decoder),oE=114,K3=36,V3=37,iu=class{constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}get[F3](){return!0}toString(){return this.string==null&&(this.string=me.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return ee.createV1(oE,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e instanceof Uint8Array)return de(this.multihash.bytes,e);if(typeof e=="string")return oe(e).equals(this);if(e?.multihash?.bytes!=null)return de(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[_M](){return`PeerId(${this.toString()})`}},ja=class extends iu{constructor(e){super({...e,type:"RSA"}),this.type="RSA",this.publicKey=e.publicKey}},Za=class extends iu{constructor(e){super({...e,type:"Ed25519"}),this.type="Ed25519",this.publicKey=e.multihash.digest}},Ja=class extends iu{constructor(e){super({...e,type:"secp256k1"}),this.type="secp256k1",this.publicKey=e.multihash.digest}};function oe(r,e){if(e=e??sE,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=ui(me.decode(`z${r}`));return r.startsWith("12D")?new Za({multihash:t}):r.startsWith("16U")?new Ja({multihash:t}):new ja({multihash:t})}return vt(sE.decode(r))}function vt(r){try{let e=ui(r);if(e.code===hi.code){if(e.digest.length===K3)return new Za({multihash:e});if(e.digest.length===V3)return new Ja({multihash:e})}if(e.code===Ce.code)return new ja({multihash:e})}catch{return SM(ee.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function SM(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==oE)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===Ce.code)return new ja({multihash:r.multihash});if(e.code===hi.code){if(e.digest.length===K3)return new Za({multihash:r.multihash});if(e.digest.length===V3)return new Ja({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function zt(r,e){return r.length===K3?new Za({multihash:Bn(hi.code,r),privateKey:e}):r.length===V3?new Ja({multihash:Bn(hi.code,r),privateKey:e}):new ja({multihash:await Ce.digest(r),publicKey:r,privateKey:e})}var t0=T("libp2p:keychain"),IM="/pkcs8/",cE="/info/",Fo=new WeakMap,Ko={minKeyLength:112/8,minSaltLength:128/8,minIterationCount:1e3},q3={dek:{keyLength:512/8,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"}};function es(r){return r==null||typeof r!="string"?!1:r===(0,aE.default)(r.trim())&&r.length>0}async function nt(){let t=Math.random()*800+200;await new Promise(n=>setTimeout(n,t))}function Ii(r){return new ve(IM+r)}function qs(r){return new ve(cE+r)}var Vo=class{constructor(e,t){if(this.components=e,this.init=Vs(q3,t),this.init.pass!=null&&this.init.pass?.length<20)throw new Error("pass must be least 20 characters");if(this.init.dek?.keyLength!=null&&this.init.dek.keyLength<Ko.minKeyLength)throw new Error(`dek.keyLength must be least ${Ko.minKeyLength} bytes`);if(this.init.dek?.salt?.length!=null&&this.init.dek.salt.length<Ko.minSaltLength)throw new Error(`dek.saltLength must be least ${Ko.minSaltLength} bytes`);if(this.init.dek?.iterationCount!=null&&this.init.dek.iterationCount<Ko.minIterationCount)throw new Error(`dek.iterationCount must be least ${Ko.minIterationCount}`);let n=this.init.pass!=null&&this.init.dek?.salt!=null?nu(this.init.pass,this.init.dek?.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";Fo.set(this,{dek:n})}static generateOptions(){let e=Object.assign({},q3),t=Math.ceil(Ko.minSaltLength/3)*3;return e.dek.salt=O(In(t),"base64"),e}static get options(){return q3}async createKey(e,t,n=2048){if(!es(e)||e==="self")throw await nt(),new w("Invalid key name",Oe.ERR_INVALID_KEY_NAME);if(typeof t!="string")throw await nt(),new w("Invalid key type",Oe.ERR_INVALID_KEY_TYPE);let i=Ii(e);if(await this.components.datastore.has(i))throw await nt(),new w("Key name already exists",Oe.ERR_KEY_ALREADY_EXISTS);switch(t.toLowerCase()){case"rsa":if(!Number.isSafeInteger(n)||n<2048)throw await nt(),new w("Invalid RSA key size",Oe.ERR_INVALID_KEY_SIZE);break;default:break}let o;try{let a=await eu(t,n),c=await a.id(),l=Fo.get(this);if(l==null)throw new w("dek missing",Oe.ERR_INVALID_PARAMETERS);let u=l.dek,h=await a.export(u);o={name:e,id:c};let f=this.components.datastore.batch();f.put(i,K(h)),f.put(qs(e),K(JSON.stringify(o))),await f.commit()}catch(a){throw await nt(),a}return o}async listKeys(){let e={prefix:cE},t=[];for await(let n of this.components.datastore.query(e))t.push(JSON.parse(O(n.value)));return t}async findKeyById(e){try{let n=(await this.listKeys()).find(i=>i.id===e);if(n==null)throw new w(`Key with id '${e}' does not exist.`,Oe.ERR_KEY_NOT_FOUND);return n}catch(t){throw await nt(),t}}async findKeyByName(e){if(!es(e))throw await nt(),new w(`Invalid key name '${e}'`,Oe.ERR_INVALID_KEY_NAME);let t=qs(e);try{let n=await this.components.datastore.get(t);return JSON.parse(O(n))}catch(n){throw await nt(),t0.error(n),new w(`Key '${e}' does not exist.`,Oe.ERR_KEY_NOT_FOUND)}}async removeKey(e){if(!es(e)||e==="self")throw await nt(),new w(`Invalid key name '${e}'`,Oe.ERR_INVALID_KEY_NAME);let t=Ii(e),n=await this.findKeyByName(e),i=this.components.datastore.batch();return i.delete(t),i.delete(qs(e)),await i.commit(),n}async renameKey(e,t){if(!es(e)||e==="self")throw await nt(),new w(`Invalid old key name '${e}'`,Oe.ERR_OLD_KEY_NAME_INVALID);if(!es(t)||t==="self")throw await nt(),new w(`Invalid new key name '${t}'`,Oe.ERR_NEW_KEY_NAME_INVALID);let n=Ii(e),i=Ii(t),s=qs(e),o=qs(t);if(await this.components.datastore.has(i))throw await nt(),new w(`Key '${t}' already exists`,Oe.ERR_KEY_ALREADY_EXISTS);try{let c=await this.components.datastore.get(n),l=await this.components.datastore.get(s),u=JSON.parse(O(l));u.name=t;let h=this.components.datastore.batch();return h.put(i,c),h.put(o,K(JSON.stringify(u))),h.delete(n),h.delete(s),await h.commit(),u}catch(c){throw await nt(),c}}async exportKey(e,t){if(!es(e))throw await nt(),new w(`Invalid key name '${e}'`,Oe.ERR_INVALID_KEY_NAME);if(t==null)throw await nt(),new w("Password is required",Oe.ERR_PASSWORD_REQUIRED);let n=Ii(e);try{let i=await this.components.datastore.get(n),s=O(i),o=Fo.get(this);if(o==null)throw new w("dek missing",Oe.ERR_INVALID_PARAMETERS);let a=o.dek;return await(await Ya(s,a)).export(t)}catch(i){throw await nt(),i}}async exportPeerId(e){let t="temporary-password",n=await this.exportKey(e,t),i=await Ya(n,t);return await zt(i.public.bytes,i.bytes)}async importKey(e,t,n){if(!es(e)||e==="self")throw await nt(),new w(`Invalid key name '${e}'`,Oe.ERR_INVALID_KEY_NAME);if(t==null)throw await nt(),new w("PEM encoded key is required",Oe.ERR_PEM_REQUIRED);let i=Ii(e);if(await this.components.datastore.has(i))throw await nt(),new w(`Key '${e}' already exists`,Oe.ERR_KEY_ALREADY_EXISTS);let o;try{o=await Ya(t,n)}catch{throw await nt(),new w("Cannot read the key, most likely the password is wrong",Oe.ERR_CANNOT_READ_KEY)}let a;try{a=await o.id();let u=Fo.get(this);if(u==null)throw new w("dek missing",Oe.ERR_INVALID_PARAMETERS);let h=u.dek;t=await o.export(h)}catch(u){throw await nt(),u}let c={name:e,id:a},l=this.components.datastore.batch();return l.put(i,K(t)),l.put(qs(e),K(JSON.stringify(c))),await l.commit(),c}async importPeer(e,t){try{if(!es(e))throw new w(`Invalid key name '${e}'`,Oe.ERR_INVALID_KEY_NAME);if(t==null)throw new w("PeerId is required",Oe.ERR_MISSING_PRIVATE_KEY);if(t.privateKey==null)throw new w("PeerId.privKey is required",Oe.ERR_MISSING_PRIVATE_KEY);let n=await an(t.privateKey),i=Ii(e);if(await this.components.datastore.has(i))throw await nt(),new w(`Key '${e}' already exists`,Oe.ERR_KEY_ALREADY_EXISTS);let o=Fo.get(this);if(o==null)throw new w("dek missing",Oe.ERR_INVALID_PARAMETERS);let a=o.dek,c=await n.export(a),l={name:e,id:t.toString()},u=this.components.datastore.batch();return u.put(i,K(c)),u.put(qs(e),K(JSON.stringify(l))),await u.commit(),l}catch(n){throw await nt(),n}}async getPrivateKey(e){if(!es(e))throw await nt(),new w(`Invalid key name '${e}'`,Oe.ERR_INVALID_KEY_NAME);try{let t=Ii(e),n=await this.components.datastore.get(t);return O(n)}catch(t){throw await nt(),t0.error(t),new w(`Key '${e}' does not exist.`,Oe.ERR_KEY_NOT_FOUND)}}async rotateKeychainPass(e,t){if(typeof e!="string")throw await nt(),new w(`Invalid old pass type '${typeof e}'`,Oe.ERR_INVALID_OLD_PASS_TYPE);if(typeof t!="string")throw await nt(),new w(`Invalid new pass type '${typeof t}'`,Oe.ERR_INVALID_NEW_PASS_TYPE);if(t.length<20)throw await nt(),new w(`Invalid pass length ${t.length}`,Oe.ERR_INVALID_PASS_LENGTH);t0("recreating keychain");let n=Fo.get(this);if(n==null)throw new w("dek missing",Oe.ERR_INVALID_PARAMETERS);let i=n.dek;this.init.pass=t;let s=t!=null&&this.init.dek?.salt!=null?nu(t,this.init.dek.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";Fo.set(this,{dek:s});let o=await this.listKeys();for(let a of o){let c=await this.components.datastore.get(Ii(a.name)),l=O(c),u=await Ya(l,i),h=s.toString(),f=await u.export(h),d=this.components.datastore.batch(),p={name:a.name,id:a.id};d.put(Ii(a.name),K(f)),d.put(qs(a.name),K(JSON.stringify(p))),await d.commit()}t0("keychain reconstructed")}};function ts(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),i=n.value;return n.done===!0||i==null?{done:!0,value:void 0}:{done:!1,value:e(i)}}};return t}var Fr=class{constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){this.map.delete(e.toString())}entries(){return ts(this.map.entries(),e=>[oe(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,oe(n),this)})}get(e){return this.map.get(e.toString())}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),t)}keys(){return ts(this.map.keys(),e=>oe(e))}values(){return this.map.values()}get size(){return this.map.size}};var vr=class{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 ts(this.set.entries(),e=>{let t=oe(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=oe(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return ts(this.set.values(),e=>oe(e))}intersection(e){let t=new vr;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new vr;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new vr;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var ec=class{constructor(e){if(this.list=[],e!=null)for(let t of e)this.list.push(t.toString())}[Symbol.iterator](){return ts(this.list.entries(),e=>oe(e[1]))}concat(e){let t=new ec(this);for(let n of e)t.push(n);return t}entries(){return ts(this.list.entries(),e=>[e[0],oe(e[1])])}every(e){return this.list.every((t,n)=>e(oe(t),n,this))}filter(e){let t=new ec;return this.list.forEach((n,i)=>{let s=oe(n);e(s,i,this)&&t.push(s)}),t}find(e){let t=this.list.find((n,i)=>e(oe(n),i,this));if(t!=null)return oe(t)}findIndex(e){return this.list.findIndex((t,n)=>e(oe(t),n,this))}forEach(e){this.list.forEach((t,n)=>{e(oe(t),n,this)})}includes(e){return this.list.includes(e.toString())}indexOf(e){return this.list.indexOf(e.toString())}pop(){let e=this.list.pop();if(e!=null)return oe(e)}push(...e){for(let t of e)this.list.push(t.toString())}shift(){let e=this.list.shift();if(e!=null)return oe(e)}unshift(...e){let t=this.list.length;for(let n=e.length-1;n>-1;n--)t=this.list.unshift(e[n].toString());return t}get length(){return this.list.length}};var z3;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.id!=null&&(n.uint32(10),n.bytes(t.id)),t.pubKey!=null&&(n.uint32(18),n.bytes(t.pubKey)),t.privKey!=null&&(n.uint32(26),n.bytes(t.privKey)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.id=t.bytes();break;case 2:i.pubKey=t.bytes();break;case 3:i.privKey=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(z3||(z3={}));var r0=async()=>{let r=await eu("Ed25519"),e=await AM(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function lE(r){return await zt(Wa(r))}async function AM(r){return await zt(Wa(r.public),B3(r))}var uE={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var su;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.publicKey=t.bytes();break;case 2:i.payloadType=t.bytes();break;case 3:i.payload=t.bytes();break;case 5:i.signature=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(su||(su={}));var TM,Wt=class{constructor(e){let{peerId:t,payloadType:n,payload:i,signature:s}=e;this.peerId=t,this.payloadType=n,this.payload=i,this.signature=s}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=su.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return de(this.marshal(),e.marshal())}async validate(e){let t=hE(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return await rr(this.peerId.publicKey).verify(t.subarray(),this.signature)}};TM=Wt;Wt.createFromProtobuf=async r=>{let e=su.decode(r),t=await zt(e.publicKey);return new Wt({peerId:t,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};Wt.seal=async(r,e)=>{if(e.privateKey==null)throw new Error("Missing private key");let t=r.domain,n=r.codec,i=r.marshal(),s=hE(t,n,i),a=await(await an(e.privateKey)).sign(s.subarray());return new Wt({peerId:e,payloadType:n,payload:i,signature:a})};Wt.openAndCertify=async(r,e)=>{let t=await Wt.createFromProtobuf(r);if(!await t.validate(e))throw new w("envelope signature is not valid for the given domain",uE.ERR_SIGNATURE_NOT_VALID);return t};var hE=(r,e,t)=>{let n=K(r),i=ot.encode(n.byteLength),s=ot.encode(e.length),o=ot.encode(t.length);return new j(i,n,s,e,o,t)};var tm=F(Eo(),1);var nc=F(Eo(),1);var n0=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,i){return this.readAtomically(()=>{let s=0,o=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*i)-1;for(;;){let u=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let f=Number.parseInt(h,e);if(!Number.isNaN(f))return f});if(u===void 0)break;if(s*=e,s+=u,s>l||(o+=1,t!==void 0&&o>t))return}if(o!==0)return!n&&c&&o>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;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 i=n*2;if(n<t.length-3){let o=this.readSeparator(":",n,()=>this.readIPv4Addr());if(o!==void 0)return t[i]=o[0],t[i+1]=o[1],t[i+2]=o[2],t[i+3]=o[3],[i+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[i,!1];t[i]=s>>8,t[i+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,i]=e(t);if(n===16)return t;if(i||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),o=16-(n+2),[a]=e(s.subarray(0,o));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var fE=45,DM=15,tc=new n0;function H3(r){if(!(r.length>DM))return tc.new(r).parseWith(()=>tc.readIPv4Addr())}function $3(r){if(!(r.length>fE))return tc.new(r).parseWith(()=>tc.readIPv6Addr())}function i0(r){if(!(r.length>fE))return tc.new(r).parseWith(()=>tc.readIPAddr())}var die=parseInt("0xFFFF",16),pie=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var Ai=F(Eo(),1);function mE(r){return!!H3(r)}function gE(r){return!!$3(r)}function rc(r){return!!i0(r)}var yE=mE,LM=gE,G3=function(r){let e=0;if(r=r.toString().trim(),yE(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(LM(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=yE(t[n]),o;s&&(o=G3(t[n]),t[n]=O(o.slice(0,2),"base16")),o!=null&&++n<8&&t.splice(n,0,O(o.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 s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let i=new Uint8Array(e+16);for(n=0;n<t.length;n++){let s=parseInt(t[n],16);i[e++]=s>>8&255,i[e++]=s&255}return i}throw new Error("invalid ip address")},wE=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let i=[];for(let s=0;s<t;s++)i.push(r[e+s]);return i.join(".")}if(t===16){let i=[];for(let s=0;s<t;s+=2)i.push(n.getUint16(e+s).toString(16));return i.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var ou={},W3={},BM=[[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"],[777,-1,"memory"]];BM.forEach(r=>{let e=MM(...r);W3[e.code]=e,ou[e.name]=e});function MM(r,e,t,n,i){return{code:r,size:e,name:t,resolvable:!!n,path:!!i}}function X(r){if(typeof r=="number"){if(W3[r]!=null)return W3[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(ou[r]!=null)return ou[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var jie=X("ip4"),Zie=X("ip6"),Jie=X("ipcidr");function s0(r,e){switch(X(r).code){case 4:case 41:return FM(e);case 42:return vE(e);case 6:case 273:case 33:case 132:return SE(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return vE(e);case 421:return zM(e);case 444:return xE(e);case 445:return xE(e);case 466:return qM(e);default:return O(e,"base16")}}function _E(r,e){switch(X(r).code){case 4:return bE(e);case 41:return bE(e);case 42:return EE(e);case 6:case 273:case 33:case 132:return Q3(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return EE(e);case 421:return KM(e);case 444:return HM(e);case 445:return $M(e);case 466:return VM(e);default:return K(e,"base16")}}var Y3=Object.values(wn).map(r=>r.decoder),UM=function(){let r=Y3[0].or(Y3[1]);return Y3.slice(2).forEach(e=>r=r.or(e)),r}();function bE(r){if(!rc(r))throw new Error("invalid ip address");return G3(r)}function FM(r){let e=wE(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!rc(e))throw new Error("invalid ip address");return e}function Q3(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function SE(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function EE(r){let e=K(r),t=Uint8Array.from(Ai.default.encode(e.length));return le([t,e],t.length+e.length)}function vE(r){let e=Ai.default.decode(r);if(r=r.slice(Ai.default.decode.bytes),r.length!==e)throw new Error("inconsistent lengths");return O(r)}function KM(r){let e;r[0]==="Q"||r[0]==="1"?e=ui(me.decode(`z${r}`)).bytes:e=ee.parse(r).multihash.bytes;let t=Uint8Array.from(Ai.default.encode(e.length));return le([t,e],t.length+e.length)}function VM(r){let e=UM.decode(r),t=Uint8Array.from(Ai.default.encode(e.length));return le([t,e],t.length+e.length)}function qM(r){let e=Ai.default.decode(r),t=r.slice(Ai.default.decode.bytes);if(t.length!==e)throw new Error("inconsistent lengths");return"u"+O(t,"base64url")}function zM(r){let e=Ai.default.decode(r),t=r.slice(Ai.default.decode.bytes);if(t.length!==e)throw new Error("inconsistent lengths");return O(t,"base58btc")}function HM(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=Gt.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=Q3(n);return le([t,i],t.length+i.length)}function $M(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=Gt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=Q3(n);return le([t,i],t.length+i.length)}function xE(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=O(e,"base32"),i=SE(t);return`${n}:${i}`}function GM(r){let e=[],t=r.split("/").slice(1);if(t.length===1&&t[0]==="")return[];for(let n=0;n<t.length;n++){let i=t[n],s=X(i);if(s.size===0){e.push([i]);continue}if(n++,n>=t.length)throw IE("invalid address: "+r);if(s.path===!0){e.push([i,em(t.slice(n).join("/"))]);break}e.push([i,t[n]])}return e}function WM(r){let e=[];return r.map(t=>{let n=c0(t);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),em(e.join("/"))}function YM(r){return r.map(e=>{Array.isArray(e)||(e=[e]);let t=c0(e);return e.length>1?[t.code,_E(t.code,e[1])]:[t.code]})}function X3(r){return r.map(e=>{let t=c0(e);return e[1]!=null?[t.code,s0(t.code,e[1])]:[t.code]})}function j3(r){return a0(le(r.map(e=>{let t=c0(e),n=Uint8Array.from(nc.default.encode(t.code));return e.length>1&&e[1]!=null&&(n=le([n,e[1]])),n})))}function Z3(r,e){return r.size>0?r.size/8:r.size===0?0:nc.default.decode(e)+(nc.default.decode.bytes??0)}function o0(r){let e=[],t=0;for(;t<r.length;){let n=nc.default.decode(r,t),i=nc.default.decode.bytes??0,s=X(n),o=Z3(s,r.slice(t+i));if(o===0){e.push([n]),t+=i;continue}let a=r.slice(t+i,t+i+o);if(t+=o+i,t>r.length)throw IE("Invalid address Uint8Array: "+O(r,"base16"));e.push([n,a])}return e}function J3(r){let e=o0(r),t=X3(e);return WM(t)}function QM(r){r=em(r);let e=GM(r),t=YM(e);return j3(t)}function RE(r){return QM(r)}function a0(r){let e=XM(r);if(e!=null)throw e;return Uint8Array.from(r)}function XM(r){try{o0(r)}catch(e){return e}}function em(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function IE(r){return new Error("Error parsing address: "+r)}function c0(r){return X(r[0])}var ZM=Symbol.for("nodejs.util.inspect.custom"),JM=[X("dns").code,X("dns4").code,X("dns6").code,X("dnsaddr").code],rm=new Map,AE=Symbol.for("@multiformats/js-multiaddr/multiaddr");function qo(r){return!!r?.[AE]}var rs=class{bytes;#e;#t;#n;#r;[AE]=!0;constructor(e){if(e==null&&(e=""),e instanceof Uint8Array)this.bytes=a0(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);this.bytes=RE(e)}else if(qo(e))this.bytes=a0(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr")}toString(){return this.#e==null&&(this.#e=J3(this.bytes)),this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,i,s="",o=X("tcp"),a=X("udp"),c=X("ip4"),l=X("ip6"),u=X("dns6"),h=X("ip6zone");for(let[d,p]of this.stringTuples())d===h.code&&(s=`%${p??""}`),JM.includes(d)&&(t=o.name,i=443,n=`${p??""}${s}`,e=d===u.code?6:4),(d===o.code||d===a.code)&&(t=X(d).name,i=parseInt(p??"")),(d===c.code||d===l.code)&&(t=X(d).name,n=`${p??""}${s}`,e=d===l.code?6:4);if(e==null||t==null||n==null||i==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:i}}protos(){return this.protoCodes().map(e=>Object.assign({},X(e)))}protoCodes(){let e=[],t=this.bytes,n=0;for(;n<t.length;){let i=tm.default.decode(t,n),s=tm.default.decode.bytes??0,o=X(i),a=Z3(o,t.slice(n+s));n+=a+s,e.push(i)}return e}protoNames(){return this.protos().map(e=>e.name)}tuples(){return this.#t==null&&(this.#t=o0(this.bytes)),this.#t}stringTuples(){return this.#n==null&&(this.#n=X3(this.tuples())),this.#n}encapsulate(e){return e=new rs(e),new rs(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),i=n.lastIndexOf(t);if(i<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new rs(n.slice(0,i))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new rs(j3(t.slice(0,n)));return this}getPeerId(){try{let t=this.stringTuples().filter(n=>n[0]===ou.ipfs.code).pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?O(me.decode(`z${n}`),"base58btc"):O(ee.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){if(this.#r===void 0)try{this.#r=this.stringTuples().filter(e=>X(e[0]).path===!0)[0][1],this.#r==null&&(this.#r=null)}catch{this.#r=null}return this.#r}equals(e){return de(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=rm.get(t.name);if(n==null)throw new w(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(s=>new rs(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[ZM](){return`Multiaddr(${J3(this.bytes)})`}};function se(r){return new rs(r)}function TE(r,e){let t=(n,i)=>n.toString().localeCompare(i.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,i)=>e[i].equals(n)))}var au;(function(r){let e;(function(n){let i;n.codec=()=>(i==null&&(i=ne((s,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(o.uint32(10),o.bytes(s.multiaddr)),a.lengthDelimited!==!1&&o.ldelim()},(s,o)=>{let a={multiaddr:new Uint8Array(0)},c=o==null?s.len:s.pos+o;for(;s.pos<c;){let l=s.uint32();switch(l>>>3){case 1:a.multiaddr=s.bytes();break;default:s.skipType(l&7);break}}return a})),i),n.encode=s=>re(s,n.codec()),n.decode=s=>te(s,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=ne((n,i,s={})=>{if(s.lengthDelimited!==!1&&i.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(i.uint32(10),i.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(i.uint32(16),i.uint64(n.seq)),n.addresses!=null)for(let o of n.addresses)i.uint32(26),r.AddressInfo.codec().encode(o,i);s.lengthDelimited!==!1&&i.ldelim()},(n,i)=>{let s={peerId:new Uint8Array(0),seq:0n,addresses:[]},o=i==null?n.len:n.pos+i;for(;n.pos<o;){let a=n.uint32();switch(a>>>3){case 1:s.peerId=n.bytes();break;case 2:s.seq=n.uint64();break;case 3:s.addresses.push(r.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return s})),t),r.encode=n=>re(n,r.codec()),r.decode=n=>te(n,r.codec())})(au||(au={}));var DE="libp2p-peer-record",CE=Uint8Array.from([3,1]);var Ut=class{constructor(e){this.domain=Ut.DOMAIN,this.codec=Ut.CODEC;let{peerId:t,multiaddrs:n,seqNumber:i}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=i??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=au.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof Ut)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!TE(this.multiaddrs,e.multiaddrs))}};Ut.createFromProtobuf=r=>{let e=au.decode(r),t=vt(e.peerId),n=(e.addresses??[]).map(s=>se(s.multiaddr)),i=e.seq;return new Ut({peerId:t,multiaddrs:n,seqNumber:i})};Ut.DOMAIN=DE;Ut.CODEC=CE;var cr={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var ic;(function(r){let e;(function(i){let s;i.codec=()=>(s==null&&(s=ne((o,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),o.key!=null&&o.key!==""&&(a.uint32(10),a.string(o.key)),o.value!=null&&o.value.byteLength>0&&(a.uint32(18),a.bytes(o.value)),c.lengthDelimited!==!1&&a.ldelim()},(o,a)=>{let c={key:"",value:new Uint8Array(0)},l=a==null?o.len:o.pos+a;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:c.key=o.string();break;case 2:c.value=o.bytes();break;default:o.skipType(u&7);break}}return c})),s),i.encode=o=>re(o,i.codec()),i.decode=o=>te(o,i.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(i){let s;i.codec=()=>(s==null&&(s=ne((o,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),o.key!=null&&o.key!==""&&(a.uint32(10),a.string(o.key)),o.value!=null&&(a.uint32(18),u0.codec().encode(o.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(o,a)=>{let c={key:""},l=a==null?o.len:o.pos+a;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:c.key=o.string();break;case 2:c.value=u0.codec().decode(o,o.uint32());break;default:o.skipType(u&7);break}}return c})),s),i.encode=o=>re(o,i.codec()),i.decode=o=>te(o,i.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=ne((i,s,o={})=>{if(o.lengthDelimited!==!1&&s.fork(),i.addresses!=null)for(let a of i.addresses)s.uint32(10),l0.codec().encode(a,s);if(i.protocols!=null)for(let a of i.protocols)s.uint32(18),s.string(a);if(i.publicKey!=null&&(s.uint32(34),s.bytes(i.publicKey)),i.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(i.peerRecordEnvelope)),i.metadata!=null&&i.metadata.size!==0)for(let[a,c]of i.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(i.tags!=null&&i.tags.size!==0)for(let[a,c]of i.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.addresses.push(l0.codec().decode(i,i.uint32()));break;case 2:o.protocols.push(i.string());break;case 4:o.publicKey=i.bytes();break;case 5:o.peerRecordEnvelope=i.bytes();break;case 6:{let l=r.Peer$metadataEntry.codec().decode(i,i.uint32());o.metadata.set(l.key,l.value);break}case 7:{let l=r.Peer$tagsEntry.codec().decode(i,i.uint32());o.tags.set(l.key,l.value);break}default:i.skipType(c&7);break}}return o})),n),r.encode=i=>re(i,r.codec()),r.decode=i=>te(i,r.codec())})(ic||(ic={}));var l0;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={multiaddr:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.multiaddr=t.bytes();break;case 2:i.isCertified=t.bool();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(l0||(l0={}));var u0;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.value=t.uint32();break;case 2:i.expiry=t.uint64();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(u0||(u0={}));async function sc(r,e){let t=ic.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=await lE(rr(t.publicKey)));let n=new Map,i=BigInt(Date.now());for(let[s,o]of t.tags.entries())o.expiry!=null&&o.expiry<i||n.set(s,o);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:o})=>({multiaddr:se(s),isCertified:o??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var nm="/peers/";function oc(r){if(!e0(r)||r.type==null)throw new w("Invalid PeerId",cr.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new ve(`${nm}${e}`)}async function PE(r,e,t){let n=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=se(i.multiaddr)),!qo(i.multiaddr))throw new w("Multiaddr was invalid",cr.ERR_INVALID_PARAMETERS);if(!await e(r,i.multiaddr))continue;let s=i.isCertified??!1,o=i.multiaddr.toString(),a=n.get(o);a!=null?i.isCertified=a.isCertified||s:n.set(o,{multiaddr:i.multiaddr,isCertified:s})}return[...n.values()].sort((i,s)=>i.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:i,multiaddr:s})=>({isCertified:i,multiaddr:s.bytes}))}async function f0(r,e,t,n){if(e==null)throw new w("Invalid PeerData",cr.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!de(e.publicKey,r.publicKey))throw new w("publicKey bytes do not match peer id publicKey bytes",cr.ERR_INVALID_PARAMETERS);let i=n.existingPeer;if(i!=null&&!r.equals(i.id))throw new w("peer id did not match existing peer id",cr.ERR_INVALID_PARAMETERS);let s=i?.addresses??[],o=new Set(i?.protocols??[]),a=i?.metadata??new Map,c=i?.tags??new Map,l=i?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(h=>({isCertified:!1,multiaddr:h}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(o=new Set(e.protocols)),e.metadata!=null){let h=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=h0(h,{validate:kE})}if(e.tags!=null){let h=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=h0(h,{validate:NE,map:LE})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(h=>({isCertified:!1,multiaddr:h}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(o=new Set([...o,...e.protocols])),e.metadata!=null){let h=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[f,d]of h)d==null?a.delete(f):a.set(f,d);a=h0([...a.entries()],{validate:kE})}if(e.tags!=null){let h=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),f=new Map(c);for(let[d,p]of h)p==null?f.delete(d):f.set(d,p);c=h0([...f.entries()],{validate:NE,map:LE})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u={addresses:await PE(r,n.addressFilter??(async()=>!0),s),protocols:[...o.values()].sort((h,f)=>h.localeCompare(f)),metadata:a,tags:c,publicKey:i?.id.publicKey??e.publicKey??r.publicKey,peerRecordEnvelope:l};return r.type!=="RSA"&&delete u.publicKey,u}function h0(r,e){let t=new Map;for(let[n,i]of r)i!=null&&e.validate(n,i);for(let[n,i]of r.sort(([s],[o])=>s.localeCompare(o)))i!=null&&t.set(n,e.map?.(n,i)??i);return t}function kE(r,e){if(typeof r!="string")throw new w("Metadata key must be a string",cr.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new w("Metadata value must be a Uint8Array",cr.ERR_INVALID_PARAMETERS)}function NE(r,e){if(typeof r!="string")throw new w("Tag name must be a string",cr.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new w("Tag value must be an integer",cr.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new w("Tag value must be between 0-100",cr.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new w("Tag ttl must be an integer",cr.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new w("Tag ttl must be between greater than 0",cr.ERR_INVALID_PARAMETERS)}}function LE(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}}var d0=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=Nl({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(oc(e))}async delete(e){if(this.peerId.equals(e))throw new w("Cannot delete self peer",cr.ERR_INVALID_PARAMETERS);await this.datastore.delete(oc(e))}async load(e){let t=await this.datastore.get(oc(e));return sc(e,t)}async save(e,t){let{existingBuf:n,existingPeer:i}=await this.#e(e),s=await f0(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,i)}async patch(e,t){let{existingBuf:n,existingPeer:i}=await this.#e(e),s=await f0(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:i});return this.#t(e,s,n,i)}async merge(e,t){let{existingBuf:n,existingPeer:i}=await this.#e(e),s=await f0(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:i});return this.#t(e,s,n,i)}async*all(){for await(let{key:e,value:t}of this.datastore.query({prefix:nm})){let n=e.toString().split("/")[2],i=Gt.decode(n),s=vt(i);s.equals(this.peerId)||(yield sc(s,t))}}async#e(e){try{let t=await this.datastore.get(oc(e)),n=await sc(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}return{}}async#t(e,t,n,i){let s=ic.encode(t);return n!=null&&de(s,n)?{peer:await sc(e,s),previous:i,updated:!1}:(await this.datastore.put(oc(e),s),{peer:await sc(e,s),previous:i,updated:!0})}};var lt=T("libp2p:peer-store"),p0=class{store;events;peerId;constructor(e,t={}){this.events=e.events,this.peerId=e.peerId,this.store=new d0(e,t)}async forEach(e){lt.trace("forEach await read lock");let t=await this.store.lock.readLock();lt.trace("forEach got read lock");try{for await(let n of this.store.all())e(n)}finally{lt.trace("forEach release read lock"),t()}}async all(){lt.trace("all await read lock");let e=await this.store.lock.readLock();lt.trace("all got read lock");try{let t=[];for await(let n of this.store.all())t.push(n);return t}finally{lt.trace("all release read lock"),e()}}async delete(e){lt.trace("delete await write lock");let t=await this.store.lock.writeLock();lt.trace("delete got write lock");try{await this.store.delete(e)}finally{lt.trace("delete release write lock"),t()}}async has(e){lt.trace("has await read lock");let t=await this.store.lock.readLock();lt.trace("has got read lock");try{return await this.store.has(e)}finally{lt.trace("has release read lock"),t()}}async get(e){lt.trace("get await read lock");let t=await this.store.lock.readLock();lt.trace("get got read lock");try{return await this.store.load(e)}finally{lt.trace("get release read lock"),t()}}async save(e,t){lt.trace("save await write lock");let n=await this.store.lock.writeLock();lt.trace("save got write lock");try{let i=await this.store.save(e,t);return this.#e(e,i),i.peer}finally{lt.trace("save release write lock"),n()}}async patch(e,t){lt.trace("patch await write lock");let n=await this.store.lock.writeLock();lt.trace("patch got write lock");try{let i=await this.store.patch(e,t);return this.#e(e,i),i.peer}finally{lt.trace("patch release write lock"),n()}}async merge(e,t){lt.trace("merge await write lock");let n=await this.store.lock.writeLock();lt.trace("merge got write lock");try{let i=await this.store.merge(e,t);return this.#e(e,i),i.peer}finally{lt.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await Wt.openAndCertify(e,Ut.DOMAIN);if(t?.equals(n.peerId)===!1)return lt("envelope peer id was not the expected peer id - expected: %p received: %p",t,n.peerId),!1;let i=Ut.createFromProtobuf(n.payload),s;try{s=await this.get(n.peerId)}catch(o){if(o.code!=="ERR_NOT_FOUND")throw o}if(s?.peerRecordEnvelope!=null){let o=await Wt.createFromProtobuf(s.peerRecordEnvelope),a=Ut.createFromProtobuf(o.payload);if(a.seqNumber>=i.seqNumber)return lt("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,i.seqNumber),!1}return await this.patch(i.peerId,{peerRecordEnvelope:e,addresses:i.multiaddrs.map(o=>({isCertified:!0,multiaddr:o}))}),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function OE(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var eU=T("libp2p:address-manager"),tU=r=>r;function im(r,e){let t=r.getPeerId();return t!=null&&oe(t).equals(e)&&(r=r.decapsulate(se(`/p2p/${e.toString()}`))),r}var m0=class{components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:i=[]}=t;this.components=e,this.listen=n.map(s=>s.toString()),this.announce=new Set(i.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??tU,this._updatePeerStoreAddresses=OE(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>se(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=>{eU.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>se(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>se(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>se(e))}addObservedAddr(e){e=im(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=im(e,this.components.peerId);let t=e.toString(),i=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),i||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=im(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,i])=>i.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>se(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};function BE(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}var sm=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>BE(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")}},rU=["metrics","connectionProtector"],nU=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function ME(r={}){let e=new sm(r);return new Proxy(e,{get(n,i,s){if(typeof i=="string"&&!nU.includes(i)){let o=e.components[i];if(o==null&&!rU.includes(i))throw new w(`${i} not set`,"ERR_SERVICE_MISSING");return o}return Reflect.get(n,i,s)},set(n,i,s){return typeof i=="string"?e.components[i]=s:Reflect.set(n,i,s),!0}})}var HE=F(UE(),1);var FE="[a-fA-F\\d:]",zs=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${FE})|(?<=${FE})(?=\\s|$))`:"",Zn="(?: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}",Ht="[a-fA-F\\d]{1,4}",g0=`
|
|
53
53
|
(?:
|
|
54
54
|
(?:${Ht}:){7}(?:${Ht}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
|
|
55
55
|
(?:${Ht}:){6}(?:${Zn}|:${Ht}|:)| // 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
|
|
@@ -81,7 +81,7 @@ a=candidate:1467250027 1 UDP 1467250027 ${t} ${n} typ host\r
|
|
|
81
81
|
a=ice-ufrag:`+e+`
|
|
82
82
|
`).replace(/\na=ice-pwd:[^\n]*\n/,`
|
|
83
83
|
a=ice-pwd:`+e+`
|
|
84
|
-
`),r}var bA=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),EA=r=>[...Array(r)].map(()=>bA.at(Math.floor(Math.random()*bA.length))).join("");var xd=T("libp2p:webrtc:transport"),E$=1e4,v$=X("webrtc-direct").code,m5=X("certhash").code,_d=class{metrics;components;init;constructor(e,t={}){this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dial events by type"})})}async dial(e,t){let n=await this._connect(e,t);return xd(`dialing address - ${e.toString()}`),n}createListener(e){throw DR("WebRTCTransport.createListener")}filter(e){return e.filter(x$)}[Symbol.toStringTag]="@libp2p/webrtc-direct";[Ti]=!0;async _connect(e,t){let n=new AbortController,i=n.signal,s=e.getPeerId();if(s===null)throw id("we need to have the remote's PeerId");let o=oe(s),a=d5(vd(e)),c=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:p5(a.name)}),l=new RTCPeerConnection({certificates:[c]}),u=new Promise((P,M)=>{let W=l.createDataChannel("",{negotiated:!0,id:0}),ue=setTimeout(()=>{let he=`Data channel was never opened: state: ${W.readyState}`;xd.error(he),this.metrics?.dialerEvents.increment({open_error:!0}),M(I8("data",he))},E$);W.onopen=he=>{clearTimeout(ue),P(W)},W.onerror=he=>{clearTimeout(ue);let Ve=`Error opening a data channel for handshaking: ${he.target?.toString()??"not specified"}`;xd.error(Ve),this.metrics?.dialerEvents.increment({unknown_error:!0}),M(I8("data",Ve))}}),h="libp2p+webrtc+v1/"+EA(32),f=await l.createOffer(),d=wA(f,h);await l.setLocalDescription(d);let p=yA(e,h);await l.setRemoteDescription(p);let m=await u,g=this.components.peerId,y=this.generateNoisePrologue(l,a.code,e),b=b1({prologueBytes:y})(),E=Kc({channel:m,direction:"inbound",dataChannelOptions:this.init.dataChannel}),I={...E,sink:E.sink.bind(E),source:async function*(){for await(let P of E.source)for(let M of P)yield M}()},v=new ra({peerConnection:l,remoteAddr:e,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),_=zu?"iceconnectionstatechange":"connectionstatechange";l.addEventListener(_,()=>{switch(l.connectionState){case"failed":case"disconnected":case"closed":v.close().catch(P=>{xd.error("error closing connection",P)}).finally(()=>{n.abort()});break;default:break}},{signal:i}),this.metrics?.dialerEvents.increment({peer_connection:!0});let A=new na({peerConnection:l,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await b.secureInbound(g,I,o),t.upgrader.upgradeOutbound(v,{skipProtection:!0,skipEncryption:!0,muxerFactory:A})}generateNoisePrologue(e,t,n){if(e.getConfiguration().certificates?.length===0)throw qu("no local certificate");let i=gA(e);if(i==null)throw qu("no local fingerprint found");let s=i.trim().toLowerCase().replaceAll(":",""),o=K(s,"hex"),a=vA.encode(o,t),c=f5.decode(vd(n)),l=K("libp2p-webrtc-noise:");return le([l,a,c])}};function x$(r){let e=r.protoCodes();return e.includes(v$)&&e.includes(m5)&&r.getPeerId()!=null&&!e.includes(X("p2p-circuit").code)}function xA(r){return e=>new _d(e,r)}function _A(r){return e=>new ud(e,r)}function SA(r){let e;try{e=X("sni").code}catch{return null}for(let[t,n]of r)if(t===e&&n!==void 0)return n;return null}function RA(r){return r.some(([e,t])=>e===X("tls").code)}function gn(r,e,t){let n=IA[X(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${X(r).name}`);let i=n(e,t);return r===X("ip6").code?`[${i}]`:i}var IA={ip4:(r,e)=>r,ip6:(r,e)=>e.length===0?r:`[${r}]`,tcp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`tcp://${gn(t[0],t[1]??"",e)}:${r}`},udp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`udp://${gn(t[0],t[1]??"",e)}:${r}`},dnsaddr:(r,e)=>r,dns4:(r,e)=>r,dns6:(r,e)=>r,dns:(r,e)=>r,ipfs:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${gn(t[0],t[1]??"",e)}/ipfs/${r}`},p2p:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${gn(t[0],t[1]??"",e)}/p2p/${r}`},http:(r,e)=>{let t=RA(e),n=SA(e);if(t&&n!==null)return`https://${n}`;let i=t?"https://":"http://",s=e.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let o=gn(s[0],s[1]??"",e);return o=o.replace("tcp://",""),`${i}${o}`},tls:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return gn(t[0],t[1]??"",e)},sni:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return gn(t[0],t[1]??"",e)},https:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=gn(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=RA(e),n=SA(e);if(t&&n!==null)return`wss://${n}`;let i=t?"wss://":"ws://",s=e.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let o=gn(s[0],s[1]??"",e);return o=o.replace("tcp://",""),`${i}${o}`},wss:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=gn(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${gn(t[0],t[1]??"",e)}/p2p-websocket-star`},"p2p-webrtc-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${gn(t[0],t[1]??"",e)}/p2p-webrtc-star`},"p2p-webrtc-direct":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${gn(t[0],t[1]??"",e)}/p2p-webrtc-direct`}};function AA(r,e){let n=se(r).stringTuples(),i=n.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let s=X(i[0]),o=IA[s.name];if(o==null)throw new Error(`No interpreter found for ${s.name}`);let a=o(i[1]??"",n);return e?.assumeHttp!==!1&&i[0]===X("tcp").code&&(a=a.replace("tcp://","http://"),(i[1]==="443"||i[1]==="80")&&(i[1]==="443"&&(a=a.replace("http://","https://")),a=a.substring(0,a.lastIndexOf(":")))),a}var TA=WebSocket;var kA=F(CA(),1);function PA(r){return r instanceof ArrayBuffer||r?.constructor?.name==="ArrayBuffer"&&typeof r?.byteLength=="number"}var NA=r=>{r.binaryType="arraybuffer";let e=async()=>{await new Promise((s,o)=>{if(n){s();return}if(i!=null){o(i);return}let a=u=>{r.removeEventListener("open",c),r.removeEventListener("error",l),u()},c=()=>{a(s)},l=u=>{a(()=>{o(u.error??new Error(`connect ECONNREFUSED ${r.url}`))})};r.addEventListener("open",c),r.addEventListener("error",l)})},t=async function*(){let s=new kA.EventIterator(({push:o,stop:a,fail:c})=>{let l=h=>{let f=null;typeof h.data=="string"&&(f=K(h.data)),PA(h.data)&&(f=new Uint8Array(h.data)),h.data instanceof Uint8Array&&(f=h.data),f!=null&&o(f)},u=h=>{c(h.error??new Error("Socket error"))};return r.addEventListener("message",l),r.addEventListener("error",u),r.addEventListener("close",a),()=>{r.removeEventListener("message",l),r.removeEventListener("error",u),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let o of s)yield PA(o)?new Uint8Array(o):o}(),n=r.readyState===1,i;return r.addEventListener("open",()=>{n=!0,i=null}),r.addEventListener("close",()=>{n=!1,i=null}),r.addEventListener("error",s=>{n||(i=s.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var LA=async r=>{if(r.readyState>=2)throw new Error("socket closed");r.readyState!==1&&await new Promise((e,t)=>{function n(){r.removeEventListener("open",i),r.removeEventListener("error",s)}function i(){n(),e()}function s(o){n(),t(o.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",i),r.addEventListener("error",s)})};var OA=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let i of n){try{await LA(r)}catch(s){if(s.message==="socket closed")break;throw s}r.send(i)}e.closeOnEnd!=null&&r.readyState<=1&&await new Promise((i,s)=>{r.addEventListener("close",o=>{if(o.wasClean||o.code===1006)i();else{let a=Object.assign(new Error("ws error"),{event:o});s(a)}}),setTimeout(()=>{r.close()})})});var BA=(r,e)=>{e=e??{};let t=NA(r),n=e.remoteAddress,i=e.remotePort;if(r.url!=null)try{let o=new URL(r.url);n=o.hostname,i=parseInt(o.port,10)}catch{}if(n==null||i==null)throw new Error("Remote connection did not have address and/or port");return{sink:OA(r,e),source:t,connected:async()=>{await t.connected()},close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(o=>{r.addEventListener("close",()=>{o()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:i,socket:r}};var HA=F(zA(),1),N$={http:"ws",https:"wss"},L$="ws",$A=(r,e)=>(0,HA.relative)(r,e,N$,L$);function GA(r,e){let t=typeof window>"u"?"":window.location;e=e??{};let n=$A(r,t.toString()),i=new TA(n,e.websocket);return BA(i,e)}var QA=F(YA(),1),E5=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,Id=(0,QA.default)(),Ad=E5&&!Id,XA=Id&&!E5,jA=Id&&E5,ZA=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&globalThis.process.release.name==="node"&&!Id,Td=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,_6e=typeof globalThis.process<"u"&&typeof globalThis.process.env<"u"&&globalThis.process.env["NODE"+(()=>"_")()+"ENV"]==="test",JA=typeof navigator<"u"&&navigator.product==="ReactNative";function rT(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return Cc.matches(t)||Xo.matches(t)})}function nT(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return Xo.matches(t)})}function iT(){throw new Error("WebSocket Servers can not be created in the browser!")}var v5=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},x5=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},sT=r=>globalThis.DOMException===void 0?new x5(r):new DOMException(r),oT=r=>{let e=r.reason===void 0?sT("This operation was aborted."):r.reason;return e instanceof Error?e:sT(e)};function _5(r,e){let{milliseconds:t,fallback:n,message:i,customTimers:s={setTimeout,clearTimeout}}=e,o,a=new Promise((c,l)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(t===Number.POSITIVE_INFINITY){c(r);return}if(e.signal){let{signal:h}=e;h.aborted&&l(oT(h)),h.addEventListener("abort",()=>{l(oT(h))})}let u=new v5;o=s.setTimeout.call(void 0,()=>{if(n){try{c(n())}catch(h){l(h)}return}typeof r.cancel=="function"&&r.cancel(),i===!1?c():i instanceof Error?l(i):(u.message=i??`Promise timed out after ${t} milliseconds`,l(u))},t),(async()=>{try{c(await r)}catch(h){l(h)}finally{s.clearTimeout.call(void 0,o)}})()});return a.clear=()=>{s.clearTimeout.call(void 0,o),o=void 0},a}var aT=T("libp2p:websockets:socket");function cT(r,e,t){t=t??{};let n={async sink(i){t?.signal!=null&&(i=gt(i,t.signal));try{await r.sink(i)}catch(s){s.type!=="aborted"&&aT.error(s)}},source:t.signal!=null?gt(r.source,t.signal):r.source,remoteAddr:e,timeline:{open:Date.now()},async close(){let i=Date.now();try{await _5(r.close(),{milliseconds:2e3})}catch{let{host:o,port:a}=n.remoteAddr.toOptions();aT("timeout closing stream to %s:%s after %dms, destroying it manually",o,a,Date.now()-i),r.destroy()}finally{n.timeline.close=Date.now()}}};return r.socket.addEventListener("close",()=>{n.timeline.close==null&&(n.timeline.close=Date.now())},{once:!0}),n}var lo=T("libp2p:websockets"),S5=class{init;constructor(e){this.init=e}[Symbol.toStringTag]="@libp2p/websockets";[Ti]=!0;async dial(e,t){lo("dialing %s",e),t=t??{};let n=await this._connect(e,t),i=cT(n,e);lo("new outbound connection %s",i.remoteAddr);let s=await t.upgrader.upgradeOutbound(i);return lo("outbound connection %s upgraded",i.remoteAddr),s}async _connect(e,t){if(t?.signal?.aborted===!0)throw new Qr;let n=e.toOptions();lo("dialing %s:%s",n.host,n.port);let i=Pe(),s=l=>{lo.error("connection error:",l),i.reject(l)},o=GA(AA(e),this.init);if(o.socket.on!=null?o.socket.on("error",s):o.socket.onerror=s,t.signal==null)return await Promise.race([o.connected(),i.promise]),lo("connected %s",e),o;let a,c=new Promise((l,u)=>{if(a=()=>{u(new Qr),o.close().catch(h=>{lo.error("error closing raw socket",h)})},t?.signal?.aborted===!0){a();return}t?.signal?.addEventListener("abort",a)});try{await Promise.race([c,i.promise,o.connected()])}finally{a!=null&&t?.signal?.removeEventListener("abort",a)}return lo("connected %s",e),o}createListener(e){return iT({...this.init,...e})}filter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):Ad||Td?nT(e):rT(e)}};function lT(r={}){return()=>new S5(r)}function Dd(r){return r[Symbol.asyncIterator]!=null}var Cd=r=>{let e=ot.encodingLength(r),t=Ir(e);return ot.encode(r,t),Cd.bytes=e,t};Cd.bytes=0;function Pd(r,e){e=e??{};let t=e.lengthEncoder??Cd;function*n(i){let s=t(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return Dd(r)?async function*(){for await(let i of r)yield*n(i)}():function*(){for(let i of r)yield*n(i)}()}Pd.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Cd;return new j(t(r.byteLength),r)};var Xc=F(li(),1);var U$=8,F$=1024*1024*4,aa;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(aa||(aa={}));var I5=r=>{let e=ot.decode(r);return I5.bytes=ot.encodingLength(e),e};I5.bytes=0;function R5(r,e){let t=new j,n=aa.LENGTH,i=-1,s=e?.lengthDecoder??I5,o=e?.maxLengthLength??U$,a=e?.maxDataLength??F$;function*c(){for(;t.byteLength>0;){if(n===aa.LENGTH)try{if(i=s(t),i<0)throw(0,Xc.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,Xc.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(i),n=aa.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>o)throw(0,Xc.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw l}if(n===aa.DATA){if(t.byteLength<i)break;let l=t.sublist(0,i);t.consume(i),e?.onData!=null&&e.onData(l),yield l,n=aa.LENGTH}}}return Dd(r)?async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw(0,Xc.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw(0,Xc.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}R5.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:s,value:o}=await r.next(t);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}}();return R5(n,{...e??{},onLength:s=>{t=s}})};var kd=F(li(),1),uT=r=>ot.decode(r);uT.bytes=0;function A5(r,e={}){let t=et();r.sink(t).catch(o=>{t.end(o)}),r.sink=async o=>{for await(let a of o)t.push(a)};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let i=new j,s={read:async o=>{if(o==null){let{done:c,value:l}=await n.next();return c===!0?new j:l}for(;i.byteLength<o;){let{value:c,done:l}=await n.next();if(l===!0)throw(0,kd.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF");i.append(c)}let a=i.sublist(0,o);return i.consume(o),a},readLP:async()=>{let o=-1,a=new j,c=e?.lengthDecoder??uT;for(;;){a.append(await s.read(1));try{o=c(a)}catch(l){if(l instanceof RangeError)continue;throw l}if(o>-1)break;if(e?.maxLengthLength!=null&&a.byteLength>e.maxLengthLength)throw(0,kd.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG")}if(e?.maxDataLength!=null&&o>e.maxDataLength)throw(0,kd.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");return await s.read(o)},readPB:async o=>{let a=await s.readLP();if(a==null)throw new Error("Value is null");let c=a instanceof Uint8Array?a:a.subarray();return o.decode(c)},write:o=>{o instanceof Uint8Array?t.push(o):t.push(o.subarray())},writeLP:o=>{s.write(Pd.single(o,e))},writePB:(o,a)=>{s.writeLP(a.encode(o))},pb:o=>({read:async()=>await s.readPB(o),write:a=>{s.writePB(a,o)},unwrap:()=>s}),unwrap:()=>{let o=r.source;return r.source=async function*(){yield*i,yield*o}(),r}};return s}async function*T5(...r){let e=et({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async t=>{for await(let n of t)e.push(n)})),e.end()}catch(t){e.end(t)}}),yield*e}var V$=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},hT=r=>r!=null&&(typeof r[Symbol.asyncIterator]=="function"||typeof r[Symbol.iterator]=="function"||typeof r.next=="function"),D5=r=>r!=null&&typeof r.sink=="function"&&hT(r.source),q$=r=>e=>{let t=r.sink(e);if(t.then!=null){let n=et({objectMode:!0});return t.then(()=>{n.end()},s=>{n.end(s)}),T5(n,async function*(){yield*r.source,n.end()}())}return r.source};function fT(r,...e){if(D5(r)){let n=r;r=()=>n.source}else if(hT(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&D5(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)D5(t[n])&&(t[n]=q$(t[n]));return V$(...t)}function dT(r){return globalThis?.Buffer?.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r)}var Nd=r=>{let e=ot.encodingLength(r),t=dT(e);return ot.encode(r,t),Nd.bytes=e,t};Nd.bytes=0;function pT(r){r=r??{};let e=r.lengthEncoder??Nd;return async function*(n){for await(let i of n){let s=e(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}}}pT.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Nd;return new j(t(r.byteLength),r)};var Ju=F(li(),1),z$=8,H$=1024*1024*4,ca;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(ca||(ca={}));var C5=r=>{let e=ot.decode(r);return C5.bytes=ot.encodingLength(e),e};C5.bytes=0;function eh(r){return async function*(t){let n=new j,i=ca.LENGTH,s=-1,o=r?.lengthDecoder??C5,a=r?.maxLengthLength??z$,c=r?.maxDataLength??H$;for await(let l of t)for(n.append(l);n.byteLength>0;){if(i===ca.LENGTH)try{if(s=o(n),s<0)throw(0,Ju.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(s>c)throw(0,Ju.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=o.bytes;n.consume(u),r?.onLength!=null&&r.onLength(s),i=ca.DATA}catch(u){if(u instanceof RangeError){if(n.byteLength>a)throw(0,Ju.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(i===ca.DATA){if(n.byteLength<s)break;let u=n.sublist(0,s);n.consume(s),r?.onData!=null&&r.onData(u),yield u,i=ca.LENGTH}}if(n.byteLength>0)throw(0,Ju.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}}eh.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:s,value:o}=await r.next(t);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}}();return eh({...e??{},onLength:s=>{t=s}})(n)};var mT=!!globalThis.process?.env?.DUMP_SESSION_KEYS;var ST=F(vT(),1),jc=F(R4(),1),Bd=F(_T(),1),L5=F(Ru(),1),RT={hashSHA256(r){return(0,Bd.hash)(r)},getHKDF(r,e){let i=new ST.HKDF(Bd.SHA256,e,r).expand(96),s=i.subarray(0,32),o=i.subarray(32,64),a=i.subarray(64,96);return[s,o,a]},generateX25519KeyPair(){let r=jc.generateKeyPair();return{publicKey:r.publicKey,privateKey:r.secretKey}},generateX25519KeyPairFromSeed(r){let e=jc.generateKeyPairFromSeed(r);return{publicKey:e.publicKey,privateKey:e.secretKey}},generateX25519SharedKey(r,e){return jc.sharedKey(r,e)},chaCha20Poly1305Encrypt(r,e,t,n){return new L5.ChaCha20Poly1305(n).seal(e,r,t)},chaCha20Poly1305Decrypt(r,e,t,n,i){return new L5.ChaCha20Poly1305(n).open(e,r,t,i)}};var O5=F(Ru(),1);var Z$=r=>globalThis.Buffer?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r),Zc=r=>{let e=Z$(2);return new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(0,r,!1),e};Zc.bytes=2;var rh=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");return r instanceof Uint8Array?new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,!1):r.getUint16(0)};rh.bytes=2;function IT(r){return le([r.ne,r.ciphertext],r.ne.length+r.ciphertext.length)}function AT(r){return le([r.ne,r.ns,r.ciphertext],r.ne.length+r.ns.length+r.ciphertext.length)}function TT(r){return le([r.ns,r.ciphertext],r.ns.length+r.ciphertext.length)}function DT(r){if(r.length<32)throw new Error("Cannot decode stage 0 MessageBuffer: length less than 32 bytes.");return{ne:r.subarray(0,32),ciphertext:r.subarray(32,r.length),ns:new Uint8Array(0)}}function CT(r){if(r.length<80)throw new Error("Cannot decode stage 1 MessageBuffer: length less than 80 bytes.");return{ne:r.subarray(0,32),ns:r.subarray(32,80),ciphertext:r.subarray(80,r.length)}}function PT(r){if(r.length<48)throw new Error("Cannot decode stage 2 MessageBuffer: length less than 48 bytes.");return{ne:new Uint8Array(0),ns:r.subarray(0,48),ciphertext:r.subarray(48,r.length)}}function NT(r,e){return async function*(t){for await(let n of t)for(let i=0;i<n.length;i+=65519){let s=i+65519;s>n.length&&(s=n.length);let o=r.encrypt(n.subarray(i,s),r.session);e?.encryptedPackets.increment(),yield Zc(o.byteLength),yield o}}}function LT(r,e){return async function*(t){for await(let n of t)for(let i=0;i<n.length;i+=65535){let s=i+65535;if(s>n.length&&(s=n.length),s-O5.TAG_LENGTH<i)throw new Error("Invalid chunk");let o=n.subarray(i,s),a=n.subarray(i,s-O5.TAG_LENGTH),{plaintext:c,valid:l}=r.decrypt(o,r.session,a);if(!l)throw e?.decryptErrors.increment(),new Error("Failed to validate decrypted chunk");e?.decryptedPackets.increment(),yield c}}}var la=class extends Error{constructor(e="Unexpected Peer"){super(e),this.code=la.code}static get code(){return"ERR_UNEXPECTED_PEER"}},ds=class extends Error{constructor(e="Invalid crypto exchange"){super(e),this.code=ds.code}static get code(){return"ERR_INVALID_CRYPTO_EXCHANGE"}};var Md;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.webtransportCerthashes!=null)for(let s of t.webtransportCerthashes)n.uint32(10),n.bytes(s);i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={webtransportCerthashes:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.webtransportCerthashes.push(t.bytes());break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(Md||(Md={}));var ih;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||t.identityKey!=null&&t.identityKey.byteLength>0)&&(n.uint32(10),n.bytes(t.identityKey??new Uint8Array(0))),(i.writeDefaults===!0||t.identitySig!=null&&t.identitySig.byteLength>0)&&(n.uint32(18),n.bytes(t.identitySig??new Uint8Array(0))),t.extensions!=null&&(n.uint32(34),Md.codec().encode(t.extensions,n,{writeDefaults:!1})),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={identityKey:new Uint8Array(0),identitySig:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.identityKey=t.bytes();break;case 2:i.identitySig=t.bytes();break;case 4:i.extensions=Md.codec().decode(t,t.uint32());break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(ih||(ih={}));async function OT(r,e,t){let n=await eG(r,BT(e));if(r.publicKey==null)throw new Error("PublicKey was missing from local PeerId");return J$(r.publicKey,n,t)}function J$(r,e,t){return ih.encode({identityKey:r,identitySig:e,extensions:t??{webtransportCerthashes:[]}}).subarray()}async function eG(r,e){if(r.privateKey==null)throw new Error("PrivateKey was missing from PeerId");return await(await an(r.privateKey)).sign(e)}async function B5(r){return await zt(r.identityKey)}function M5(r){return ih.decode(r)}function BT(r){let e=K("noise-libp2p-static-key:");return le([e,r],e.length+r.length)}async function U5(r,e,t){let n=await zt(e.identityKey);if(!n.equals(t))throw new Error(`Payload identity key ${n.toString()} does not match expected remote peer ${t.toString()}`);let i=BT(r);if(n.publicKey==null)throw new Error("PublicKey was missing from PeerId");if(e.identitySig==null)throw new Error("Signature was missing from message");if(!await rr(n.publicKey).verify(i,e.identitySig))throw new Error("Static key doesn't match to peer that signed payload!");return n}function sh(r){return!(!(r instanceof Uint8Array)||r.length!==32)}var sr=T("libp2p:noise");var Nn;mT?Nn=sr:Nn=Object.assign(()=>{},{enabled:!1,trace:()=>{},error:()=>{}});function MT(r){Nn(`LOCAL_STATIC_PUBLIC_KEY ${O(r.publicKey,"hex")}`),Nn(`LOCAL_STATIC_PRIVATE_KEY ${O(r.privateKey,"hex")}`)}function F5(r){r?(Nn(`LOCAL_PUBLIC_EPHEMERAL_KEY ${O(r.publicKey,"hex")}`),Nn(`LOCAL_PRIVATE_EPHEMERAL_KEY ${O(r.privateKey,"hex")}`)):Nn("Missing local ephemeral keys.")}function UT(r){Nn(`REMOTE_STATIC_PUBLIC_KEY ${O(r,"hex")}`)}function K5(r){Nn(`REMOTE_EPHEMERAL_PUBLIC_KEY ${O(r,"hex")}`)}function FT(r){r.cs1&&r.cs2?(Nn(`CIPHER_STATE_1 ${r.cs1.n.getUint64()} ${O(r.cs1.k,"hex")}`),Nn(`CIPHER_STATE_2 ${r.cs2.n.getUint64()} ${O(r.cs2.k,"hex")}`)):Nn("Missing cipher state.")}var tG="Cipherstate has reached maximum n, a new handshake must be performed",Ud=class{constructor(e=0){this.n=e,this.bytes=new Uint8Array(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>4294967295)throw new Error(tG)}};var Fd=class{constructor(e){this.crypto=e}encryptWithAd(e,t,n){let i=this.encrypt(e.k,e.n,t,n);return e.n.increment(),i}decryptWithAd(e,t,n,i){let{plaintext:s,valid:o}=this.decrypt(e.k,e.n,t,n,i);return o&&e.n.increment(),{plaintext:s,valid:o}}hasKey(e){return!this.isEmptyKey(e.k)}createEmptyKey(){return new Uint8Array(32)}isEmptyKey(e){let t=this.createEmptyKey();return de(t,e)}encrypt(e,t,n,i){return t.assertValue(),this.crypto.chaCha20Poly1305Encrypt(i,t.getBytes(),n,e)}encryptAndHash(e,t){let n;return this.hasKey(e.cs)?n=this.encryptWithAd(e.cs,e.h,t):n=t,this.mixHash(e,n),n}decrypt(e,t,n,i,s){t.assertValue();let o=this.crypto.chaCha20Poly1305Decrypt(i,t.getBytes(),n,e,s);return o?{plaintext:o,valid:!0}:{plaintext:new Uint8Array(0),valid:!1}}decryptAndHash(e,t){let n,i=!0;return this.hasKey(e.cs)?{plaintext:n,valid:i}=this.decryptWithAd(e.cs,e.h,t):n=t,this.mixHash(e,t),{plaintext:n,valid:i}}dh(e,t){try{let n=this.crypto.generateX25519SharedKey(e,t);return n.length===32?n:n.subarray(0,32)}catch(n){let i=n;return sr.error(i),new Uint8Array(32)}}mixHash(e,t){e.h=this.getHash(e.h,t)}getHash(e,t){return this.crypto.hashSHA256(le([e,t],e.length+t.length))}mixKey(e,t){let[n,i]=this.crypto.getHKDF(e.ck,t);e.cs=this.initializeKey(i),e.ck=n}initializeKey(e){return{k:e,n:new Ud}}initializeSymmetric(e){let t=K(e,"utf-8"),n=this.hashProtocolName(t),i=n,s=this.createEmptyKey();return{cs:this.initializeKey(s),ck:i,h:n}}hashProtocolName(e){if(e.length<=32){let t=new Uint8Array(32);return t.set(e),t}else return this.getHash(e,new Uint8Array(0))}split(e){let[t,n]=this.crypto.getHKDF(e.ck,new Uint8Array(0)),i=this.initializeKey(t),s=this.initializeKey(n);return{cs1:i,cs2:s}}writeMessageRegular(e,t){let n=this.encryptWithAd(e,new Uint8Array(0),t),i=this.createEmptyKey(),s=new Uint8Array(0);return{ne:i,ns:s,ciphertext:n}}readMessageRegular(e,t){return this.decryptWithAd(e,new Uint8Array(0),t.ciphertext)}};var Kd=class extends Fd{initializeInitiator(e,t,n,i){let s="Noise_XX_25519_ChaChaPoly_SHA256",o=this.initializeSymmetric(s);this.mixHash(o,e);let a=new Uint8Array(32);return{ss:o,s:t,rs:n,psk:i,re:a}}initializeResponder(e,t,n,i){let s="Noise_XX_25519_ChaChaPoly_SHA256",o=this.initializeSymmetric(s);this.mixHash(o,e);let a=new Uint8Array(32);return{ss:o,s:t,rs:n,psk:i,re:a}}writeMessageA(e,t,n){let i=new Uint8Array(0);n!==void 0?e.e=n:e.e=this.crypto.generateX25519KeyPair();let s=e.e.publicKey;this.mixHash(e.ss,s);let o=this.encryptAndHash(e.ss,t);return{ne:s,ns:i,ciphertext:o}}writeMessageB(e,t){e.e=this.crypto.generateX25519KeyPair();let n=e.e.publicKey;this.mixHash(e.ss,n),this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));let i=e.s.publicKey,s=this.encryptAndHash(e.ss,i);this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));let o=this.encryptAndHash(e.ss,t);return{ne:n,ns:s,ciphertext:o}}writeMessageC(e,t){let n=e.s.publicKey,i=this.encryptAndHash(e.ss,n);this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));let s=this.encryptAndHash(e.ss,t),a={ne:this.createEmptyKey(),ns:i,ciphertext:s},{cs1:c,cs2:l}=this.split(e.ss);return{h:e.ss.h,messageBuffer:a,cs1:c,cs2:l}}readMessageA(e,t){return sh(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),this.decryptAndHash(e.ss,t.ciphertext)}readMessageB(e,t){if(sh(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),!e.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));let{plaintext:n,valid:i}=this.decryptAndHash(e.ss,t.ns);i&&sh(n)&&(e.rs=n),this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));let{plaintext:s,valid:o}=this.decryptAndHash(e.ss,t.ciphertext);return{plaintext:s,valid:i&&o}}readMessageC(e,t){let{plaintext:n,valid:i}=this.decryptAndHash(e.ss,t.ns);if(i&&sh(n)&&(e.rs=n),!e.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));let{plaintext:s,valid:o}=this.decryptAndHash(e.ss,t.ciphertext),{cs1:a,cs2:c}=this.split(e.ss);return{h:e.ss.h,plaintext:s,valid:i&&o,cs1:a,cs2:c}}initSession(e,t,n){let i=this.createEmptyKey(),s=new Uint8Array(32),o;return e?o=this.initializeInitiator(t,n,s,i):o=this.initializeResponder(t,n,s,i),{hs:o,i:e,mc:0}}sendMessage(e,t,n){let i;if(e.mc===0)i=this.writeMessageA(e.hs,t,n);else if(e.mc===1)i=this.writeMessageB(e.hs,t);else if(e.mc===2){let{h:s,messageBuffer:o,cs1:a,cs2:c}=this.writeMessageC(e.hs,t);i=o,e.h=s,e.cs1=a,e.cs2=c}else if(e.mc>2)if(e.i){if(!e.cs1)throw new Error("CS1 (cipher state) is not defined");i=this.writeMessageRegular(e.cs1,t)}else{if(!e.cs2)throw new Error("CS2 (cipher state) is not defined");i=this.writeMessageRegular(e.cs2,t)}else throw new Error("Session invalid.");return e.mc++,i}recvMessage(e,t){let n=new Uint8Array(0),i=!1;if(e.mc===0)({plaintext:n,valid:i}=this.readMessageA(e.hs,t));else if(e.mc===1)({plaintext:n,valid:i}=this.readMessageB(e.hs,t));else if(e.mc===2){let{h:s,plaintext:o,valid:a,cs1:c,cs2:l}=this.readMessageC(e.hs,t);n=o,i=a,e.h=s,e.cs1=c,e.cs2=l}return e.mc++,{plaintext:n,valid:i}}};var Vd=class{constructor(e,t,n,i,s,o,a,c){this.remoteExtensions={webtransportCerthashes:[]},this.isInitiator=e,this.payload=t,this.prologue=n,this.staticKeypair=s,this.connection=o,a&&(this.remotePeer=a),this.xx=c??new Kd(i),this.session=this.xx.initSession(this.isInitiator,this.prologue,this.staticKeypair)}async propose(){if(MT(this.session.hs.s),this.isInitiator){sr.trace("Stage 0 - Initiator starting to send first message.");let e=this.xx.sendMessage(this.session,new Uint8Array(0));this.connection.writeLP(IT(e)),sr.trace("Stage 0 - Initiator finished sending first message."),F5(this.session.hs.e)}else{sr.trace("Stage 0 - Responder waiting to receive first message...");let e=DT((await this.connection.readLP()).subarray()),{valid:t}=this.xx.recvMessage(this.session,e);if(!t)throw new ds("xx handshake stage 0 validation fail");sr.trace("Stage 0 - Responder received first message."),K5(this.session.hs.re)}}async exchange(){if(this.isInitiator){sr.trace("Stage 1 - Initiator waiting to receive first message from responder...");let e=CT((await this.connection.readLP()).subarray()),{plaintext:t,valid:n}=this.xx.recvMessage(this.session,e);if(!n)throw new ds("xx handshake stage 1 validation fail");sr.trace("Stage 1 - Initiator received the message."),K5(this.session.hs.re),UT(this.session.hs.rs),sr.trace("Initiator going to check remote's signature...");try{let i=M5(t);this.remotePeer=this.remotePeer||await B5(i),await U5(this.session.hs.rs,i,this.remotePeer),this.setRemoteNoiseExtension(i.extensions)}catch(i){let s=i;throw new la(`Error occurred while verifying signed payload: ${s.message}`)}sr.trace("All good with the signature!")}else{sr.trace("Stage 1 - Responder sending out first message with signed payload and static key.");let e=this.xx.sendMessage(this.session,this.payload);this.connection.writeLP(AT(e)),sr.trace("Stage 1 - Responder sent the second handshake message with signed payload."),F5(this.session.hs.e)}}async finish(){if(this.isInitiator){sr.trace("Stage 2 - Initiator sending third handshake message.");let e=this.xx.sendMessage(this.session,this.payload);this.connection.writeLP(TT(e)),sr.trace("Stage 2 - Initiator sent message with signed payload.")}else{sr.trace("Stage 2 - Responder waiting for third handshake message...");let e=PT((await this.connection.readLP()).subarray()),{plaintext:t,valid:n}=this.xx.recvMessage(this.session,e);if(!n)throw new ds("xx handshake stage 2 validation fail");sr.trace("Stage 2 - Responder received the message, finished handshake.");try{let i=M5(t);this.remotePeer=this.remotePeer||await B5(i),await U5(this.session.hs.rs,i,this.remotePeer),this.setRemoteNoiseExtension(i.extensions)}catch(i){let s=i;throw new la(`Error occurred while verifying signed payload: ${s.message}`)}}FT(this.session)}encrypt(e,t){let n=this.getCS(t);return this.xx.encryptWithAd(n,new Uint8Array(0),e)}decrypt(e,t,n){let i=this.getCS(t,!1);return this.xx.decryptWithAd(i,new Uint8Array(0),e,n)}getRemoteStaticKey(){return this.session.hs.rs}getCS(e,t=!0){if(!e.cs1||!e.cs2)throw new ds("Handshake not completed properly, cipher state does not exist.");return this.isInitiator?t?e.cs1:e.cs2:t?e.cs2:e.cs1}setRemoteNoiseExtension(e){e&&(this.remoteExtensions=e)}};function KT(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}var qd=class{constructor(e={}){this.protocol="/noise";let{staticNoiseKey:t,extensions:n,crypto:i,prologueBytes:s,metrics:o}=e;this.crypto=i??RT,this.extensions=n,this.metrics=o?KT(o):void 0,t?this.staticKeys=this.crypto.generateX25519KeyPairFromSeed(t):this.staticKeys=this.crypto.generateX25519KeyPair(),this.prologue=s??new Uint8Array(0)}async secureOutbound(e,t,n){let i=A5(t,{lengthEncoder:Zc,lengthDecoder:rh,maxDataLength:65535}),s=await this.performHandshake({connection:i,isInitiator:!0,localPeer:e,remotePeer:n});return{conn:await this.createSecureConnection(i,s),remoteExtensions:s.remoteExtensions,remotePeer:s.remotePeer}}async secureInbound(e,t,n){let i=A5(t,{lengthEncoder:Zc,lengthDecoder:rh,maxDataLength:65535}),s=await this.performHandshake({connection:i,isInitiator:!1,localPeer:e,remotePeer:n});return{conn:await this.createSecureConnection(i,s),remotePeer:s.remotePeer,remoteExtensions:s.remoteExtensions}}async performHandshake(e){let t=await OT(e.localPeer,this.staticKeys.publicKey,this.extensions);return await this.performXXHandshake(e,t)}async performXXHandshake(e,t){let{isInitiator:n,remotePeer:i,connection:s}=e,o=new Vd(n,t,this.prologue,this.crypto,this.staticKeys,s,i);try{await o.propose(),await o.exchange(),await o.finish(),this.metrics?.xxHandshakeSuccesses.increment()}catch(a){if(this.metrics?.xxHandshakeErrors.increment(),a instanceof Error)throw a.message=`Error occurred during XX handshake: ${a.message}`,a}return o}async createSecureConnection(e,t){let[n,i]=Y0(),s=e.unwrap();return await fT(n,NT(t,this.metrics),s,eh({lengthDecoder:rh}),LT(t,this.metrics),n),i}};function VT(r={}){return()=>new qd(r)}var Hr=T("libp2p:webtransport"),rG=Object.values(wn).map(r=>r.decoder).reduce((r,e)=>r.or(e));function nG(r){return Mn.decode(rG.decode(r))}function qT(){return{source:{[Symbol.asyncIterator](){return{async next(){return new Promise(()=>{})}}}},sink:async r=>new Promise(()=>{})}}async function zT(r,e,t,n,i){let s=r.writable.getWriter(),o=r.readable.getReader();await s.ready;function a(){let f=n.findIndex(d=>d===h);f!==-1&&(n.splice(f,1),h.stat.timeline.close=Date.now(),i?.(h))}let c=!1,l=!1;(async function(){let f=await s.closed.catch(d=>d);if(f!=null){let d=f.message;d.includes("aborted by the remote server")||d.includes("STOP_SENDING")||Hr.error(`WebTransport writer closed unexpectedly: streamId=${e} err=${f.message}`)}c=!0,c&&l&&a()})().catch(()=>{Hr.error("WebTransport failed to cleanup closed stream")}),async function(){let f=await o.closed.catch(d=>d);f!=null&&Hr.error(`WebTransport reader closed unexpectedly: streamId=${e} err=${f.message}`),l=!0,c&&l&&a()}().catch(()=>{Hr.error("WebTransport failed to cleanup closed stream")});let u=!1,h={id:e,abort(f){c||(s.abort(),c=!0),h.closeRead(),l=!0,a()},close(){h.closeRead(),h.closeWrite(),a()},closeRead(){l||(o.cancel().catch(f=>{f.toString().includes("RESET_STREAM")===!0&&(c=!0)}),l=!0),c&&a()},closeWrite(){c||(c=!0,s.close().catch(f=>{f.toString().includes("RESET_STREAM")===!0&&(l=!0)})),l&&a()},reset(){h.close()},stat:{direction:t,timeline:{open:Date.now()}},metadata:{},source:async function*(){for(;;){let f=await o.read();if(f.done===!0){l=!0,c&&a();return}yield new j(f.value)}}(),sink:async function(f){if(u)throw new Error("sink already called on stream");u=!0;try{for await(let d of f)if(d instanceof Uint8Array)await s.write(d);else for(let p of d)await s.write(p)}finally{h.closeWrite()}}};return h}function iG(r){let e=r.stringTuples(),{url:t,certhashes:n,remotePeer:i}=e.reduce((s,[o,a])=>{switch(o){case X("ip6").code:case X("dns6").code:a?.includes(":")===!0&&(a=`[${a}]`);case X("ip4").code:case X("dns4").code:if(s.seenHost||s.seenPort)throw new Error("Invalid multiaddr, saw host and already saw the host or port");return{...s,url:`${s.url}${a??""}`,seenHost:!0};case X("quic").code:case X("quic-v1").code:case X("webtransport").code:if(!s.seenHost||!s.seenPort)throw new Error("Invalid multiaddr, Didn't see host and port, but saw quic/webtransport");return s;case X("udp").code:if(s.seenPort)throw new Error("Invalid multiaddr, saw port but already saw the port");return{...s,url:`${s.url}:${a??""}`,seenPort:!0};case X("certhash").code:if(!s.seenHost||!s.seenPort)throw new Error("Invalid multiaddr, saw the certhash before seeing the host and port");return{...s,certhashes:s.certhashes.concat([nG(a??"")])};case X("p2p").code:return{...s,remotePeer:oe(a??"")};default:throw new Error(`unexpected component in multiaddr: ${o} ${X(o).name} ${a??""} `)}},{url:"https://",seenHost:!1,seenPort:!1,certhashes:[]});return{url:t,certhashes:n,remotePeer:i}}function sG(r,e){return e.filter(n=>!!r.find(i=>{if(n.length!==i.length)return!1;for(let s=0;s<n.length;s++)if(i[s]!==n[s])return!1;return!0})).length===e.length}var V5=class{components;config;constructor(e,t={}){this.components=e,this.config={maxInboundStreams:t.maxInboundStreams??1e3}}[Symbol.toStringTag]="@libp2p/webtransport";[Ti]=!0;async dial(e,t){Hr("dialing %s",e);let n=this.components.peerId;if(n===void 0)throw new Error("Need a local peerid");t=t??{};let{url:i,certhashes:s,remotePeer:o}=iG(e);if(s.length===0)throw new Error("Expected multiaddr to contain certhashes");let a=new WebTransport(`${i}/.well-known/libp2p-webtransport?type=noise`,{serverCertificateHashes:s.map(l=>({algorithm:"sha-256",value:l.digest}))});if(a.closed.catch(l=>{Hr.error("WebTransport transport closed due to:",l)}),await a.ready,o==null)throw new Error("Need a target peerid");if(!await this.authenticateWebTransport(a,n,o,s))throw new Error("Failed to authenticate webtransport");let c={close:async l=>{l!=null&&Hr("Closing webtransport with err:",l),a.close()},remoteAddr:e,timeline:{open:Date.now()},...qT()};a.closed.catch(l=>{Hr.error("WebTransport connection closed:",l),c.timeline.close=Date.now()});try{t?.signal?.throwIfAborted()}catch(l){throw a.close(),l}return t.upgrader.upgradeOutbound(c,{skipEncryption:!0,muxerFactory:this.webtransportMuxer(a),skipProtection:!0})}async authenticateWebTransport(e,t,n,i){let s=await e.createBidirectionalStream(),o=s.writable.getWriter(),a=s.readable.getReader();await o.ready;let c={source:async function*(){for(;;){let h=await a.read();if(h.value!=null&&(yield h.value),h.done===!0)break}}(),sink:async function(h){for await(let f of h)await o.write(f)}},l=VT()(),{remoteExtensions:u}=await l.secureOutbound(t,c,n);if(o.close().catch(h=>{Hr.error(`Failed to close authentication stream writer: ${h.message}`)}),a.cancel().catch(h=>{Hr.error(`Failed to close authentication stream reader: ${h.message}`)}),!sG(u?.webtransportCerthashes??[],i.map(h=>h.bytes)))throw new Error("Our certhashes are not a subset of the remote's reported certhashes");return!0}webtransportMuxer(e){let t=0,n=this.config;return{protocol:"webtransport",createStreamMuxer:i=>{typeof i=="function"&&(i={onIncomingStream:i});let s=[];(async function(){let a=e.incomingBidirectionalStreams.getReader();for(;;){let{done:c,value:l}=await a.read();if(c===!0)break;if(s.length>=n.maxInboundStreams)l.writable.close().catch(u=>{Hr.error(`Failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)}),l.readable.cancel().catch(u=>{Hr.error(`Failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)});else{let u=await zT(l,String(t++),"inbound",s,i?.onStreamEnd);s.push(u),i?.onIncomingStream?.(u)}}})().catch(()=>{Hr.error("WebTransport failed to receive incoming stream")});let o={protocol:"webtransport",streams:s,newStream:async a=>{let c=await e.createBidirectionalStream(),l=await zT(c,String(t++),i?.direction??"outbound",s,i?.onStreamEnd);return s.push(l),l},close:a=>{a!=null&&Hr("Closing webtransport muxer with err:",a),e.close()},...qT()};try{i?.signal?.throwIfAborted()}catch(a){throw e.close(),a}return o}}}createListener(e){throw new Error("Webtransport servers are not supported in Node or the browser")}filter(e){return e.filter(t=>t.protoNames().includes("webtransport"))}};function HT(r={}){return e=>new V5(e,r)}var Ui;(function(r){let e;(function(i){i.EOL="EOL"})(e=r.ValidityType||(r.ValidityType={}));let t;(function(i){i[i.EOL=0]="EOL"})(t||(t={})),function(i){i.codec=()=>At(t)}(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=ne((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.value!=null&&(s.uint32(10),s.bytes(i.value)),i.signature!=null&&(s.uint32(18),s.bytes(i.signature)),i.validityType!=null&&(s.uint32(24),r.ValidityType.codec().encode(i.validityType,s)),i.validity!=null&&(s.uint32(34),s.bytes(i.validity)),i.sequence!=null&&(s.uint32(40),s.uint64(i.sequence)),i.ttl!=null&&(s.uint32(48),s.uint64(i.ttl)),i.pubKey!=null&&(s.uint32(58),s.bytes(i.pubKey)),i.signatureV2!=null&&(s.uint32(66),s.bytes(i.signatureV2)),i.data!=null&&(s.uint32(74),s.bytes(i.data)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.value=i.bytes();break;case 2:o.signature=i.bytes();break;case 3:o.validityType=r.ValidityType.codec().decode(i);break;case 4:o.validity=i.bytes();break;case 5:o.sequence=i.uint64();break;case 6:o.ttl=i.uint64();break;case 7:o.pubKey=i.bytes();break;case 8:o.signatureV2=i.bytes();break;case 9:o.data=i.bytes();break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>re(i,r.codec()),r.decode=i=>te(i,r.codec())})(Ui||(Ui={}));var oh=F(li(),1);var $T="ERR_IPNS_EXPIRED_RECORD",zd="ERR_UNRECOGNIZED_VALIDITY";var ho="ERR_SIGNATURE_VERIFICATION",GT="ERR_UNRECOGNIZED_FORMAT";var q5="ERR_UNDEFINED_PARAMETER",WT="ERR_INVALID_RECORD_DATA",YT="ERR_INVALID_EMBEDDED_KEY";var XT=T("ipns:utils"),oG=K("/ipns/");function ah(r){let e=new RegExp("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d+)Z"),t=String(r).trim().match(e);if(t==null)throw new Error("Invalid format");let n=parseInt(t[1],10),i=parseInt(t[2],10)-1,s=parseInt(t[3],10),o=parseInt(t[4],10),a=parseInt(t[5],10),c=parseInt(t[6],10),l=parseInt(t[7].slice(0,-6),10);return new Date(Date.UTC(n,i,s,o,a,c,l))}var jT=async(r,e)=>{if(e==null||r==null){let n=new Error("one or more of the provided parameters are not defined");throw XT.error(n),(0,oh.default)(n,q5)}let t;if(e.pubKey!=null){try{t=rr(e.pubKey)}catch(i){throw XT.error(i),i}if(!(await zt(e.pubKey)).equals(r))throw(0,oh.default)(new Error("Embedded public key did not match PeerID"),YT)}else r.publicKey!=null&&(t=rr(r.publicKey));if(t!=null)return t;throw(0,oh.default)(new Error("no public key is available"),q5)};var ZT=r=>{let e=K("ipns-signature:");return le([e,r])};var JT=r=>{let e=Ui.decode(r);return e.sequence!=null&&(e.sequence=BigInt(e.sequence)),e.ttl!=null&&(e.ttl=BigInt(e.ttl)),{value:e.value??new Uint8Array(0),signature:e.signature??new Uint8Array(0),validityType:e.validityType??Ui.ValidityType.EOL,validity:e.validity??new Uint8Array(0),sequence:e.sequence??0n,pubKey:e.pubKey,ttl:e.ttl??void 0,signatureV2:e.signatureV2,data:e.data}};var eD=r=>vt(r.slice(oG.length));var tD=r=>{let e=zn(r);if(e.ValidityType===0)e.ValidityType=Ui.ValidityType.EOL;else throw(0,oh.default)(new Error("Unknown validity type"),zd);return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e};var rD=(r,e)=>{let t=e.map((n,i)=>({entry:Ui.decode(n),index:i}));return t.sort((n,i)=>{if(n.entry.signatureV2!=null&&i.entry.signatureV2==null)return-1;if(n.entry.signatureV2==null&&i.entry.signatureV2!=null)return 1;let s=n.entry.sequence??0n,o=i.entry.sequence??0n;if(s>o)return-1;if(s<o)return 1;let a=n.entry.validity??new Uint8Array(0),c=i.entry.validity??new Uint8Array(0),l=ah(O(a)),u=ah(O(c));return l.getTime()>u.getTime()?-1:l.getTime()<u.getTime()?1:0}),t[0].index};var Ln=F(li(),1);var ch=T("ipns:validator"),aG=async(r,e)=>{let{value:t,validityType:n,validity:i}=e,s,o;if(e.signatureV2!=null&&e.data!=null)o=e.signatureV2,s=ZT(e.data),cG(e);else throw(0,Ln.default)(new Error("missing data or signatureV2"),ho);let a;try{a=await r.verify(s,o)}catch{a=!1}if(!a)throw ch.error("record signature verification failed"),(0,Ln.default)(new Error("record signature verification failed"),ho);if(i!=null&&n===Ui.ValidityType.EOL){let c;try{c=ah(O(i))}catch{throw ch.error("unrecognized validity format (not an rfc3339 format)"),(0,Ln.default)(new Error("unrecognized validity format (not an rfc3339 format)"),GT)}if(c.getTime()<Date.now())throw ch.error("record has expired"),(0,Ln.default)(new Error("record has expired"),$T)}else if(n!=null)throw ch.error("unrecognized validity type"),(0,Ln.default)(new Error("unrecognized validity type"),zd);ch("ipns entry for %b is valid",t)},cG=r=>{if(r.data==null)throw(0,Ln.default)(new Error("Record data is missing"),WT);let e=tD(r.data);if(!de(e.Value,r.value))throw(0,Ln.default)(new Error('Field "value" did not match between protobuf and CBOR'),ho);if(!de(e.Validity,r.validity))throw(0,Ln.default)(new Error('Field "validity" did not match between protobuf and CBOR'),ho);if(e.ValidityType!==r.validityType)throw(0,Ln.default)(new Error('Field "validityType" did not match between protobuf and CBOR'),ho);if(e.Sequence!==r.sequence)throw(0,Ln.default)(new Error('Field "sequence" did not match between protobuf and CBOR'),ho);if(e.TTL!==r.ttl)throw(0,Ln.default)(new Error('Field "ttl" did not match between protobuf and CBOR'),ho)},nD=async(r,e)=>{let t=eD(r),n=JT(e),i=await jT(t,n);await aG(i,n)};var H5=F(jr(),1);var iD="libp2p",sD="autonat",oD="1.0.0";var we;(function(r){let e;(function(l){l.DIAL="DIAL",l.DIAL_RESPONSE="DIAL_RESPONSE"})(e=r.MessageType||(r.MessageType={}));let t;(function(l){l[l.DIAL=0]="DIAL",l[l.DIAL_RESPONSE=1]="DIAL_RESPONSE"})(t||(t={})),function(l){l.codec=()=>At(t)}(e=r.MessageType||(r.MessageType={}));let n;(function(l){l.OK="OK",l.E_DIAL_ERROR="E_DIAL_ERROR",l.E_DIAL_REFUSED="E_DIAL_REFUSED",l.E_BAD_REQUEST="E_BAD_REQUEST",l.E_INTERNAL_ERROR="E_INTERNAL_ERROR"})(n=r.ResponseStatus||(r.ResponseStatus={}));let i;(function(l){l[l.OK=0]="OK",l[l.E_DIAL_ERROR=100]="E_DIAL_ERROR",l[l.E_DIAL_REFUSED=101]="E_DIAL_REFUSED",l[l.E_BAD_REQUEST=200]="E_BAD_REQUEST",l[l.E_INTERNAL_ERROR=300]="E_INTERNAL_ERROR"})(i||(i={})),function(l){l.codec=()=>At(i)}(n=r.ResponseStatus||(r.ResponseStatus={}));let s;(function(l){let u;l.codec=()=>(u==null&&(u=ne((h,f,d={})=>{if(d.lengthDelimited!==!1&&f.fork(),h.id!=null&&(f.uint32(10),f.bytes(h.id)),h.addrs!=null)for(let p of h.addrs)f.uint32(18),f.bytes(p);d.lengthDelimited!==!1&&f.ldelim()},(h,f)=>{let d={addrs:[]},p=f==null?h.len:h.pos+f;for(;h.pos<p;){let m=h.uint32();switch(m>>>3){case 1:d.id=h.bytes();break;case 2:d.addrs.push(h.bytes());break;default:h.skipType(m&7);break}}return d})),u),l.encode=h=>re(h,l.codec()),l.decode=h=>te(h,l.codec())})(s=r.PeerInfo||(r.PeerInfo={}));let o;(function(l){let u;l.codec=()=>(u==null&&(u=ne((h,f,d={})=>{d.lengthDelimited!==!1&&f.fork(),h.peer!=null&&(f.uint32(10),r.PeerInfo.codec().encode(h.peer,f)),d.lengthDelimited!==!1&&f.ldelim()},(h,f)=>{let d={},p=f==null?h.len:h.pos+f;for(;h.pos<p;){let m=h.uint32();switch(m>>>3){case 1:d.peer=r.PeerInfo.codec().decode(h,h.uint32());break;default:h.skipType(m&7);break}}return d})),u),l.encode=h=>re(h,l.codec()),l.decode=h=>te(h,l.codec())})(o=r.Dial||(r.Dial={}));let a;(function(l){let u;l.codec=()=>(u==null&&(u=ne((h,f,d={})=>{d.lengthDelimited!==!1&&f.fork(),h.status!=null&&(f.uint32(8),r.ResponseStatus.codec().encode(h.status,f)),h.statusText!=null&&(f.uint32(18),f.string(h.statusText)),h.addr!=null&&(f.uint32(26),f.bytes(h.addr)),d.lengthDelimited!==!1&&f.ldelim()},(h,f)=>{let d={},p=f==null?h.len:h.pos+f;for(;h.pos<p;){let m=h.uint32();switch(m>>>3){case 1:d.status=r.ResponseStatus.codec().decode(h);break;case 2:d.statusText=h.string();break;case 3:d.addr=h.bytes();break;default:h.skipType(m&7);break}}return d})),u),l.encode=h=>re(h,l.codec()),l.decode=h=>te(h,l.codec())})(a=r.DialResponse||(r.DialResponse={}));let c;r.codec=()=>(c==null&&(c=ne((l,u,h={})=>{h.lengthDelimited!==!1&&u.fork(),l.type!=null&&(u.uint32(8),r.MessageType.codec().encode(l.type,u)),l.dial!=null&&(u.uint32(18),r.Dial.codec().encode(l.dial,u)),l.dialResponse!=null&&(u.uint32(26),r.DialResponse.codec().encode(l.dialResponse,u)),h.lengthDelimited!==!1&&u.ldelim()},(l,u)=>{let h={},f=u==null?l.len:l.pos+u;for(;l.pos<f;){let d=l.uint32();switch(d>>>3){case 1:h.type=r.MessageType.codec().decode(l);break;case 2:h.dial=r.Dial.codec().decode(l,l.uint32());break;case 3:h.dialResponse=r.DialResponse.codec().decode(l,l.uint32());break;default:l.skipType(d&7);break}}return h})),c),r.encode=l=>re(l,r.codec()),r.decode=l=>te(l,r.codec())})(we||(we={}));var Ye=T("libp2p:autonat"),z5=4,$5=class{components;startupDelay;refreshInterval;protocol;timeout;maxInboundStreams;maxOutboundStreams;verifyAddressTimeout;started;constructor(e,t){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix??iD}/${sD}/${oD}`,this.timeout=t.timeout??3e4,this.maxInboundStreams=t.maxInboundStreams??1,this.maxOutboundStreams=t.maxOutboundStreams??1,this.startupDelay=t.startupDelay??5e3,this.refreshInterval=t.refreshInterval??6e4,this._verifyExternalAddresses=this._verifyExternalAddresses.bind(this)}isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(this.protocol,e=>{this.handleIncomingAutonatStream(e).catch(t=>{Ye.error("error handling incoming autonat stream",t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.startupDelay),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),clearTimeout(this.verifyAddressTimeout),this.started=!1}async handleIncomingAutonatStream(e){let t=st([AbortSignal.timeout(this.timeout)]);try{(0,H5.setMaxListeners)?.(1/0,t)}catch{}let n=this.components.addressManager.getAddresses().map(i=>i.toOptions().host);try{let i=br(e.stream,t),s=this;await be(i,o=>Tt(o),async function*(o){let a=await Jn(o);if(a==null){Ye("no message received"),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"No message was sent"}});return}let c;try{c=we.decode(a)}catch(m){Ye.error("could not decode message",m),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"Could not decode message"}});return}let l=c.dial;if(l==null){Ye.error("dial was missing from message"),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"No Dial message found in message"}});return}let u,h=l.peer;if(h==null||h.id==null){Ye.error("PeerId missing from message"),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"missing peer info"}});return}try{u=vt(h.id)}catch(m){Ye.error("invalid PeerId",m),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"bad peer id"}});return}if(Ye("incoming request from %p",u),!e.connection.remotePeer.equals(u)){Ye("target peer %p did not equal sending peer %p",u,e.connection.remotePeer),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"peer id mismatch"}});return}let f=h.addrs.map(m=>se(m)).filter(m=>{let g=m.toOptions().host===e.connection.remoteAddr.toOptions().host;return Ye.trace("request to dial %s was sent from %s is same host %s",m,e.connection.remoteAddr,g),g}).filter(m=>{let g=m.toOptions().host,y=!(An(g)??!1);return Ye.trace("host %s was public %s",g,y),y}).filter(m=>{let g=m.toOptions().host,y=!n.includes(g);return Ye.trace("host %s was not our host %s",g,y),y}).filter(m=>{let g=!!s.components.transportManager.transportForMultiaddr(m);return Ye.trace("transport for %s is supported %s",m,g),g}).map(m=>(m.getPeerId()==null&&(m=m.encapsulate(`/p2p/${u.toString()}`)),m));if(f.length===0){Ye("no valid multiaddrs for %p in message",u),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_DIAL_REFUSED,statusText:"no dialable addresses"}});return}Ye("dial multiaddrs %s for peer %p",f.map(m=>m.toString()).join(", "),u);let d="",p=f[0];for await(let m of f){let g;p=m;try{if(g=await s.components.connectionManager.openConnection(m,{signal:t}),!g.remoteAddr.equals(m))throw Ye.error("tried to dial %s but dialed %s",m,g.remoteAddr),new Error("Unexpected remote address");Ye("Success %p",u),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.OK,addr:g.remoteAddr.decapsulateCode(X("p2p").code).bytes}});return}catch(y){Ye("could not dial %p",u,y),d=y.message}finally{g!=null&&await g.close()}}yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_DIAL_ERROR,statusText:d,addr:p.bytes}})},o=>yt(o),e.stream)}catch(i){Ye.error("error handling incoming autonat stream",i)}finally{t.clear()}}_verifyExternalAddresses(){this.verifyExternalAddresses().catch(e=>{Ye.error("error verifying external address",e)})}async verifyExternalAddresses(){if(clearTimeout(this.verifyAddressTimeout),!this.isStarted())return;let e=this.components.addressManager,t=e.getObservedAddrs().filter(s=>{let o=s.toOptions();return!(An(o.host)??!1)});if(t.length===0){Ye("no public addresses found, not requesting verification"),this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.refreshInterval);return}let n=AbortSignal.timeout(this.timeout);try{(0,H5.setMaxListeners)?.(1/0,n)}catch{}let i=this;try{Ye("verify multiaddrs %s",t.map(h=>h.toString()).join(", "));let s=we.encode({type:we.MessageType.DIAL,dial:{peer:{id:this.components.peerId.toBytes(),addrs:t.map(h=>h.bytes)}}}),a=(await r0()).toBytes(),c={},l=[],u=async h=>{try{Ye("asking %p to verify multiaddr",h.id);let f=await i.components.connectionManager.openConnection(h.id,{signal:n}),d=await f.newStream(this.protocol,{signal:n}),p=br(d,n),m=await be([s],y=>yt(y),p,y=>Tt(y),async y=>Jn(y));if(m==null){Ye("no response received from %p",f.remotePeer);return}let g=we.decode(m);if(g.type!==we.MessageType.DIAL_RESPONSE||g.dialResponse==null){Ye("invalid autonat response from %p",f.remotePeer);return}if(g.dialResponse.status===we.ResponseStatus.OK){let y=f.remoteAddr.toOptions(),b;if(y.family===4)b=y.host.split(".")[0];else if(y.family===6)b=y.host.split(":")[0];else{Ye('remote address "%s" was not IP4 or IP6?',y.host);return}if(l.includes(b)){Ye("already have response from network segment %d - %s",b,y.host);return}l.push(b)}return g.dialResponse}catch(f){Ye.error("error asking remote to verify multiaddr",f)}};for await(let h of Zo(Un(this.components.peerRouting.getClosestPeers(a,{signal:n}),f=>async()=>u(f)),{concurrency:z5}))try{if(h==null)continue;let f=h.addr==null?t[0]:se(h.addr);if(Ye("autonat response for %s is %s",f,h.status),h.status===we.ResponseStatus.E_BAD_REQUEST||h.status===we.ResponseStatus.E_DIAL_REFUSED||h.addr==null&&t.length>1)continue;if(!t.some(p=>p.equals(f))){Ye("peer reported %s as %s but it was not in our observed address list",f,h.status);continue}let d=f.toString();if(c[d]==null&&(c[d]={success:0,failure:0}),h.status===we.ResponseStatus.OK?c[d].success++:h.status===we.ResponseStatus.E_DIAL_ERROR&&c[d].failure++,c[d].success===z5){Ye("%s is externally dialable",f),e.confirmObservedAddr(f);return}if(c[d].failure===z5){Ye("%s is not externally dialable",f),e.removeObservedAddr(f);return}}catch(f){Ye.error("could not verify external address",f)}}finally{this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.refreshInterval)}}};function aD(r={}){return e=>new $5(e,r)}var bG=F(jr(),1);var G5="/libp2p/relay";var cD="circuit-relay-relay";var lD=BigInt(131072),fo="/libp2p/circuit/relay/0.2.0/hop",Hd="/libp2p/circuit/relay/0.2.0/stop",pG=30*1e3,mG=30*1e3;var ps;(function(r){let e;(function(i){i.RESERVE="RESERVE",i.CONNECT="CONNECT",i.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(i){i[i.RESERVE=0]="RESERVE",i[i.CONNECT=1]="CONNECT",i[i.STATUS=2]="STATUS"})(t||(t={})),function(i){i.codec=()=>At(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=ne((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.type!=null&&(s.uint32(8),r.Type.codec().encode(i.type,s)),i.peer!=null&&(s.uint32(18),Jc.codec().encode(i.peer,s)),i.reservation!=null&&(s.uint32(26),$d.codec().encode(i.reservation,s)),i.limit!=null&&(s.uint32(34),el.codec().encode(i.limit,s)),i.status!=null&&(s.uint32(40),or.codec().encode(i.status,s)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.type=r.Type.codec().decode(i);break;case 2:o.peer=Jc.codec().decode(i,i.uint32());break;case 3:o.reservation=$d.codec().decode(i,i.uint32());break;case 4:o.limit=el.codec().decode(i,i.uint32());break;case 5:o.status=or.codec().decode(i);break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>re(i,r.codec()),r.decode=i=>te(i,r.codec())})(ps||(ps={}));var ai;(function(r){let e;(function(i){i.CONNECT="CONNECT",i.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(i){i[i.CONNECT=0]="CONNECT",i[i.STATUS=1]="STATUS"})(t||(t={})),function(i){i.codec=()=>At(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=ne((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.type!=null&&(s.uint32(8),r.Type.codec().encode(i.type,s)),i.peer!=null&&(s.uint32(18),Jc.codec().encode(i.peer,s)),i.limit!=null&&(s.uint32(26),el.codec().encode(i.limit,s)),i.status!=null&&(s.uint32(32),or.codec().encode(i.status,s)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.type=r.Type.codec().decode(i);break;case 2:o.peer=Jc.codec().decode(i,i.uint32());break;case 3:o.limit=el.codec().decode(i,i.uint32());break;case 4:o.status=or.codec().decode(i);break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>re(i,r.codec()),r.decode=i=>te(i,r.codec())})(ai||(ai={}));var Jc;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.id!=null&&t.id.byteLength>0&&(n.uint32(10),n.bytes(t.id)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={id:new Uint8Array(0),addrs:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.id=t.bytes();break;case 2:i.addrs.push(t.bytes());break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(Jc||(Jc={}));var $d;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.expire!=null&&t.expire!==0n&&(n.uint32(8),n.uint64(t.expire)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);t.voucher!=null&&(n.uint32(26),n.bytes(t.voucher)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={expire:0n,addrs:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.expire=t.uint64();break;case 2:i.addrs.push(t.bytes());break;case 3:i.voucher=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})($d||($d={}));var el;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.duration!=null&&(n.uint32(8),n.uint32(t.duration)),t.data!=null&&(n.uint32(16),n.uint64(t.data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.duration=t.uint32();break;case 2:i.data=t.uint64();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(el||(el={}));var or;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(or||(or={}));var W5;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(W5||(W5={}));(function(r){r.codec=()=>At(W5)})(or||(or={}));var Y5;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.relay!=null&&t.relay.byteLength>0&&(n.uint32(10),n.bytes(t.relay)),t.peer!=null&&t.peer.byteLength>0&&(n.uint32(18),n.bytes(t.peer)),t.expiration!=null&&t.expiration!==0n&&(n.uint32(24),n.uint64(t.expiration)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={relay:new Uint8Array(0),peer:new Uint8Array(0),expiration:0n},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.relay=t.bytes();break;case 2:i.peer=t.bytes();break;case 3:i.expiration=t.uint64();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(Y5||(Y5={}));var A7e=T("libp2p:circuit-relay:utils");async function Q5(r){let e=new TextEncoder().encode(r),t=await Ce.digest(e);return ee.createV0(t)}function X5(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var wG=F(pD(),1);var K7e=T("libp2p:circuit-relay:advert-service");var m9e=T("libp2p:circuit-relay:server");var EG=T("libp2p:stream:converter");function j5(r,e={}){let{stream:t,remoteAddr:n}=r,{sink:i,source:s}=t,o=async function*(){for await(let l of s)l instanceof Uint8Array?yield l:yield*l}(),a={async sink(l){e.signal!=null&&(l=gt(l,e.signal));try{await i(l),await c()}catch(u){u.type!=="aborted"&&EG(u)}},source:e.signal!=null?gt(o,e.signal):o,remoteAddr:n,timeline:{open:Date.now(),close:void 0},async close(){await i(async function*(){yield new Uint8Array(0)}()),await c()}};async function c(){a.timeline.close==null&&(a.timeline.close=Date.now()),await Promise.resolve()}return a}var po=T("libp2p:circuit-relay:discover-relays"),Gd=class extends Fe{peerId;peerStore;contentRouting;registrar;started;topologyId;constructor(e){super(),this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.contentRouting=e.contentRouting,this.registrar=e.registrar}isStarted(){return this.started}async start(){this.topologyId=await this.registrar.register(fo,Es({onConnect:e=>{this.safeDispatchEvent("relay:discover",{detail:e})}})),this.discover().catch(e=>{po.error("error listening on relays",e)}),this.started=!0}stop(){this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.started=!1}async discover(){po("searching peer store for relays");let e=(await this.peerStore.all()).filter(({protocols:t})=>t.includes(fo)).sort(()=>Math.random()-.5);for(let t of e)po("found relay peer %p in content peer store",t.id),this.safeDispatchEvent("relay:discover",{detail:t.id});po("found %d relay peers in peer store",e.length);try{po("searching content routing for relays");let t=await Q5(G5),n=0;for await(let i of this.contentRouting.findProviders(t))if(i.multiaddrs.length>0&&!i.id.equals(this.peerId)){let s=i.id;n++,await this.peerStore.merge(s,{multiaddrs:i.multiaddrs}),po("found relay peer %p in content routing",s),this.safeDispatchEvent("relay:discover",{detail:s})}po("found %d relay peers in content routing",n)}catch(t){po.error("failed when finding relays on the network",t)}}};var gD=T("libp2p:circuit-relay:transport:listener"),Z5=class extends Fe{connectionManager;relayStore;listeningAddrs;constructor(e){super(),this.connectionManager=e.connectionManager,this.relayStore=e.relayStore,this.listeningAddrs=new Fr,this.relayStore.addEventListener("relay:removed",t=>{this.#e(t.detail)})}async listen(e){gD("listen on %s",e);let t=e.getPeerId(),n;if(t!=null){let s=oe(t),o=this.connectionManager.getConnectionsMap().get(s)??[];o.length>0&&(n=o[0])}if(n==null){let s=e.toString().split("/p2p-circuit").find(a=>a!==""),o=se(s);n=await this.connectionManager.openConnection(o)}if(!this.relayStore.hasReservation(n.remotePeer)){await this.relayStore.addRelay(n.remotePeer,"configured");return}let i=this.relayStore.getReservation(n.remotePeer);if(i==null)throw new w("Did not have reservation after making reservation","ERR_NO_RESERVATION");if(this.listeningAddrs.has(n.remotePeer)){gD("already listening on relay %p",n.remotePeer);return}this.listeningAddrs.set(n.remotePeer,i.addrs.map(s=>se(s).encapsulate("/p2p-circuit"))),this.safeDispatchEvent("listening",{})}getAddrs(){return[...this.listeningAddrs.values()].flat()}async close(){}#e(e){let t=this.listeningAddrs.has(e);this.listeningAddrs.delete(e),t&&this.safeDispatchEvent("close",{})}};function yD(r){return new Z5(r)}var yn=T("libp2p:circuit-relay:transport:reservation-store"),xG=60*1e3*10,_G=60*1e3*5,SG=30*1e3,Wd=class extends Fe{peerId;connectionManager;transportManager;peerStore;events;reserveQueue;reservations;maxDiscoveredRelays;started;constructor(e,t){super(),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.transportManager=e.transportManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new Fr,this.maxDiscoveredRelays=t?.discoverRelays??0,this.started=!1,this.reserveQueue=new wt({concurrency:t?.reservationConcurrency??1}),this.events.addEventListener("peer:disconnect",n=>{this.#t(n.detail)})}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!0}async addRelay(e,t){if(this.peerId.equals(e)){yn("not trying to use self as relay");return}yn("add relay %p",e),await this.reserveQueue.add(async()=>{try{let n=this.reservations.get(e);if(n!=null){if(X5(n.reservation.expire)>xG){yn("already have reservation on relay peer %p and it expires in more than 10 minutes",e);return}clearTimeout(n.timeout),this.reservations.delete(e)}if(t==="discovered"&&[...this.reservations.values()].reduce((l,u)=>(u.type==="discovered"&&l++,l),0)>=this.maxDiscoveredRelays){yn("already have enough discovered relays");return}let i=await this.connectionManager.openConnection(e);if(i.remoteAddr.protoNames().includes("p2p-circuit")){yn("not creating reservation over relayed connection");return}let s=await this.#e(i);yn("created reservation on relay peer %p",e);let o=X5(s.expire),a=Math.min(Math.max(o-_G,SG),Math.pow(2,31)-1),c=setTimeout(()=>{this.addRelay(e,t).catch(l=>{yn.error("could not refresh reservation to relay %p",e,l)})},a);this.reservations.set(e,{timeout:c,reservation:s,type:t}),await this.peerStore.merge(e,{tags:{[cD]:{value:1,ttl:o}}}),await this.transportManager.listen([se(`/p2p/${e.toString()}/p2p-circuit`)])}catch(n){yn.error("could not reserve slot on %p",e,n),this.reservations.delete(e)}})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}async#e(e){yn("requesting reservation from %s",e.remotePeer);let t=await e.newStream(fo),i=qr(t).pb(ps);i.write({type:ps.Type.RESERVE});let s;try{s=await i.read()}catch(a){throw yn.error("error parsing reserve message response from %p because",e.remotePeer,a),a}finally{t.close()}if(s.status===or.OK&&s.reservation!=null)return s.reservation;let o=`reservation failed with status ${s.status??"undefined"}`;throw yn.error(o),new Error(o)}#t(e){let t=this.reservations.get(e);t!=null&&(yn("connection to relay %p closed, removing reservation from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),this.safeDispatchEvent("relay:removed",{detail:e}),this.reservations.size<this.maxDiscoveredRelays&&(yn("not enough relays %d/%d",this.reservations.size,this.maxDiscoveredRelays),this.safeDispatchEvent("relay:not-enough-relays",{})))}};var $r=T("libp2p:circuit-relay:transport"),RG=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(se)}catch{return!1}return!0},J5=class{discovery;registrar;peerStore;connectionManager;peerId;upgrader;addressManager;connectionGater;reservationStore;started;constructor(e,t){this.registrar=e.registrar,this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.peerId=e.peerId,this.upgrader=e.upgrader,this.addressManager=e.addressManager,this.connectionGater=e.connectionGater,t.discoverRelays!=null&&t.discoverRelays>0&&(this.discovery=new Gd(e),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(i=>{$r.error("could not add discovered relay %p",n.detail,i)})})),this.reservationStore=new Wd(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.discover().catch(n=>{$r.error("could not discover relays",n)})}),this.started=!1}isStarted(){return this.started}async start(){await this.reservationStore.start(),await this.discovery?.start(),await this.registrar.handle(Hd,e=>{this.onStop(e).catch(t=>{$r.error(t)})}),this.started=!0}async stop(){this.discovery?.stop(),await this.reservationStore.stop(),await this.registrar.unhandle(Hd),this.started=!1}[Ti]=!0;[Symbol.toStringTag]="libp2p/circuit-relay-v2";async dial(e,t={}){if(e.protoCodes().filter(p=>p===290).length!==1){let p="Invalid circuit relay address";throw $r.error(p,e),new w(p,q.ERR_RELAYED_DIAL)}let n=e.toString().split("/p2p-circuit"),i=se(n[0]),s=se(n[n.length-1]),o=i.getPeerId(),a=s.getPeerId();if(o==null||a==null){let p=`Circuit relay dial to ${e.toString()} failed as address did not have peer ids`;throw $r.error(p),new w(p,q.ERR_RELAYED_DIAL)}let c=oe(o),l=oe(a),u=!1,f=this.connectionManager.getConnections(c)[0];f==null&&(await this.peerStore.merge(c,{multiaddrs:[i]}),f=await this.connectionManager.openConnection(c,t),u=!0);let d;try{return d=await f.newStream([fo]),await this.connectV2({stream:d,connection:f,destinationPeer:l,destinationAddr:s,relayAddr:i,ma:e,disconnectOnFailure:u})}catch(p){throw $r.error(`Circuit relay dial to destination ${l.toString()} via relay ${c.toString()} failed`,p),d?.abort(p),u&&await f.close(),p}}async connectV2({stream:e,connection:t,destinationPeer:n,destinationAddr:i,relayAddr:s,ma:o,disconnectOnFailure:a}){try{let c=qr(e),l=c.pb(ps);l.write({type:ps.Type.CONNECT,peer:{id:n.toBytes(),addrs:[se(i).bytes]}});let u=await l.read();if(u.status!==or.OK)throw new w(`failed to connect via relay with status ${u?.status?.toString()??"undefined"}`,q.ERR_HOP_REQUEST_FAILED);let h=j5({stream:c.unwrap(),remoteAddr:o,localAddr:s.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`)});return $r("new outbound connection %s",h.remoteAddr),await this.upgrader.upgradeOutbound(h)}catch(c){throw $r.error(`Circuit relay dial to destination ${n.toString()} via relay ${t.remotePeer.toString()} failed`,c),a&&await t.close(),c}}createListener(e){return yD({connectionManager:this.connectionManager,relayStore:this.reservationStore})}filter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>ni.matches(t))}async onStop({connection:e,stream:t}){let n=qr(t),i=await n.readPB(ai);if($r("received circuit v2 stop protocol request from %s",e.remotePeer),i?.type===void 0)return;let s=n.pb(ai);if($r("new circuit relay v2 stop stream from %s",e.remotePeer),i.type!==ai.Type.CONNECT){$r.error("invalid stop connect request via peer %s",e.remotePeer),s.write({type:ai.Type.STATUS,status:or.UNEXPECTED_MESSAGE});return}if(!RG(i)){$r.error("invalid stop connect request via peer %s",e.remotePeer),s.write({type:ai.Type.STATUS,status:or.MALFORMED_MESSAGE});return}let o=vt(i.peer.id);if(await this.connectionGater.denyInboundRelayedConnection?.(e.remotePeer,o)===!0){s.write({type:ai.Type.STATUS,status:or.PERMISSION_DENIED});return}s.write({type:ai.Type.STATUS,status:or.OK});let a=e.remoteAddr.encapsulate(`/p2p-circuit/p2p/${o.toString()}`),c=this.addressManager.getAddresses()[0],l=j5({stream:n.unwrap(),remoteAddr:a,localAddr:c});$r("new inbound connection %s",l.remoteAddr),await this.upgrader.upgradeInbound(l),$r("%s connection %s upgraded","inbound",l.remoteAddr)}};function e6(r={}){return e=>new J5(e,r)}var wD="0.45.5";var t6=`js-libp2p/${wD}`;var bD="0.1.0",ED="id",vD="id/push",xD="1.0.0",_D="1.0.0";var Yd=F(jr(),1);var mo;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.protocolVersion!=null&&(n.uint32(42),n.string(t.protocolVersion)),t.agentVersion!=null&&(n.uint32(50),n.string(t.agentVersion)),t.publicKey!=null&&(n.uint32(10),n.bytes(t.publicKey)),t.listenAddrs!=null)for(let s of t.listenAddrs)n.uint32(18),n.bytes(s);if(t.observedAddr!=null&&(n.uint32(34),n.bytes(t.observedAddr)),t.protocols!=null)for(let s of t.protocols)n.uint32(26),n.string(s);t.signedPeerRecord!=null&&(n.uint32(66),n.bytes(t.signedPeerRecord)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={listenAddrs:[],protocols:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 5:i.protocolVersion=t.string();break;case 6:i.agentVersion=t.string();break;case 1:i.publicKey=t.bytes();break;case 2:i.listenAddrs.push(t.bytes());break;case 4:i.observedAddr=t.bytes();break;case 3:i.protocols.push(t.string());break;case 8:i.signedPeerRecord=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(mo||(mo={}));var Lr=T("libp2p:identify"),SD=1024*8,ci={protocolPrefix:"ipfs",agentVersion:t6,timeout:6e4,maxInboundStreams:1,maxOutboundStreams:1,maxPushIncomingStreams:1,maxPushOutgoingStreams:1,maxObservedAddresses:10,maxIdentifyMessageSize:8192},Qd=class{identifyProtocolStr;identifyPushProtocolStr;host;started;timeout;peerId;peerStore;registrar;connectionManager;addressManager;maxInboundStreams;maxOutboundStreams;maxPushIncomingStreams;maxPushOutgoingStreams;maxIdentifyMessageSize;maxObservedAddresses;events;constructor(e,t){this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.events=e.events,this.identifyProtocolStr=`/${t.protocolPrefix??ci.protocolPrefix}/${ED}/${xD}`,this.identifyPushProtocolStr=`/${t.protocolPrefix??ci.protocolPrefix}/${vD}/${_D}`,this.timeout=t.timeout??ci.timeout,this.maxInboundStreams=t.maxInboundStreams??ci.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??ci.maxOutboundStreams,this.maxPushIncomingStreams=t.maxPushIncomingStreams??ci.maxPushIncomingStreams,this.maxPushOutgoingStreams=t.maxPushOutgoingStreams??ci.maxPushOutgoingStreams,this.maxIdentifyMessageSize=t.maxIdentifyMessageSize??ci.maxIdentifyMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??ci.maxObservedAddresses,this.host={protocolVersion:`${t.protocolPrefix??ci.protocolPrefix}/${bD}`,agentVersion:t.agentVersion??ci.agentVersion},e.events.addEventListener("connection:open",n=>{let i=n.detail;this.identify(i).catch(s=>{Lr.error("error during identify trigged by connection:open",s)})}),e.events.addEventListener("self:peer:update",n=>{this.push().catch(i=>{Lr.error(i)})}),this.host.agentVersion===t6&&(ZA||XA?this.host.agentVersion+=` UserAgent=${globalThis.process.version}`:(Ad||Td||jA||JA)&&(this.host.agentVersion+=` UserAgent=${globalThis.navigator.userAgent}`))}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:K(this.host.agentVersion),ProtocolVersion:K(this.host.protocolVersion)}}),await this.registrar.handle(this.identifyProtocolStr,e=>{this._handleIdentify(e).catch(t=>{Lr.error(t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),await this.registrar.handle(this.identifyPushProtocolStr,e=>{this._handlePush(e).catch(t=>{Lr.error(t)})},{maxInboundStreams:this.maxPushIncomingStreams,maxOutboundStreams:this.maxPushOutgoingStreams}),this.started=!0)}async stop(){await this.registrar.unhandle(this.identifyProtocolStr),await this.registrar.unhandle(this.identifyPushProtocolStr),this.started=!1}async pushToConnections(e){let t=this.addressManager.getAddresses().map(u=>u.decapsulateCode(X("p2p").code)),n=new Ut({peerId:this.peerId,multiaddrs:t}),i=await Wt.seal(n,this.peerId),s=this.registrar.getProtocols(),o=await this.peerStore.get(this.peerId),a=O(o.metadata.get("AgentVersion")??K(this.host.agentVersion)),c=O(o.metadata.get("ProtocolVersion")??K(this.host.protocolVersion)),l=e.map(async u=>{let h,f=AbortSignal.timeout(this.timeout);try{(0,Yd.setMaxListeners)?.(1/0,f)}catch{}try{h=await u.newStream([this.identifyPushProtocolStr],{signal:f}),await br(h,f).sink(be([mo.encode({listenAddrs:t.map(p=>p.bytes),signedPeerRecord:i.marshal(),protocols:s,agentVersion:a,protocolVersion:c})],p=>yt(p)))}catch(d){Lr.error("could not push identify update to peer",d)}finally{h?.close()}});await Promise.all(l)}async push(){if(!this.isStarted())return;let e=[];await Promise.all(this.connectionManager.getConnections().map(async t=>{try{if(!(await this.peerStore.get(t.remotePeer)).protocols.includes(this.identifyPushProtocolStr))return;e.push(t)}catch(n){if(n.code!==q.ERR_NOT_FOUND)throw n}})),await this.pushToConnections(e)}async _identify(e,t={}){let n,i=st([AbortSignal.timeout(this.timeout),t?.signal]);try{(0,Yd.setMaxListeners)?.(1/0,i)}catch{}try{n=await e.newStream([this.identifyProtocolStr],{signal:i});let s=br(n,i),o=await be([],s,a=>Tt(a,{maxDataLength:this.maxIdentifyMessageSize??SD}),async a=>Jn(a));if(o==null)throw new w("No data could be retrieved",q.ERR_CONNECTION_ENDED);try{return mo.decode(o)}catch(a){throw new w(String(a),q.ERR_INVALID_MESSAGE)}}finally{n?.close(),i.clear()}}async identify(e,t={}){let n=await this._identify(e,t),{publicKey:i,protocols:s,observedAddr:o}=n;if(i==null)throw new w("public key was missing from identify message",q.ERR_MISSING_PUBLIC_KEY);let a=await zt(i);if(!e.remotePeer.equals(a))throw new w("identified peer does not match the expected peer",q.ERR_INVALID_PEER);if(this.peerId.equals(a))throw new w("identified peer is our own peer id?",q.ERR_INVALID_PEER);let c=IG(o);Lr("identify completed for peer %p and protocols %o",a,s),Lr("our observed address is %s",c),c!=null&&this.addressManager.getObservedAddrs().length<(this.maxObservedAddresses??1/0)&&(Lr("storing our observed address %s",c?.toString()),this.addressManager.addObservedAddr(c));let l=await this.#e(e.remotePeer,n),u={peerId:a,protocolVersion:n.protocolVersion,agentVersion:n.agentVersion,publicKey:n.publicKey,listenAddrs:n.listenAddrs.map(h=>se(h)),observedAddr:n.observedAddr==null?void 0:se(n.observedAddr),protocols:n.protocols,signedPeerRecord:l};this.events.safeDispatchEvent("peer:identify",{detail:u})}async _handleIdentify(e){let{connection:t,stream:n}=e,i=AbortSignal.timeout(this.timeout);try{(0,Yd.setMaxListeners)?.(1/0,i)}catch{}try{let s=this.peerId.publicKey??new Uint8Array(0),o=await this.peerStore.get(this.peerId),a=this.addressManager.getAddresses().map(f=>f.decapsulateCode(X("p2p").code)),c=o.peerRecordEnvelope;if(a.length>0&&c==null){let f=new Ut({peerId:this.peerId,multiaddrs:a});c=(await Wt.seal(f,this.peerId)).marshal().subarray()}let l=mo.encode({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:s,listenAddrs:a.map(f=>f.bytes),signedPeerRecord:c,observedAddr:t.remoteAddr.bytes,protocols:o.protocols}),u=br(n,i),h=be([l],f=>yt(f));await u.sink(h)}catch(s){Lr.error("could not respond to identify request",s)}finally{n.close()}}async _handlePush(e){let{connection:t,stream:n}=e;try{if(this.peerId.equals(t.remotePeer))throw new Error("received push from ourselves?");let i=br(n,AbortSignal.timeout(this.timeout)),o=await qr(i,{maxDataLength:this.maxIdentifyMessageSize??SD}).readPB(mo);await this.#e(t.remotePeer,o)}catch(i){Lr.error("received invalid message",i);return}finally{n.close()}Lr("handled push from %p",t.remotePeer)}async#e(e,t){if(Lr("received identify from %p",e),t==null)throw new Error("Message was null or undefined");let n={addresses:t.listenAddrs.map(s=>({isCertified:!1,multiaddr:se(s)})),protocols:t.protocols,metadata:new Map,peerRecordEnvelope:t.signedPeerRecord},i;if(t.signedPeerRecord!=null){Lr("received signedPeerRecord in push from %p",e);let s=t.signedPeerRecord,o=await Wt.openAndCertify(s,Ut.DOMAIN),a=Ut.createFromProtobuf(o.payload);if(!a.peerId.equals(o.peerId))throw new Error("signing key does not match PeerId in the PeerRecord");if(!e.equals(a.peerId))throw new Error("signing key does not match remote PeerId");let c;try{c=await this.peerStore.get(a.peerId)}catch(l){if(l.code!=="ERR_NOT_FOUND")throw l}if(c!=null&&(n.metadata=c.metadata,c.peerRecordEnvelope!=null)){let l=await Wt.createFromProtobuf(c.peerRecordEnvelope),u=Ut.createFromProtobuf(l.payload);u.seqNumber>=a.seqNumber&&(Lr("sequence number was lower or equal to existing sequence number - stored: %d received: %d",u.seqNumber,a.seqNumber),a=u,s=c.peerRecordEnvelope)}n.peerRecordEnvelope=s,n.addresses=a.multiaddrs.map(l=>({isCertified:!0,multiaddr:l})),i={seq:a.seqNumber,addresses:a.multiaddrs}}else Lr("%p did not send a signed peer record",e);return t.agentVersion!=null&&n.metadata.set("AgentVersion",K(t.agentVersion)),t.protocolVersion!=null&&n.metadata.set("ProtocolVersion",K(t.protocolVersion)),await this.peerStore.patch(e,n),i}};function IG(r){if(r!=null&&r.length>0)try{return se(r)}catch{}}function RD(r={}){return e=>new Qd(e,r)}var ID={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function AD(){return{addresses:{listen:["/webrtc"]},transports:[_A(),xA(),HT(),lT(),e6({discoverRelays:1})],connectionEncryption:[b1()],streamMuxers:[wS(),TR()],peerDiscovery:[CS(ID)],contentRouters:[MS("https://cid.contact")],services:{identify:RD(),autoNAT:aD(),pubsub:y_(),dht:yR({clientMode:!0,validators:{ipns:nD},selectors:{ipns:rD}})}}}async function TD(r,e){let t=AD();return e=e??{},hx({datastore:r,...t,...e,start:!1})}var r6="1.2.2",Xd="helia";var AG=T("helia");async function TG(r={}){let e=r.datastore??new wo,t=r.blockstore??new ol,n;DG(r.libp2p)?n=r.libp2p:n=await TD(e,r.libp2p);let i=new yf({...r,datastore:e,blockstore:t,libp2p:n});return r.start!==!1&&await i.start(),i.libp2p.isStarted()?await DD(i):i.libp2p.addEventListener("start",()=>{DD(i).catch(s=>{AG.error("could not add Helia to agent version",s)})}),i}function DG(r){return r==null?!1:["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"].every(t=>typeof r[t]=="function")}async function DD(r){let t=(await r.libp2p.peerStore.get(r.libp2p.peerId)).metadata.get("AgentVersion");if(t==null)return;let n=new TextDecoder().decode(t);n.match(/js-libp2p\/\d+\.\d+\.\d+\sUserAgent=/)!=null&&(n.includes(Xd)?n=`${Xd}/${r6} ${n.split(" ").slice(1).join(" ")}`:n=`${Xd}/${r6} ${n}`,await r.libp2p.peerStore.merge(r.libp2p.peerId,{metadata:{AgentVersion:new TextEncoder().encode(n)}}))}return uh(CG);})();
|
|
84
|
+
`),r}var bA=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),EA=r=>[...Array(r)].map(()=>bA.at(Math.floor(Math.random()*bA.length))).join("");var xd=T("libp2p:webrtc:transport"),E$=1e4,v$=X("webrtc-direct").code,m5=X("certhash").code,_d=class{metrics;components;init;constructor(e,t={}){this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dial events by type"})})}async dial(e,t){let n=await this._connect(e,t);return xd(`dialing address - ${e.toString()}`),n}createListener(e){throw DR("WebRTCTransport.createListener")}filter(e){return e.filter(x$)}[Symbol.toStringTag]="@libp2p/webrtc-direct";[Ti]=!0;async _connect(e,t){let n=new AbortController,i=n.signal,s=e.getPeerId();if(s===null)throw id("we need to have the remote's PeerId");let o=oe(s),a=d5(vd(e)),c=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:p5(a.name)}),l=new RTCPeerConnection({certificates:[c]}),u=new Promise((P,M)=>{let W=l.createDataChannel("",{negotiated:!0,id:0}),ue=setTimeout(()=>{let he=`Data channel was never opened: state: ${W.readyState}`;xd.error(he),this.metrics?.dialerEvents.increment({open_error:!0}),M(I8("data",he))},E$);W.onopen=he=>{clearTimeout(ue),P(W)},W.onerror=he=>{clearTimeout(ue);let Ve=`Error opening a data channel for handshaking: ${he.target?.toString()??"not specified"}`;xd.error(Ve),this.metrics?.dialerEvents.increment({unknown_error:!0}),M(I8("data",Ve))}}),h="libp2p+webrtc+v1/"+EA(32),f=await l.createOffer(),d=wA(f,h);await l.setLocalDescription(d);let p=yA(e,h);await l.setRemoteDescription(p);let m=await u,g=this.components.peerId,y=this.generateNoisePrologue(l,a.code,e),b=b1({prologueBytes:y})(),E=Kc({channel:m,direction:"inbound",dataChannelOptions:this.init.dataChannel}),I={...E,sink:E.sink.bind(E),source:async function*(){for await(let P of E.source)for(let M of P)yield M}()},v=new ra({peerConnection:l,remoteAddr:e,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),_=zu?"iceconnectionstatechange":"connectionstatechange";l.addEventListener(_,()=>{switch(l.connectionState){case"failed":case"disconnected":case"closed":v.close().catch(P=>{xd.error("error closing connection",P)}).finally(()=>{n.abort()});break;default:break}},{signal:i}),this.metrics?.dialerEvents.increment({peer_connection:!0});let A=new na({peerConnection:l,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await b.secureInbound(g,I,o),t.upgrader.upgradeOutbound(v,{skipProtection:!0,skipEncryption:!0,muxerFactory:A})}generateNoisePrologue(e,t,n){if(e.getConfiguration().certificates?.length===0)throw qu("no local certificate");let i=gA(e);if(i==null)throw qu("no local fingerprint found");let s=i.trim().toLowerCase().replaceAll(":",""),o=K(s,"hex"),a=vA.encode(o,t),c=f5.decode(vd(n)),l=K("libp2p-webrtc-noise:");return le([l,a,c])}};function x$(r){let e=r.protoCodes();return e.includes(v$)&&e.includes(m5)&&r.getPeerId()!=null&&!e.includes(X("p2p-circuit").code)}function xA(r){return e=>new _d(e,r)}function _A(r){return e=>new ud(e,r)}function SA(r){let e;try{e=X("sni").code}catch{return null}for(let[t,n]of r)if(t===e&&n!==void 0)return n;return null}function RA(r){return r.some(([e,t])=>e===X("tls").code)}function gn(r,e,t){let n=IA[X(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${X(r).name}`);let i=n(e,t);return r===X("ip6").code?`[${i}]`:i}var IA={ip4:(r,e)=>r,ip6:(r,e)=>e.length===0?r:`[${r}]`,tcp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`tcp://${gn(t[0],t[1]??"",e)}:${r}`},udp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`udp://${gn(t[0],t[1]??"",e)}:${r}`},dnsaddr:(r,e)=>r,dns4:(r,e)=>r,dns6:(r,e)=>r,dns:(r,e)=>r,ipfs:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${gn(t[0],t[1]??"",e)}/ipfs/${r}`},p2p:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${gn(t[0],t[1]??"",e)}/p2p/${r}`},http:(r,e)=>{let t=RA(e),n=SA(e);if(t&&n!==null)return`https://${n}`;let i=t?"https://":"http://",s=e.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let o=gn(s[0],s[1]??"",e);return o=o.replace("tcp://",""),`${i}${o}`},tls:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return gn(t[0],t[1]??"",e)},sni:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return gn(t[0],t[1]??"",e)},https:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=gn(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=RA(e),n=SA(e);if(t&&n!==null)return`wss://${n}`;let i=t?"wss://":"ws://",s=e.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let o=gn(s[0],s[1]??"",e);return o=o.replace("tcp://",""),`${i}${o}`},wss:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=gn(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${gn(t[0],t[1]??"",e)}/p2p-websocket-star`},"p2p-webrtc-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${gn(t[0],t[1]??"",e)}/p2p-webrtc-star`},"p2p-webrtc-direct":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${gn(t[0],t[1]??"",e)}/p2p-webrtc-direct`}};function AA(r,e){let n=se(r).stringTuples(),i=n.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let s=X(i[0]),o=IA[s.name];if(o==null)throw new Error(`No interpreter found for ${s.name}`);let a=o(i[1]??"",n);return e?.assumeHttp!==!1&&i[0]===X("tcp").code&&(a=a.replace("tcp://","http://"),(i[1]==="443"||i[1]==="80")&&(i[1]==="443"&&(a=a.replace("http://","https://")),a=a.substring(0,a.lastIndexOf(":")))),a}var TA=WebSocket;var kA=F(CA(),1);function PA(r){return r instanceof ArrayBuffer||r?.constructor?.name==="ArrayBuffer"&&typeof r?.byteLength=="number"}var NA=r=>{r.binaryType="arraybuffer";let e=async()=>{await new Promise((s,o)=>{if(n){s();return}if(i!=null){o(i);return}let a=u=>{r.removeEventListener("open",c),r.removeEventListener("error",l),u()},c=()=>{a(s)},l=u=>{a(()=>{o(u.error??new Error(`connect ECONNREFUSED ${r.url}`))})};r.addEventListener("open",c),r.addEventListener("error",l)})},t=async function*(){let s=new kA.EventIterator(({push:o,stop:a,fail:c})=>{let l=h=>{let f=null;typeof h.data=="string"&&(f=K(h.data)),PA(h.data)&&(f=new Uint8Array(h.data)),h.data instanceof Uint8Array&&(f=h.data),f!=null&&o(f)},u=h=>{c(h.error??new Error("Socket error"))};return r.addEventListener("message",l),r.addEventListener("error",u),r.addEventListener("close",a),()=>{r.removeEventListener("message",l),r.removeEventListener("error",u),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let o of s)yield PA(o)?new Uint8Array(o):o}(),n=r.readyState===1,i;return r.addEventListener("open",()=>{n=!0,i=null}),r.addEventListener("close",()=>{n=!1,i=null}),r.addEventListener("error",s=>{n||(i=s.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var LA=async r=>{if(r.readyState>=2)throw new Error("socket closed");r.readyState!==1&&await new Promise((e,t)=>{function n(){r.removeEventListener("open",i),r.removeEventListener("error",s)}function i(){n(),e()}function s(o){n(),t(o.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",i),r.addEventListener("error",s)})};var OA=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let i of n){try{await LA(r)}catch(s){if(s.message==="socket closed")break;throw s}r.send(i)}e.closeOnEnd!=null&&r.readyState<=1&&await new Promise((i,s)=>{r.addEventListener("close",o=>{if(o.wasClean||o.code===1006)i();else{let a=Object.assign(new Error("ws error"),{event:o});s(a)}}),setTimeout(()=>{r.close()})})});var BA=(r,e)=>{e=e??{};let t=NA(r),n=e.remoteAddress,i=e.remotePort;if(r.url!=null)try{let o=new URL(r.url);n=o.hostname,i=parseInt(o.port,10)}catch{}if(n==null||i==null)throw new Error("Remote connection did not have address and/or port");return{sink:OA(r,e),source:t,connected:async()=>{await t.connected()},close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(o=>{r.addEventListener("close",()=>{o()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:i,socket:r}};var HA=F(zA(),1),N$={http:"ws",https:"wss"},L$="ws",$A=(r,e)=>(0,HA.relative)(r,e,N$,L$);function GA(r,e){let t=typeof window>"u"?"":window.location;e=e??{};let n=$A(r,t.toString()),i=new TA(n,e.websocket);return BA(i,e)}var QA=F(YA(),1),E5=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,Id=(0,QA.default)(),Ad=E5&&!Id,XA=Id&&!E5,jA=Id&&E5,ZA=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&globalThis.process.release.name==="node"&&!Id,Td=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,_6e=typeof globalThis.process<"u"&&typeof globalThis.process.env<"u"&&globalThis.process.env["NODE"+(()=>"_")()+"ENV"]==="test",JA=typeof navigator<"u"&&navigator.product==="ReactNative";function rT(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return Cc.matches(t)||Xo.matches(t)})}function nT(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return Xo.matches(t)})}function iT(){throw new Error("WebSocket Servers can not be created in the browser!")}var v5=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},x5=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},sT=r=>globalThis.DOMException===void 0?new x5(r):new DOMException(r),oT=r=>{let e=r.reason===void 0?sT("This operation was aborted."):r.reason;return e instanceof Error?e:sT(e)};function _5(r,e){let{milliseconds:t,fallback:n,message:i,customTimers:s={setTimeout,clearTimeout}}=e,o,a=new Promise((c,l)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(t===Number.POSITIVE_INFINITY){c(r);return}if(e.signal){let{signal:h}=e;h.aborted&&l(oT(h)),h.addEventListener("abort",()=>{l(oT(h))})}let u=new v5;o=s.setTimeout.call(void 0,()=>{if(n){try{c(n())}catch(h){l(h)}return}typeof r.cancel=="function"&&r.cancel(),i===!1?c():i instanceof Error?l(i):(u.message=i??`Promise timed out after ${t} milliseconds`,l(u))},t),(async()=>{try{c(await r)}catch(h){l(h)}finally{s.clearTimeout.call(void 0,o)}})()});return a.clear=()=>{s.clearTimeout.call(void 0,o),o=void 0},a}var aT=T("libp2p:websockets:socket");function cT(r,e,t){t=t??{};let n={async sink(i){t?.signal!=null&&(i=gt(i,t.signal));try{await r.sink(i)}catch(s){s.type!=="aborted"&&aT.error(s)}},source:t.signal!=null?gt(r.source,t.signal):r.source,remoteAddr:e,timeline:{open:Date.now()},async close(){let i=Date.now();try{await _5(r.close(),{milliseconds:2e3})}catch{let{host:o,port:a}=n.remoteAddr.toOptions();aT("timeout closing stream to %s:%s after %dms, destroying it manually",o,a,Date.now()-i),r.destroy()}finally{n.timeline.close=Date.now()}}};return r.socket.addEventListener("close",()=>{n.timeline.close==null&&(n.timeline.close=Date.now())},{once:!0}),n}var lo=T("libp2p:websockets"),S5=class{init;constructor(e){this.init=e}[Symbol.toStringTag]="@libp2p/websockets";[Ti]=!0;async dial(e,t){lo("dialing %s",e),t=t??{};let n=await this._connect(e,t),i=cT(n,e);lo("new outbound connection %s",i.remoteAddr);let s=await t.upgrader.upgradeOutbound(i);return lo("outbound connection %s upgraded",i.remoteAddr),s}async _connect(e,t){if(t?.signal?.aborted===!0)throw new Qr;let n=e.toOptions();lo("dialing %s:%s",n.host,n.port);let i=Pe(),s=l=>{lo.error("connection error:",l),i.reject(l)},o=GA(AA(e),this.init);if(o.socket.on!=null?o.socket.on("error",s):o.socket.onerror=s,t.signal==null)return await Promise.race([o.connected(),i.promise]),lo("connected %s",e),o;let a,c=new Promise((l,u)=>{if(a=()=>{u(new Qr),o.close().catch(h=>{lo.error("error closing raw socket",h)})},t?.signal?.aborted===!0){a();return}t?.signal?.addEventListener("abort",a)});try{await Promise.race([c,i.promise,o.connected()])}finally{a!=null&&t?.signal?.removeEventListener("abort",a)}return lo("connected %s",e),o}createListener(e){return iT({...this.init,...e})}filter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):Ad||Td?nT(e):rT(e)}};function lT(r={}){return()=>new S5(r)}function Dd(r){return r[Symbol.asyncIterator]!=null}var Cd=r=>{let e=ot.encodingLength(r),t=Ir(e);return ot.encode(r,t),Cd.bytes=e,t};Cd.bytes=0;function Pd(r,e){e=e??{};let t=e.lengthEncoder??Cd;function*n(i){let s=t(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return Dd(r)?async function*(){for await(let i of r)yield*n(i)}():function*(){for(let i of r)yield*n(i)}()}Pd.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Cd;return new j(t(r.byteLength),r)};var Xc=F(li(),1);var U$=8,F$=1024*1024*4,aa;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(aa||(aa={}));var I5=r=>{let e=ot.decode(r);return I5.bytes=ot.encodingLength(e),e};I5.bytes=0;function R5(r,e){let t=new j,n=aa.LENGTH,i=-1,s=e?.lengthDecoder??I5,o=e?.maxLengthLength??U$,a=e?.maxDataLength??F$;function*c(){for(;t.byteLength>0;){if(n===aa.LENGTH)try{if(i=s(t),i<0)throw(0,Xc.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,Xc.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(i),n=aa.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>o)throw(0,Xc.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw l}if(n===aa.DATA){if(t.byteLength<i)break;let l=t.sublist(0,i);t.consume(i),e?.onData!=null&&e.onData(l),yield l,n=aa.LENGTH}}}return Dd(r)?async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw(0,Xc.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw(0,Xc.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}R5.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:s,value:o}=await r.next(t);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}}();return R5(n,{...e??{},onLength:s=>{t=s}})};var kd=F(li(),1),uT=r=>ot.decode(r);uT.bytes=0;function A5(r,e={}){let t=et();r.sink(t).catch(o=>{t.end(o)}),r.sink=async o=>{for await(let a of o)t.push(a)};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let i=new j,s={read:async o=>{if(o==null){let{done:c,value:l}=await n.next();return c===!0?new j:l}for(;i.byteLength<o;){let{value:c,done:l}=await n.next();if(l===!0)throw(0,kd.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF");i.append(c)}let a=i.sublist(0,o);return i.consume(o),a},readLP:async()=>{let o=-1,a=new j,c=e?.lengthDecoder??uT;for(;;){a.append(await s.read(1));try{o=c(a)}catch(l){if(l instanceof RangeError)continue;throw l}if(o>-1)break;if(e?.maxLengthLength!=null&&a.byteLength>e.maxLengthLength)throw(0,kd.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG")}if(e?.maxDataLength!=null&&o>e.maxDataLength)throw(0,kd.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");return await s.read(o)},readPB:async o=>{let a=await s.readLP();if(a==null)throw new Error("Value is null");let c=a instanceof Uint8Array?a:a.subarray();return o.decode(c)},write:o=>{o instanceof Uint8Array?t.push(o):t.push(o.subarray())},writeLP:o=>{s.write(Pd.single(o,e))},writePB:(o,a)=>{s.writeLP(a.encode(o))},pb:o=>({read:async()=>await s.readPB(o),write:a=>{s.writePB(a,o)},unwrap:()=>s}),unwrap:()=>{let o=r.source;return r.source=async function*(){yield*i,yield*o}(),r}};return s}async function*T5(...r){let e=et({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async t=>{for await(let n of t)e.push(n)})),e.end()}catch(t){e.end(t)}}),yield*e}var V$=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},hT=r=>r!=null&&(typeof r[Symbol.asyncIterator]=="function"||typeof r[Symbol.iterator]=="function"||typeof r.next=="function"),D5=r=>r!=null&&typeof r.sink=="function"&&hT(r.source),q$=r=>e=>{let t=r.sink(e);if(t.then!=null){let n=et({objectMode:!0});return t.then(()=>{n.end()},s=>{n.end(s)}),T5(n,async function*(){yield*r.source,n.end()}())}return r.source};function fT(r,...e){if(D5(r)){let n=r;r=()=>n.source}else if(hT(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&D5(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)D5(t[n])&&(t[n]=q$(t[n]));return V$(...t)}function dT(r){return globalThis?.Buffer?.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r)}var Nd=r=>{let e=ot.encodingLength(r),t=dT(e);return ot.encode(r,t),Nd.bytes=e,t};Nd.bytes=0;function pT(r){r=r??{};let e=r.lengthEncoder??Nd;return async function*(n){for await(let i of n){let s=e(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}}}pT.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Nd;return new j(t(r.byteLength),r)};var Ju=F(li(),1),z$=8,H$=1024*1024*4,ca;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(ca||(ca={}));var C5=r=>{let e=ot.decode(r);return C5.bytes=ot.encodingLength(e),e};C5.bytes=0;function eh(r){return async function*(t){let n=new j,i=ca.LENGTH,s=-1,o=r?.lengthDecoder??C5,a=r?.maxLengthLength??z$,c=r?.maxDataLength??H$;for await(let l of t)for(n.append(l);n.byteLength>0;){if(i===ca.LENGTH)try{if(s=o(n),s<0)throw(0,Ju.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(s>c)throw(0,Ju.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=o.bytes;n.consume(u),r?.onLength!=null&&r.onLength(s),i=ca.DATA}catch(u){if(u instanceof RangeError){if(n.byteLength>a)throw(0,Ju.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(i===ca.DATA){if(n.byteLength<s)break;let u=n.sublist(0,s);n.consume(s),r?.onData!=null&&r.onData(u),yield u,i=ca.LENGTH}}if(n.byteLength>0)throw(0,Ju.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}}eh.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:s,value:o}=await r.next(t);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}}();return eh({...e??{},onLength:s=>{t=s}})(n)};var mT=!!globalThis.process?.env?.DUMP_SESSION_KEYS;var ST=F(vT(),1),jc=F(R4(),1),Bd=F(_T(),1),L5=F(Ru(),1),RT={hashSHA256(r){return(0,Bd.hash)(r)},getHKDF(r,e){let i=new ST.HKDF(Bd.SHA256,e,r).expand(96),s=i.subarray(0,32),o=i.subarray(32,64),a=i.subarray(64,96);return[s,o,a]},generateX25519KeyPair(){let r=jc.generateKeyPair();return{publicKey:r.publicKey,privateKey:r.secretKey}},generateX25519KeyPairFromSeed(r){let e=jc.generateKeyPairFromSeed(r);return{publicKey:e.publicKey,privateKey:e.secretKey}},generateX25519SharedKey(r,e){return jc.sharedKey(r,e)},chaCha20Poly1305Encrypt(r,e,t,n){return new L5.ChaCha20Poly1305(n).seal(e,r,t)},chaCha20Poly1305Decrypt(r,e,t,n,i){return new L5.ChaCha20Poly1305(n).open(e,r,t,i)}};var O5=F(Ru(),1);var Z$=r=>globalThis.Buffer?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r),Zc=r=>{let e=Z$(2);return new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(0,r,!1),e};Zc.bytes=2;var rh=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");return r instanceof Uint8Array?new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,!1):r.getUint16(0)};rh.bytes=2;function IT(r){return le([r.ne,r.ciphertext],r.ne.length+r.ciphertext.length)}function AT(r){return le([r.ne,r.ns,r.ciphertext],r.ne.length+r.ns.length+r.ciphertext.length)}function TT(r){return le([r.ns,r.ciphertext],r.ns.length+r.ciphertext.length)}function DT(r){if(r.length<32)throw new Error("Cannot decode stage 0 MessageBuffer: length less than 32 bytes.");return{ne:r.subarray(0,32),ciphertext:r.subarray(32,r.length),ns:new Uint8Array(0)}}function CT(r){if(r.length<80)throw new Error("Cannot decode stage 1 MessageBuffer: length less than 80 bytes.");return{ne:r.subarray(0,32),ns:r.subarray(32,80),ciphertext:r.subarray(80,r.length)}}function PT(r){if(r.length<48)throw new Error("Cannot decode stage 2 MessageBuffer: length less than 48 bytes.");return{ne:new Uint8Array(0),ns:r.subarray(0,48),ciphertext:r.subarray(48,r.length)}}function NT(r,e){return async function*(t){for await(let n of t)for(let i=0;i<n.length;i+=65519){let s=i+65519;s>n.length&&(s=n.length);let o=r.encrypt(n.subarray(i,s),r.session);e?.encryptedPackets.increment(),yield Zc(o.byteLength),yield o}}}function LT(r,e){return async function*(t){for await(let n of t)for(let i=0;i<n.length;i+=65535){let s=i+65535;if(s>n.length&&(s=n.length),s-O5.TAG_LENGTH<i)throw new Error("Invalid chunk");let o=n.subarray(i,s),a=n.subarray(i,s-O5.TAG_LENGTH),{plaintext:c,valid:l}=r.decrypt(o,r.session,a);if(!l)throw e?.decryptErrors.increment(),new Error("Failed to validate decrypted chunk");e?.decryptedPackets.increment(),yield c}}}var la=class extends Error{constructor(e="Unexpected Peer"){super(e),this.code=la.code}static get code(){return"ERR_UNEXPECTED_PEER"}},ds=class extends Error{constructor(e="Invalid crypto exchange"){super(e),this.code=ds.code}static get code(){return"ERR_INVALID_CRYPTO_EXCHANGE"}};var Md;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.webtransportCerthashes!=null)for(let s of t.webtransportCerthashes)n.uint32(10),n.bytes(s);i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={webtransportCerthashes:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.webtransportCerthashes.push(t.bytes());break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(Md||(Md={}));var ih;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||t.identityKey!=null&&t.identityKey.byteLength>0)&&(n.uint32(10),n.bytes(t.identityKey??new Uint8Array(0))),(i.writeDefaults===!0||t.identitySig!=null&&t.identitySig.byteLength>0)&&(n.uint32(18),n.bytes(t.identitySig??new Uint8Array(0))),t.extensions!=null&&(n.uint32(34),Md.codec().encode(t.extensions,n,{writeDefaults:!1})),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={identityKey:new Uint8Array(0),identitySig:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.identityKey=t.bytes();break;case 2:i.identitySig=t.bytes();break;case 4:i.extensions=Md.codec().decode(t,t.uint32());break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(ih||(ih={}));async function OT(r,e,t){let n=await eG(r,BT(e));if(r.publicKey==null)throw new Error("PublicKey was missing from local PeerId");return J$(r.publicKey,n,t)}function J$(r,e,t){return ih.encode({identityKey:r,identitySig:e,extensions:t??{webtransportCerthashes:[]}}).subarray()}async function eG(r,e){if(r.privateKey==null)throw new Error("PrivateKey was missing from PeerId");return await(await an(r.privateKey)).sign(e)}async function B5(r){return await zt(r.identityKey)}function M5(r){return ih.decode(r)}function BT(r){let e=K("noise-libp2p-static-key:");return le([e,r],e.length+r.length)}async function U5(r,e,t){let n=await zt(e.identityKey);if(!n.equals(t))throw new Error(`Payload identity key ${n.toString()} does not match expected remote peer ${t.toString()}`);let i=BT(r);if(n.publicKey==null)throw new Error("PublicKey was missing from PeerId");if(e.identitySig==null)throw new Error("Signature was missing from message");if(!await rr(n.publicKey).verify(i,e.identitySig))throw new Error("Static key doesn't match to peer that signed payload!");return n}function sh(r){return!(!(r instanceof Uint8Array)||r.length!==32)}var sr=T("libp2p:noise");var Nn;mT?Nn=sr:Nn=Object.assign(()=>{},{enabled:!1,trace:()=>{},error:()=>{}});function MT(r){Nn(`LOCAL_STATIC_PUBLIC_KEY ${O(r.publicKey,"hex")}`),Nn(`LOCAL_STATIC_PRIVATE_KEY ${O(r.privateKey,"hex")}`)}function F5(r){r?(Nn(`LOCAL_PUBLIC_EPHEMERAL_KEY ${O(r.publicKey,"hex")}`),Nn(`LOCAL_PRIVATE_EPHEMERAL_KEY ${O(r.privateKey,"hex")}`)):Nn("Missing local ephemeral keys.")}function UT(r){Nn(`REMOTE_STATIC_PUBLIC_KEY ${O(r,"hex")}`)}function K5(r){Nn(`REMOTE_EPHEMERAL_PUBLIC_KEY ${O(r,"hex")}`)}function FT(r){r.cs1&&r.cs2?(Nn(`CIPHER_STATE_1 ${r.cs1.n.getUint64()} ${O(r.cs1.k,"hex")}`),Nn(`CIPHER_STATE_2 ${r.cs2.n.getUint64()} ${O(r.cs2.k,"hex")}`)):Nn("Missing cipher state.")}var tG="Cipherstate has reached maximum n, a new handshake must be performed",Ud=class{constructor(e=0){this.n=e,this.bytes=new Uint8Array(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>4294967295)throw new Error(tG)}};var Fd=class{constructor(e){this.crypto=e}encryptWithAd(e,t,n){let i=this.encrypt(e.k,e.n,t,n);return e.n.increment(),i}decryptWithAd(e,t,n,i){let{plaintext:s,valid:o}=this.decrypt(e.k,e.n,t,n,i);return o&&e.n.increment(),{plaintext:s,valid:o}}hasKey(e){return!this.isEmptyKey(e.k)}createEmptyKey(){return new Uint8Array(32)}isEmptyKey(e){let t=this.createEmptyKey();return de(t,e)}encrypt(e,t,n,i){return t.assertValue(),this.crypto.chaCha20Poly1305Encrypt(i,t.getBytes(),n,e)}encryptAndHash(e,t){let n;return this.hasKey(e.cs)?n=this.encryptWithAd(e.cs,e.h,t):n=t,this.mixHash(e,n),n}decrypt(e,t,n,i,s){t.assertValue();let o=this.crypto.chaCha20Poly1305Decrypt(i,t.getBytes(),n,e,s);return o?{plaintext:o,valid:!0}:{plaintext:new Uint8Array(0),valid:!1}}decryptAndHash(e,t){let n,i=!0;return this.hasKey(e.cs)?{plaintext:n,valid:i}=this.decryptWithAd(e.cs,e.h,t):n=t,this.mixHash(e,t),{plaintext:n,valid:i}}dh(e,t){try{let n=this.crypto.generateX25519SharedKey(e,t);return n.length===32?n:n.subarray(0,32)}catch(n){let i=n;return sr.error(i),new Uint8Array(32)}}mixHash(e,t){e.h=this.getHash(e.h,t)}getHash(e,t){return this.crypto.hashSHA256(le([e,t],e.length+t.length))}mixKey(e,t){let[n,i]=this.crypto.getHKDF(e.ck,t);e.cs=this.initializeKey(i),e.ck=n}initializeKey(e){return{k:e,n:new Ud}}initializeSymmetric(e){let t=K(e,"utf-8"),n=this.hashProtocolName(t),i=n,s=this.createEmptyKey();return{cs:this.initializeKey(s),ck:i,h:n}}hashProtocolName(e){if(e.length<=32){let t=new Uint8Array(32);return t.set(e),t}else return this.getHash(e,new Uint8Array(0))}split(e){let[t,n]=this.crypto.getHKDF(e.ck,new Uint8Array(0)),i=this.initializeKey(t),s=this.initializeKey(n);return{cs1:i,cs2:s}}writeMessageRegular(e,t){let n=this.encryptWithAd(e,new Uint8Array(0),t),i=this.createEmptyKey(),s=new Uint8Array(0);return{ne:i,ns:s,ciphertext:n}}readMessageRegular(e,t){return this.decryptWithAd(e,new Uint8Array(0),t.ciphertext)}};var Kd=class extends Fd{initializeInitiator(e,t,n,i){let s="Noise_XX_25519_ChaChaPoly_SHA256",o=this.initializeSymmetric(s);this.mixHash(o,e);let a=new Uint8Array(32);return{ss:o,s:t,rs:n,psk:i,re:a}}initializeResponder(e,t,n,i){let s="Noise_XX_25519_ChaChaPoly_SHA256",o=this.initializeSymmetric(s);this.mixHash(o,e);let a=new Uint8Array(32);return{ss:o,s:t,rs:n,psk:i,re:a}}writeMessageA(e,t,n){let i=new Uint8Array(0);n!==void 0?e.e=n:e.e=this.crypto.generateX25519KeyPair();let s=e.e.publicKey;this.mixHash(e.ss,s);let o=this.encryptAndHash(e.ss,t);return{ne:s,ns:i,ciphertext:o}}writeMessageB(e,t){e.e=this.crypto.generateX25519KeyPair();let n=e.e.publicKey;this.mixHash(e.ss,n),this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));let i=e.s.publicKey,s=this.encryptAndHash(e.ss,i);this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));let o=this.encryptAndHash(e.ss,t);return{ne:n,ns:s,ciphertext:o}}writeMessageC(e,t){let n=e.s.publicKey,i=this.encryptAndHash(e.ss,n);this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));let s=this.encryptAndHash(e.ss,t),a={ne:this.createEmptyKey(),ns:i,ciphertext:s},{cs1:c,cs2:l}=this.split(e.ss);return{h:e.ss.h,messageBuffer:a,cs1:c,cs2:l}}readMessageA(e,t){return sh(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),this.decryptAndHash(e.ss,t.ciphertext)}readMessageB(e,t){if(sh(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),!e.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));let{plaintext:n,valid:i}=this.decryptAndHash(e.ss,t.ns);i&&sh(n)&&(e.rs=n),this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));let{plaintext:s,valid:o}=this.decryptAndHash(e.ss,t.ciphertext);return{plaintext:s,valid:i&&o}}readMessageC(e,t){let{plaintext:n,valid:i}=this.decryptAndHash(e.ss,t.ns);if(i&&sh(n)&&(e.rs=n),!e.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));let{plaintext:s,valid:o}=this.decryptAndHash(e.ss,t.ciphertext),{cs1:a,cs2:c}=this.split(e.ss);return{h:e.ss.h,plaintext:s,valid:i&&o,cs1:a,cs2:c}}initSession(e,t,n){let i=this.createEmptyKey(),s=new Uint8Array(32),o;return e?o=this.initializeInitiator(t,n,s,i):o=this.initializeResponder(t,n,s,i),{hs:o,i:e,mc:0}}sendMessage(e,t,n){let i;if(e.mc===0)i=this.writeMessageA(e.hs,t,n);else if(e.mc===1)i=this.writeMessageB(e.hs,t);else if(e.mc===2){let{h:s,messageBuffer:o,cs1:a,cs2:c}=this.writeMessageC(e.hs,t);i=o,e.h=s,e.cs1=a,e.cs2=c}else if(e.mc>2)if(e.i){if(!e.cs1)throw new Error("CS1 (cipher state) is not defined");i=this.writeMessageRegular(e.cs1,t)}else{if(!e.cs2)throw new Error("CS2 (cipher state) is not defined");i=this.writeMessageRegular(e.cs2,t)}else throw new Error("Session invalid.");return e.mc++,i}recvMessage(e,t){let n=new Uint8Array(0),i=!1;if(e.mc===0)({plaintext:n,valid:i}=this.readMessageA(e.hs,t));else if(e.mc===1)({plaintext:n,valid:i}=this.readMessageB(e.hs,t));else if(e.mc===2){let{h:s,plaintext:o,valid:a,cs1:c,cs2:l}=this.readMessageC(e.hs,t);n=o,i=a,e.h=s,e.cs1=c,e.cs2=l}return e.mc++,{plaintext:n,valid:i}}};var Vd=class{constructor(e,t,n,i,s,o,a,c){this.remoteExtensions={webtransportCerthashes:[]},this.isInitiator=e,this.payload=t,this.prologue=n,this.staticKeypair=s,this.connection=o,a&&(this.remotePeer=a),this.xx=c??new Kd(i),this.session=this.xx.initSession(this.isInitiator,this.prologue,this.staticKeypair)}async propose(){if(MT(this.session.hs.s),this.isInitiator){sr.trace("Stage 0 - Initiator starting to send first message.");let e=this.xx.sendMessage(this.session,new Uint8Array(0));this.connection.writeLP(IT(e)),sr.trace("Stage 0 - Initiator finished sending first message."),F5(this.session.hs.e)}else{sr.trace("Stage 0 - Responder waiting to receive first message...");let e=DT((await this.connection.readLP()).subarray()),{valid:t}=this.xx.recvMessage(this.session,e);if(!t)throw new ds("xx handshake stage 0 validation fail");sr.trace("Stage 0 - Responder received first message."),K5(this.session.hs.re)}}async exchange(){if(this.isInitiator){sr.trace("Stage 1 - Initiator waiting to receive first message from responder...");let e=CT((await this.connection.readLP()).subarray()),{plaintext:t,valid:n}=this.xx.recvMessage(this.session,e);if(!n)throw new ds("xx handshake stage 1 validation fail");sr.trace("Stage 1 - Initiator received the message."),K5(this.session.hs.re),UT(this.session.hs.rs),sr.trace("Initiator going to check remote's signature...");try{let i=M5(t);this.remotePeer=this.remotePeer||await B5(i),await U5(this.session.hs.rs,i,this.remotePeer),this.setRemoteNoiseExtension(i.extensions)}catch(i){let s=i;throw new la(`Error occurred while verifying signed payload: ${s.message}`)}sr.trace("All good with the signature!")}else{sr.trace("Stage 1 - Responder sending out first message with signed payload and static key.");let e=this.xx.sendMessage(this.session,this.payload);this.connection.writeLP(AT(e)),sr.trace("Stage 1 - Responder sent the second handshake message with signed payload."),F5(this.session.hs.e)}}async finish(){if(this.isInitiator){sr.trace("Stage 2 - Initiator sending third handshake message.");let e=this.xx.sendMessage(this.session,this.payload);this.connection.writeLP(TT(e)),sr.trace("Stage 2 - Initiator sent message with signed payload.")}else{sr.trace("Stage 2 - Responder waiting for third handshake message...");let e=PT((await this.connection.readLP()).subarray()),{plaintext:t,valid:n}=this.xx.recvMessage(this.session,e);if(!n)throw new ds("xx handshake stage 2 validation fail");sr.trace("Stage 2 - Responder received the message, finished handshake.");try{let i=M5(t);this.remotePeer=this.remotePeer||await B5(i),await U5(this.session.hs.rs,i,this.remotePeer),this.setRemoteNoiseExtension(i.extensions)}catch(i){let s=i;throw new la(`Error occurred while verifying signed payload: ${s.message}`)}}FT(this.session)}encrypt(e,t){let n=this.getCS(t);return this.xx.encryptWithAd(n,new Uint8Array(0),e)}decrypt(e,t,n){let i=this.getCS(t,!1);return this.xx.decryptWithAd(i,new Uint8Array(0),e,n)}getRemoteStaticKey(){return this.session.hs.rs}getCS(e,t=!0){if(!e.cs1||!e.cs2)throw new ds("Handshake not completed properly, cipher state does not exist.");return this.isInitiator?t?e.cs1:e.cs2:t?e.cs2:e.cs1}setRemoteNoiseExtension(e){e&&(this.remoteExtensions=e)}};function KT(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}var qd=class{constructor(e={}){this.protocol="/noise";let{staticNoiseKey:t,extensions:n,crypto:i,prologueBytes:s,metrics:o}=e;this.crypto=i??RT,this.extensions=n,this.metrics=o?KT(o):void 0,t?this.staticKeys=this.crypto.generateX25519KeyPairFromSeed(t):this.staticKeys=this.crypto.generateX25519KeyPair(),this.prologue=s??new Uint8Array(0)}async secureOutbound(e,t,n){let i=A5(t,{lengthEncoder:Zc,lengthDecoder:rh,maxDataLength:65535}),s=await this.performHandshake({connection:i,isInitiator:!0,localPeer:e,remotePeer:n});return{conn:await this.createSecureConnection(i,s),remoteExtensions:s.remoteExtensions,remotePeer:s.remotePeer}}async secureInbound(e,t,n){let i=A5(t,{lengthEncoder:Zc,lengthDecoder:rh,maxDataLength:65535}),s=await this.performHandshake({connection:i,isInitiator:!1,localPeer:e,remotePeer:n});return{conn:await this.createSecureConnection(i,s),remotePeer:s.remotePeer,remoteExtensions:s.remoteExtensions}}async performHandshake(e){let t=await OT(e.localPeer,this.staticKeys.publicKey,this.extensions);return await this.performXXHandshake(e,t)}async performXXHandshake(e,t){let{isInitiator:n,remotePeer:i,connection:s}=e,o=new Vd(n,t,this.prologue,this.crypto,this.staticKeys,s,i);try{await o.propose(),await o.exchange(),await o.finish(),this.metrics?.xxHandshakeSuccesses.increment()}catch(a){if(this.metrics?.xxHandshakeErrors.increment(),a instanceof Error)throw a.message=`Error occurred during XX handshake: ${a.message}`,a}return o}async createSecureConnection(e,t){let[n,i]=Y0(),s=e.unwrap();return await fT(n,NT(t,this.metrics),s,eh({lengthDecoder:rh}),LT(t,this.metrics),n),i}};function VT(r={}){return()=>new qd(r)}var Hr=T("libp2p:webtransport"),rG=Object.values(wn).map(r=>r.decoder).reduce((r,e)=>r.or(e));function nG(r){return Mn.decode(rG.decode(r))}function qT(){return{source:{[Symbol.asyncIterator](){return{async next(){return new Promise(()=>{})}}}},sink:async r=>new Promise(()=>{})}}async function zT(r,e,t,n,i){let s=r.writable.getWriter(),o=r.readable.getReader();await s.ready;function a(){let f=n.findIndex(d=>d===h);f!==-1&&(n.splice(f,1),h.stat.timeline.close=Date.now(),i?.(h))}let c=!1,l=!1;(async function(){let f=await s.closed.catch(d=>d);if(f!=null){let d=f.message;d.includes("aborted by the remote server")||d.includes("STOP_SENDING")||Hr.error(`WebTransport writer closed unexpectedly: streamId=${e} err=${f.message}`)}c=!0,c&&l&&a()})().catch(()=>{Hr.error("WebTransport failed to cleanup closed stream")}),async function(){let f=await o.closed.catch(d=>d);f!=null&&Hr.error(`WebTransport reader closed unexpectedly: streamId=${e} err=${f.message}`),l=!0,c&&l&&a()}().catch(()=>{Hr.error("WebTransport failed to cleanup closed stream")});let u=!1,h={id:e,abort(f){c||(s.abort(),c=!0),h.closeRead(),l=!0,a()},close(){h.closeRead(),h.closeWrite(),a()},closeRead(){l||(o.cancel().catch(f=>{f.toString().includes("RESET_STREAM")===!0&&(c=!0)}),l=!0),c&&a()},closeWrite(){c||(c=!0,s.close().catch(f=>{f.toString().includes("RESET_STREAM")===!0&&(l=!0)})),l&&a()},reset(){h.close()},stat:{direction:t,timeline:{open:Date.now()}},metadata:{},source:async function*(){for(;;){let f=await o.read();if(f.done===!0){l=!0,c&&a();return}yield new j(f.value)}}(),sink:async function(f){if(u)throw new Error("sink already called on stream");u=!0;try{for await(let d of f)if(d instanceof Uint8Array)await s.write(d);else for(let p of d)await s.write(p)}finally{h.closeWrite()}}};return h}function iG(r){let e=r.stringTuples(),{url:t,certhashes:n,remotePeer:i}=e.reduce((s,[o,a])=>{switch(o){case X("ip6").code:case X("dns6").code:a?.includes(":")===!0&&(a=`[${a}]`);case X("ip4").code:case X("dns4").code:if(s.seenHost||s.seenPort)throw new Error("Invalid multiaddr, saw host and already saw the host or port");return{...s,url:`${s.url}${a??""}`,seenHost:!0};case X("quic").code:case X("quic-v1").code:case X("webtransport").code:if(!s.seenHost||!s.seenPort)throw new Error("Invalid multiaddr, Didn't see host and port, but saw quic/webtransport");return s;case X("udp").code:if(s.seenPort)throw new Error("Invalid multiaddr, saw port but already saw the port");return{...s,url:`${s.url}:${a??""}`,seenPort:!0};case X("certhash").code:if(!s.seenHost||!s.seenPort)throw new Error("Invalid multiaddr, saw the certhash before seeing the host and port");return{...s,certhashes:s.certhashes.concat([nG(a??"")])};case X("p2p").code:return{...s,remotePeer:oe(a??"")};default:throw new Error(`unexpected component in multiaddr: ${o} ${X(o).name} ${a??""} `)}},{url:"https://",seenHost:!1,seenPort:!1,certhashes:[]});return{url:t,certhashes:n,remotePeer:i}}function sG(r,e){return e.filter(n=>!!r.find(i=>{if(n.length!==i.length)return!1;for(let s=0;s<n.length;s++)if(i[s]!==n[s])return!1;return!0})).length===e.length}var V5=class{components;config;constructor(e,t={}){this.components=e,this.config={maxInboundStreams:t.maxInboundStreams??1e3}}[Symbol.toStringTag]="@libp2p/webtransport";[Ti]=!0;async dial(e,t){Hr("dialing %s",e);let n=this.components.peerId;if(n===void 0)throw new Error("Need a local peerid");t=t??{};let{url:i,certhashes:s,remotePeer:o}=iG(e);if(s.length===0)throw new Error("Expected multiaddr to contain certhashes");let a=new WebTransport(`${i}/.well-known/libp2p-webtransport?type=noise`,{serverCertificateHashes:s.map(l=>({algorithm:"sha-256",value:l.digest}))});if(a.closed.catch(l=>{Hr.error("WebTransport transport closed due to:",l)}),await a.ready,o==null)throw new Error("Need a target peerid");if(!await this.authenticateWebTransport(a,n,o,s))throw new Error("Failed to authenticate webtransport");let c={close:async l=>{l!=null&&Hr("Closing webtransport with err:",l),a.close()},remoteAddr:e,timeline:{open:Date.now()},...qT()};a.closed.catch(l=>{Hr.error("WebTransport connection closed:",l),c.timeline.close=Date.now()});try{t?.signal?.throwIfAborted()}catch(l){throw a.close(),l}return t.upgrader.upgradeOutbound(c,{skipEncryption:!0,muxerFactory:this.webtransportMuxer(a),skipProtection:!0})}async authenticateWebTransport(e,t,n,i){let s=await e.createBidirectionalStream(),o=s.writable.getWriter(),a=s.readable.getReader();await o.ready;let c={source:async function*(){for(;;){let h=await a.read();if(h.value!=null&&(yield h.value),h.done===!0)break}}(),sink:async function(h){for await(let f of h)await o.write(f)}},l=VT()(),{remoteExtensions:u}=await l.secureOutbound(t,c,n);if(o.close().catch(h=>{Hr.error(`Failed to close authentication stream writer: ${h.message}`)}),a.cancel().catch(h=>{Hr.error(`Failed to close authentication stream reader: ${h.message}`)}),!sG(u?.webtransportCerthashes??[],i.map(h=>h.bytes)))throw new Error("Our certhashes are not a subset of the remote's reported certhashes");return!0}webtransportMuxer(e){let t=0,n=this.config;return{protocol:"webtransport",createStreamMuxer:i=>{typeof i=="function"&&(i={onIncomingStream:i});let s=[];(async function(){let a=e.incomingBidirectionalStreams.getReader();for(;;){let{done:c,value:l}=await a.read();if(c===!0)break;if(s.length>=n.maxInboundStreams)l.writable.close().catch(u=>{Hr.error(`Failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)}),l.readable.cancel().catch(u=>{Hr.error(`Failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)});else{let u=await zT(l,String(t++),"inbound",s,i?.onStreamEnd);s.push(u),i?.onIncomingStream?.(u)}}})().catch(()=>{Hr.error("WebTransport failed to receive incoming stream")});let o={protocol:"webtransport",streams:s,newStream:async a=>{let c=await e.createBidirectionalStream(),l=await zT(c,String(t++),i?.direction??"outbound",s,i?.onStreamEnd);return s.push(l),l},close:a=>{a!=null&&Hr("Closing webtransport muxer with err:",a),e.close()},...qT()};try{i?.signal?.throwIfAborted()}catch(a){throw e.close(),a}return o}}}createListener(e){throw new Error("Webtransport servers are not supported in Node or the browser")}filter(e){return e.filter(t=>t.protoNames().includes("webtransport"))}};function HT(r={}){return e=>new V5(e,r)}var Ui;(function(r){let e;(function(i){i.EOL="EOL"})(e=r.ValidityType||(r.ValidityType={}));let t;(function(i){i[i.EOL=0]="EOL"})(t||(t={})),function(i){i.codec=()=>At(t)}(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=ne((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.value!=null&&(s.uint32(10),s.bytes(i.value)),i.signature!=null&&(s.uint32(18),s.bytes(i.signature)),i.validityType!=null&&(s.uint32(24),r.ValidityType.codec().encode(i.validityType,s)),i.validity!=null&&(s.uint32(34),s.bytes(i.validity)),i.sequence!=null&&(s.uint32(40),s.uint64(i.sequence)),i.ttl!=null&&(s.uint32(48),s.uint64(i.ttl)),i.pubKey!=null&&(s.uint32(58),s.bytes(i.pubKey)),i.signatureV2!=null&&(s.uint32(66),s.bytes(i.signatureV2)),i.data!=null&&(s.uint32(74),s.bytes(i.data)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.value=i.bytes();break;case 2:o.signature=i.bytes();break;case 3:o.validityType=r.ValidityType.codec().decode(i);break;case 4:o.validity=i.bytes();break;case 5:o.sequence=i.uint64();break;case 6:o.ttl=i.uint64();break;case 7:o.pubKey=i.bytes();break;case 8:o.signatureV2=i.bytes();break;case 9:o.data=i.bytes();break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>re(i,r.codec()),r.decode=i=>te(i,r.codec())})(Ui||(Ui={}));var oh=F(li(),1);var $T="ERR_IPNS_EXPIRED_RECORD",zd="ERR_UNRECOGNIZED_VALIDITY";var ho="ERR_SIGNATURE_VERIFICATION",GT="ERR_UNRECOGNIZED_FORMAT";var q5="ERR_UNDEFINED_PARAMETER",WT="ERR_INVALID_RECORD_DATA",YT="ERR_INVALID_EMBEDDED_KEY";var XT=T("ipns:utils"),oG=K("/ipns/");function ah(r){let e=new RegExp("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d+)Z"),t=String(r).trim().match(e);if(t==null)throw new Error("Invalid format");let n=parseInt(t[1],10),i=parseInt(t[2],10)-1,s=parseInt(t[3],10),o=parseInt(t[4],10),a=parseInt(t[5],10),c=parseInt(t[6],10),l=parseInt(t[7].slice(0,-6),10);return new Date(Date.UTC(n,i,s,o,a,c,l))}var jT=async(r,e)=>{if(e==null||r==null){let n=new Error("one or more of the provided parameters are not defined");throw XT.error(n),(0,oh.default)(n,q5)}let t;if(e.pubKey!=null){try{t=rr(e.pubKey)}catch(i){throw XT.error(i),i}if(!(await zt(e.pubKey)).equals(r))throw(0,oh.default)(new Error("Embedded public key did not match PeerID"),YT)}else r.publicKey!=null&&(t=rr(r.publicKey));if(t!=null)return t;throw(0,oh.default)(new Error("no public key is available"),q5)};var ZT=r=>{let e=K("ipns-signature:");return le([e,r])};var JT=r=>{let e=Ui.decode(r);return e.sequence!=null&&(e.sequence=BigInt(e.sequence)),e.ttl!=null&&(e.ttl=BigInt(e.ttl)),{value:e.value??new Uint8Array(0),signature:e.signature??new Uint8Array(0),validityType:e.validityType??Ui.ValidityType.EOL,validity:e.validity??new Uint8Array(0),sequence:e.sequence??0n,pubKey:e.pubKey,ttl:e.ttl??void 0,signatureV2:e.signatureV2,data:e.data}};var eD=r=>vt(r.slice(oG.length));var tD=r=>{let e=zn(r);if(e.ValidityType===0)e.ValidityType=Ui.ValidityType.EOL;else throw(0,oh.default)(new Error("Unknown validity type"),zd);return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e};var rD=(r,e)=>{let t=e.map((n,i)=>({entry:Ui.decode(n),index:i}));return t.sort((n,i)=>{if(n.entry.signatureV2!=null&&i.entry.signatureV2==null)return-1;if(n.entry.signatureV2==null&&i.entry.signatureV2!=null)return 1;let s=n.entry.sequence??0n,o=i.entry.sequence??0n;if(s>o)return-1;if(s<o)return 1;let a=n.entry.validity??new Uint8Array(0),c=i.entry.validity??new Uint8Array(0),l=ah(O(a)),u=ah(O(c));return l.getTime()>u.getTime()?-1:l.getTime()<u.getTime()?1:0}),t[0].index};var Ln=F(li(),1);var ch=T("ipns:validator"),aG=async(r,e)=>{let{value:t,validityType:n,validity:i}=e,s,o;if(e.signatureV2!=null&&e.data!=null)o=e.signatureV2,s=ZT(e.data),cG(e);else throw(0,Ln.default)(new Error("missing data or signatureV2"),ho);let a;try{a=await r.verify(s,o)}catch{a=!1}if(!a)throw ch.error("record signature verification failed"),(0,Ln.default)(new Error("record signature verification failed"),ho);if(i!=null&&n===Ui.ValidityType.EOL){let c;try{c=ah(O(i))}catch{throw ch.error("unrecognized validity format (not an rfc3339 format)"),(0,Ln.default)(new Error("unrecognized validity format (not an rfc3339 format)"),GT)}if(c.getTime()<Date.now())throw ch.error("record has expired"),(0,Ln.default)(new Error("record has expired"),$T)}else if(n!=null)throw ch.error("unrecognized validity type"),(0,Ln.default)(new Error("unrecognized validity type"),zd);ch("ipns entry for %b is valid",t)},cG=r=>{if(r.data==null)throw(0,Ln.default)(new Error("Record data is missing"),WT);let e=tD(r.data);if(!de(e.Value,r.value))throw(0,Ln.default)(new Error('Field "value" did not match between protobuf and CBOR'),ho);if(!de(e.Validity,r.validity))throw(0,Ln.default)(new Error('Field "validity" did not match between protobuf and CBOR'),ho);if(e.ValidityType!==r.validityType)throw(0,Ln.default)(new Error('Field "validityType" did not match between protobuf and CBOR'),ho);if(e.Sequence!==r.sequence)throw(0,Ln.default)(new Error('Field "sequence" did not match between protobuf and CBOR'),ho);if(e.TTL!==r.ttl)throw(0,Ln.default)(new Error('Field "ttl" did not match between protobuf and CBOR'),ho)},nD=async(r,e)=>{let t=eD(r),n=JT(e),i=await jT(t,n);await aG(i,n)};var H5=F(jr(),1);var iD="libp2p",sD="autonat",oD="1.0.0";var we;(function(r){let e;(function(l){l.DIAL="DIAL",l.DIAL_RESPONSE="DIAL_RESPONSE"})(e=r.MessageType||(r.MessageType={}));let t;(function(l){l[l.DIAL=0]="DIAL",l[l.DIAL_RESPONSE=1]="DIAL_RESPONSE"})(t||(t={})),function(l){l.codec=()=>At(t)}(e=r.MessageType||(r.MessageType={}));let n;(function(l){l.OK="OK",l.E_DIAL_ERROR="E_DIAL_ERROR",l.E_DIAL_REFUSED="E_DIAL_REFUSED",l.E_BAD_REQUEST="E_BAD_REQUEST",l.E_INTERNAL_ERROR="E_INTERNAL_ERROR"})(n=r.ResponseStatus||(r.ResponseStatus={}));let i;(function(l){l[l.OK=0]="OK",l[l.E_DIAL_ERROR=100]="E_DIAL_ERROR",l[l.E_DIAL_REFUSED=101]="E_DIAL_REFUSED",l[l.E_BAD_REQUEST=200]="E_BAD_REQUEST",l[l.E_INTERNAL_ERROR=300]="E_INTERNAL_ERROR"})(i||(i={})),function(l){l.codec=()=>At(i)}(n=r.ResponseStatus||(r.ResponseStatus={}));let s;(function(l){let u;l.codec=()=>(u==null&&(u=ne((h,f,d={})=>{if(d.lengthDelimited!==!1&&f.fork(),h.id!=null&&(f.uint32(10),f.bytes(h.id)),h.addrs!=null)for(let p of h.addrs)f.uint32(18),f.bytes(p);d.lengthDelimited!==!1&&f.ldelim()},(h,f)=>{let d={addrs:[]},p=f==null?h.len:h.pos+f;for(;h.pos<p;){let m=h.uint32();switch(m>>>3){case 1:d.id=h.bytes();break;case 2:d.addrs.push(h.bytes());break;default:h.skipType(m&7);break}}return d})),u),l.encode=h=>re(h,l.codec()),l.decode=h=>te(h,l.codec())})(s=r.PeerInfo||(r.PeerInfo={}));let o;(function(l){let u;l.codec=()=>(u==null&&(u=ne((h,f,d={})=>{d.lengthDelimited!==!1&&f.fork(),h.peer!=null&&(f.uint32(10),r.PeerInfo.codec().encode(h.peer,f)),d.lengthDelimited!==!1&&f.ldelim()},(h,f)=>{let d={},p=f==null?h.len:h.pos+f;for(;h.pos<p;){let m=h.uint32();switch(m>>>3){case 1:d.peer=r.PeerInfo.codec().decode(h,h.uint32());break;default:h.skipType(m&7);break}}return d})),u),l.encode=h=>re(h,l.codec()),l.decode=h=>te(h,l.codec())})(o=r.Dial||(r.Dial={}));let a;(function(l){let u;l.codec=()=>(u==null&&(u=ne((h,f,d={})=>{d.lengthDelimited!==!1&&f.fork(),h.status!=null&&(f.uint32(8),r.ResponseStatus.codec().encode(h.status,f)),h.statusText!=null&&(f.uint32(18),f.string(h.statusText)),h.addr!=null&&(f.uint32(26),f.bytes(h.addr)),d.lengthDelimited!==!1&&f.ldelim()},(h,f)=>{let d={},p=f==null?h.len:h.pos+f;for(;h.pos<p;){let m=h.uint32();switch(m>>>3){case 1:d.status=r.ResponseStatus.codec().decode(h);break;case 2:d.statusText=h.string();break;case 3:d.addr=h.bytes();break;default:h.skipType(m&7);break}}return d})),u),l.encode=h=>re(h,l.codec()),l.decode=h=>te(h,l.codec())})(a=r.DialResponse||(r.DialResponse={}));let c;r.codec=()=>(c==null&&(c=ne((l,u,h={})=>{h.lengthDelimited!==!1&&u.fork(),l.type!=null&&(u.uint32(8),r.MessageType.codec().encode(l.type,u)),l.dial!=null&&(u.uint32(18),r.Dial.codec().encode(l.dial,u)),l.dialResponse!=null&&(u.uint32(26),r.DialResponse.codec().encode(l.dialResponse,u)),h.lengthDelimited!==!1&&u.ldelim()},(l,u)=>{let h={},f=u==null?l.len:l.pos+u;for(;l.pos<f;){let d=l.uint32();switch(d>>>3){case 1:h.type=r.MessageType.codec().decode(l);break;case 2:h.dial=r.Dial.codec().decode(l,l.uint32());break;case 3:h.dialResponse=r.DialResponse.codec().decode(l,l.uint32());break;default:l.skipType(d&7);break}}return h})),c),r.encode=l=>re(l,r.codec()),r.decode=l=>te(l,r.codec())})(we||(we={}));var Ye=T("libp2p:autonat"),z5=4,$5=class{components;startupDelay;refreshInterval;protocol;timeout;maxInboundStreams;maxOutboundStreams;verifyAddressTimeout;started;constructor(e,t){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix??iD}/${sD}/${oD}`,this.timeout=t.timeout??3e4,this.maxInboundStreams=t.maxInboundStreams??1,this.maxOutboundStreams=t.maxOutboundStreams??1,this.startupDelay=t.startupDelay??5e3,this.refreshInterval=t.refreshInterval??6e4,this._verifyExternalAddresses=this._verifyExternalAddresses.bind(this)}isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(this.protocol,e=>{this.handleIncomingAutonatStream(e).catch(t=>{Ye.error("error handling incoming autonat stream",t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.startupDelay),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),clearTimeout(this.verifyAddressTimeout),this.started=!1}async handleIncomingAutonatStream(e){let t=st([AbortSignal.timeout(this.timeout)]);try{(0,H5.setMaxListeners)?.(1/0,t)}catch{}let n=this.components.addressManager.getAddresses().map(i=>i.toOptions().host);try{let i=br(e.stream,t),s=this;await be(i,o=>Tt(o),async function*(o){let a=await Jn(o);if(a==null){Ye("no message received"),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"No message was sent"}});return}let c;try{c=we.decode(a)}catch(m){Ye.error("could not decode message",m),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"Could not decode message"}});return}let l=c.dial;if(l==null){Ye.error("dial was missing from message"),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"No Dial message found in message"}});return}let u,h=l.peer;if(h==null||h.id==null){Ye.error("PeerId missing from message"),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"missing peer info"}});return}try{u=vt(h.id)}catch(m){Ye.error("invalid PeerId",m),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"bad peer id"}});return}if(Ye("incoming request from %p",u),!e.connection.remotePeer.equals(u)){Ye("target peer %p did not equal sending peer %p",u,e.connection.remotePeer),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"peer id mismatch"}});return}let f=h.addrs.map(m=>se(m)).filter(m=>{let g=m.toOptions().host===e.connection.remoteAddr.toOptions().host;return Ye.trace("request to dial %s was sent from %s is same host %s",m,e.connection.remoteAddr,g),g}).filter(m=>{let g=m.toOptions().host,y=!(An(g)??!1);return Ye.trace("host %s was public %s",g,y),y}).filter(m=>{let g=m.toOptions().host,y=!n.includes(g);return Ye.trace("host %s was not our host %s",g,y),y}).filter(m=>{let g=!!s.components.transportManager.transportForMultiaddr(m);return Ye.trace("transport for %s is supported %s",m,g),g}).map(m=>(m.getPeerId()==null&&(m=m.encapsulate(`/p2p/${u.toString()}`)),m));if(f.length===0){Ye("no valid multiaddrs for %p in message",u),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_DIAL_REFUSED,statusText:"no dialable addresses"}});return}Ye("dial multiaddrs %s for peer %p",f.map(m=>m.toString()).join(", "),u);let d="",p=f[0];for await(let m of f){let g;p=m;try{if(g=await s.components.connectionManager.openConnection(m,{signal:t}),!g.remoteAddr.equals(m))throw Ye.error("tried to dial %s but dialed %s",m,g.remoteAddr),new Error("Unexpected remote address");Ye("Success %p",u),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.OK,addr:g.remoteAddr.decapsulateCode(X("p2p").code).bytes}});return}catch(y){Ye("could not dial %p",u,y),d=y.message}finally{g!=null&&await g.close()}}yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_DIAL_ERROR,statusText:d,addr:p.bytes}})},o=>yt(o),e.stream)}catch(i){Ye.error("error handling incoming autonat stream",i)}finally{t.clear()}}_verifyExternalAddresses(){this.verifyExternalAddresses().catch(e=>{Ye.error("error verifying external address",e)})}async verifyExternalAddresses(){if(clearTimeout(this.verifyAddressTimeout),!this.isStarted())return;let e=this.components.addressManager,t=e.getObservedAddrs().filter(s=>{let o=s.toOptions();return!(An(o.host)??!1)});if(t.length===0){Ye("no public addresses found, not requesting verification"),this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.refreshInterval);return}let n=AbortSignal.timeout(this.timeout);try{(0,H5.setMaxListeners)?.(1/0,n)}catch{}let i=this;try{Ye("verify multiaddrs %s",t.map(h=>h.toString()).join(", "));let s=we.encode({type:we.MessageType.DIAL,dial:{peer:{id:this.components.peerId.toBytes(),addrs:t.map(h=>h.bytes)}}}),a=(await r0()).toBytes(),c={},l=[],u=async h=>{try{Ye("asking %p to verify multiaddr",h.id);let f=await i.components.connectionManager.openConnection(h.id,{signal:n}),d=await f.newStream(this.protocol,{signal:n}),p=br(d,n),m=await be([s],y=>yt(y),p,y=>Tt(y),async y=>Jn(y));if(m==null){Ye("no response received from %p",f.remotePeer);return}let g=we.decode(m);if(g.type!==we.MessageType.DIAL_RESPONSE||g.dialResponse==null){Ye("invalid autonat response from %p",f.remotePeer);return}if(g.dialResponse.status===we.ResponseStatus.OK){let y=f.remoteAddr.toOptions(),b;if(y.family===4)b=y.host.split(".")[0];else if(y.family===6)b=y.host.split(":")[0];else{Ye('remote address "%s" was not IP4 or IP6?',y.host);return}if(l.includes(b)){Ye("already have response from network segment %d - %s",b,y.host);return}l.push(b)}return g.dialResponse}catch(f){Ye.error("error asking remote to verify multiaddr",f)}};for await(let h of Zo(Un(this.components.peerRouting.getClosestPeers(a,{signal:n}),f=>async()=>u(f)),{concurrency:z5}))try{if(h==null)continue;let f=h.addr==null?t[0]:se(h.addr);if(Ye("autonat response for %s is %s",f,h.status),h.status===we.ResponseStatus.E_BAD_REQUEST||h.status===we.ResponseStatus.E_DIAL_REFUSED||h.addr==null&&t.length>1)continue;if(!t.some(p=>p.equals(f))){Ye("peer reported %s as %s but it was not in our observed address list",f,h.status);continue}let d=f.toString();if(c[d]==null&&(c[d]={success:0,failure:0}),h.status===we.ResponseStatus.OK?c[d].success++:h.status===we.ResponseStatus.E_DIAL_ERROR&&c[d].failure++,c[d].success===z5){Ye("%s is externally dialable",f),e.confirmObservedAddr(f);return}if(c[d].failure===z5){Ye("%s is not externally dialable",f),e.removeObservedAddr(f);return}}catch(f){Ye.error("could not verify external address",f)}}finally{this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.refreshInterval)}}};function aD(r={}){return e=>new $5(e,r)}var bG=F(jr(),1);var G5="/libp2p/relay";var cD="circuit-relay-relay";var lD=BigInt(131072),fo="/libp2p/circuit/relay/0.2.0/hop",Hd="/libp2p/circuit/relay/0.2.0/stop",pG=30*1e3,mG=30*1e3;var ps;(function(r){let e;(function(i){i.RESERVE="RESERVE",i.CONNECT="CONNECT",i.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(i){i[i.RESERVE=0]="RESERVE",i[i.CONNECT=1]="CONNECT",i[i.STATUS=2]="STATUS"})(t||(t={})),function(i){i.codec=()=>At(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=ne((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.type!=null&&(s.uint32(8),r.Type.codec().encode(i.type,s)),i.peer!=null&&(s.uint32(18),Jc.codec().encode(i.peer,s)),i.reservation!=null&&(s.uint32(26),$d.codec().encode(i.reservation,s)),i.limit!=null&&(s.uint32(34),el.codec().encode(i.limit,s)),i.status!=null&&(s.uint32(40),or.codec().encode(i.status,s)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.type=r.Type.codec().decode(i);break;case 2:o.peer=Jc.codec().decode(i,i.uint32());break;case 3:o.reservation=$d.codec().decode(i,i.uint32());break;case 4:o.limit=el.codec().decode(i,i.uint32());break;case 5:o.status=or.codec().decode(i);break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>re(i,r.codec()),r.decode=i=>te(i,r.codec())})(ps||(ps={}));var ai;(function(r){let e;(function(i){i.CONNECT="CONNECT",i.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(i){i[i.CONNECT=0]="CONNECT",i[i.STATUS=1]="STATUS"})(t||(t={})),function(i){i.codec=()=>At(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=ne((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.type!=null&&(s.uint32(8),r.Type.codec().encode(i.type,s)),i.peer!=null&&(s.uint32(18),Jc.codec().encode(i.peer,s)),i.limit!=null&&(s.uint32(26),el.codec().encode(i.limit,s)),i.status!=null&&(s.uint32(32),or.codec().encode(i.status,s)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.type=r.Type.codec().decode(i);break;case 2:o.peer=Jc.codec().decode(i,i.uint32());break;case 3:o.limit=el.codec().decode(i,i.uint32());break;case 4:o.status=or.codec().decode(i);break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>re(i,r.codec()),r.decode=i=>te(i,r.codec())})(ai||(ai={}));var Jc;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.id!=null&&t.id.byteLength>0&&(n.uint32(10),n.bytes(t.id)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={id:new Uint8Array(0),addrs:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.id=t.bytes();break;case 2:i.addrs.push(t.bytes());break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(Jc||(Jc={}));var $d;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.expire!=null&&t.expire!==0n&&(n.uint32(8),n.uint64(t.expire)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);t.voucher!=null&&(n.uint32(26),n.bytes(t.voucher)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={expire:0n,addrs:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.expire=t.uint64();break;case 2:i.addrs.push(t.bytes());break;case 3:i.voucher=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})($d||($d={}));var el;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.duration!=null&&(n.uint32(8),n.uint32(t.duration)),t.data!=null&&(n.uint32(16),n.uint64(t.data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.duration=t.uint32();break;case 2:i.data=t.uint64();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(el||(el={}));var or;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(or||(or={}));var W5;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(W5||(W5={}));(function(r){r.codec=()=>At(W5)})(or||(or={}));var Y5;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.relay!=null&&t.relay.byteLength>0&&(n.uint32(10),n.bytes(t.relay)),t.peer!=null&&t.peer.byteLength>0&&(n.uint32(18),n.bytes(t.peer)),t.expiration!=null&&t.expiration!==0n&&(n.uint32(24),n.uint64(t.expiration)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={relay:new Uint8Array(0),peer:new Uint8Array(0),expiration:0n},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.relay=t.bytes();break;case 2:i.peer=t.bytes();break;case 3:i.expiration=t.uint64();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(Y5||(Y5={}));var A7e=T("libp2p:circuit-relay:utils");async function Q5(r){let e=new TextEncoder().encode(r),t=await Ce.digest(e);return ee.createV0(t)}function X5(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var wG=F(pD(),1);var K7e=T("libp2p:circuit-relay:advert-service");var m9e=T("libp2p:circuit-relay:server");var EG=T("libp2p:stream:converter");function j5(r,e={}){let{stream:t,remoteAddr:n}=r,{sink:i,source:s}=t,o=async function*(){for await(let l of s)l instanceof Uint8Array?yield l:yield*l}(),a={async sink(l){e.signal!=null&&(l=gt(l,e.signal));try{await i(l),await c()}catch(u){u.type!=="aborted"&&EG(u)}},source:e.signal!=null?gt(o,e.signal):o,remoteAddr:n,timeline:{open:Date.now(),close:void 0},async close(){await i(async function*(){yield new Uint8Array(0)}()),await c()}};async function c(){a.timeline.close==null&&(a.timeline.close=Date.now()),await Promise.resolve()}return a}var po=T("libp2p:circuit-relay:discover-relays"),Gd=class extends Fe{peerId;peerStore;contentRouting;registrar;started;topologyId;constructor(e){super(),this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.contentRouting=e.contentRouting,this.registrar=e.registrar}isStarted(){return this.started}async start(){this.topologyId=await this.registrar.register(fo,Es({onConnect:e=>{this.safeDispatchEvent("relay:discover",{detail:e})}})),this.discover().catch(e=>{po.error("error listening on relays",e)}),this.started=!0}stop(){this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.started=!1}async discover(){po("searching peer store for relays");let e=(await this.peerStore.all()).filter(({protocols:t})=>t.includes(fo)).sort(()=>Math.random()-.5);for(let t of e)po("found relay peer %p in content peer store",t.id),this.safeDispatchEvent("relay:discover",{detail:t.id});po("found %d relay peers in peer store",e.length);try{po("searching content routing for relays");let t=await Q5(G5),n=0;for await(let i of this.contentRouting.findProviders(t))if(i.multiaddrs.length>0&&!i.id.equals(this.peerId)){let s=i.id;n++,await this.peerStore.merge(s,{multiaddrs:i.multiaddrs}),po("found relay peer %p in content routing",s),this.safeDispatchEvent("relay:discover",{detail:s})}po("found %d relay peers in content routing",n)}catch(t){po.error("failed when finding relays on the network",t)}}};var gD=T("libp2p:circuit-relay:transport:listener"),Z5=class extends Fe{connectionManager;relayStore;listeningAddrs;constructor(e){super(),this.connectionManager=e.connectionManager,this.relayStore=e.relayStore,this.listeningAddrs=new Fr,this.relayStore.addEventListener("relay:removed",t=>{this.#e(t.detail)})}async listen(e){gD("listen on %s",e);let t=e.getPeerId(),n;if(t!=null){let s=oe(t),o=this.connectionManager.getConnectionsMap().get(s)??[];o.length>0&&(n=o[0])}if(n==null){let s=e.toString().split("/p2p-circuit").find(a=>a!==""),o=se(s);n=await this.connectionManager.openConnection(o)}if(!this.relayStore.hasReservation(n.remotePeer)){await this.relayStore.addRelay(n.remotePeer,"configured");return}let i=this.relayStore.getReservation(n.remotePeer);if(i==null)throw new w("Did not have reservation after making reservation","ERR_NO_RESERVATION");if(this.listeningAddrs.has(n.remotePeer)){gD("already listening on relay %p",n.remotePeer);return}this.listeningAddrs.set(n.remotePeer,i.addrs.map(s=>se(s).encapsulate("/p2p-circuit"))),this.safeDispatchEvent("listening",{})}getAddrs(){return[...this.listeningAddrs.values()].flat()}async close(){}#e(e){let t=this.listeningAddrs.has(e);this.listeningAddrs.delete(e),t&&this.safeDispatchEvent("close",{})}};function yD(r){return new Z5(r)}var yn=T("libp2p:circuit-relay:transport:reservation-store"),xG=60*1e3*10,_G=60*1e3*5,SG=30*1e3,Wd=class extends Fe{peerId;connectionManager;transportManager;peerStore;events;reserveQueue;reservations;maxDiscoveredRelays;started;constructor(e,t){super(),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.transportManager=e.transportManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new Fr,this.maxDiscoveredRelays=t?.discoverRelays??0,this.started=!1,this.reserveQueue=new wt({concurrency:t?.reservationConcurrency??1}),this.events.addEventListener("peer:disconnect",n=>{this.#t(n.detail)})}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!0}async addRelay(e,t){if(this.peerId.equals(e)){yn("not trying to use self as relay");return}yn("add relay %p",e),await this.reserveQueue.add(async()=>{try{let n=this.reservations.get(e);if(n!=null){if(X5(n.reservation.expire)>xG){yn("already have reservation on relay peer %p and it expires in more than 10 minutes",e);return}clearTimeout(n.timeout),this.reservations.delete(e)}if(t==="discovered"&&[...this.reservations.values()].reduce((l,u)=>(u.type==="discovered"&&l++,l),0)>=this.maxDiscoveredRelays){yn("already have enough discovered relays");return}let i=await this.connectionManager.openConnection(e);if(i.remoteAddr.protoNames().includes("p2p-circuit")){yn("not creating reservation over relayed connection");return}let s=await this.#e(i);yn("created reservation on relay peer %p",e);let o=X5(s.expire),a=Math.min(Math.max(o-_G,SG),Math.pow(2,31)-1),c=setTimeout(()=>{this.addRelay(e,t).catch(l=>{yn.error("could not refresh reservation to relay %p",e,l)})},a);this.reservations.set(e,{timeout:c,reservation:s,type:t}),await this.peerStore.merge(e,{tags:{[cD]:{value:1,ttl:o}}}),await this.transportManager.listen([se(`/p2p/${e.toString()}/p2p-circuit`)])}catch(n){yn.error("could not reserve slot on %p",e,n),this.reservations.delete(e)}})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}async#e(e){yn("requesting reservation from %s",e.remotePeer);let t=await e.newStream(fo),i=qr(t).pb(ps);i.write({type:ps.Type.RESERVE});let s;try{s=await i.read()}catch(a){throw yn.error("error parsing reserve message response from %p because",e.remotePeer,a),a}finally{t.close()}if(s.status===or.OK&&s.reservation!=null)return s.reservation;let o=`reservation failed with status ${s.status??"undefined"}`;throw yn.error(o),new Error(o)}#t(e){let t=this.reservations.get(e);t!=null&&(yn("connection to relay %p closed, removing reservation from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),this.safeDispatchEvent("relay:removed",{detail:e}),this.reservations.size<this.maxDiscoveredRelays&&(yn("not enough relays %d/%d",this.reservations.size,this.maxDiscoveredRelays),this.safeDispatchEvent("relay:not-enough-relays",{})))}};var $r=T("libp2p:circuit-relay:transport"),RG=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(se)}catch{return!1}return!0},J5=class{discovery;registrar;peerStore;connectionManager;peerId;upgrader;addressManager;connectionGater;reservationStore;started;constructor(e,t){this.registrar=e.registrar,this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.peerId=e.peerId,this.upgrader=e.upgrader,this.addressManager=e.addressManager,this.connectionGater=e.connectionGater,t.discoverRelays!=null&&t.discoverRelays>0&&(this.discovery=new Gd(e),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(i=>{$r.error("could not add discovered relay %p",n.detail,i)})})),this.reservationStore=new Wd(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.discover().catch(n=>{$r.error("could not discover relays",n)})}),this.started=!1}isStarted(){return this.started}async start(){await this.reservationStore.start(),await this.discovery?.start(),await this.registrar.handle(Hd,e=>{this.onStop(e).catch(t=>{$r.error(t)})}),this.started=!0}async stop(){this.discovery?.stop(),await this.reservationStore.stop(),await this.registrar.unhandle(Hd),this.started=!1}[Ti]=!0;[Symbol.toStringTag]="libp2p/circuit-relay-v2";async dial(e,t={}){if(e.protoCodes().filter(p=>p===290).length!==1){let p="Invalid circuit relay address";throw $r.error(p,e),new w(p,q.ERR_RELAYED_DIAL)}let n=e.toString().split("/p2p-circuit"),i=se(n[0]),s=se(n[n.length-1]),o=i.getPeerId(),a=s.getPeerId();if(o==null||a==null){let p=`Circuit relay dial to ${e.toString()} failed as address did not have peer ids`;throw $r.error(p),new w(p,q.ERR_RELAYED_DIAL)}let c=oe(o),l=oe(a),u=!1,f=this.connectionManager.getConnections(c)[0];f==null&&(await this.peerStore.merge(c,{multiaddrs:[i]}),f=await this.connectionManager.openConnection(c,t),u=!0);let d;try{return d=await f.newStream([fo]),await this.connectV2({stream:d,connection:f,destinationPeer:l,destinationAddr:s,relayAddr:i,ma:e,disconnectOnFailure:u})}catch(p){throw $r.error(`Circuit relay dial to destination ${l.toString()} via relay ${c.toString()} failed`,p),d?.abort(p),u&&await f.close(),p}}async connectV2({stream:e,connection:t,destinationPeer:n,destinationAddr:i,relayAddr:s,ma:o,disconnectOnFailure:a}){try{let c=qr(e),l=c.pb(ps);l.write({type:ps.Type.CONNECT,peer:{id:n.toBytes(),addrs:[se(i).bytes]}});let u=await l.read();if(u.status!==or.OK)throw new w(`failed to connect via relay with status ${u?.status?.toString()??"undefined"}`,q.ERR_HOP_REQUEST_FAILED);let h=j5({stream:c.unwrap(),remoteAddr:o,localAddr:s.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`)});return $r("new outbound connection %s",h.remoteAddr),await this.upgrader.upgradeOutbound(h)}catch(c){throw $r.error(`Circuit relay dial to destination ${n.toString()} via relay ${t.remotePeer.toString()} failed`,c),a&&await t.close(),c}}createListener(e){return yD({connectionManager:this.connectionManager,relayStore:this.reservationStore})}filter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>ni.matches(t))}async onStop({connection:e,stream:t}){let n=qr(t),i=await n.readPB(ai);if($r("received circuit v2 stop protocol request from %s",e.remotePeer),i?.type===void 0)return;let s=n.pb(ai);if($r("new circuit relay v2 stop stream from %s",e.remotePeer),i.type!==ai.Type.CONNECT){$r.error("invalid stop connect request via peer %s",e.remotePeer),s.write({type:ai.Type.STATUS,status:or.UNEXPECTED_MESSAGE});return}if(!RG(i)){$r.error("invalid stop connect request via peer %s",e.remotePeer),s.write({type:ai.Type.STATUS,status:or.MALFORMED_MESSAGE});return}let o=vt(i.peer.id);if(await this.connectionGater.denyInboundRelayedConnection?.(e.remotePeer,o)===!0){s.write({type:ai.Type.STATUS,status:or.PERMISSION_DENIED});return}s.write({type:ai.Type.STATUS,status:or.OK});let a=e.remoteAddr.encapsulate(`/p2p-circuit/p2p/${o.toString()}`),c=this.addressManager.getAddresses()[0],l=j5({stream:n.unwrap(),remoteAddr:a,localAddr:c});$r("new inbound connection %s",l.remoteAddr),await this.upgrader.upgradeInbound(l),$r("%s connection %s upgraded","inbound",l.remoteAddr)}};function e6(r={}){return e=>new J5(e,r)}var wD="0.45.5";var t6=`js-libp2p/${wD}`;var bD="0.1.0",ED="id",vD="id/push",xD="1.0.0",_D="1.0.0";var Yd=F(jr(),1);var mo;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.protocolVersion!=null&&(n.uint32(42),n.string(t.protocolVersion)),t.agentVersion!=null&&(n.uint32(50),n.string(t.agentVersion)),t.publicKey!=null&&(n.uint32(10),n.bytes(t.publicKey)),t.listenAddrs!=null)for(let s of t.listenAddrs)n.uint32(18),n.bytes(s);if(t.observedAddr!=null&&(n.uint32(34),n.bytes(t.observedAddr)),t.protocols!=null)for(let s of t.protocols)n.uint32(26),n.string(s);t.signedPeerRecord!=null&&(n.uint32(66),n.bytes(t.signedPeerRecord)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={listenAddrs:[],protocols:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 5:i.protocolVersion=t.string();break;case 6:i.agentVersion=t.string();break;case 1:i.publicKey=t.bytes();break;case 2:i.listenAddrs.push(t.bytes());break;case 4:i.observedAddr=t.bytes();break;case 3:i.protocols.push(t.string());break;case 8:i.signedPeerRecord=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(mo||(mo={}));var Lr=T("libp2p:identify"),SD=1024*8,ci={protocolPrefix:"ipfs",agentVersion:t6,timeout:6e4,maxInboundStreams:1,maxOutboundStreams:1,maxPushIncomingStreams:1,maxPushOutgoingStreams:1,maxObservedAddresses:10,maxIdentifyMessageSize:8192},Qd=class{identifyProtocolStr;identifyPushProtocolStr;host;started;timeout;peerId;peerStore;registrar;connectionManager;addressManager;maxInboundStreams;maxOutboundStreams;maxPushIncomingStreams;maxPushOutgoingStreams;maxIdentifyMessageSize;maxObservedAddresses;events;constructor(e,t){this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.events=e.events,this.identifyProtocolStr=`/${t.protocolPrefix??ci.protocolPrefix}/${ED}/${xD}`,this.identifyPushProtocolStr=`/${t.protocolPrefix??ci.protocolPrefix}/${vD}/${_D}`,this.timeout=t.timeout??ci.timeout,this.maxInboundStreams=t.maxInboundStreams??ci.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??ci.maxOutboundStreams,this.maxPushIncomingStreams=t.maxPushIncomingStreams??ci.maxPushIncomingStreams,this.maxPushOutgoingStreams=t.maxPushOutgoingStreams??ci.maxPushOutgoingStreams,this.maxIdentifyMessageSize=t.maxIdentifyMessageSize??ci.maxIdentifyMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??ci.maxObservedAddresses,this.host={protocolVersion:`${t.protocolPrefix??ci.protocolPrefix}/${bD}`,agentVersion:t.agentVersion??ci.agentVersion},e.events.addEventListener("connection:open",n=>{let i=n.detail;this.identify(i).catch(s=>{Lr.error("error during identify trigged by connection:open",s)})}),e.events.addEventListener("self:peer:update",n=>{this.push().catch(i=>{Lr.error(i)})}),this.host.agentVersion===t6&&(ZA||XA?this.host.agentVersion+=` UserAgent=${globalThis.process.version}`:(Ad||Td||jA||JA)&&(this.host.agentVersion+=` UserAgent=${globalThis.navigator.userAgent}`))}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:K(this.host.agentVersion),ProtocolVersion:K(this.host.protocolVersion)}}),await this.registrar.handle(this.identifyProtocolStr,e=>{this._handleIdentify(e).catch(t=>{Lr.error(t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),await this.registrar.handle(this.identifyPushProtocolStr,e=>{this._handlePush(e).catch(t=>{Lr.error(t)})},{maxInboundStreams:this.maxPushIncomingStreams,maxOutboundStreams:this.maxPushOutgoingStreams}),this.started=!0)}async stop(){await this.registrar.unhandle(this.identifyProtocolStr),await this.registrar.unhandle(this.identifyPushProtocolStr),this.started=!1}async pushToConnections(e){let t=this.addressManager.getAddresses().map(u=>u.decapsulateCode(X("p2p").code)),n=new Ut({peerId:this.peerId,multiaddrs:t}),i=await Wt.seal(n,this.peerId),s=this.registrar.getProtocols(),o=await this.peerStore.get(this.peerId),a=O(o.metadata.get("AgentVersion")??K(this.host.agentVersion)),c=O(o.metadata.get("ProtocolVersion")??K(this.host.protocolVersion)),l=e.map(async u=>{let h,f=AbortSignal.timeout(this.timeout);try{(0,Yd.setMaxListeners)?.(1/0,f)}catch{}try{h=await u.newStream([this.identifyPushProtocolStr],{signal:f}),await br(h,f).sink(be([mo.encode({listenAddrs:t.map(p=>p.bytes),signedPeerRecord:i.marshal(),protocols:s,agentVersion:a,protocolVersion:c})],p=>yt(p)))}catch(d){Lr.error("could not push identify update to peer",d)}finally{h?.close()}});await Promise.all(l)}async push(){if(!this.isStarted())return;let e=[];await Promise.all(this.connectionManager.getConnections().map(async t=>{try{if(!(await this.peerStore.get(t.remotePeer)).protocols.includes(this.identifyPushProtocolStr))return;e.push(t)}catch(n){if(n.code!==q.ERR_NOT_FOUND)throw n}})),await this.pushToConnections(e)}async _identify(e,t={}){let n,i=st([AbortSignal.timeout(this.timeout),t?.signal]);try{(0,Yd.setMaxListeners)?.(1/0,i)}catch{}try{n=await e.newStream([this.identifyProtocolStr],{signal:i});let s=br(n,i),o=await be([],s,a=>Tt(a,{maxDataLength:this.maxIdentifyMessageSize??SD}),async a=>Jn(a));if(o==null)throw new w("No data could be retrieved",q.ERR_CONNECTION_ENDED);try{return mo.decode(o)}catch(a){throw new w(String(a),q.ERR_INVALID_MESSAGE)}}finally{n?.close(),i.clear()}}async identify(e,t={}){let n=await this._identify(e,t),{publicKey:i,protocols:s,observedAddr:o}=n;if(i==null)throw new w("public key was missing from identify message",q.ERR_MISSING_PUBLIC_KEY);let a=await zt(i);if(!e.remotePeer.equals(a))throw new w("identified peer does not match the expected peer",q.ERR_INVALID_PEER);if(this.peerId.equals(a))throw new w("identified peer is our own peer id?",q.ERR_INVALID_PEER);let c=IG(o);Lr("identify completed for peer %p and protocols %o",a,s),Lr("our observed address is %s",c),c!=null&&this.addressManager.getObservedAddrs().length<(this.maxObservedAddresses??1/0)&&(Lr("storing our observed address %s",c?.toString()),this.addressManager.addObservedAddr(c));let l=await this.#e(e.remotePeer,n),u={peerId:a,protocolVersion:n.protocolVersion,agentVersion:n.agentVersion,publicKey:n.publicKey,listenAddrs:n.listenAddrs.map(h=>se(h)),observedAddr:n.observedAddr==null?void 0:se(n.observedAddr),protocols:n.protocols,signedPeerRecord:l};this.events.safeDispatchEvent("peer:identify",{detail:u})}async _handleIdentify(e){let{connection:t,stream:n}=e,i=AbortSignal.timeout(this.timeout);try{(0,Yd.setMaxListeners)?.(1/0,i)}catch{}try{let s=this.peerId.publicKey??new Uint8Array(0),o=await this.peerStore.get(this.peerId),a=this.addressManager.getAddresses().map(f=>f.decapsulateCode(X("p2p").code)),c=o.peerRecordEnvelope;if(a.length>0&&c==null){let f=new Ut({peerId:this.peerId,multiaddrs:a});c=(await Wt.seal(f,this.peerId)).marshal().subarray()}let l=mo.encode({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:s,listenAddrs:a.map(f=>f.bytes),signedPeerRecord:c,observedAddr:t.remoteAddr.bytes,protocols:o.protocols}),u=br(n,i),h=be([l],f=>yt(f));await u.sink(h)}catch(s){Lr.error("could not respond to identify request",s)}finally{n.close()}}async _handlePush(e){let{connection:t,stream:n}=e;try{if(this.peerId.equals(t.remotePeer))throw new Error("received push from ourselves?");let i=br(n,AbortSignal.timeout(this.timeout)),o=await qr(i,{maxDataLength:this.maxIdentifyMessageSize??SD}).readPB(mo);await this.#e(t.remotePeer,o)}catch(i){Lr.error("received invalid message",i);return}finally{n.close()}Lr("handled push from %p",t.remotePeer)}async#e(e,t){if(Lr("received identify from %p",e),t==null)throw new Error("Message was null or undefined");let n={addresses:t.listenAddrs.map(s=>({isCertified:!1,multiaddr:se(s)})),protocols:t.protocols,metadata:new Map,peerRecordEnvelope:t.signedPeerRecord},i;if(t.signedPeerRecord!=null){Lr("received signedPeerRecord in push from %p",e);let s=t.signedPeerRecord,o=await Wt.openAndCertify(s,Ut.DOMAIN),a=Ut.createFromProtobuf(o.payload);if(!a.peerId.equals(o.peerId))throw new Error("signing key does not match PeerId in the PeerRecord");if(!e.equals(a.peerId))throw new Error("signing key does not match remote PeerId");let c;try{c=await this.peerStore.get(a.peerId)}catch(l){if(l.code!=="ERR_NOT_FOUND")throw l}if(c!=null&&(n.metadata=c.metadata,c.peerRecordEnvelope!=null)){let l=await Wt.createFromProtobuf(c.peerRecordEnvelope),u=Ut.createFromProtobuf(l.payload);u.seqNumber>=a.seqNumber&&(Lr("sequence number was lower or equal to existing sequence number - stored: %d received: %d",u.seqNumber,a.seqNumber),a=u,s=c.peerRecordEnvelope)}n.peerRecordEnvelope=s,n.addresses=a.multiaddrs.map(l=>({isCertified:!0,multiaddr:l})),i={seq:a.seqNumber,addresses:a.multiaddrs}}else Lr("%p did not send a signed peer record",e);return t.agentVersion!=null&&n.metadata.set("AgentVersion",K(t.agentVersion)),t.protocolVersion!=null&&n.metadata.set("ProtocolVersion",K(t.protocolVersion)),await this.peerStore.patch(e,n),i}};function IG(r){if(r!=null&&r.length>0)try{return se(r)}catch{}}function RD(r={}){return e=>new Qd(e,r)}var ID={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function AD(){return{addresses:{listen:["/webrtc"]},transports:[_A(),xA(),HT(),lT(),e6({discoverRelays:1})],connectionEncryption:[b1()],streamMuxers:[wS(),TR()],peerDiscovery:[CS(ID)],contentRouters:[MS("https://cid.contact")],services:{identify:RD(),autoNAT:aD(),pubsub:y_(),dht:yR({clientMode:!0,validators:{ipns:nD},selectors:{ipns:rD}})}}}async function TD(r,e){let t=AD();return e=e??{},hx({datastore:r,...t,...e,start:!1})}var r6="1.3.0",Xd="helia";var AG=T("helia");async function TG(r={}){let e=r.datastore??new wo,t=r.blockstore??new ol,n;DG(r.libp2p)?n=r.libp2p:n=await TD(e,r.libp2p);let i=new yf({...r,datastore:e,blockstore:t,libp2p:n});return r.start!==!1&&await i.start(),i.libp2p.isStarted()?await DD(i):i.libp2p.addEventListener("start",()=>{DD(i).catch(s=>{AG.error("could not add Helia to agent version",s)})}),i}function DG(r){return r==null?!1:["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"].every(t=>typeof r[t]=="function")}async function DD(r){let t=(await r.libp2p.peerStore.get(r.libp2p.peerId)).metadata.get("AgentVersion");if(t==null)return;let n=new TextDecoder().decode(t);n.match(/js-libp2p\/\d+\.\d+\.\d+\sUserAgent=/)!=null&&(n.includes(Xd)?n=`${Xd}/${r6} ${n.split(" ").slice(1).join(" ")}`:n=`${Xd}/${r6} ${n}`,await r.libp2p.peerStore.merge(r.libp2p.peerId,{metadata:{AgentVersion:new TextEncoder().encode(n)}}))}return uh(CG);})();
|
|
85
85
|
/*! Bundled license information:
|
|
86
86
|
|
|
87
87
|
@noble/ed25519/lib/esm/index.js:
|