helia 7.1.6 → 7.1.7-dc9e15bc

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -99,7 +99,7 @@ a=end-of-candidates
99
99
  `:`
100
100
  `;try{r.sdp=r.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
101
101
  a=ice-ufrag:`+e+t).replace(/\na=ice-pwd:[^\n]*\n/,`
102
- a=ice-pwd:`+e+t)}catch{}return r}var G5=T("libp2p-webrtc-noise:");function WC(r,e,t){let n=r.trim().toLowerCase().replaceAll(":",""),o=T(n,"hex"),s=or(ze.code,o),i=q5.decode(z5(e)),a=G5.byteLength+s.bytes.byteLength+i.byteLength;return t==="server"?Ve([G5,i,s.bytes],a):Ve([G5,s.bytes,i],a)}function SH(r,e){return r.role==="server"}async function GC(r,e,t,n){let o=r.createDataChannel("",{negotiated:!0,id:0});try{if(n.role==="client"){n.log.trace("client creating local offer");let d=await r.createOffer();n.log.trace("client created local offer %s",d.sdp);let f=W5(d,t);n.log.trace("client setting local offer %s",f.sdp),await r.setLocalDescription(f);let h=VC(n.remoteAddr,t);n.log.trace("client setting server description %s",h.sdp),await r.setRemoteDescription(h)}else{let d=qC(n.remoteAddr,t);n.log.trace("server setting client %s %s",d.type,d.sdp),await r.setRemoteDescription(d),n.log.trace("server creating local answer");let f=await r.createAnswer();n.log.trace("server created local answer");let h=W5(f,t);n.log.trace("server setting local description %s",f.sdp),await r.setLocalDescription(h)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await qo(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),SH(n,r)){let d=r.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(HC(d))}let s=KC(r.localDescription?.sdp);if(s==null)throw new qs("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let i=WC(s,n.remoteAddr,n.role),a=gm({prologueBytes:i})(n),c=lf({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),l=uf({peerConnection:r,remoteAddr:n.remoteAddr,metrics:n.events,direction:n.role==="client"?"outbound":"inbound",log:n.logger.forComponent("libp2p:webrtc-direct:connection")});if(r.addEventListener("connectionstatechange",()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":l.close().catch(d=>{n.log.error("error closing connection - %e",d),l.abort(d)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let d=await a.secureInbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});return n.log.trace("%s upgrade outbound",n.role),await n.upgrader.upgradeOutbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:d.remotePeer,muxerFactory:e,signal:n.signal})}n.log.trace("%s secure outbound",n.role);let u=await a.secureOutbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});l.remoteAddr=l.remoteAddr.encapsulate(`/p2p/${u.remotePeer}`),n.log.trace("%s upgrade inbound",n.role),await n.upgrader.upgradeInbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:u.remotePeer,muxerFactory:e,signal:n.signal})}catch(s){throw e.close(),o.close(),r.close(),s}}async function jC(r,e,t={}){let n=t.certificate;n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof t.rtcConfiguration=="function"?await t.rtcConfiguration():t.rtcConfiguration,s=new RTCPeerConnection({...o??{},certificates:[n]}),i=new Vs({peerConnection:s,metrics:t.events,log:t.log,dataChannelOptions:t.dataChannel,maxEarlyStreams:t.maxEarlyStreams});return{peerConnection:s,muxerFactory:i}}var J2=class{log;metrics;components;init;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[Yo]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Se]=["@libp2p/transport"];async dial(e,t){this.log("dial %a",e),t.signal.throwIfAborted();let n,o=e.getComponents().findLast(c=>c.code===421)?.value;o!=null&&(n=Je(o));let s=OC(),{peerConnection:i,muxerFactory:a}=await jC("client",s,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},events:this.metrics?.dialerEvents,log:this.log,dataChannel:this.init.dataChannel,maxEarlyStreams:this.init.maxEarlyStreams});try{return await GC(i,a,s,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:t.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:t.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(c){throw i.close(),c}}createListener(e){throw new G2("WebRTCDirectTransport.createListener")}listenFilter(e){return[]}dialFilter(e){return e.filter(zl.exactMatch)}};function YC(r){return e=>new J2(e,r)}function XC(r){return e=>new Z2(e,r)}var AH=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function TH(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=AH(r),d=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(g){n(),i(g);return}c.push(p),t.count===c.length&&(n(),s(c))},f=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,d);for(let h of t.rejectionEvents)a.includes(h)||u(h,f)};for(let h of a)l(h,d);for(let h of t.rejectionEvents)a.includes(h)||l(h,f);t.signal&&t.signal.addEventListener("abort",()=>{f(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=ar(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function QC(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=TH(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function ZC(){throw new Error("WebSocket Servers can not be created in the browser!")}var IH=1024*1024*4,CH=10,j5=class extends rs{websocket;maxBufferedAmount;checkBufferedAmountTask;constructor(e){super(e),this.websocket=e.websocket,this.maxBufferedAmount=e.maxBufferedAmount??IH,this.checkBufferedAmountTask=Ya(this.checkBufferedAmount.bind(this),e.bufferedAmountPollInterval??CH),this.websocket.addEventListener("close",t=>{if(this.log('closed - code %d, reason "%s", wasClean %s',t.code,t.reason,t.wasClean),this.checkBufferedAmountTask.stop(),!t.wasClean){this.onRemoteReset();return}this.onTransportClosed()},{once:!0}),this.websocket.addEventListener("message",t=>{try{let n;if(typeof t.data=="string")n=T(t.data);else if(t.data instanceof ArrayBuffer)n=new Uint8Array(t.data,0,t.data.byteLength);else{this.abort(new Error("Incorrect binary type"));return}this.onData(n)}catch(n){this.log.error("error receiving data - %e",n)}})}sendData(e){for(let n of e)this.websocket.send(J(n));let t=this.websocket.bufferedAmount<this.maxBufferedAmount;return t||this.checkBufferedAmountTask.start(),{sentBytes:e.byteLength,canSendMore:t}}sendReset(){this.websocket.close(1006)}async sendClose(e){this.websocket.close(),e?.signal?.throwIfAborted()}sendPause(){}sendResume(){}checkBufferedAmount(){this.log("buffered amount now %d",this.websocket.bufferedAmount),this.websocket.bufferedAmount===0&&(this.checkBufferedAmountTask.stop(),this.safeDispatchEvent("drain"))}};function JC(r){return new j5(r)}var Y5=class{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[Yo]=!0;[Symbol.toStringTag]="@libp2p/websockets";[Se]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=JC({websocket:await this._connect(e,t),remoteAddr:e,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:websockets:connection"),maxBufferedAmount:this.init.maxBufferedAmount,bufferedAmountPollInterval:this.init.bufferedAmountPollInterval});this.log("new outbound connection %s",n.remoteAddr);let o=await t.upgrader.upgradeOutbound(n,t);return this.log("outbound connection %s upgraded",n.remoteAddr),o}async _connect(e,t){t?.signal?.throwIfAborted();let n=vs(e);this.log("create websocket connection to %s",n);let o=new WebSocket(n);o.binaryType="arraybuffer";try{t.onProgress?.(new R("websockets:open-connection")),await QC(o,"open",t)}catch(s){if(t.signal?.aborted)throw this.metrics?.dialerEvents.increment({abort:!0}),new la(`Could not connect to ${n}`);this.metrics?.dialerEvents.increment({error:!0});try{o.close()}catch{}throw s}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),o}createListener(e){return ZC({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e.filter(t=>mo.exactMatch(t)||gi.exactMatch(t))}dialFilter(e){return this.listenFilter(e)}};function ek(r={}){return e=>new Y5(e,r)}var tk={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dnsaddr/va1.bootstrap.libp2p.io/p2p/12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function rk(r={}){return{nodeInfo:{...r.nodeInfo},privateKey:r.privateKey,dns:r.dns,addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[pT(),XC(),YC(),ek()],connectionEncrypters:[gm()],streamMuxers:[ZA(),EC()],peerDiscovery:[nT(tk)],services:{autoNAT:rT(),dcutr:yT(),delegatedContentRouting:fx(Du()),delegatedPeerRouting:hx(Du()),dht:mC({clientMode:!0}),identify:OI(),identifyPush:BI(),keychain:qp(r.keychain),ping:IC(),http:kI(),...r.services}}}function nk(r,e){return kH(r,rk(e))}function kH(r,e){let t;Object.defineProperty(r,"libp2p",{configurable:!0,enumerable:!0,get(){if(t!=null)return t;throw new Pr}});let n={name:"libp2p",start:async o=>{if(t==null){e.privateKey==null&&(e.privateKey=await Q6(o.datastore,e.keychain)),e.nodeInfo??={},e.nodeInfo.name??=o.info.name,e.nodeInfo.version??=o.info.version,e.nodeInfo.userAgent??=`${o.info.name}/${o.info.version} ${tm()}`,e.datastore??=o.datastore,t=await LS(e);let s=o.routing.findProviders.bind(o.routing);o.routing.findProviders=async function*(c,l){yield*Sc(s.call(o.routing,c,l),async u=>{if(u.router!=="libp2p-router"){let d=X5(u);await t.peerStore.merge(d.id,d)}})};let i=o.routing.findPeer.bind(o.routing);o.routing.findPeer=async function(c,l){let u=await i(c,l);if(u.router!=="libp2p-router"){let d=X5(u);await t.peerStore.merge(d.id,d)}return u};let a=o.routing.getClosestPeers.bind(o.routing);o.routing.getClosestPeers=async function*(c,l){yield*Sc(a.call(o.routing,c,l),async u=>{if(u.router!=="libp2p-router"){let d=X5(u);await t.peerStore.merge(d.id,d)}})}}try{o.hasRouter("libp2p-router")||o.addRouter(NS(t)),RS(o.libp2p)&&await o.libp2p.start()}catch(s){if(s.name!=="NotStartedError")throw s}},stop:async()=>{await t?.stop()}};return r.addMixin(n),r}function X5(r){return{id:ft(r.id),multiaddrs:r.multiaddrs}}var J5={};he(J5,{code:()=>MH,decode:()=>FH,decodeOptions:()=>OH,encode:()=>UH,encodeOptions:()=>DH,name:()=>BH,toByteView:()=>sk});var ok=42;function sk(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function _H(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=V.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new N(w.tag,ok),new N(w.bytes,t)]}function PH(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function LH(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}function RH(r){for(let e of r.keys())if(typeof e!="string"||e.length===0)throw new Error("Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded");return null}var Q5={float64:!0,typeEncoders:{Map:RH,Object:_H,undefined:PH,number:LH}},DH={...Q5,typeEncoders:{...Q5.typeEncoders}};function NH(r){let e=r();if(e[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return V.decode(e.subarray(1))}var Z5={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{[ok]:NH}},OH={...Z5,tags:{...Z5.tags}},BH="dag-cbor",MH=113,UH=r=>vi(r,Q5),FH=r=>bn(sk(r),Z5);var o7={};he(o7,{code:()=>XH,decode:()=>ck,encode:()=>ak,format:()=>QH,name:()=>YH,parse:()=>JH,stringify:()=>QH});var e7=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(w.equals(t.type,w.array)&&(t.elements++,t.elements!==1&&e.push([44])),w.equals(t.type,w.map)&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[w.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s);e.push(o)}[w.negint.major](e,t){this[w.uint.major](e,t)}[w.bytes.major](e,t){throw new Error(`${Mn} unsupported type: Uint8Array`)}[w.string.major](e,t){this.prefix(e);let n=Ma(JSON.stringify(t.value));e.push(n.length>32?wi(n):n)}[w.array.major](e,t){this.prefix(e),this.inRecursive.push({type:w.array,elements:0}),e.push([91])}[w.map.major](e,t){this.prefix(e),this.inRecursive.push({type:w.map,elements:0}),e.push([123])}[w.tag.major](e,t){}[w.float.major](e,t){if(t.type.name==="break"){let i=this.inRecursive.pop();if(i){if(w.equals(i.type,w.array))e.push([93]);else if(w.equals(i.type,w.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(`${Mn} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),o=[],s=!1;for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i),!s&&(o[i]===46||o[i]===101||o[i]===69)&&(s=!0);s||(o.push(46),o.push(48)),e.push(o)}};function $H(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${Mn} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==w.string||n.type!==w.string)throw new Error(`${Mn} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${Mn} unexpected duplicate map keys, this is not supported`)}var KH={addBreakTokens:!0,mapSorter:$H};function t7(r,e){return e=Object.assign({},KH,e),Rh(r,new e7,e)}var rl=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos<e.length)throw new Error(`${W} 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(`${W} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,o=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new N(w.uint,0,this._pos-e);if(o([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${W} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${W} unexpected token at position ${this._pos}`);n=!0,this._pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,o([48,49,50,51,52,53,54,55,56,57]));let s=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),i=parseFloat(s);return n?new N(w.float,i,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(i)?new N(i>=0?w.uint:w.negint,i,this._pos-e):new N(i>=0?w.uint:w.negint,BigInt(s),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${W} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let s=this._pos,i=0;s<this.data.length&&i<65536;s++,i++){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 N(w.string,c,i)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${W} unexpected end of unicode escape sequence at position ${this._pos}`);let s=0;for(let i=0;i<4;i++){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(`${W} unexpected unicode escape character at position ${this._pos}`);s=s*16+a,this._pos++}return s},o=()=>{let s=this.ch(),i=null,a=s>239?4:s>223?3:s>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${W} unexpected unicode sequence at position ${this._pos}`);let c,l,u,d;switch(a){case 1:s<128&&(i=s);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(d=(s&31)<<6|c&63,d>127&&(i=d));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(d=(s&15)<<12|(c&63)<<6|l&63,d>2047&&(d<55296||d>57343)&&(i=d));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&&(d=(s&15)<<18|(c&63)<<12|(l&63)<<6|u&63,d>65535&&d<1114112&&(i=d))}i===null?(i=65533,a=1):i>65535&&(i-=65536,t.push(i>>>10&1023|55296),i=56320|i&1023),t.push(i),this._pos+=a};for(;!this.done();){let s=this.ch(),i;switch(s){case 92:if(this._pos++,this.done())throw new Error(`${W} unexpected string termination at position ${this._pos}`);switch(i=this.ch(),this._pos++,i){case 34:case 39:case 92:case 47:t.push(i);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(`${W} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new N(w.string,n9(t),this._pos-e);default:if(s<32)throw new Error(`${W} invalid control character at position ${this._pos}`);s<128?(t.push(s),this._pos++):o()}}throw new Error(`${W} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new N(w.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new N(w.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new N(w.null,null,4);case 102:return this.expect([102,97,108,115,101]),new N(w.false,!1,5);case 116:return this.expect([116,114,117,101]),new N(w.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(`${W} 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 N(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${W} 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 N(w.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 N(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${W} 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 N(w.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${W} 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(`${W} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function r7(r,e){return e=Object.assign({tokenizer:new rl(r,e)},e),bn(r,e)}function VH(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function qH(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=V.asCID(r);if(!e)return null;let t=e.toString();return[new N(w.map,1/0,1),new N(w.string,"/",1),new N(w.string,t,t.length),new N(w.break,void 0,1)]}function eg(r){let e=He.encode(r).slice(1);return[new N(w.map,1/0,1),new N(w.string,"/",1),new N(w.map,1/0,1),new N(w.string,"bytes",5),new N(w.string,e,e.length),new N(w.break,void 0,1),new N(w.break,void 0,1)]}function _n(r){return eg(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function zH(r){return eg(new Uint8Array(r))}function WH(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function GH(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var jH={typeEncoders:{Object:qH,Buffer:eg,Uint8Array:eg,Int8Array:_n,Uint16Array:_n,Int16Array:_n,Uint32Array:_n,Int32Array:_n,Float32Array:_n,Float64Array:_n,Uint8ClampedArray:_n,BigInt64Array:_n,BigUint64Array:_n,DataView:_n,ArrayBuffer:zH,undefined:WH,number:GH}},n7=class extends rl{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(w.equals(e.type,w.map)){let t=this._next();if(w.equals(t.type,w.string)&&t.value==="/"){let n=this._next();if(w.equals(n.type,w.string)){let o=this._next();if(!w.equals(o.type,w.break))throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new N(w.tag,42,0)}if(w.equals(n.type,w.map)){let o=this._next();if(w.equals(o.type,w.string)&&o.value==="bytes"){let s=this._next();if(w.equals(s.type,w.string)){for(let a=0;a<2;a++){let c=this._next();if(!w.equals(c.type,w.break))throw new Error("Invalid encoded Bytes form")}let i=He.decode(`m${s.value}`);return new N(w.bytes,i,s.value.length)}this.tokenBuffer.push(s)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},ik={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{42:r=>V.parse(r())}},YH="dag-json",XH=297,ak=r=>t7(r,jH),ck=r=>{let e=VH(r),t=Object.assign(ik,{tokenizer:new n7(e,ik)});return r7(e,t)},QH=r=>ZH.decode(ak(r));var ZH=new TextDecoder,JH=r=>ck(eV.encode(r)),eV=new TextEncoder;var hk=Ws($6(),1);var mr=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},df=class extends Error{static name="DecryptionFailedError";name="DecryptionFailedError"};async function uk(r,e,t){r=r.replaceAll("-----BEGIN ENCRYPTED PRIVATE KEY-----",""),r=r.replaceAll("-----END ENCRYPTED PRIVATE KEY-----",""),r=r.replaceAll("\r",""),r=r.replaceAll(`
102
+ a=ice-pwd:`+e+t)}catch{}return r}var G5=T("libp2p-webrtc-noise:");function WC(r,e,t){let n=r.trim().toLowerCase().replaceAll(":",""),o=T(n,"hex"),s=or(ze.code,o),i=q5.decode(z5(e)),a=G5.byteLength+s.bytes.byteLength+i.byteLength;return t==="server"?Ve([G5,i,s.bytes],a):Ve([G5,s.bytes,i],a)}function SH(r,e){return r.role==="server"}async function GC(r,e,t,n){let o=r.createDataChannel("",{negotiated:!0,id:0});try{if(n.role==="client"){n.log.trace("client creating local offer");let d=await r.createOffer();n.log.trace("client created local offer %s",d.sdp);let f=W5(d,t);n.log.trace("client setting local offer %s",f.sdp),await r.setLocalDescription(f);let h=VC(n.remoteAddr,t);n.log.trace("client setting server description %s",h.sdp),await r.setRemoteDescription(h)}else{let d=qC(n.remoteAddr,t);n.log.trace("server setting client %s %s",d.type,d.sdp),await r.setRemoteDescription(d),n.log.trace("server creating local answer");let f=await r.createAnswer();n.log.trace("server created local answer");let h=W5(f,t);n.log.trace("server setting local description %s",f.sdp),await r.setLocalDescription(h)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await qo(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),SH(n,r)){let d=r.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(HC(d))}let s=KC(r.localDescription?.sdp);if(s==null)throw new qs("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let i=WC(s,n.remoteAddr,n.role),a=gm({prologueBytes:i})(n),c=lf({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),l=uf({peerConnection:r,remoteAddr:n.remoteAddr,metrics:n.events,direction:n.role==="client"?"outbound":"inbound",log:n.logger.forComponent("libp2p:webrtc-direct:connection")});if(r.addEventListener("connectionstatechange",()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":l.close().catch(d=>{n.log.error("error closing connection - %e",d),l.abort(d)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let d=await a.secureInbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});return n.log.trace("%s upgrade outbound",n.role),await n.upgrader.upgradeOutbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:d.remotePeer,muxerFactory:e,signal:n.signal})}n.log.trace("%s secure outbound",n.role);let u=await a.secureOutbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});l.remoteAddr=l.remoteAddr.encapsulate(`/p2p/${u.remotePeer}`),n.log.trace("%s upgrade inbound",n.role),await n.upgrader.upgradeInbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:u.remotePeer,muxerFactory:e,signal:n.signal})}catch(s){throw e.close(),o.close(),r.close(),s}}async function jC(r,e,t={}){let n=t.certificate;n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof t.rtcConfiguration=="function"?await t.rtcConfiguration():t.rtcConfiguration,s=new RTCPeerConnection({...o??{},certificates:[n]}),i=new Vs({peerConnection:s,metrics:t.events,log:t.log,dataChannelOptions:t.dataChannel,maxEarlyStreams:t.maxEarlyStreams});return{peerConnection:s,muxerFactory:i}}var J2=class{log;metrics;components;init;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[Yo]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Se]=["@libp2p/transport"];async dial(e,t){this.log("dial %a",e),t.signal.throwIfAborted();let n,o=e.getComponents().findLast(c=>c.code===421)?.value;o!=null&&(n=Je(o));let s=OC(),{peerConnection:i,muxerFactory:a}=await jC("client",s,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},events:this.metrics?.dialerEvents,log:this.log,dataChannel:this.init.dataChannel,maxEarlyStreams:this.init.maxEarlyStreams});try{return await GC(i,a,s,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:t.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:t.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(c){throw i.close(),c}}createListener(e){throw new G2("WebRTCDirectTransport.createListener")}listenFilter(e){return[]}dialFilter(e){return e.filter(zl.exactMatch)}};function YC(r){return e=>new J2(e,r)}function XC(r){return e=>new Z2(e,r)}var AH=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function TH(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=AH(r),d=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(g){n(),i(g);return}c.push(p),t.count===c.length&&(n(),s(c))},f=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,d);for(let h of t.rejectionEvents)a.includes(h)||u(h,f)};for(let h of a)l(h,d);for(let h of t.rejectionEvents)a.includes(h)||l(h,f);t.signal&&t.signal.addEventListener("abort",()=>{f(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=ar(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function QC(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=TH(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function ZC(){throw new Error("WebSocket Servers can not be created in the browser!")}var IH=1024*1024*4,CH=10,j5=class extends rs{websocket;maxBufferedAmount;checkBufferedAmountTask;constructor(e){super(e),this.websocket=e.websocket,this.maxBufferedAmount=e.maxBufferedAmount??IH,this.checkBufferedAmountTask=Ya(this.checkBufferedAmount.bind(this),e.bufferedAmountPollInterval??CH),this.websocket.addEventListener("close",t=>{if(this.log('closed - code %d, reason "%s", wasClean %s',t.code,t.reason,t.wasClean),this.checkBufferedAmountTask.stop(),!t.wasClean){this.onRemoteReset();return}this.onTransportClosed()},{once:!0}),this.websocket.addEventListener("message",t=>{try{let n;if(typeof t.data=="string")n=T(t.data);else if(t.data instanceof ArrayBuffer)n=new Uint8Array(t.data,0,t.data.byteLength);else{this.abort(new Error("Incorrect binary type"));return}this.onData(n)}catch(n){this.log.error("error receiving data - %e",n)}})}sendData(e){for(let n of e)this.websocket.send(J(n));let t=this.websocket.bufferedAmount<this.maxBufferedAmount;return t||this.checkBufferedAmountTask.start(),{sentBytes:e.byteLength,canSendMore:t}}sendReset(){this.websocket.close(1006)}async sendClose(e){this.websocket.close(),e?.signal?.throwIfAborted()}sendPause(){}sendResume(){}checkBufferedAmount(){this.log("buffered amount now %d",this.websocket.bufferedAmount),this.websocket.bufferedAmount===0&&(this.checkBufferedAmountTask.stop(),this.safeDispatchEvent("drain"))}};function JC(r){return new j5(r)}var Y5=class{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[Yo]=!0;[Symbol.toStringTag]="@libp2p/websockets";[Se]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=JC({websocket:await this._connect(e,t),remoteAddr:e,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:websockets:connection"),maxBufferedAmount:this.init.maxBufferedAmount,bufferedAmountPollInterval:this.init.bufferedAmountPollInterval});this.log("new outbound connection %s",n.remoteAddr);let o=await t.upgrader.upgradeOutbound(n,t);return this.log("outbound connection %s upgraded",n.remoteAddr),o}async _connect(e,t){t?.signal?.throwIfAborted();let n=vs(e);this.log("create websocket connection to %s",n);let o=new WebSocket(n);o.binaryType="arraybuffer";try{t.onProgress?.(new R("websockets:open-connection")),await QC(o,"open",t)}catch(s){if(t.signal?.aborted)throw this.metrics?.dialerEvents.increment({abort:!0}),new la(`Could not connect to ${n}`);this.metrics?.dialerEvents.increment({error:!0});try{o.close()}catch{}throw s}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),o}createListener(e){return ZC({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e.filter(t=>mo.exactMatch(t)||gi.exactMatch(t))}dialFilter(e){return this.listenFilter(e)}};function ek(r={}){return e=>new Y5(e,r)}var tk={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dnsaddr/va1.bootstrap.libp2p.io/p2p/12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function rk(r){return{...r,addresses:{...r?.addresses,listen:["/p2p-circuit","/webrtc",...r?.addresses?.listen??[]]},transports:[pT(),XC(),YC(),ek(),...r?.transports??[]],connectionEncrypters:[gm(),...r?.connectionEncrypters??[]],streamMuxers:[ZA(),EC(),...r?.streamMuxers??[]],peerDiscovery:[nT(tk),...r?.peerDiscovery??[]],services:{autoNAT:rT(),dcutr:yT(),delegatedContentRouting:fx(Du()),delegatedPeerRouting:hx(Du()),dht:mC({clientMode:!0}),identify:OI(),identifyPush:BI(),keychain:qp(r?.keychain),ping:IC(),http:kI(),...r?.services}}}function nk(r,e){return kH(r,rk(e))}function kH(r,e){let t;Object.defineProperty(r,"libp2p",{configurable:!0,enumerable:!0,get(){if(t!=null)return t;throw new Pr}});let n={name:"libp2p",start:async o=>{if(t==null){e.privateKey==null&&(e.privateKey=await Q6(o.datastore,e.keychain)),e.nodeInfo??={},e.nodeInfo.name??=o.info.name,e.nodeInfo.version??=o.info.version,e.nodeInfo.userAgent??=`${o.info.name}/${o.info.version} ${tm()}`,e.datastore??=o.datastore,t=await LS(e);let s=o.routing.findProviders.bind(o.routing);o.routing.findProviders=async function*(c,l){yield*Sc(s.call(o.routing,c,l),async u=>{if(u.router!=="libp2p-router"){let d=X5(u);await t.peerStore.merge(d.id,d)}})};let i=o.routing.findPeer.bind(o.routing);o.routing.findPeer=async function(c,l){let u=await i(c,l);if(u.router!=="libp2p-router"){let d=X5(u);await t.peerStore.merge(d.id,d)}return u};let a=o.routing.getClosestPeers.bind(o.routing);o.routing.getClosestPeers=async function*(c,l){yield*Sc(a.call(o.routing,c,l),async u=>{if(u.router!=="libp2p-router"){let d=X5(u);await t.peerStore.merge(d.id,d)}})}}try{o.hasRouter("libp2p-router")||o.addRouter(NS(t)),RS(o.libp2p)&&await o.libp2p.start()}catch(s){if(s.name!=="NotStartedError")throw s}},stop:async()=>{await t?.stop()}};return r.addMixin(n),r}function X5(r){return{id:ft(r.id),multiaddrs:r.multiaddrs}}var J5={};he(J5,{code:()=>MH,decode:()=>FH,decodeOptions:()=>OH,encode:()=>UH,encodeOptions:()=>DH,name:()=>BH,toByteView:()=>sk});var ok=42;function sk(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function _H(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=V.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new N(w.tag,ok),new N(w.bytes,t)]}function PH(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function LH(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}function RH(r){for(let e of r.keys())if(typeof e!="string"||e.length===0)throw new Error("Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded");return null}var Q5={float64:!0,typeEncoders:{Map:RH,Object:_H,undefined:PH,number:LH}},DH={...Q5,typeEncoders:{...Q5.typeEncoders}};function NH(r){let e=r();if(e[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return V.decode(e.subarray(1))}var Z5={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{[ok]:NH}},OH={...Z5,tags:{...Z5.tags}},BH="dag-cbor",MH=113,UH=r=>vi(r,Q5),FH=r=>bn(sk(r),Z5);var o7={};he(o7,{code:()=>XH,decode:()=>ck,encode:()=>ak,format:()=>QH,name:()=>YH,parse:()=>JH,stringify:()=>QH});var e7=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(w.equals(t.type,w.array)&&(t.elements++,t.elements!==1&&e.push([44])),w.equals(t.type,w.map)&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[w.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s);e.push(o)}[w.negint.major](e,t){this[w.uint.major](e,t)}[w.bytes.major](e,t){throw new Error(`${Mn} unsupported type: Uint8Array`)}[w.string.major](e,t){this.prefix(e);let n=Ma(JSON.stringify(t.value));e.push(n.length>32?wi(n):n)}[w.array.major](e,t){this.prefix(e),this.inRecursive.push({type:w.array,elements:0}),e.push([91])}[w.map.major](e,t){this.prefix(e),this.inRecursive.push({type:w.map,elements:0}),e.push([123])}[w.tag.major](e,t){}[w.float.major](e,t){if(t.type.name==="break"){let i=this.inRecursive.pop();if(i){if(w.equals(i.type,w.array))e.push([93]);else if(w.equals(i.type,w.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(`${Mn} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),o=[],s=!1;for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i),!s&&(o[i]===46||o[i]===101||o[i]===69)&&(s=!0);s||(o.push(46),o.push(48)),e.push(o)}};function $H(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${Mn} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==w.string||n.type!==w.string)throw new Error(`${Mn} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${Mn} unexpected duplicate map keys, this is not supported`)}var KH={addBreakTokens:!0,mapSorter:$H};function t7(r,e){return e=Object.assign({},KH,e),Rh(r,new e7,e)}var rl=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos<e.length)throw new Error(`${W} 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(`${W} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,o=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new N(w.uint,0,this._pos-e);if(o([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${W} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${W} unexpected token at position ${this._pos}`);n=!0,this._pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,o([48,49,50,51,52,53,54,55,56,57]));let s=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),i=parseFloat(s);return n?new N(w.float,i,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(i)?new N(i>=0?w.uint:w.negint,i,this._pos-e):new N(i>=0?w.uint:w.negint,BigInt(s),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${W} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let s=this._pos,i=0;s<this.data.length&&i<65536;s++,i++){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 N(w.string,c,i)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${W} unexpected end of unicode escape sequence at position ${this._pos}`);let s=0;for(let i=0;i<4;i++){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(`${W} unexpected unicode escape character at position ${this._pos}`);s=s*16+a,this._pos++}return s},o=()=>{let s=this.ch(),i=null,a=s>239?4:s>223?3:s>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${W} unexpected unicode sequence at position ${this._pos}`);let c,l,u,d;switch(a){case 1:s<128&&(i=s);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(d=(s&31)<<6|c&63,d>127&&(i=d));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(d=(s&15)<<12|(c&63)<<6|l&63,d>2047&&(d<55296||d>57343)&&(i=d));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&&(d=(s&15)<<18|(c&63)<<12|(l&63)<<6|u&63,d>65535&&d<1114112&&(i=d))}i===null?(i=65533,a=1):i>65535&&(i-=65536,t.push(i>>>10&1023|55296),i=56320|i&1023),t.push(i),this._pos+=a};for(;!this.done();){let s=this.ch(),i;switch(s){case 92:if(this._pos++,this.done())throw new Error(`${W} unexpected string termination at position ${this._pos}`);switch(i=this.ch(),this._pos++,i){case 34:case 39:case 92:case 47:t.push(i);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(`${W} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new N(w.string,n9(t),this._pos-e);default:if(s<32)throw new Error(`${W} invalid control character at position ${this._pos}`);s<128?(t.push(s),this._pos++):o()}}throw new Error(`${W} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new N(w.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new N(w.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new N(w.null,null,4);case 102:return this.expect([102,97,108,115,101]),new N(w.false,!1,5);case 116:return this.expect([116,114,117,101]),new N(w.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(`${W} 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 N(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${W} 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 N(w.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 N(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${W} 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 N(w.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${W} 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(`${W} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function r7(r,e){return e=Object.assign({tokenizer:new rl(r,e)},e),bn(r,e)}function VH(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function qH(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=V.asCID(r);if(!e)return null;let t=e.toString();return[new N(w.map,1/0,1),new N(w.string,"/",1),new N(w.string,t,t.length),new N(w.break,void 0,1)]}function eg(r){let e=He.encode(r).slice(1);return[new N(w.map,1/0,1),new N(w.string,"/",1),new N(w.map,1/0,1),new N(w.string,"bytes",5),new N(w.string,e,e.length),new N(w.break,void 0,1),new N(w.break,void 0,1)]}function _n(r){return eg(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function zH(r){return eg(new Uint8Array(r))}function WH(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function GH(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var jH={typeEncoders:{Object:qH,Buffer:eg,Uint8Array:eg,Int8Array:_n,Uint16Array:_n,Int16Array:_n,Uint32Array:_n,Int32Array:_n,Float32Array:_n,Float64Array:_n,Uint8ClampedArray:_n,BigInt64Array:_n,BigUint64Array:_n,DataView:_n,ArrayBuffer:zH,undefined:WH,number:GH}},n7=class extends rl{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(w.equals(e.type,w.map)){let t=this._next();if(w.equals(t.type,w.string)&&t.value==="/"){let n=this._next();if(w.equals(n.type,w.string)){let o=this._next();if(!w.equals(o.type,w.break))throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new N(w.tag,42,0)}if(w.equals(n.type,w.map)){let o=this._next();if(w.equals(o.type,w.string)&&o.value==="bytes"){let s=this._next();if(w.equals(s.type,w.string)){for(let a=0;a<2;a++){let c=this._next();if(!w.equals(c.type,w.break))throw new Error("Invalid encoded Bytes form")}let i=He.decode(`m${s.value}`);return new N(w.bytes,i,s.value.length)}this.tokenBuffer.push(s)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},ik={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{42:r=>V.parse(r())}},YH="dag-json",XH=297,ak=r=>t7(r,jH),ck=r=>{let e=VH(r),t=Object.assign(ik,{tokenizer:new n7(e,ik)});return r7(e,t)},QH=r=>ZH.decode(ak(r));var ZH=new TextDecoder,JH=r=>ck(eV.encode(r)),eV=new TextEncoder;var hk=Ws($6(),1);var mr=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},df=class extends Error{static name="DecryptionFailedError";name="DecryptionFailedError"};async function uk(r,e,t){r=r.replaceAll("-----BEGIN ENCRYPTED PRIVATE KEY-----",""),r=r.replaceAll("-----END ENCRYPTED PRIVATE KEY-----",""),r=r.replaceAll("\r",""),r=r.replaceAll(`
103
103
  `,"");let n=He.decode(`m${r}`),o=un(n),s=o[0][1][0][1][0],i=lk(o[0][1][0][1][1]),a=lk(o[0][1][0][1][2]),c=o[0][1][0][1][4][1],l=o[0][1][0][1][4][2],u=await e.decrypt(s,c,l,{iterations:i,keyLength:a*8,hash:"SHA-512",algorithm:"AES-CBC",signal:t?.signal}),f=un(u)[2],h=ir.encode({Type:0,Data:f});return _l().privateKeyFromProtobuf(h)}function lk(r){if(r.length===0)return 0;let e=[...r].map(t=>t.toString(16).padStart(2,"0")).join("");return parseInt(e,16)}var tV="/pkcs8/",pk="/info/",rV=Symbol.for("@libp2p/service-capabilities"),ff={iterations:1e4,salt:T("you should override this value with a crypto secure random number"),hash:"SHA-512",algorithm:"AES-GCM"},nl={iterations:32767,saltLength:16,ivLength:12,hash:"SHA-256",keyLength:128,algorithm:"AES-GCM"},s7=20,tg={minKeyLength:112/8,minSaltLength:128/8,minIterations:1e3},dk={"SHA-256":128,"SHA-384":192,"SHA-512":256};function hf(r){return r==null||typeof r!="string"?!1:r===(0,hk.default)(r.trim())&&r.length>0}function ol(r){return new $e(tV+r)}function rg(r){return new $e(pk+r)}async function nV(r,e){let t=r.toProtobuf(),n=await ze.digest(t);return e?.signal?.throwIfAborted(),Ee.encode(n.bytes).substring(1)}function oV(r){if(typeof r=="string")return T(r);if(r instanceof Uint8Array)return J(r)}var ng=class{components;self;cipher;salt;keychainDekOptions;privateKeyDekOptions;constructor(e,t={}){if(this.components=e,this.self=t.selfKey??"self",this.salt=oV(t.salt)??ff.salt,this.keychainDekOptions={iterations:t.iterations??ff.iterations,hash:t.hash??ff.hash,keyLength:dk[t.hash??ff.hash],algorithm:ff.algorithm},this.privateKeyDekOptions={iterations:nl.iterations,hash:nl.hash,saltLength:nl.saltLength,ivLength:nl.ivLength,keyLength:nl.keyLength,algorithm:nl.algorithm},t.password!=null&&t.password.length<s7)throw new Error("password must be least 20 characters");if(this.salt.byteLength!=null&&this.salt.byteLength<tg.minSaltLength)throw new Error(`salt must be least ${tg.minSaltLength} bytes`);if(t.iterations!=null&&t.iterations<tg.minIterations)throw new Error(`iterations must be least ${tg.minIterations}`);if(dk[this.keychainDekOptions.hash]==null)throw new mr("Unsupported hash");this.cipher=fk(t.password??"",this.salt,this.keychainDekOptions,this.privateKeyDekOptions)}[rV]=["@ipshipyard/keychain"];async generateKey(e,t){let o=await(await this.components.getCrypto(t?.type??"Ed25519",t)).generatePrivateKey(t);return this.importKey(e,o,t)}async importKey(e,t,n){if(!hf(e))throw new mr(`Invalid key name '${e}'`);if(t==null)throw new mr("Key is required");if(await this.components.datastore.has(ol(e),n))throw new mr(`Key '${e}' already exists`);let s=this.components.datastore.batch();return await this._importKey(e,t,this.cipher,s,n),await s.commit(n),t}async _importKey(e,t,n,o,s){let i=t.toProtobuf(),a=await n.encrypt(i),c=Ve([a.salt,a.iv,a.cipherText],a.salt.byteLength+a.iv.byteLength+a.cipherText.byteLength),l=He.encode(c),u={name:e,id:await nV(t,s)};o.put(ol(e),T(l)),o.put(rg(e),T(JSON.stringify(u)))}async exportKey(e,t){if(!hf(e))throw new mr(`Invalid key name '${e}'`);return this._exportKey(e,this.cipher,t)}async _exportKey(e,t,n){let o=await this.components.datastore.get(ol(e),n),s=O(o),i;if(s.includes("BEGIN ENCRYPTED PRIVATE KEY"))return uk(s,t,n);try{let a=He.decode(s),c=a.subarray(0,16),l=a.subarray(16,28),u=a.subarray(28),d=await t.decrypt(c,l,u,n),f=ir.decode(d);if(f.Type==null)throw new df("Unknown key type");return i=await this.components.getCrypto(f.Type,n),await i.privateKeyFromProtobuf(d)}catch(a){throw a.name==="OperationError"?new df(a.message):a}}async removeKey(e,t){if(!hf(e)||e===this.self)throw new mr(`Invalid key name '${e}'`);let n=this.components.datastore.batch();n.delete(ol(e)),n.delete(rg(e)),await n.commit(t)}async*listKeys(e){let t={prefix:pk};for await(let n of this.components.datastore.query(t,e))yield JSON.parse(O(n.value))}async renameKey(e,t,n){if(!hf(e)||e===this.self)throw new mr(`Invalid old key name '${e}'`);if(!hf(t)||t===this.self)throw new mr(`Invalid new key name '${t}'`);let o=ol(e),s=ol(t),i=rg(e),a=rg(t);if(await this.components.datastore.has(s,n))throw new mr(`Key '${t}' already exists`);let l=await this.components.datastore.get(o,n),u=await this.components.datastore.get(i,n),d=JSON.parse(O(u));d.name=t;let f=this.components.datastore.batch();f.put(s,l),f.put(a,T(JSON.stringify(d))),f.delete(o),f.delete(i),await f.commit(n)}async rotateKeychainPass(e,t){if(typeof e!="string")throw new mr(`Invalid new pass type '${typeof e}'`);if(e.length<s7)throw new mr(`Invalid pass length ${e.length}, must be at least ${s7}`);let n=this.cipher,o=this.cipher=fk(e,this.salt,this.keychainDekOptions,this.privateKeyDekOptions),s=this.components.datastore.batch();for await(let i of this.listKeys(t)){let a=await this._exportKey(i.name,n);await this._importKey(i.name,a,o,s,t)}await s.commit(t)}async loadPublicKeyFromProtobuf(e,t){let n=wr.decode(e);if(n.Type==null)throw new mr("Protobuf was missing Type");return(await this.components.getCrypto(n.Type,t)).publicKeyFromProtobuf(e,t)}},sV={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function fk(r,e,t,n){let o;async function s(l,u,d,f){let h,p=T(l),g=await crypto.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);try{h=await crypto.subtle.deriveKey({name:"PBKDF2",salt:J(u),iterations:f.iterations,hash:{name:f.hash}},g,{name:f.algorithm??"AES-GCM",length:f.keyLength},!0,d)}catch(y){if(l==="")h=await crypto.subtle.importKey("jwk",sV,{name:f.algorithm??"AES-GCM"},!0,d);else throw y}return h}async function i(){if(r==="")return r;let l=await s(r,e,["encrypt","decrypt"],t);return(await crypto.subtle.exportKey("jwk",l)).k??""}async function a(l,u){o==null&&(o=await i());let d=crypto.getRandomValues(new Uint8Array(n.saltLength)),f=crypto.getRandomValues(new Uint8Array(n.ivLength)),h=await s(o,d,["encrypt"],n),p=await crypto.subtle.encrypt({name:"AES-GCM",iv:f},h,l);return u?.signal?.throwIfAborted(),{salt:d,iv:f,cipherText:new Uint8Array(p)}}async function c(l,u,d,f){o==null&&(o=await i());let h=await s(o,l,["decrypt"],{iterations:f?.iterations??n.iterations,keyLength:f?.keyLength??n.keyLength,hash:f?.hash??n.hash,algorithm:f?.algorithm??"AES-GCM"}),p=await crypto.subtle.decrypt({name:f?.algorithm??"AES-GCM",iv:J(u)},h,J(d));return f?.signal?.throwIfAborted(),new Uint8Array(p)}return{encrypt:a,decrypt:c}}function mk(r){return e=>new ng(e,r)}Qe.formatters.z=r=>r==null?"undefined":Ee.baseEncode(r);Qe.formatters.b=r=>r==null?"undefined":mt.baseEncode(r);Qe.formatters.k=r=>r==null?"undefined":nr.baseEncode(r);Qe.formatters.m=r=>r==null?"undefined":He.baseEncode(r);Qe.formatters.e=r=>r==null?"undefined":wk(r);function gk(r,e=""){let t=yk(r.message),n=yk(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
104
104
  `).join(`
105
105
  ${e}`)}`:`${t}
@@ -110,7 +110,7 @@ ${e}`)}`:n!=null?`${n.split(`
110
110
  ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function iV(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function wk(r,e=""){if(iV(r)){let t=gk(r,e);return r.errors.length>0?(e=`${e} `,t+=`
111
111
  ${e}${r.errors.map(n=>`${wk(n,`${e}`)}`).join(`
112
112
  ${e}`)}`):t+=`
113
- ${e}[Error list was empty]`,t.trim()}return gk(r,e)}function aV(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function bk(r){return{forComponent(e){return Ek(e,r)}}}function Ek(r,e){let t=aV(`${r}:trace`);return Qe.enabled(`${r}:trace`)&&Qe.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=Qe(`${r}:trace`,e)),Object.assign(Qe(r,e),{error:Qe(`${r}:error`,e),trace:t,newScope:n=>Ek(`${r}:${n}`,e)})}function yk(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var zo=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,bytes:o}of e)await this.put(n,o,t),yield n}get(e,t){throw new Error(".get is not implemented")}async*getMany(e,t){for await(let n of e)yield{cid:n,bytes:this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};function cV(r){return typeof r?.then=="function"}var pf=class extends zo{data;constructor(){super(),this.data=new Map}put(e,t,n){n?.signal?.throwIfAborted();let o;if(t instanceof Uint8Array)o=[t];else{let s=Oo(t);if(cV(s))return s.then(i=>this._put(e,i,n));o=s}return this._put(e,o,n)}_put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(mt.encode(e.multihash.bytes),t),e}*get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(mt.encode(e.multihash.bytes));if(n==null)throw new vr;yield*n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(mt.encode(e.multihash.bytes))}async delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(mt.encode(e.multihash.bytes))}*getAll(e){e?.signal?.throwIfAborted();for(let[t,n]of this.data.entries())yield{cid:V.createV1(lo,Ae(mt.decode(t))),bytes:(async function*(){yield*n})()},e?.signal?.throwIfAborted()}};var Nve=Ga("blockstore:core:tiered");var xk="SHARDING";var tSe=new $e(xk);var mSe=Ga("datastore:core:tiered");var og=class{lock;child;pins;routing;started;constructor(e,t,n,o={}){this.child=e,this.pins=t,this.routing=n,this.lock=Zu({singleProcess:o.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await dt(this.child),this.started=!0}async stop(){await Ct(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{o()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async*get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new tu("Block was pinned - please unpin and try again");await this.routing.cancelReprovide(e,t),await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let o=this;yield*this.child.deleteMany((async function*(){for await(let s of e){if(await o.pins.isPinned(s))throw new tu("Block was pinned - please unpin and try again");await o.routing.cancelReprovide(s,t),yield s}})(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var i7=new $e("/version"),Sk=1;async function Ak(r){if(!await r.has(i7)){await r.put(i7,T(`${Sk}`));return}let e=await r.get(i7),t=O(e);if(parseInt(t,10)!==Sk)throw new qh("Invalid datastore version, a datastore migration may be required")}var f7={};he(f7,{code:()=>d7,createLink:()=>Nk,createNode:()=>Dk,decode:()=>vV,encode:()=>xV,name:()=>EV,prepare:()=>l7,validate:()=>u7});var uV=new TextDecoder;function a7(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let o=r[e++];if(t+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[t,e]}function sg(r,e){let t;[t,e]=a7(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 Tk(r,e){let t;return[t,e]=a7(r,e),[t&7,t>>3,e]}function dV(r){let e={},t=r.length,n=0;for(;n<t;){let o,s;if([o,s,n]=Tk(r,n),s===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=sg(r,n)}else if(s===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let i;[i,n]=sg(r,n),e.Name=uV.decode(i)}else if(s===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=a7(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 Ik(r){let e=r.length,t=0,n,o=!1,s;for(;t<e;){let a,c;if([a,c,t]=Tk(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]=sg(r,t),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=sg(r,t),n.push(dV(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 i={};return s&&(i.Data=s),i.Links=n||[],i}var kk=new TextEncoder,Ck=2**32,fV=2**31;function hV(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=mf(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=kk.encode(r.Name);t-=n.length,e.set(n,t),t=mf(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=mf(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function _k(r){let e=mV(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=mf(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let s=hV(r.Links[o],t.subarray(0,n));n-=s,n=mf(t,n,s)-1,t[n]=18}return t}function pV(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+sl(t)}if(typeof r.Name=="string"){let t=kk.encode(r.Name).length;e+=1+t+sl(t)}return typeof r.Tsize=="number"&&(e+=1+sl(r.Tsize)),e}function mV(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+sl(t)}if(r.Links)for(let t of r.Links){let n=pV(t);e+=1+n+sl(n)}return e}function mf(r,e,t){e-=sl(t);let n=e;for(;t>=fV;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function sl(r){return r%2===0&&r++,Math.floor((gV(r)+6)/7)}function gV(r){let e=0;return r>=Ck&&(r=Math.floor(r/Ck),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+yV[r]}var yV=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var wV=["Data","Links"],bV=["Hash","Name","Tsize"],c7=new TextEncoder;function Lk(r,e){if(r===e)return 0;let t=r.Name?c7.encode(r.Name):[],n=e.Name?c7.encode(e.Name):[],o=t.length,s=n.length;for(let i=0,a=Math.min(o,s);i<a;++i)if(t[i]!==n[i]){o=t[i],s=n[i];break}return o<s?-1:s<o?1:0}function Pk(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function Rk(r){if(typeof r.asCID=="object"){let t=V.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=V.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=V.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=V.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function l7(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=c7.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(Rk),e.Links.sort(Lk);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function u7(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!Pk(r,wV))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<r.Links.length;e++){let t=r.Links[e];if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!Pk(t,bV))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(t.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(t.Hash==null||!t.Hash["/"]||t.Hash["/"]!==t.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(t.Name!==void 0&&typeof t.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(t.Tsize!==void 0){if(typeof t.Tsize!="number"||t.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(t.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&Lk(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function Dk(r,e=[]){return l7({Data:r,Links:e})}function Nk(r,e,t){return Rk({Hash:t,Name:r,Tsize:e})}function Ok(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var EV="dag-pb",d7=112;function xV(r){u7(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),_k(e)}function vV(r){let e=Ok(r),t=Ik(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let s={};try{s.Hash=V.decode(o.Hash)}catch{}if(!s.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(s.Name=o.Name),o.Tsize!==void 0&&(s.Tsize=o.Tsize),s})),n}function Bk(r=[],e){let t={[d7]:f7,[lo]:ni};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);us(s)?o=await s:o=s,t[o.code]=o}if(o!=null)return o;throw new Rl(`Could not load codec for ${n}`)}}function Mk(r=[],e){let t={};return r=[r3(),o3(),_l(),...r],r.forEach(n=>{t[n.type]=n,t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);us(s)?o=await s:o=s,t[o.type]=o,t[o.code]=o}if(o!=null)return o;throw new Dl(`Could not load crypto for ${o}`)}}function Uk(r=[],e){let t={[ze.code]:ze,[tt.code]:tt};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);us(s)?o=await s:o=s,t[o.code]=o}if(o!=null)return o;throw new Ll(`No hasher configured for multihash code 0x${n.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`)}}var ig=0,il=class extends Error{static name="IdentityHashDigestTooLongError";name="IdentityHashDigestTooLongError"},ag=class extends zo{child;maxDigestLength;constructor(e,t){super(),this.child=e,this.maxDigestLength=t?.maxDigestLength}put(e,t,n){if(e.multihash.code===ig){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new il(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);return n?.signal?.throwIfAborted(),e}return this.child==null?(n?.signal?.throwIfAborted(),e):this.child.put(e,t,n)}async*get(e,t){if(e.multihash.code===ig){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new il(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);t?.signal?.throwIfAborted(),yield e.multihash.digest;return}if(this.child==null)throw t?.signal?.throwIfAborted(),new vr;yield*this.child.get(e,t)}has(e,t){if(e.multihash.code===ig){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new il(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);return t?.signal?.throwIfAborted(),!0}return this.child==null?(t?.signal?.throwIfAborted(),!1):this.child.has(e,t)}delete(e,t){if(e.code===ig){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new il(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);t?.signal?.throwIfAborted();return}if(this.child!=null)return this.child.delete(e,t)}async*getAll(e){this.child!=null&&(yield*this.child.getAll(e)),e?.signal?.throwIfAborted()}};var SV=128,al=class{child;getHasher;log;logger;blockBrokers;constructor(e,t={}){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.blockBrokers=e.blockBrokers,this.child=new ag(e.blockstore,{maxDigestLength:t.maxIdentityHashDigestLength??SV}),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new R("blocks:put:duplicate",e)),e):(n.onProgress?.(new R("blocks:put:providers:notify",e)),await Promise.all(this.blockBrokers.map(async o=>o.announce?.(e,n))),n.onProgress?.(new R("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=Ur(e,async({cid:s})=>{let i=await this.child.has(s,t);return i&&t.onProgress?.(new R("blocks:put-many:duplicate",s)),!i}),o=Sc(n,async({cid:s})=>{t.onProgress?.(new R("blocks:put-many:providers:notify",s)),await Promise.all(this.blockBrokers.map(async i=>i.announce?.(s,t)))});t.onProgress?.(new R("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async*get(e,t={}){let n=await this.child.has(e,t),o=t.offline===!0;if(!n){if(o)throw new ru("The block was present in the blockstore and the node is running offline so cannot fetch it");let s=await this.getHasher(e.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new R("blocks:get:providers:get",e));let i=await Fk(e,this.blockBrokers,s,{...t,log:this.log});t.onProgress?.(new R("blocks:get:blockstore:put",e)),await this.child.put(e,i,t),t.onProgress?.(new R("blocks:get:providers:notify",e)),await Promise.all(this.blockBrokers.map(async a=>a.announce?.(e,t))),yield i;return}t.onProgress?.(new R("blocks:get:blockstore:get",e)),yield*this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new R("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(Sc(e,async n=>{let o=await this.child.has(n,t),s=t.offline===!0;if(!o){if(s)throw new ru("The block was present in the blockstore and the node is running offline so cannot fetch it");let i=await this.getHasher(n.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new R("blocks:get-many:providers:get",n));let a=await Fk(n,this.blockBrokers,i,{...t,log:this.log});t.onProgress?.(new R("blocks:get-many:blockstore:put",n)),await this.child.put(n,a,t),t.onProgress?.(new R("blocks:get-many:providers:notify",n)),await Promise.all(this.blockBrokers.map(async c=>c.announce?.(n,t)))}}))}async delete(e,t={}){t.onProgress?.(new R("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new R("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 R("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}};async function Fk(r,e,t,n){let o=TV(r,t),s=new AbortController,i=ue([s.signal,n.signal]);s.signal;let a=[];for(let c of e)AV(c)&&a.push(c);if(a.length===0)throw new bo(`No block brokers capable of retrieving blocks are configured, the CID ${r} cannot be fetched from the network`);try{return await Promise.any(a.map(async c=>{try{let l=!1,u=await c.retrieve(r,{...n,signal:i,validateFn:async d=>{await o(d),n.signal?.throwIfAborted(),l=!0}});return l||(await o(u),n.signal?.throwIfAborted()),u}catch(l){throw n.log.error("could not retrieve verified block for %c from %s - %e",r,c.name,l),l}}))}catch(c){throw new Wh(c.errors,`Failed to load block for ${r}`)}finally{s.abort(),i.clear()}}function AV(r){return typeof r.retrieve=="function"}var TV=(r,e)=>{if(e==null)throw new v(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`);return async t=>{let n,o=e.digest(t,{truncate:r.multihash.digest.byteLength});if(us(o)?n=await o:n=o,!ee(n.digest,r.multihash.digest))throw new fa("Hash of downloaded block did not match multihash from passed CID")}};var cg=class extends al{closeController;constructor(e,t){super(e),this.closeController=new AbortController,this.closeController.signal,this.log=e.logger.forComponent(`helia:session-storage:${t.root}`)}close(){this.closeController.abort()}async addPeer(e,t){await Promise.all(this.blockBrokers.map(n=>n.addPeer(e,t)))}async put(e,t,n={}){let o=ue([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=ue([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async*get(e,t={}){let n=ue([this.closeController.signal,t.signal]);try{yield*super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=ue([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=ue([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=ue([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=ue([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=ue([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};var lg=class extends al{started;constructor(e,t={}){super(e,t),this.started=!1}isStarted(){return this.started}async start(){await dt(this.child,...this.blockBrokers),this.started=!0}async stop(){await Ct(this.child,...this.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){if(this.blockBrokers.length===0)throw new bo("No block brokers configured");let n=this.blockBrokers.map(o=>o.createSession?.(t)).filter(o=>o!=null);if(n.length===0)throw new bo(`No configured block brokers support sessions - tried ${this.blockBrokers.map(o=>o.name).join(", ")}`);return new cg({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}};var Kk="/pin/",$k="/pinned-block/",h7=nr;function ug(r){return r.version===0&&(r=r.toV1()),new $e(`${Kk}${r.toString(h7)}`)}var dg=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=ug(e);if(await this.datastore.has(n))throw new Vh("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new v("Depth must be greater than or equal to 0");let s=(t.walker??S4())({blockstore:this.blockstore,getCodec:this.getCodec});for await(let a of s.walk(e,{...t,depth:o})){let c=a.block.cid;await this.#e(c,l=>l.pinnedBy.find(u=>ee(u,e.bytes))!=null?!1:(l.pinCount++,l.pinnedBy.push(e.bytes),!0),t),yield c}let i={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,vi(i),t)}async#e(e,t,n){let o=new $e(`${$k}${h7.encode(e.multihash.bytes)}`),s={pinCount:0,pinnedBy:[]};try{s=bn(await this.datastore.get(o,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(s)){if(s.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,vi(s),n),n.onProgress?.(new R("helia:pin:add",e))}}async*rm(e,t={}){let n=ug(e),o=await this.datastore.get(n,t),s=bn(o);await this.datastore.delete(n,t);let i=(t.walker??S4())({blockstore:this.blockstore,getCodec:this.getCodec});for await(let a of i.walk(e,{...t,depth:s.depth})){let c=a.block.cid;await this.#e(c,l=>(l.pinCount--,l.pinnedBy=l.pinnedBy.filter(u=>ee(u,e.bytes)),!0),{...t,depth:s.depth}),yield c}}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:Kk+(e.cid!=null?`${e.cid.toString(nr)}`:"")},e)){let o=V.parse(t.toString().substring(5),nr),s=bn(n);yield{cid:o,...s}}}async isPinned(e,t={}){let n=new $e(`${$k}${h7.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=ug(e),o=await this.datastore.get(n,t);return bn(o)}async setMetadata(e,t,n){let o=ug(e),s=await this.datastore.get(o,n),i=bn(s);i.metadata=t??{},await this.datastore.put(o,vi(i),n)}};var IV=5,fg=class{name;log;routers;providerLookupConcurrency;constructor(e,t){this.name="helia",this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??IV,this.findProviders=e.metrics?.traceFunction("helia.routing.findProviders",this.findProviders.bind(this),{optionsIndex:1})??this.findProviders,this.provide=e.metrics?.traceFunction("helia.routing.provide",this.provide.bind(this),{optionsIndex:1})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("helia.routing.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1})??this.cancelReprovide,this.put=e.metrics?.traceFunction("helia.routing.put",this.put.bind(this),{optionsIndex:2})??this.put,this.get=e.metrics?.traceFunction("helia.routing.get",this.get.bind(this),{optionsIndex:1})??this.get,this.findPeer=e.metrics?.traceFunction("helia.routing.findPeer",this.findPeer.bind(this),{optionsIndex:1})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("helia.routing.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1})??this.getClosestPeers}async start(){await dt(...this.routers)}async stop(){await Ct(...this.routers)}hasRouter(e){return this.routers.findIndex(t=>t.name===e)!==-1}addRouter(e){this.routers.push(e)}async*findProviders(e,t={}){if(this.routers.length===0)throw new Zo("No content routers available");let n=0,o=[],s=this;async function*i(u){let d=0,f=u.map(async function*(p){let g=0;t?.onProgress?.(new R("helia:routing:find-providers:start",{router:p.name,cid:e}));try{for await(let y of p.findProviders(e,t))g++,t?.onProgress?.(new R("helia:routing:find-providers:provider",{router:p.name,cid:e,provider:y})),yield y}catch(y){o.push(y)}finally{s.log("router %s found %d providers for %c",p.name,g,e),t?.onProgress?.(new R("helia:routing:find-providers:end",{router:p.name,cid:e,found:g})),d++,d===u.length&&h.size===0&&h.emitIdle()}}),h=new ct({concurrency:s.providerLookupConcurrency});for await(let p of cr(h.toGenerator(),...f))if(p!=null){if(p.multiaddrs.length===0){if(h.queue.find(g=>g.options.peer.equals(p.id))!=null)continue;h.add(async()=>{try{let g=await s.findPeer(p.id,t);return g.multiaddrs.length===0?null:{...g,protocols:p.protocols,router:p.router,fallback:p.fallback}}catch(g){return s.log.error("could not load multiaddrs for peer %p - %e",p.id,g),null}},{peer:p.id,signal:t.signal}).catch(g=>{s.log.error("could not load multiaddrs for peer %p - %e",p.id,g)});continue}n++,yield p}}let a=aa(this.routers,"findProviders"),c=a.filter(u=>u.capabilities==null||!u.capabilities().includes("fallback")),l=a.filter(u=>u.capabilities?.().includes("fallback")===!0);this.log("findProviders for %c start using routers %s",e,c.map(u=>u.name).join(", ")),yield*i(c),l.length>0&&(this.log("findProviders for %c using fallback routers %s",e,l.map(u=>u.name).join(", ")),yield*i(l)),this.log("findProviders finished, found %d providers for %c",n,e)}async provide(e,t={}){if(this.routers.length===0)throw new Zo("No content routers available");await Promise.all(aa(this.routers,"provide").map(async n=>{t?.onProgress?.(new R("helia:routing:provide:start",{router:n.name,cid:e})),await n.provide(e,t),t?.onProgress?.(new R("helia:routing:provide:end",{router:n.name,cid:e}))}))}async cancelReprovide(e,t={}){await Promise.all(aa(this.routers,"cancelReprovide").map(async n=>{t?.onProgress?.(new R("helia:routing:cancel-reprovide:start",{router:n.name,cid:e})),await n.cancelReprovide(e,t),t?.onProgress?.(new R("helia:routing:cancel-reprovide:end",{router:n.name,cid:e}))}))}async put(e,t,n){await Promise.all(aa(this.routers,"put").map(async o=>{n?.onProgress?.(new R("helia:routing:put:start",{router:o.name,key:e,value:t})),await o.put(e,t,n),n?.onProgress?.(new R("helia:routing:put:end",{router:o.name,key:e,value:t}))}))}async get(e,t){let n=[],o,s=new AbortController,i=ue([s.signal,t?.signal]);try{o=await Promise.any(aa(this.routers,"get").map(async a=>{t?.onProgress?.(new R("helia:routing:get:start",{router:a.name,key:e}));try{return await a.get(e,{...t,signal:i})}catch(c){throw this.log("router %s failed with %e",a.name,c),n.push(c),c}finally{t?.onProgress?.(new R("helia:routing:get:end",{router:a.name,key:e}))}}))}catch{}finally{s.abort(),i.clear()}if(o==null)throw new zh(n,`Failed to get value key ${O(e,"base58btc")}`);return o}async findPeer(e,t){if(this.routers.length===0)throw new Zo("No peer routers available");let n=new AbortController,o=ue([n.signal,t?.signal]);let s=this,i=cr(...aa(this.routers,"findPeer").map(a=>(async function*(){t?.onProgress?.(new R("helia:routing:find-peer:start",{router:a.name,peerId:e}));try{yield await a.findPeer(e,{...t,signal:o})}catch(c){s.log.error(c)}finally{t?.onProgress?.(new R("helia:routing:find-peer:end",{router:a.name,peerId:e}))}})()));try{for await(let a of i)if(a!=null)return a}finally{n.abort(),o.clear()}throw new Pe("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Zo("No peer routers available");for await(let n of cr(...aa(this.routers,"getClosestPeers").map(async function*(o){t?.onProgress?.(new R("helia:routing:get-closest-peers:start",{router:o.name,key:e}));try{yield*o.getClosestPeers(e,t)}finally{t?.onProgress?.(new R("helia:routing:get-closest-peers:end",{router:o.name,key:e}))}})))n!=null&&(yield n)}};function aa(r,e){return r.filter(t=>t[e]!=null)}var hg=class{info;blockstore;datastore;events;pins;logger;routing;getCodec;getHasher;getCrypto;dns;keychain;metrics;status;log;blockBrokers;mixins;components;constructor(e){this.info={name:e.name,version:e.version},this.logger=e.logger??bk(),this.log=this.logger.forComponent("helia"),this.getHasher=Uk(e.hashers,e.loadHasher),this.getCodec=Bk(e.codecs,e.loadCodec),this.getCrypto=Mk(e.cryptos,e.loadCrypto),this.dns=e.dns??F0(),this.metrics=e.metrics,this.events=new fe,this.status="stopped",this.mixins=[],this.components={blockstore:e.blockstore??new pf,datastore:e.datastore??new Yi,logger:this.logger,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,getCrypto:this.getCrypto,dns:this.dns,metrics:this.metrics,...e.components??{}},this.keychain=this.components.keychain=mk()(this.components),this.routing=this.components.routing=new fg(this.components,{routers:(e.routers??[]).flatMap(n=>(typeof n=="function"&&(n=n(this.components)),[n])),providerLookupConcurrency:e.providerLookupConcurrency}),this.blockBrokers=this.components.blockBrokers=(e.blockBrokers??[]).map(n=>(typeof n=="function"&&(n=n(this.components)),n));let t=new lg(this.components,e);this.pins=new dg(this.components.datastore,t,this.getCodec),this.blockstore=new og(t,this.pins,this.routing,{holdGcLock:e.holdGcLock??!0}),this.datastore=this.components.datastore}hasRouter(e){return this.routing.hasRouter(e)}addRouter(e){typeof e=="function"&&(e=e(this.components)),this.routing.addRouter(e)}hasBlockBroker(e){return this.blockBrokers.findIndex(t=>t.name===e)!==-1}addBlockBroker(e){typeof e=="function"&&(e=e(this.components)),this.blockBrokers.push(e)}addMixin(e){if(this.mixins.find(t=>t.name===e.name)!=null)throw new bo(`A mixin with the name "${e.name} is already present`);this.mixins.push(e)}async start(){this.status="starting",await Ak(this.datastore),await dt(this.blockstore,this.datastore,this.routing,...this.blockBrokers);for(let e of this.mixins)await e.start?.(this);return this.status="started",this.events.dispatchEvent(new CustomEvent("start",{detail:this})),this}async stop(){this.status="stopping";for(let e of this.mixins)await e.stop?.(this);return await Ct(this.blockstore,this.datastore,this.routing,...this.blockBrokers),this.status="stopped",this.events.dispatchEvent(new CustomEvent("stop",{detail:this})),this}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,o=this.blockstore.unwrap();this.log("gc start"),await xr(o.deleteMany((async function*(){for await(let{cid:s}of o.getAll())try{if(await n.pins.isPinned(s,e))continue;yield s,e.onProgress?.(new R("helia:gc:deleted",s))}catch(i){n.log.error("error during gc - %e",i),e.onProgress?.(new R("helia:gc:error",i))}})()))}finally{t()}this.log("gc finished")}};var Hk="7.1.6",Vk="helia";function CV(r={}){return ux(nk(Rx(qk({...r,codecs:[J5,o7,Lf,...r.codecs??[]],hashers:[zg,...r.hashers??[]]}))))}function qk(r={}){return new hg({name:Vk,version:Hk,...r})}return Jk(kV);})();
113
+ ${e}[Error list was empty]`,t.trim()}return gk(r,e)}function aV(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function bk(r){return{forComponent(e){return Ek(e,r)}}}function Ek(r,e){let t=aV(`${r}:trace`);return Qe.enabled(`${r}:trace`)&&Qe.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=Qe(`${r}:trace`,e)),Object.assign(Qe(r,e),{error:Qe(`${r}:error`,e),trace:t,newScope:n=>Ek(`${r}:${n}`,e)})}function yk(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var zo=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,bytes:o}of e)await this.put(n,o,t),yield n}get(e,t){throw new Error(".get is not implemented")}async*getMany(e,t){for await(let n of e)yield{cid:n,bytes:this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};function cV(r){return typeof r?.then=="function"}var pf=class extends zo{data;constructor(){super(),this.data=new Map}put(e,t,n){n?.signal?.throwIfAborted();let o;if(t instanceof Uint8Array)o=[t];else{let s=Oo(t);if(cV(s))return s.then(i=>this._put(e,i,n));o=s}return this._put(e,o,n)}_put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(mt.encode(e.multihash.bytes),t),e}*get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(mt.encode(e.multihash.bytes));if(n==null)throw new vr;yield*n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(mt.encode(e.multihash.bytes))}async delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(mt.encode(e.multihash.bytes))}*getAll(e){e?.signal?.throwIfAborted();for(let[t,n]of this.data.entries())yield{cid:V.createV1(lo,Ae(mt.decode(t))),bytes:(async function*(){yield*n})()},e?.signal?.throwIfAborted()}};var Nve=Ga("blockstore:core:tiered");var xk="SHARDING";var tSe=new $e(xk);var mSe=Ga("datastore:core:tiered");var og=class{lock;child;pins;routing;started;constructor(e,t,n,o={}){this.child=e,this.pins=t,this.routing=n,this.lock=Zu({singleProcess:o.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await dt(this.child),this.started=!0}async stop(){await Ct(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{o()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async*get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new tu("Block was pinned - please unpin and try again");await this.routing.cancelReprovide(e,t),await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let o=this;yield*this.child.deleteMany((async function*(){for await(let s of e){if(await o.pins.isPinned(s))throw new tu("Block was pinned - please unpin and try again");await o.routing.cancelReprovide(s,t),yield s}})(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var i7=new $e("/version"),Sk=1;async function Ak(r){if(!await r.has(i7)){await r.put(i7,T(`${Sk}`));return}let e=await r.get(i7),t=O(e);if(parseInt(t,10)!==Sk)throw new qh("Invalid datastore version, a datastore migration may be required")}var f7={};he(f7,{code:()=>d7,createLink:()=>Nk,createNode:()=>Dk,decode:()=>vV,encode:()=>xV,name:()=>EV,prepare:()=>l7,validate:()=>u7});var uV=new TextDecoder;function a7(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let o=r[e++];if(t+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[t,e]}function sg(r,e){let t;[t,e]=a7(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 Tk(r,e){let t;return[t,e]=a7(r,e),[t&7,t>>3,e]}function dV(r){let e={},t=r.length,n=0;for(;n<t;){let o,s;if([o,s,n]=Tk(r,n),s===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=sg(r,n)}else if(s===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let i;[i,n]=sg(r,n),e.Name=uV.decode(i)}else if(s===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=a7(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 Ik(r){let e=r.length,t=0,n,o=!1,s;for(;t<e;){let a,c;if([a,c,t]=Tk(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]=sg(r,t),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=sg(r,t),n.push(dV(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 i={};return s&&(i.Data=s),i.Links=n||[],i}var kk=new TextEncoder,Ck=2**32,fV=2**31;function hV(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=mf(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=kk.encode(r.Name);t-=n.length,e.set(n,t),t=mf(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=mf(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function _k(r){let e=mV(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=mf(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let s=hV(r.Links[o],t.subarray(0,n));n-=s,n=mf(t,n,s)-1,t[n]=18}return t}function pV(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+sl(t)}if(typeof r.Name=="string"){let t=kk.encode(r.Name).length;e+=1+t+sl(t)}return typeof r.Tsize=="number"&&(e+=1+sl(r.Tsize)),e}function mV(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+sl(t)}if(r.Links)for(let t of r.Links){let n=pV(t);e+=1+n+sl(n)}return e}function mf(r,e,t){e-=sl(t);let n=e;for(;t>=fV;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function sl(r){return r%2===0&&r++,Math.floor((gV(r)+6)/7)}function gV(r){let e=0;return r>=Ck&&(r=Math.floor(r/Ck),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+yV[r]}var yV=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var wV=["Data","Links"],bV=["Hash","Name","Tsize"],c7=new TextEncoder;function Lk(r,e){if(r===e)return 0;let t=r.Name?c7.encode(r.Name):[],n=e.Name?c7.encode(e.Name):[],o=t.length,s=n.length;for(let i=0,a=Math.min(o,s);i<a;++i)if(t[i]!==n[i]){o=t[i],s=n[i];break}return o<s?-1:s<o?1:0}function Pk(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function Rk(r){if(typeof r.asCID=="object"){let t=V.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=V.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=V.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=V.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function l7(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=c7.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(Rk),e.Links.sort(Lk);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function u7(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!Pk(r,wV))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<r.Links.length;e++){let t=r.Links[e];if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!Pk(t,bV))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(t.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(t.Hash==null||!t.Hash["/"]||t.Hash["/"]!==t.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(t.Name!==void 0&&typeof t.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(t.Tsize!==void 0){if(typeof t.Tsize!="number"||t.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(t.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&Lk(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function Dk(r,e=[]){return l7({Data:r,Links:e})}function Nk(r,e,t){return Rk({Hash:t,Name:r,Tsize:e})}function Ok(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var EV="dag-pb",d7=112;function xV(r){u7(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),_k(e)}function vV(r){let e=Ok(r),t=Ik(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let s={};try{s.Hash=V.decode(o.Hash)}catch{}if(!s.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(s.Name=o.Name),o.Tsize!==void 0&&(s.Tsize=o.Tsize),s})),n}function Bk(r=[],e){let t={[d7]:f7,[lo]:ni};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);us(s)?o=await s:o=s,t[o.code]=o}if(o!=null)return o;throw new Rl(`Could not load codec for ${n}`)}}function Mk(r=[],e){let t={};return r=[r3(),o3(),_l(),...r],r.forEach(n=>{t[n.type]=n,t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);us(s)?o=await s:o=s,t[o.type]=o,t[o.code]=o}if(o!=null)return o;throw new Dl(`Could not load crypto for ${o}`)}}function Uk(r=[],e){let t={[ze.code]:ze,[tt.code]:tt};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);us(s)?o=await s:o=s,t[o.code]=o}if(o!=null)return o;throw new Ll(`No hasher configured for multihash code 0x${n.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`)}}var ig=0,il=class extends Error{static name="IdentityHashDigestTooLongError";name="IdentityHashDigestTooLongError"},ag=class extends zo{child;maxDigestLength;constructor(e,t){super(),this.child=e,this.maxDigestLength=t?.maxDigestLength}put(e,t,n){if(e.multihash.code===ig){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new il(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);return n?.signal?.throwIfAborted(),e}return this.child==null?(n?.signal?.throwIfAborted(),e):this.child.put(e,t,n)}async*get(e,t){if(e.multihash.code===ig){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new il(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);t?.signal?.throwIfAborted(),yield e.multihash.digest;return}if(this.child==null)throw t?.signal?.throwIfAborted(),new vr;yield*this.child.get(e,t)}has(e,t){if(e.multihash.code===ig){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new il(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);return t?.signal?.throwIfAborted(),!0}return this.child==null?(t?.signal?.throwIfAborted(),!1):this.child.has(e,t)}delete(e,t){if(e.code===ig){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new il(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);t?.signal?.throwIfAborted();return}if(this.child!=null)return this.child.delete(e,t)}async*getAll(e){this.child!=null&&(yield*this.child.getAll(e)),e?.signal?.throwIfAborted()}};var SV=128,al=class{child;getHasher;log;logger;blockBrokers;constructor(e,t={}){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.blockBrokers=e.blockBrokers,this.child=new ag(e.blockstore,{maxDigestLength:t.maxIdentityHashDigestLength??SV}),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new R("blocks:put:duplicate",e)),e):(n.onProgress?.(new R("blocks:put:providers:notify",e)),await Promise.all(this.blockBrokers.map(async o=>o.announce?.(e,n))),n.onProgress?.(new R("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=Ur(e,async({cid:s})=>{let i=await this.child.has(s,t);return i&&t.onProgress?.(new R("blocks:put-many:duplicate",s)),!i}),o=Sc(n,async({cid:s})=>{t.onProgress?.(new R("blocks:put-many:providers:notify",s)),await Promise.all(this.blockBrokers.map(async i=>i.announce?.(s,t)))});t.onProgress?.(new R("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async*get(e,t={}){let n=await this.child.has(e,t),o=t.offline===!0;if(!n){if(o)throw new ru("The block was present in the blockstore and the node is running offline so cannot fetch it");let s=await this.getHasher(e.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new R("blocks:get:providers:get",e));let i=await Fk(e,this.blockBrokers,s,{...t,log:this.log});t.onProgress?.(new R("blocks:get:blockstore:put",e)),await this.child.put(e,i,t),t.onProgress?.(new R("blocks:get:providers:notify",e)),await Promise.all(this.blockBrokers.map(async a=>a.announce?.(e,t))),yield i;return}t.onProgress?.(new R("blocks:get:blockstore:get",e)),yield*this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new R("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(Sc(e,async n=>{let o=await this.child.has(n,t),s=t.offline===!0;if(!o){if(s)throw new ru("The block was present in the blockstore and the node is running offline so cannot fetch it");let i=await this.getHasher(n.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new R("blocks:get-many:providers:get",n));let a=await Fk(n,this.blockBrokers,i,{...t,log:this.log});t.onProgress?.(new R("blocks:get-many:blockstore:put",n)),await this.child.put(n,a,t),t.onProgress?.(new R("blocks:get-many:providers:notify",n)),await Promise.all(this.blockBrokers.map(async c=>c.announce?.(n,t)))}}))}async delete(e,t={}){t.onProgress?.(new R("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new R("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 R("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}};async function Fk(r,e,t,n){let o=TV(r,t),s=new AbortController,i=ue([s.signal,n.signal]);s.signal;let a=[];for(let c of e)AV(c)&&a.push(c);if(a.length===0)throw new bo(`No block brokers capable of retrieving blocks are configured, the CID ${r} cannot be fetched from the network`);try{return await Promise.any(a.map(async c=>{try{let l=!1,u=await c.retrieve(r,{...n,signal:i,validateFn:async d=>{await o(d),n.signal?.throwIfAborted(),l=!0}});return l||(await o(u),n.signal?.throwIfAborted()),u}catch(l){throw n.log.error("could not retrieve verified block for %c from %s - %e",r,c.name,l),l}}))}catch(c){throw new Wh(c.errors,`Failed to load block for ${r}`)}finally{s.abort(),i.clear()}}function AV(r){return typeof r.retrieve=="function"}var TV=(r,e)=>{if(e==null)throw new v(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`);return async t=>{let n,o=e.digest(t,{truncate:r.multihash.digest.byteLength});if(us(o)?n=await o:n=o,!ee(n.digest,r.multihash.digest))throw new fa("Hash of downloaded block did not match multihash from passed CID")}};var cg=class extends al{closeController;constructor(e,t){super(e),this.closeController=new AbortController,this.closeController.signal,this.log=e.logger.forComponent(`helia:session-storage:${t.root}`)}close(){this.closeController.abort()}async addPeer(e,t){await Promise.all(this.blockBrokers.map(n=>n.addPeer(e,t)))}async put(e,t,n={}){let o=ue([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=ue([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async*get(e,t={}){let n=ue([this.closeController.signal,t.signal]);try{yield*super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=ue([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=ue([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=ue([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=ue([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=ue([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};var lg=class extends al{started;constructor(e,t={}){super(e,t),this.started=!1}isStarted(){return this.started}async start(){await dt(this.child,...this.blockBrokers),this.started=!0}async stop(){await Ct(this.child,...this.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){if(this.blockBrokers.length===0)throw new bo("No block brokers configured");let n=this.blockBrokers.map(o=>o.createSession?.(t)).filter(o=>o!=null);if(n.length===0)throw new bo(`No configured block brokers support sessions - tried ${this.blockBrokers.map(o=>o.name).join(", ")}`);return new cg({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}};var Kk="/pin/",$k="/pinned-block/",h7=nr;function ug(r){return r.version===0&&(r=r.toV1()),new $e(`${Kk}${r.toString(h7)}`)}var dg=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=ug(e);if(await this.datastore.has(n))throw new Vh("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new v("Depth must be greater than or equal to 0");let s=(t.walker??S4())({blockstore:this.blockstore,getCodec:this.getCodec});for await(let a of s.walk(e,{...t,depth:o})){let c=a.block.cid;await this.#e(c,l=>l.pinnedBy.find(u=>ee(u,e.bytes))!=null?!1:(l.pinCount++,l.pinnedBy.push(e.bytes),!0),t),yield c}let i={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,vi(i),t)}async#e(e,t,n){let o=new $e(`${$k}${h7.encode(e.multihash.bytes)}`),s={pinCount:0,pinnedBy:[]};try{s=bn(await this.datastore.get(o,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(s)){if(s.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,vi(s),n),n.onProgress?.(new R("helia:pin:add",e))}}async*rm(e,t={}){let n=ug(e),o=await this.datastore.get(n,t),s=bn(o);await this.datastore.delete(n,t);let i=(t.walker??S4())({blockstore:this.blockstore,getCodec:this.getCodec});for await(let a of i.walk(e,{...t,depth:s.depth})){let c=a.block.cid;await this.#e(c,l=>(l.pinCount--,l.pinnedBy=l.pinnedBy.filter(u=>ee(u,e.bytes)),!0),{...t,depth:s.depth}),yield c}}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:Kk+(e.cid!=null?`${e.cid.toString(nr)}`:"")},e)){let o=V.parse(t.toString().substring(5),nr),s=bn(n);yield{cid:o,...s}}}async isPinned(e,t={}){let n=new $e(`${$k}${h7.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=ug(e),o=await this.datastore.get(n,t);return bn(o)}async setMetadata(e,t,n){let o=ug(e),s=await this.datastore.get(o,n),i=bn(s);i.metadata=t??{},await this.datastore.put(o,vi(i),n)}};var IV=5,fg=class{name;log;routers;providerLookupConcurrency;constructor(e,t){this.name="helia",this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??IV,this.findProviders=e.metrics?.traceFunction("helia.routing.findProviders",this.findProviders.bind(this),{optionsIndex:1})??this.findProviders,this.provide=e.metrics?.traceFunction("helia.routing.provide",this.provide.bind(this),{optionsIndex:1})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("helia.routing.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1})??this.cancelReprovide,this.put=e.metrics?.traceFunction("helia.routing.put",this.put.bind(this),{optionsIndex:2})??this.put,this.get=e.metrics?.traceFunction("helia.routing.get",this.get.bind(this),{optionsIndex:1})??this.get,this.findPeer=e.metrics?.traceFunction("helia.routing.findPeer",this.findPeer.bind(this),{optionsIndex:1})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("helia.routing.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1})??this.getClosestPeers}async start(){await dt(...this.routers)}async stop(){await Ct(...this.routers)}hasRouter(e){return this.routers.findIndex(t=>t.name===e)!==-1}addRouter(e){this.routers.push(e)}async*findProviders(e,t={}){if(this.routers.length===0)throw new Zo("No content routers available");let n=0,o=[],s=this;async function*i(u){let d=0,f=u.map(async function*(p){let g=0;t?.onProgress?.(new R("helia:routing:find-providers:start",{router:p.name,cid:e}));try{for await(let y of p.findProviders(e,t))g++,t?.onProgress?.(new R("helia:routing:find-providers:provider",{router:p.name,cid:e,provider:y})),yield y}catch(y){o.push(y)}finally{s.log("router %s found %d providers for %c",p.name,g,e),t?.onProgress?.(new R("helia:routing:find-providers:end",{router:p.name,cid:e,found:g})),d++,d===u.length&&h.size===0&&h.emitIdle()}}),h=new ct({concurrency:s.providerLookupConcurrency});for await(let p of cr(h.toGenerator(),...f))if(p!=null){if(p.multiaddrs.length===0){if(h.queue.find(g=>g.options.peer.equals(p.id))!=null)continue;h.add(async()=>{try{let g=await s.findPeer(p.id,t);return g.multiaddrs.length===0?null:{...g,protocols:p.protocols,router:p.router,fallback:p.fallback}}catch(g){return s.log.error("could not load multiaddrs for peer %p - %e",p.id,g),null}},{peer:p.id,signal:t.signal}).catch(g=>{s.log.error("could not load multiaddrs for peer %p - %e",p.id,g)});continue}n++,yield p}}let a=aa(this.routers,"findProviders"),c=a.filter(u=>u.capabilities==null||!u.capabilities().includes("fallback")),l=a.filter(u=>u.capabilities?.().includes("fallback")===!0);this.log("findProviders for %c start using routers %s",e,c.map(u=>u.name).join(", ")),yield*i(c),l.length>0&&(this.log("findProviders for %c using fallback routers %s",e,l.map(u=>u.name).join(", ")),yield*i(l)),this.log("findProviders finished, found %d providers for %c",n,e)}async provide(e,t={}){if(this.routers.length===0)throw new Zo("No content routers available");await Promise.all(aa(this.routers,"provide").map(async n=>{t?.onProgress?.(new R("helia:routing:provide:start",{router:n.name,cid:e})),await n.provide(e,t),t?.onProgress?.(new R("helia:routing:provide:end",{router:n.name,cid:e}))}))}async cancelReprovide(e,t={}){await Promise.all(aa(this.routers,"cancelReprovide").map(async n=>{t?.onProgress?.(new R("helia:routing:cancel-reprovide:start",{router:n.name,cid:e})),await n.cancelReprovide(e,t),t?.onProgress?.(new R("helia:routing:cancel-reprovide:end",{router:n.name,cid:e}))}))}async put(e,t,n){await Promise.all(aa(this.routers,"put").map(async o=>{n?.onProgress?.(new R("helia:routing:put:start",{router:o.name,key:e,value:t})),await o.put(e,t,n),n?.onProgress?.(new R("helia:routing:put:end",{router:o.name,key:e,value:t}))}))}async get(e,t){let n=[],o,s=new AbortController,i=ue([s.signal,t?.signal]);try{o=await Promise.any(aa(this.routers,"get").map(async a=>{t?.onProgress?.(new R("helia:routing:get:start",{router:a.name,key:e}));try{return await a.get(e,{...t,signal:i})}catch(c){throw this.log("router %s failed with %e",a.name,c),n.push(c),c}finally{t?.onProgress?.(new R("helia:routing:get:end",{router:a.name,key:e}))}}))}catch{}finally{s.abort(),i.clear()}if(o==null)throw new zh(n,`Failed to get value key ${O(e,"base58btc")}`);return o}async findPeer(e,t){if(this.routers.length===0)throw new Zo("No peer routers available");let n=new AbortController,o=ue([n.signal,t?.signal]);let s=this,i=cr(...aa(this.routers,"findPeer").map(a=>(async function*(){t?.onProgress?.(new R("helia:routing:find-peer:start",{router:a.name,peerId:e}));try{yield await a.findPeer(e,{...t,signal:o})}catch(c){s.log.error(c)}finally{t?.onProgress?.(new R("helia:routing:find-peer:end",{router:a.name,peerId:e}))}})()));try{for await(let a of i)if(a!=null)return a}finally{n.abort(),o.clear()}throw new Pe("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Zo("No peer routers available");for await(let n of cr(...aa(this.routers,"getClosestPeers").map(async function*(o){t?.onProgress?.(new R("helia:routing:get-closest-peers:start",{router:o.name,key:e}));try{yield*o.getClosestPeers(e,t)}finally{t?.onProgress?.(new R("helia:routing:get-closest-peers:end",{router:o.name,key:e}))}})))n!=null&&(yield n)}};function aa(r,e){return r.filter(t=>t[e]!=null)}var hg=class{info;blockstore;datastore;events;pins;logger;routing;getCodec;getHasher;getCrypto;dns;keychain;metrics;status;log;blockBrokers;mixins;components;constructor(e){this.info={name:e.name,version:e.version},this.logger=e.logger??bk(),this.log=this.logger.forComponent("helia"),this.getHasher=Uk(e.hashers,e.loadHasher),this.getCodec=Bk(e.codecs,e.loadCodec),this.getCrypto=Mk(e.cryptos,e.loadCrypto),this.dns=e.dns??F0(),this.metrics=e.metrics,this.events=new fe,this.status="stopped",this.mixins=[],this.components={blockstore:e.blockstore??new pf,datastore:e.datastore??new Yi,logger:this.logger,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,getCrypto:this.getCrypto,dns:this.dns,metrics:this.metrics,...e.components??{}},this.keychain=this.components.keychain=mk()(this.components),this.routing=this.components.routing=new fg(this.components,{routers:(e.routers??[]).flatMap(n=>(typeof n=="function"&&(n=n(this.components)),[n])),providerLookupConcurrency:e.providerLookupConcurrency}),this.blockBrokers=this.components.blockBrokers=(e.blockBrokers??[]).map(n=>(typeof n=="function"&&(n=n(this.components)),n));let t=new lg(this.components,e);this.pins=new dg(this.components.datastore,t,this.getCodec),this.blockstore=new og(t,this.pins,this.routing,{holdGcLock:e.holdGcLock??!0}),this.datastore=this.components.datastore}hasRouter(e){return this.routing.hasRouter(e)}addRouter(e){typeof e=="function"&&(e=e(this.components)),this.routing.addRouter(e)}hasBlockBroker(e){return this.blockBrokers.findIndex(t=>t.name===e)!==-1}addBlockBroker(e){typeof e=="function"&&(e=e(this.components)),this.blockBrokers.push(e)}addMixin(e){if(this.mixins.find(t=>t.name===e.name)!=null)throw new bo(`A mixin with the name "${e.name} is already present`);this.mixins.push(e)}async start(){this.status="starting",await Ak(this.datastore),await dt(this.blockstore,this.datastore,this.routing,...this.blockBrokers);for(let e of this.mixins)await e.start?.(this);return this.status="started",this.events.dispatchEvent(new CustomEvent("start",{detail:this})),this}async stop(){this.status="stopping";for(let e of this.mixins)await e.stop?.(this);return await Ct(this.blockstore,this.datastore,this.routing,...this.blockBrokers),this.status="stopped",this.events.dispatchEvent(new CustomEvent("stop",{detail:this})),this}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,o=this.blockstore.unwrap();this.log("gc start"),await xr(o.deleteMany((async function*(){for await(let{cid:s}of o.getAll())try{if(await n.pins.isPinned(s,e))continue;yield s,e.onProgress?.(new R("helia:gc:deleted",s))}catch(i){n.log.error("error during gc - %e",i),e.onProgress?.(new R("helia:gc:error",i))}})()))}finally{t()}this.log("gc finished")}};var Hk="7.1.7-dc9e15bc",Vk="helia";function CV(r={}){return ux(nk(Rx(qk({...r,codecs:[J5,o7,Lf,...r.codecs??[]],hashers:[zg,...r.hashers??[]]}),r.http),r.libp2p),r.bitswap)}function qk(r={}){return new hg({name:Vk,version:Hk,...r})}return Jk(kV);})();
114
114
  /*! Bundled license information:
115
115
 
116
116
  pvtsutils/build/index.js: