@helia/verified-fetch 2.5.3 → 2.5.4

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
@@ -72,7 +72,7 @@ ${[...t.errors.entries()].map(([i,s])=>`
72
72
  `),t),t.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let i=new Z(...e.map(s=>Om.single(C(`${s}
73
73
  `))),C(`
74
74
  `));t.log.trace('handle: respond with "%s" for %s',e,o),await Qs(n,i,t),t.log.trace('handle: responded with "%s" for %s',e,o);continue}t.log.trace('handle: respond with "na" for "%s"',o),await Qs(n,C(`na
75
- `),t),t.log('handle: responded with "na" for "%s"',o)}}var VM=500,d5=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:o,close:i,abort:s,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.limits=e.limits,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=i,this._abort=s,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[Y5]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new hd("the connection is being closed");if(this.status==="closed")throw new na("the connection is closed");if(Array.isArray(e)||(e=[e]),this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new sa("Cannot open protocol stream on limited connection");let n=await this._newStream(e,t);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(VM);e={...e,signal:t}}try{this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this._abort(e),this.status="closed",this.timeline.close=Date.now())}};function OA(r){return new d5(r)}function zM(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return s5}function KM(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??a5}function BA(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Bm=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(e,t){this.components=e,this.connectionEncrypters=new Map,t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=new Map,t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new fm(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=de([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,o=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=await this.components.connectionManager.acceptIncomingConnection(e),!n)throw new hm("Connection denied");await this.shouldBlockConnection("denyInboundConnection",e),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(i){throw this.metrics.errors?.increment({inbound:!0}),i}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getPeerId(),o;n!=null&&(o=Ue(n),await this.shouldBlockConnection("denyOutboundConnection",o,e));let i="outbound";return t.initiator===!1&&(i="inbound"),await this._performUpgrade(e,i,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),n}}async _performUpgrade(e,t,n){let o,i,s,a,c;this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t);let l=e;if(n?.skipProtection!==!0){let u=this.components.connectionProtector;u!=null&&(e.log("protecting the %s connection",t),l=await u.protect(e,n))}try{if(o=l,n?.skipEncryption!==!0){n?.onProgress?.(new M(`upgrader:encrypt-${t}-connection`)),{conn:o,remotePeer:i,protocol:c}=await(t==="inbound"?this._encryptInbound(l,n):this._encryptOutbound(l,n));let u={...l,...o};await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",i,u)}else{let u=e.remoteAddr.getPeerId();if(u==null)throw new Ko(`${t} connection that skipped encryption must have a peer id`);let d=Ue(u);c="native",i=d}if(i.equals(this.components.peerId)){let u=new ia("Can not dial self");throw e.abort(u),u}if(s=o,n?.muxerFactory!=null)a=n.muxerFactory;else if(this.streamMuxers.size>0){n?.onProgress?.(new M(`upgrader:multiplex-${t}-connection`));let u=await(t==="inbound"?this._multiplexInbound({...l,...o},this.streamMuxers,n):this._multiplexOutbound({...l,...o},this.streamMuxers,n));a=u.muxerFactory,s=u.stream}}catch(u){throw e.log.error("failed to upgrade inbound connection %s %a - %e",t==="inbound"?"from":"to",e.remoteAddr,u),u}return await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",i,e),e.log("successfully upgraded %s connection",t),this._createConnection({cryptoProtocol:c,direction:t,maConn:e,upgradedConn:s,muxerFactory:a,remotePeer:i,limits:n?.limits})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:o,upgradedConn:i,remotePeer:s,muxerFactory:a,limits:c}=e,l,u,d;a!=null&&(l=a.createStreamMuxer({direction:n,onIncomingStream:p=>{d!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),g=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);let{stream:y,protocol:w}=await Uu(p,m,{signal:g,log:p.log,yieldBytes:!1});if(d==null)return;d.log("incoming stream opened on %s",w);let b=zM(w,this.components.registrar);if(BA(w,"inbound",d)===b){let A=new yd(`Too many inbound protocol streams for protocol "${w}" - limit ${b}`);throw p.abort(A),A}p.source=y.source,p.sink=y.sink,p.protocol=w,y.closeWrite!=null&&(p.closeWrite=y.closeWrite),y.closeRead!=null&&(p.closeRead=y.closeRead),y.close!=null&&(p.close=y.close),await this.components.peerStore.merge(s,{protocols:[w]}),this.components.metrics?.trackProtocolStream(p,d),this._onStream({connection:d,stream:p,protocol:w})}).catch(async m=>{d.log.error("error handling incoming stream id %s - %e",p.id,m),p.timeline.close==null&&await p.close()})}}),u=async(p,m={})=>{if(l==null)throw new Ws("Connection is not multiplexed");d.log.trace("starting new stream for protocols %s",p);let g=await l.newStream();d.log.trace("started new stream %s for protocols %s",g.id,p);try{if(m.signal==null){g.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p);let A=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);m={...m,signal:A}}g.log.trace("selecting protocol from protocols %s",p);let{stream:y,protocol:w}=await Bu(g,p,{...m,log:g.log,yieldBytes:!0});g.log.trace("selected protocol %s",w);let b=KM(w,this.components.registrar,m),x=BA(w,"outbound",d);if(x>=b){let A=new Go(`Too many outbound protocol streams for protocol "${w}" - ${x}/${b}`);throw g.abort(A),A}return await this.components.peerStore.merge(s,{protocols:[w]}),g.source=y.source,g.sink=y.sink,g.protocol=w,y.closeWrite!=null&&(g.closeWrite=y.closeWrite),y.closeRead!=null&&(g.closeRead=y.closeRead),y.close!=null&&(g.close=y.close),this.components.metrics?.trackProtocolStream(g,d),g}catch(y){throw d.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",n==="inbound"?"from":"to",e.maConn.remoteAddr,p,y),g.timeline.close==null&&g.abort(y),y}},Promise.all([l.sink(i.source),i.sink(l.source)]).catch(p=>{d.log.error("error piping data through muxer - %e",p)}));let h=o.timeline;o.timeline=new Proxy(h,{set:(...p)=>(p[1]==="close"&&p[2]!=null&&h.close==null&&(async()=>{try{d.status==="open"&&await d.close()}catch(m){d.log.error("error closing connection after timeline close %e",m)}finally{this.events.safeDispatchEvent("connection:close",{detail:d})}})().catch(m=>{d.log.error("error thrown while dispatching connection:close event %e",m)}),Reflect.set(...p))}),o.timeline.upgraded=Date.now();let f=()=>{throw new Ws("Connection is not multiplexed")};return d=OA({remoteAddr:o.remoteAddr,remotePeer:s,status:"open",direction:n,timeline:o.timeline,multiplexer:l?.protocol,encryption:t,limits:c,logger:this.components.logger,newStream:u??f,getStreams:()=>l?.streams??[],close:async p=>{await l?.close(p),await o.close(p)},abort:p=>{o.abort(p),l?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:d}),d.__maConnTimeline=h,d}_onStream(e){let{connection:t,stream:n,protocol:o}=e,{handler:i,options:s}=this.components.registrar.getHandler(o);if(t.limits!=null&&s.runOnLimitedConnection!==!0)throw new sa("Cannot open protocol stream on limited connection");i({connection:t,stream:n})}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let{stream:o,protocol:i}=await Uu(e,n,{...t,log:e.log}),s=this.connectionEncrypters.get(i);if(s==null)throw new Ys(`no crypto module found for ${i}`);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,i),{...await s.secureInbound(o,t),protocol:i}}catch(o){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,o),new Ys(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:i}=await Bu(e,n,{...t,log:e.log,yieldBytes:!0}),s=this.connectionEncrypters.get(i);if(s==null)throw new Ys(`no crypto module found for ${i}`);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,i),{...await s.secureOutbound(o,t),protocol:i}}catch(o){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,o),new Ys(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let{stream:i,protocol:s}=await Bu(e,o,{...n,log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",s);let a=t.get(s);return{stream:i,muxerFactory:a}}catch(i){throw e.log.error("error multiplexing outbound connection",i),new Ws(String(i))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{let{stream:i,protocol:s}=await Uu(e,o,{...n,log:e.log}),a=t.get(s);return{stream:i,muxerFactory:a}}catch(i){throw e.log.error("error multiplexing inbound connection",i),new Ws(String(i))}}};var Mm=class extends ye{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new ye,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=n(l),d=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||d},this.peerId=e.peerId,this.logger=e.logger??ui(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??q0,i=e.nodeInfo?.version??K0,s=this.components=pA({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:i,userAgent:e.nodeInfo?.userAgent??G0(o,i)},logger:this.logger,events:t,datastore:e.datastore??new Bs,connectionGater:gA(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",aA(s,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),s.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(d=>d.multiaddr)};s.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(s)),this.components.upgrader=new Bm(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new Cm(this.components,e.transportManager)),this.configureComponent("connectionManager",new Sm(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Am(this.components,e.connectionMonitor)),this.configureComponent("registrar",new km(this.components)),this.configureComponent("addressManager",new nm(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Im(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new _m(this.components,{routers:c})),this.configureComponent("randomWalk",new Tm(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",h=>{this.#e(h)})}),e.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let u=e.services[l],d=u(this.components);if(d==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=d,this.configureComponent(l,d),d[Vn]!=null&&(this.log("registering service %s for content routing",l),c.push(d[Vn])),d[$n]!=null&&(this.log("registering service %s for peer routing",l),a.push(d[$n])),d[$i]!=null&&(this.log("registering service %s for peer discovery",l),d[$i].addEventListener?.("peer",h=>{this.#e(h)}))}mA(s)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new gr;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new D("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new D("no protocols were provided to open a stream");return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){yi(e)&&(e=Ue(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let s=await this.peerStore.get(e);if(s.id.publicKey!=null)return s.id.publicKey}catch(s){if(s.name!=="NotFoundError")throw s}let n=ge([C("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),i=gt(o);return await this.peerStore.patch(e,{publicKey:i}),i}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function Um(r={}){r.privateKey??=await Gf("Ed25519");let e=new Mm({...await rA(r),peerId:f9(r.privateKey)});return r.start!==!1&&await e.start(),e}async function MA(r){let e=r.libp2p??{};e.privateKey==null&&r.datastore!=null&&(e.privateKey=await H8(r.datastore,r.keychain));let t=Lu(e);return t.datastore=t.datastore??r.datastore,await Um({...t,...e,start:!1})}async function UA(r={}){let e=r.datastore??new Bs,t=r.blockstore??new du,n;qM(r.libp2p)?n=r.libp2p:n=await MA({...r,libp2p:{dns:r.dns,...r.libp2p,start:void 0},datastore:e});let o=new _p({...r,libp2p:n,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[Jl(),Kl()],routers:r.routers??[k6(n),I6()],metrics:n.metrics});return r.start!==!1&&await o.start(),o}function qM(r){return r==null?!1:["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"].every(t=>typeof r[t]=="function")}function FA(){let r=Lu();r.start=!1,r.addresses={listen:[]},r.transports=[H0(),z0()],r.peerDiscovery=[];let e={dcutr:r.services.dcutr,identify:r.services.identify,keychain:r.services.keychain,ping:r.services.ping};return{...r,start:!1,services:e}}var Cc=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,VA=new Set,f5=typeof process=="object"&&process?process:{},$A=(r,e,t,n)=>{typeof f5.emitWarning=="function"?f5.emitWarning(r,e,t,n):console.error(`[${t}] ${e}: ${r}`)},Fm=globalThis.AbortController,HA=globalThis.AbortSignal;if(typeof Fm>"u"){HA=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,o){this._onabort.push(o)}},Fm=class{constructor(){e()}signal=new HA;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let o of this.signal._onabort)o(n);this.signal.onabort?.(n)}}};let r=f5.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{r&&(r=!1,$A("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var GM=r=>!VA.has(r),f7e=Symbol("type"),Di=r=>r&&r===Math.floor(r)&&r>0&&isFinite(r),zA=r=>Di(r)?r<=Math.pow(2,8)?Uint8Array:r<=Math.pow(2,16)?Uint16Array:r<=Math.pow(2,32)?Uint32Array:r<=Number.MAX_SAFE_INTEGER?Pc:null:null,Pc=class extends Array{constructor(e){super(e),this.fill(0)}},h5=class r{heap;length;static#e=!1;static create(e){let t=zA(e);if(!t)return[];r.#e=!0;let n=new r(e,t);return r.#e=!1,n}constructor(e,t){if(!r.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},Hm=class r{#e;#r;#n;#c;#m;#A;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#g;#o;#s;#t;#f;#l;#h;#u;#b;#d;#x;#E;#y;#w;#_;#p;static unsafeExposeInternals(e){return{starts:e.#E,ttls:e.#y,sizes:e.#x,keyMap:e.#o,keyList:e.#s,valList:e.#t,next:e.#f,prev:e.#l,get head(){return e.#h},get tail(){return e.#u},free:e.#b,isBackgroundFetch:t=>e.#a(t),backgroundFetch:(t,n,o,i)=>e.#O(t,n,o,i),moveToTail:t=>e.#L(t),indexes:t=>e.#I(t),rindexes:t=>e.#T(t),isStale:t=>e.#S(t)}}get max(){return this.#e}get maxSize(){return this.#r}get calculatedSize(){return this.#g}get size(){return this.#i}get fetchMethod(){return this.#m}get memoMethod(){return this.#A}get dispose(){return this.#n}get disposeAfter(){return this.#c}constructor(e){let{max:t=0,ttl:n,ttlResolution:o=1,ttlAutopurge:i,updateAgeOnGet:s,updateAgeOnHas:a,allowStale:c,dispose:l,disposeAfter:u,noDisposeOnSet:d,noUpdateTTL:h,maxSize:f=0,maxEntrySize:p=0,sizeCalculation:m,fetchMethod:g,memoMethod:y,noDeleteOnFetchRejection:w,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:x,allowStaleOnFetchAbort:A,ignoreFetchAbort:k}=e;if(t!==0&&!Di(t))throw new TypeError("max option must be a nonnegative integer");let v=t?zA(t):Array;if(!v)throw new Error("invalid max value: "+t);if(this.#e=t,this.#r=f,this.maxEntrySize=p||this.#r,this.sizeCalculation=m,this.sizeCalculation){if(!this.#r&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(y!==void 0&&typeof y!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#A=y,g!==void 0&&typeof g!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#m=g,this.#_=!!g,this.#o=new Map,this.#s=new Array(t).fill(void 0),this.#t=new Array(t).fill(void 0),this.#f=new v(t),this.#l=new v(t),this.#h=0,this.#u=0,this.#b=h5.create(t),this.#i=0,this.#g=0,typeof l=="function"&&(this.#n=l),typeof u=="function"?(this.#c=u,this.#d=[]):(this.#c=void 0,this.#d=void 0),this.#w=!!this.#n,this.#p=!!this.#c,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!h,this.noDeleteOnFetchRejection=!!w,this.allowStaleOnFetchRejection=!!x,this.allowStaleOnFetchAbort=!!A,this.ignoreFetchAbort=!!k,this.maxEntrySize!==0){if(this.#r!==0&&!Di(this.#r))throw new TypeError("maxSize must be a positive integer if specified");if(!Di(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#V()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!a,this.ttlResolution=Di(o)||o===0?o:1,this.ttlAutopurge=!!i,this.ttl=n||0,this.ttl){if(!Di(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#C()}if(this.#e===0&&this.ttl===0&&this.#r===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#r){let S="LRU_CACHE_UNBOUNDED";GM(S)&&(VA.add(S),$A("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",S,r))}}getRemainingTTL(e){return this.#o.has(e)?1/0:0}#C(){let e=new Pc(this.#e),t=new Pc(this.#e);this.#y=e,this.#E=t,this.#B=(i,s,a=Cc.now())=>{if(t[i]=s!==0?a:0,e[i]=s,s!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#S(i)&&this.#k(this.#s[i],"expire")},s+1);c.unref&&c.unref()}},this.#P=i=>{t[i]=e[i]!==0?Cc.now():0},this.#v=(i,s)=>{if(e[s]){let a=e[s],c=t[s];if(!a||!c)return;i.ttl=a,i.start=c,i.now=n||o();let l=i.now-c;i.remainingTTL=a-l}};let n=0,o=()=>{let i=Cc.now();if(this.ttlResolution>0){n=i;let s=setTimeout(()=>n=0,this.ttlResolution);s.unref&&s.unref()}return i};this.getRemainingTTL=i=>{let s=this.#o.get(i);if(s===void 0)return 0;let a=e[s],c=t[s];if(!a||!c)return 1/0;let l=(n||o())-c;return a-l},this.#S=i=>{let s=t[i],a=e[i];return!!a&&!!s&&(n||o())-s>a}}#P=()=>{};#v=()=>{};#B=()=>{};#S=()=>!1;#V(){let e=new Pc(this.#e);this.#g=0,this.#x=e,this.#R=t=>{this.#g-=e[t],e[t]=0},this.#M=(t,n,o,i)=>{if(this.#a(n))return 0;if(!Di(o))if(i){if(typeof i!="function")throw new TypeError("sizeCalculation must be a function");if(o=i(n,t),!Di(o))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return o},this.#D=(t,n,o)=>{if(e[t]=n,this.#r){let i=this.#r-e[t];for(;this.#g>i;)this.#N(!0)}this.#g+=e[t],o&&(o.entrySize=n,o.totalCalculatedSize=this.#g)}}#R=e=>{};#D=(e,t,n)=>{};#M=(e,t,n,o)=>{if(n||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#I({allowStale:e=this.allowStale}={}){if(this.#i)for(let t=this.#u;!(!this.#U(t)||((e||!this.#S(t))&&(yield t),t===this.#h));)t=this.#l[t]}*#T({allowStale:e=this.allowStale}={}){if(this.#i)for(let t=this.#h;!(!this.#U(t)||((e||!this.#S(t))&&(yield t),t===this.#u));)t=this.#f[t]}#U(e){return e!==void 0&&this.#o.get(this.#s[e])===e}*entries(){for(let e of this.#I())this.#t[e]!==void 0&&this.#s[e]!==void 0&&!this.#a(this.#t[e])&&(yield[this.#s[e],this.#t[e]])}*rentries(){for(let e of this.#T())this.#t[e]!==void 0&&this.#s[e]!==void 0&&!this.#a(this.#t[e])&&(yield[this.#s[e],this.#t[e]])}*keys(){for(let e of this.#I()){let t=this.#s[e];t!==void 0&&!this.#a(this.#t[e])&&(yield t)}}*rkeys(){for(let e of this.#T()){let t=this.#s[e];t!==void 0&&!this.#a(this.#t[e])&&(yield t)}}*values(){for(let e of this.#I())this.#t[e]!==void 0&&!this.#a(this.#t[e])&&(yield this.#t[e])}*rvalues(){for(let e of this.#T())this.#t[e]!==void 0&&!this.#a(this.#t[e])&&(yield this.#t[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(let n of this.#I()){let o=this.#t[n],i=this.#a(o)?o.__staleWhileFetching:o;if(i!==void 0&&e(i,this.#s[n],this))return this.get(this.#s[n],t)}}forEach(e,t=this){for(let n of this.#I()){let o=this.#t[n],i=this.#a(o)?o.__staleWhileFetching:o;i!==void 0&&e.call(t,i,this.#s[n],this)}}rforEach(e,t=this){for(let n of this.#T()){let o=this.#t[n],i=this.#a(o)?o.__staleWhileFetching:o;i!==void 0&&e.call(t,i,this.#s[n],this)}}purgeStale(){let e=!1;for(let t of this.#T({allowStale:!0}))this.#S(t)&&(this.#k(this.#s[t],"expire"),e=!0);return e}info(e){let t=this.#o.get(e);if(t===void 0)return;let n=this.#t[t],o=this.#a(n)?n.__staleWhileFetching:n;if(o===void 0)return;let i={value:o};if(this.#y&&this.#E){let s=this.#y[t],a=this.#E[t];if(s&&a){let c=s-(Cc.now()-a);i.ttl=c,i.start=Date.now()}}return this.#x&&(i.size=this.#x[t]),i}dump(){let e=[];for(let t of this.#I({allowStale:!0})){let n=this.#s[t],o=this.#t[t],i=this.#a(o)?o.__staleWhileFetching:o;if(i===void 0||n===void 0)continue;let s={value:i};if(this.#y&&this.#E){s.ttl=this.#y[t];let a=Cc.now()-this.#E[t];s.start=Math.floor(Date.now()-a)}this.#x&&(s.size=this.#x[t]),e.unshift([n,s])}return e}load(e){this.clear();for(let[t,n]of e){if(n.start){let o=Date.now()-n.start;n.start=Cc.now()-o}this.set(t,n.value,n)}}set(e,t,n={}){if(t===void 0)return this.delete(e),this;let{ttl:o=this.ttl,start:i,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:c}=n,{noUpdateTTL:l=this.noUpdateTTL}=n,u=this.#M(e,t,n.size||0,a);if(this.maxEntrySize&&u>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#k(e,"set"),this;let d=this.#i===0?void 0:this.#o.get(e);if(d===void 0)d=this.#i===0?this.#u:this.#b.length!==0?this.#b.pop():this.#i===this.#e?this.#N(!1):this.#i,this.#s[d]=e,this.#t[d]=t,this.#o.set(e,d),this.#f[this.#u]=d,this.#l[d]=this.#u,this.#u=d,this.#i++,this.#D(d,u,c),c&&(c.set="add"),l=!1;else{this.#L(d);let h=this.#t[d];if(t!==h){if(this.#_&&this.#a(h)){h.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=h;f!==void 0&&!s&&(this.#w&&this.#n?.(f,e,"set"),this.#p&&this.#d?.push([f,e,"set"]))}else s||(this.#w&&this.#n?.(h,e,"set"),this.#p&&this.#d?.push([h,e,"set"]));if(this.#R(d),this.#D(d,u,c),this.#t[d]=t,c){c.set="replace";let f=h&&this.#a(h)?h.__staleWhileFetching:h;f!==void 0&&(c.oldValue=f)}}else c&&(c.set="update")}if(o!==0&&!this.#y&&this.#C(),this.#y&&(l||this.#B(d,o,i),c&&this.#v(c,d)),!s&&this.#p&&this.#d){let h=this.#d,f;for(;f=h?.shift();)this.#c?.(...f)}return this}pop(){try{for(;this.#i;){let e=this.#t[this.#h];if(this.#N(!0),this.#a(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#p&&this.#d){let e=this.#d,t;for(;t=e?.shift();)this.#c?.(...t)}}}#N(e){let t=this.#h,n=this.#s[t],o=this.#t[t];return this.#_&&this.#a(o)?o.__abortController.abort(new Error("evicted")):(this.#w||this.#p)&&(this.#w&&this.#n?.(o,n,"evict"),this.#p&&this.#d?.push([o,n,"evict"])),this.#R(t),e&&(this.#s[t]=void 0,this.#t[t]=void 0,this.#b.push(t)),this.#i===1?(this.#h=this.#u=0,this.#b.length=0):this.#h=this.#f[t],this.#o.delete(n),this.#i--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:o}=t,i=this.#o.get(e);if(i!==void 0){let s=this.#t[i];if(this.#a(s)&&s.__staleWhileFetching===void 0)return!1;if(this.#S(i))o&&(o.has="stale",this.#v(o,i));else return n&&this.#P(i),o&&(o.has="hit",this.#v(o,i)),!0}else o&&(o.has="miss");return!1}peek(e,t={}){let{allowStale:n=this.allowStale}=t,o=this.#o.get(e);if(o===void 0||!n&&this.#S(o))return;let i=this.#t[o];return this.#a(i)?i.__staleWhileFetching:i}#O(e,t,n,o){let i=t===void 0?void 0:this.#t[t];if(this.#a(i))return i;let s=new Fm,{signal:a}=n;a?.addEventListener("abort",()=>s.abort(a.reason),{signal:s.signal});let c={signal:s.signal,options:n,context:o},l=(m,g=!1)=>{let{aborted:y}=s.signal,w=n.ignoreFetchAbort&&m!==void 0;if(n.status&&(y&&!g?(n.status.fetchAborted=!0,n.status.fetchError=s.signal.reason,w&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),y&&!w&&!g)return d(s.signal.reason);let b=f;return this.#t[t]===f&&(m===void 0?b.__staleWhileFetching?this.#t[t]=b.__staleWhileFetching:this.#k(e,"fetch"):(n.status&&(n.status.fetchUpdated=!0),this.set(e,m,c.options))),m},u=m=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=m),d(m)),d=m=>{let{aborted:g}=s.signal,y=g&&n.allowStaleOnFetchAbort,w=y||n.allowStaleOnFetchRejection,b=w||n.noDeleteOnFetchRejection,x=f;if(this.#t[t]===f&&(!b||x.__staleWhileFetching===void 0?this.#k(e,"fetch"):y||(this.#t[t]=x.__staleWhileFetching)),w)return n.status&&x.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),x.__staleWhileFetching;if(x.__returned===x)throw m},h=(m,g)=>{let y=this.#m?.(e,i,c);y&&y instanceof Promise&&y.then(w=>m(w===void 0?void 0:w),g),s.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(m(void 0),n.allowStaleOnFetchAbort&&(m=w=>l(w,!0)))})};n.status&&(n.status.fetchDispatched=!0);let f=new Promise(h).then(l,u),p=Object.assign(f,{__abortController:s,__staleWhileFetching:i,__returned:void 0});return t===void 0?(this.set(e,p,{...c.options,status:void 0}),t=this.#o.get(e)):this.#t[t]=p,p}#a(e){if(!this.#_)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof Fm}async fetch(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:h=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:m,forceRefresh:g=!1,status:y,signal:w}=t;if(!this.#_)return y&&(y.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:o,noDeleteOnStaleGet:i,status:y});let b={allowStale:n,updateAgeOnGet:o,noDeleteOnStaleGet:i,ttl:s,noDisposeOnSet:a,size:c,sizeCalculation:l,noUpdateTTL:u,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:h,allowStaleOnFetchAbort:p,ignoreFetchAbort:f,status:y,signal:w},x=this.#o.get(e);if(x===void 0){y&&(y.fetch="miss");let A=this.#O(e,x,b,m);return A.__returned=A}else{let A=this.#t[x];if(this.#a(A)){let $=n&&A.__staleWhileFetching!==void 0;return y&&(y.fetch="inflight",$&&(y.returnedStale=!0)),$?A.__staleWhileFetching:A.__returned=A}let k=this.#S(x);if(!g&&!k)return y&&(y.fetch="hit"),this.#L(x),o&&this.#P(x),y&&this.#v(y,x),A;let v=this.#O(e,x,b,m),I=v.__staleWhileFetching!==void 0&&n;return y&&(y.fetch=k?"stale":"refresh",I&&k&&(y.returnedStale=!0)),I?v.__staleWhileFetching:v.__returned=v}}async forceFetch(e,t={}){let n=await this.fetch(e,t);if(n===void 0)throw new Error("fetch() returned undefined");return n}memo(e,t={}){let n=this.#A;if(!n)throw new Error("no memoMethod provided to constructor");let{context:o,forceRefresh:i,...s}=t,a=this.get(e,s);if(!i&&a!==void 0)return a;let c=n(e,a,{options:s,context:o});return this.set(e,c,s),c}get(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:s}=t,a=this.#o.get(e);if(a!==void 0){let c=this.#t[a],l=this.#a(c);return s&&this.#v(s,a),this.#S(a)?(s&&(s.get="stale"),l?(s&&n&&c.__staleWhileFetching!==void 0&&(s.returnedStale=!0),n?c.__staleWhileFetching:void 0):(i||this.#k(e,"expire"),s&&n&&(s.returnedStale=!0),n?c:void 0)):(s&&(s.get="hit"),l?c.__staleWhileFetching:(this.#L(a),o&&this.#P(a),c))}else s&&(s.get="miss")}#F(e,t){this.#l[t]=e,this.#f[e]=t}#L(e){e!==this.#u&&(e===this.#h?this.#h=this.#f[e]:this.#F(this.#l[e],this.#f[e]),this.#F(this.#u,e),this.#u=e)}delete(e){return this.#k(e,"delete")}#k(e,t){let n=!1;if(this.#i!==0){let o=this.#o.get(e);if(o!==void 0)if(n=!0,this.#i===1)this.#H(t);else{this.#R(o);let i=this.#t[o];if(this.#a(i)?i.__abortController.abort(new Error("deleted")):(this.#w||this.#p)&&(this.#w&&this.#n?.(i,e,t),this.#p&&this.#d?.push([i,e,t])),this.#o.delete(e),this.#s[o]=void 0,this.#t[o]=void 0,o===this.#u)this.#u=this.#l[o];else if(o===this.#h)this.#h=this.#f[o];else{let s=this.#l[o];this.#f[s]=this.#f[o];let a=this.#f[o];this.#l[a]=this.#l[o]}this.#i--,this.#b.push(o)}}if(this.#p&&this.#d?.length){let o=this.#d,i;for(;i=o?.shift();)this.#c?.(...i)}return n}clear(){return this.#H("delete")}#H(e){for(let t of this.#T({allowStale:!0})){let n=this.#t[t];if(this.#a(n))n.__abortController.abort(new Error("deleted"));else{let o=this.#s[t];this.#w&&this.#n?.(n,o,e),this.#p&&this.#d?.push([n,o,e])}}if(this.#o.clear(),this.#t.fill(void 0),this.#s.fill(void 0),this.#y&&this.#E&&(this.#y.fill(0),this.#E.fill(0)),this.#x&&this.#x.fill(0),this.#h=0,this.#u=0,this.#b.length=0,this.#g=0,this.#i=0,this.#p&&this.#d){let t=this.#d,n;for(;n=t?.shift();)this.#c?.(...n)}}};var g5=xt(Vm(),1);var y5=40;function w5(r,e){if(!r.length)throw new Error("Unexpected end of data");let t=g5.default.decode(r);return e.seek(g5.default.decode.bytes),t}function b5(r){let e=new DataView(r.buffer,r.byteOffset,r.byteLength),t=0;return{version:2,characteristics:[e.getBigUint64(t,!0),e.getBigUint64(t+=8,!0)],dataOffset:Number(e.getBigUint64(t+=8,!0)),dataSize:Number(e.getBigUint64(t+=8,!0)),indexOffset:Number(e.getBigUint64(t+=8,!0))}}var Ni={Null:r=>r===null?r:void 0,Int:r=>Number.isInteger(r)?r:void 0,Float:r=>typeof r=="number"&&Number.isFinite(r)?r:void 0,String:r=>typeof r=="string"?r:void 0,Bool:r=>typeof r=="boolean"?r:void 0,Bytes:r=>r instanceof Uint8Array?r:void 0,Link:r=>r!==null&&typeof r=="object"&&r.asCID===r?r:void 0,List:r=>Array.isArray(r)?r:void 0,Map:r=>r!==null&&typeof r=="object"&&r.asCID!==r&&!Array.isArray(r)&&!(r instanceof Uint8Array)?r:void 0},Fu={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":Ni.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(Ni.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=Fu["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let o=e;o<r.length;o++){let i=r[o];if(i=Fu["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:Ni.Int,CarV1HeaderOrV2Pragma:r=>{if(Ni.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let o=0;o<e.length;o++){let[i,s]=e[o];switch(i){case"roots":{let a=Fu["CarV1HeaderOrV2Pragma > roots (anon)"](r[i]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=Fu.Int(r[i]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},Hu={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":Ni.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(Ni.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=Hu["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let o=e;o<r.length;o++){let i=r[o];if(i=Hu["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:Ni.Int,CarV1HeaderOrV2Pragma:r=>{if(Ni.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let o=0;o<e.length;o++){let[i,s]=e[o];switch(i){case"roots":{let a=Hu["CarV1HeaderOrV2Pragma > roots (anon)"](s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=Hu.Int(s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},x5={toTyped:Fu.CarV1HeaderOrV2Pragma,toRepresentation:Hu.CarV1HeaderOrV2Pragma};var k7e=q3();var lU=xt(Vm(),1);var D7e=[new F(E.map,2),new F(E.string,"version"),new F(E.uint,1),new F(E.string,"roots")],N7e=new F(E.tag,42);async function E5(r,e){let t=w5(await r.upTo(8),r);if(t===0)throw new Error("Invalid CAR header (zero length)");let n=await r.exactly(t,!0),o=mi(n);if(x5.toTyped(o)===void 0)throw new Error("Invalid CAR header format");if(o.version!==1&&o.version!==2||e!==void 0&&o.version!==e)throw new Error(`Invalid CAR version: ${o.version}${e!==void 0?` (expected ${e})`:""}`);if(o.version===1){if(!Array.isArray(o.roots))throw new Error("Invalid CAR header format");return o}if(o.roots!==void 0)throw new Error("Invalid CAR header format");let i=b5(await r.exactly(y5,!0));r.seek(i.dataOffset-r.pos);let s=await E5(r,1);return Object.assign(s,i)}function Vu(r){let e=0;return{async upTo(t){return r.subarray(e,e+Math.min(t,r.length-e))},async exactly(t,n=!1){if(t>r.length-e)throw new Error("Unexpected end of data");let o=r.subarray(e,e+t);return n&&(e+=t),o},seek(t){e+=t},get pos(){return e}}}var v5=xt(Vm(),1),t_=1;function S5(r){let e=Ua({version:t_,roots:r}),t=v5.default.encode(e.length),n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function r_(r){return{async setRoots(e){let t=S5(e);await r.write(t)},async writeBlock(e){let{cid:t,bytes:n}=e;await r.write(new Uint8Array(v5.default.encode(t.bytes.length+n.length))),await r.write(t.bytes),n.length&&await r.write(n)},async close(){await r.end()},version(){return t_}}}function $m(){}function n_(){let r=[],e=null,t=$m,n=!1,o=null,i=$m,s=()=>(e||(e=new Promise(l=>{t=()=>{e=null,t=$m,l()}})),e),a={write(l){r.push(l);let u=s();return i(),u},async end(){n=!0;let l=s();i(),await l}},c={async next(){let l=r.shift();return l?(r.length===0&&t(),{done:!1,value:l}):n?(t(),{done:!0,value:void 0}):(o||(o=new Promise(u=>{i=()=>(o=null,i=$m,u(c.next()))})),o)}};return{writer:a,iterator:c}}var $u=class r{constructor(e,t){this._encoder=t,this._mutex=t.setRoots(e),this._ended=!1}async put(e){if(!(e.bytes instanceof Uint8Array)||!e.cid)throw new TypeError("Can only write {cid, bytes} objects");if(this._ended)throw new Error("Already closed");let t=O.asCID(e.cid);if(!t)throw new TypeError("Can only write {cid, bytes} objects");return this._mutex=this._mutex.then(()=>this._encoder.writeBlock({cid:t,bytes:e.bytes})),this._mutex}async close(){if(this._ended)throw new Error("Already closed");return await this._mutex,this._ended=!0,this._encoder.close()}version(){return this._encoder.version()}static create(e){e=hU(e);let{encoder:t,iterator:n}=o_(),o=new r(e,t),i=new zm(n);return{writer:o,out:i}}static createAppender(){let{encoder:e,iterator:t}=o_();e.setRoots=()=>Promise.resolve();let n=new r([],e),o=new zm(t);return{writer:n,out:o}}static async updateRootsInBytes(e,t){let n=Vu(e);await E5(n);let o=S5(t);if(Number(n.pos)!==o.length)throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${n.pos} bytes, new header is ${o.length} bytes)`);return e.set(o,0),e}},zm=class{constructor(e){this._iterator=e}[Symbol.asyncIterator](){if(this._iterating)throw new Error("Multiple iterator not supported");return this._iterating=!0,this._iterator}};function o_(){let r=n_(),{writer:e,iterator:t}=r;return{encoder:r_(e),iterator:t}}function hU(r){if(r===void 0)return[];if(!Array.isArray(r)){let t=O.asCID(r);if(!t)throw new TypeError("roots must be a single CID or an array of CIDs");return[t]}let e=[];for(let t of r){let n=O.asCID(t);if(!n)throw new TypeError("roots must be a single CID or an array of CIDs");e.push(n)}return e}var pU=1,A5=class{components;constructor(e,t){this.components=e}async import(e,t){await Lt(this.components.blockstore.putMany(Je(e.blocks(),({cid:n,bytes:o})=>({cid:n,block:o})),t))}async export(e,t,n){let o=J(),i=Array.isArray(e)?e:[e],s=new Cr({concurrency:pU});s.on("idle",()=>{o.resolve()}),s.on("error",a=>{s.clear(),o.reject(a)});for(let a of i)s.add(async()=>{await this.#e(a,s,async(c,l)=>{n?.blockFilter?.has(c.multihash.bytes)!==!0&&(n?.blockFilter?.add(c.multihash.bytes),await t.put({cid:c,bytes:l}))},n)}).catch(()=>{});try{await o.promise}finally{await t.close()}}async*stream(e,t){let{writer:n,out:o}=$u.create(e);this.export(e,n,t).catch(()=>{});for await(let i of o)yield i}async#e(e,t,n,o){let i=await this.components.getCodec(e.code),s=await this.components.blockstore.get(e,o);await n(e,s);let a=Eh({bytes:s,cid:e,codec:i});for await(let[,c]of a.links())t.add(async()=>{await this.#e(c,t,n,o)})}};function i_(r,e={}){return new A5(r,e)}function zu(r,e={}){let t=ac(r),n={_cancelled:!1,async start(){this._cancelled=!1},async pull(o){try{let{value:i,done:s}=await t.next();if(this._cancelled)return;if(s===!0){o.close();return}o.enqueue(i)}catch(i){o.error(i)}},cancel(){this._cancelled=!0}};return new globalThis.ReadableStream(n,e)}function _5(r,e,t){Object.defineProperty(r,e,{enumerable:!0,configurable:!1,set:()=>{},get:()=>t})}function Uo(r,e){_5(r,"type",e)}function Fo(r,e){_5(r,"url",e)}function s_(r){_5(r,"redirected",!0)}function On(r,e,t){let n=new Response(e,{...t??{},status:200,statusText:"OK"});return t?.redirected===!0&&s_(n),Uo(n,"basic"),Fo(n,r),n.headers.set("Accept-Ranges","bytes"),n}function Rc(r,e,t){let n=new Response(e,{...t??{},status:502,statusText:"Bad Gateway"});return Uo(n,"basic"),Fo(n,r),n}function qm(r,e,t){let n=new Response(e,{...t??{},status:501,statusText:"Not Implemented"});return n.headers.set("X-Content-Type-Options","nosniff"),Uo(n,"basic"),Fo(n,r),n}function Ho(r,e,t){let n=new Response(e,{...t??{},status:406,statusText:"Not Acceptable"});return Uo(n,"basic"),Fo(n,r),n}function Gm(r,e,t){let n=new Response(e,{...t??{},status:404,statusText:"Not Found"});return Uo(n,"basic"),Fo(n,r),n}function Ku(r,e,t){e instanceof Error&&(e=e.message);let n=new Response(e,{...t??{},status:400,statusText:"Bad Request"});return Uo(n,"basic"),Fo(n,r),n}function qu(r,e,t){let n=new Response(null,{...t??{},status:301,statusText:"Moved Permanently",headers:{...t?.headers??{},location:e}});return Uo(n,"basic"),Fo(n,r),n}function Wm(r,e,{byteRangeContext:t,log:n},o){if(!t.isRangeRequest)return On(r,e,o);if(!t.isValidRangeRequest)return Km(r,e,o);let i;try{i=new Response(e,{...o??{},status:206,statusText:"Partial Content",headers:{...o?.headers??{},"content-range":t.contentRangeHeaderValue}})}catch(s){return n?.error("failed to create range response",s),Km(r,e,o)}return o?.redirected===!0&&s_(i),Uo(i,"basic"),Fo(i,r),i.headers.set("Accept-Ranges","bytes"),i}function Km(r,e,t){let n=new Response(e,{...t??{},status:416,statusText:"Requested Range Not Satisfiable"});return Uo(n,"basic"),Fo(n,r),n}var dt=class{codes=[];log;pluginOptions;constructor(e){let t=this.constructor.name.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();this.log=e.logger.forComponent(t),this.pluginOptions=e}canHandle(e){throw new Error("Not implemented")}async handle(e){throw new Error("Not implemented")}};var Ym=class extends dt{canHandle(e){return this.log("checking if we can handle %c with accept %s",e.cid,e.accept),e.accept?.startsWith("application/vnd.ipld.car")===!0||e.query.format==="car"}async handle(e){let{options:t}=e,{getBlockstore:n,helia:o}=this.pluginOptions;e.reqFormat="car",e.query.download=!0,e.query.filename=e.query.filename??`${e.cid.toString()}.car`;let i=n(e.cid,e.resource,t?.session??!0,t),s=i_({blockstore:i,getCodec:o.getCodec}),a=zu(s.stream(e.cid,t)),c=On(e.resource,a);return c.headers.set("content-type","application/vnd.ipld.car; version=1"),c}};function a_(r){let e=wr(r,{allowIndefinite:!1,coerceUndefinedToNull:!1,allowNaN:!1,allowInfinity:!1,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,allowBigInt:!1});return new TextDecoder().decode($l(e))}var qr=class extends Error{static name="InvalidRangeError";constructor(e="Invalid range request"){super(e),this.name="InvalidRangeError"}},Xm=class extends Error{static name="NoContentError";constructor(e="No content found"){super(e),this.name="NoContentError"}},Qm=class extends Error{static name="SubdomainNotSupportedError";constructor(e="Subdomain not supported"){super(e),this.name="SubdomainNotSupportedError"}};function c_({ttl:r,protocol:e,response:t}){if(t.headers.has("cache-control"))return;let n;e==="ipfs"?n="public, max-age=29030400, immutable":r==null?n="public, max-age=300":n=`public, max-age=${r}`,t.headers.set("cache-control",n)}function l_({byteStart:r,byteEnd:e,byteSize:t}){let n=t??"*";if((e??0)>=(t??1/0))throw new qr("Invalid range: Range-end index is greater than or equal to the size of the file.");if((r??0)>=(t??1/0))throw new qr("Invalid range: Range-start index is greater than or equal to the size of the file.");if(r!=null&&e==null)return t==null?`bytes */${n}`:`bytes ${r}-${t-1}/${t}`;if(r==null&&e!=null){if(t==null)return`bytes */${n}`;let o=t-1;return`bytes ${o-e+1}-${o}/${t}`}return r==null&&e==null?`bytes */${n}`:`bytes ${r}-${e}/${n}`}function jm(r,e){e!=null&&r.headers.set("X-Ipfs-Roots",e.map(t=>t.toV1().toString()).join(","))}var Bn=class extends Error{name;code;constructor(e,t,n){super(e),this.name=t,this.code=n}},Gr=class extends Bn{constructor(e="not a Unixfs node"){super(e,"NotUnixFSError","ERR_NOT_UNIXFS")}},Er=class extends Bn{constructor(e="invalid PBNode"){super(e,"InvalidPBNodeError","ERR_INVALID_PBNODE")}},Oi=class extends Bn{constructor(e="unknown error"){super(e,"InvalidPBNodeError","ERR_UNKNOWN_ERROR")}},Gu=class extends Bn{constructor(e="path already exists"){super(e,"AlreadyExistsError","ERR_ALREADY_EXISTS")}},Lc=class extends Bn{constructor(e="path does not exist"){super(e,"DoesNotExistError","ERR_DOES_NOT_EXIST")}},Dc=class extends Bn{constructor(e="no content"){super(e,"NoContentError","ERR_NO_CONTENT")}},Zm=class extends Bn{constructor(e="not a file"){super(e,"NotAFileError","ERR_NOT_A_FILE")}},Bi=class extends Bn{constructor(e="not a directory"){super(e,"NotADirectoryError","ERR_NOT_A_DIRECTORY")}},Wr=class extends Bn{constructor(e="invalid parameters"){super(e,"InvalidParametersError","ERR_INVALID_PARAMETERS")}};function mU(r){return r[Symbol.asyncIterator]!=null}function gU(r){if(mU(r))return(async()=>{let t;for await(let n of r)t=n;return t})();let e;for(let t of r)e=t;return e}var Mi=gU;var Jm=class r extends Error{static name="BadPathError";static code="ERR_BAD_PATH";name=r.name;code=r.code;constructor(e="Bad path"){super(e)}},fn=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not found"){super(e)}},e2=class r extends Error{static name="NoResolverError";static code="ERR_NO_RESOLVER";name=r.name;code=r.code;constructor(e="No resolver"){super(e)}},Ct=class r extends Error{static name="NotUnixFSError";static code="ERR_NOT_UNIXFS";name=r.name;code=r.code;constructor(e="Not UnixFS"){super(e)}},t2=class r extends Error{static name="OverReadError";static code="ERR_OVER_READ";name=r.name;code=r.code;constructor(e="Over read"){super(e)}},r2=class r extends Error{static name="UnderReadError";static code="ERR_UNDER_READ";name=r.name;code=r.code;constructor(e="Under read"){super(e)}},n2=class r extends Error{static name="NoPropError";static code="ERR_NO_PROP";name=r.name;code=r.code;constructor(e="No Property found"){super(e)}},Zs=class r extends Error{static name="InvalidParametersError";static code="ERR_INVALID_PARAMS";name=r.name;code=r.code;constructor(e="Invalid parameters"){super(e)}};function Nc(r,e,t,n,o,i,s){let a=r,c=o;for(;i.length>0;){let l=i[0];if(l in a){i.shift(),c=`${c}/${l}`;let u=O.asCID(a[l]);if(u!=null)return{entry:{type:"object",name:n,path:o,cid:t,node:e,depth:s,size:BigInt(e.length),content:async function*(){yield r}},next:{cid:u,name:l,path:c,toResolve:i}};a=a[l]}else throw new n2(`No property named ${l} found in node ${t}`)}return{entry:{type:"object",name:n,path:o,cid:t,node:e,depth:s,size:BigInt(e.length),content:async function*(){yield r}}}}var yU=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=mi(c);return Nc(l,c,r,e,t,n,i)},u_=yU;var wU=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=Ha(c);return Nc(l,c,r,e,t,n,i)},d_=wU;function bU(r,e,t,n){let o=BigInt(r.length),i=BigInt(e+o);return t>=i||n<e?new Uint8Array(0):(n>=e&&n<i&&(r=r.subarray(0,Number(n-e))),t>=e&&t<i&&(r=r.subarray(Number(t-e))),r)}var Js=bU;var xU=(r,e=0,t=r)=>{let n=BigInt(r),o=BigInt(e??0),i=BigInt(t);if(i!==n&&(i=o+i),i>n&&(i=n),o<0n)throw new Zs("Offset must be greater than or equal to 0");if(o>n)throw new Zs("Offset must be less than the file size");if(i<0n)throw new Zs("Length must be greater than or equal to 0");if(i>n)throw new Zs("Length must be less than the file size");return{start:o,end:i}},Oc=xU;var EU=r=>{async function*e(t={}){let{start:n,end:o}=Oc(r.length,t.offset,t.length),i=Js(r,0n,n,o);t.onProgress?.(new M("unixfs:exporter:progress:identity",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return e},vU=async(r,e,t,n,o,i,s,a)=>{if(n.length>0)throw new fn(`No link named ${t} found in raw node ${r}`);let c=we(r.multihash.bytes);return{entry:{type:"identity",name:e,path:t,cid:r,content:EU(c.digest),depth:i,size:BigInt(c.digest.length),node:c.digest}}},f_=vU;var SU=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=bg(c);return Nc(l,c,r,e,t,n,i)},h_=SU;var AU=r=>{async function*e(t={}){let{start:n,end:o}=Oc(r.length,t.offset,t.length),i=Js(r,0n,n,o);t.onProgress?.(new M("unixfs:exporter:progress:raw",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return e},_U=async(r,e,t,n,o,i,s,a)=>{if(n.length>0)throw new fn(`No link named ${t} found in raw node ${r}`);let c=await s.get(r,a);return{entry:{type:"raw",name:e,path:t,cid:r,content:AU(c),depth:i,size:BigInt(c.length),node:c}}},p_=_U;var Wu=class r extends Error{static name="InvalidTypeError";static code="ERR_INVALID_TYPE";name=r.name;code=r.code;constructor(e="Invalid type"){super(e)}};var Mn;(function(r){let e;(function(o){o.Raw="Raw",o.Directory="Directory",o.File="File",o.Metadata="Metadata",o.Symlink="Symlink",o.HAMTShard="HAMTShard"})(e=r.DataType||(r.DataType={}));let t;(function(o){o[o.Raw=0]="Raw",o[o.Directory=1]="Directory",o[o.File=2]="File",o[o.Metadata=3]="Metadata",o[o.Symlink=4]="Symlink",o[o.HAMTShard=5]="HAMTShard"})(t||(t={})),function(o){o.codec=()=>Ke(t)}(e=r.DataType||(r.DataType={}));let n;r.codec=()=>(n==null&&(n=re((o,i,s={})=>{if(s.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),r.DataType.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),o.filesize!=null&&(i.uint32(24),i.uint64(o.filesize)),o.blocksizes!=null)for(let a of o.blocksizes)i.uint32(32),i.uint64(a);o.hashType!=null&&(i.uint32(40),i.uint64(o.hashType)),o.fanout!=null&&(i.uint32(48),i.uint64(o.fanout)),o.mode!=null&&(i.uint32(56),i.uint32(o.mode)),o.mtime!=null&&(i.uint32(66),o2.codec().encode(o.mtime,i)),s.lengthDelimited!==!1&&i.ldelim()},(o,i)=>{let s={blocksizes:[]},a=i==null?o.len:o.pos+i;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:s.Type=r.DataType.codec().decode(o);break;case 2:s.Data=o.bytes();break;case 3:s.filesize=o.uint64();break;case 4:s.blocksizes.push(o.uint64());break;case 5:s.hashType=o.uint64();break;case 6:s.fanout=o.uint64();break;case 7:s.mode=o.uint32();break;case 8:s.mtime=o2.codec().decode(o,o.uint32());break;default:o.skipType(c&7);break}}return s})),n),r.encode=o=>te(o,r.codec()),r.decode=o=>ee(o,r.codec())})(Mn||(Mn={}));var o2;(function(r){let e;r.codec=()=>(e==null&&(e=re((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Seconds!=null&&(n.uint32(8),n.int64(t.Seconds)),t.FractionalNanoseconds!=null&&(n.uint32(21),n.fixed32(t.FractionalNanoseconds)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let s=t.uint32();switch(s>>>3){case 1:o.Seconds=t.int64();break;case 2:o.FractionalNanoseconds=t.fixed32();break;default:t.skipType(s&7);break}}return o})),e),r.encode=t=>te(t,r.codec()),r.decode=t=>ee(t,r.codec())})(o2||(o2={}));var m_;(function(r){let e;r.codec=()=>(e==null&&(e=re((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.MimeType!=null&&(n.uint32(10),n.string(t.MimeType)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let s=t.uint32();switch(s>>>3){case 1:o.MimeType=t.string();break;default:t.skipType(s&7);break}}return o})),e),r.encode=t=>te(t,r.codec()),r.decode=t=>ee(t,r.codec())})(m_||(m_={}));var g_={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},IU=["directory","hamt-sharded-directory"],y_=parseInt("0644",8),w_=parseInt("0755",8),ie=class r{static unmarshal(e){let t=Mn.decode(e),n=new r({type:g_[t.Type!=null?t.Type.toString():"File"],data:t.Data,blockSizes:t.blocksizes,mode:t.mode,mtime:t.mtime!=null?{secs:t.mtime.Seconds??0n,nsecs:t.mtime.FractionalNanoseconds}:void 0,fanout:t.fanout});return n._originalMode=t.mode??0,n}type;data;blockSizes;hashType;fanout;mtime;_mode;_originalMode;constructor(e={type:"file"}){let{type:t,data:n,blockSizes:o,hashType:i,fanout:s,mtime:a,mode:c}=e;if(t!=null&&!Object.values(g_).includes(t))throw new Wu("Type: "+t+" is not valid");this.type=t??"file",this.data=n,this.hashType=i,this.fanout=s,this.blockSizes=o??[],this._originalMode=0,this.mode=c,this.mtime=a}set mode(e){e==null?this._mode=this.isDirectory()?w_:y_:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return IU.includes(this.type)}addBlockSize(e){this.blockSizes.push(e)}removeBlockSize(e){this.blockSizes.splice(e,1)}fileSize(){if(this.isDirectory())return 0n;let e=0n;return this.blockSizes.forEach(t=>{e+=t}),this.data!=null&&(e+=BigInt(this.data.length)),e}marshal(){let e;switch(this.type){case"raw":e=Mn.DataType.Raw;break;case"directory":e=Mn.DataType.Directory;break;case"file":e=Mn.DataType.File;break;case"metadata":e=Mn.DataType.Metadata;break;case"symlink":e=Mn.DataType.Symlink;break;case"hamt-sharded-directory":e=Mn.DataType.HAMTShard;break;default:throw new Wu(`Type: ${e} is not valid`)}let t=this.data;(this.data==null||this.data.length===0)&&(t=void 0);let n;this.mode!=null&&(n=this._originalMode&4294963200|(this.mode??0),n===y_&&!this.isDirectory()&&(n=void 0),n===w_&&this.isDirectory()&&(n=void 0));let o;return this.mtime!=null&&(o={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),Mn.encode({Type:e,Data:t,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:n,mtime:o})}};var s2=xt(E_(),1);function TU(r){let e=new Array(4);for(let t=0;t<4;t++)e[t]=r&255,r=r>>8;return new Uint8Array(e)}var wwe=ji({name:"murmur3-32",code:35,encode:r=>TU(s2.default.x86.hash32(r))}),ea=ji({name:"murmur3-128",code:34,encode:r=>Xi.fromHex(s2.default.x64.hash128(r))}),bwe=ji({name:"murmur3-x64-64",code:34,encode:r=>Xi.fromHex(s2.default.x64.hash128(r)).subarray(0,8)});var A_=xt(a2(),1);var Yr=class r{_options;_popCount;_parent;_posAtParent;_children;key;constructor(e,t,n=0){this._options=e,this._popCount=0,this._parent=t,this._posAtParent=n,this._children=new A_.default,this.key=null}async put(e,t){let n=await this._findNewBucketAndPos(e);n.bucket._putAt(n,e,t)}async get(e){let t=await this._findChild(e);if(t!=null)return t.value}async del(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);n!=null&&n.key===e&&t.bucket._delAt(t.pos)}leafCount(){return this._children.compactArray().reduce((t,n)=>n instanceof r?t+n.leafCount():t+1,0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){let e=this._children.compactArray();for(let t of e)t instanceof r?yield*t.eachLeafSeries():yield t}serialize(e,t){let n=[];return t(this._children.reduce((o,i,s)=>(i!=null&&(i instanceof r?o.push(i.serialize(e,t)):o.push(e(i,s))),o),n))}async asyncTransform(e,t){return __(this,e,t)}toJSON(){return this.serialize(LU,DU)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);if(!(n instanceof r)&&n!=null&&n.key===e)return n}async _findPlace(e){let t=this._options.hash(typeof e=="string"?C(e):e),n=await t.take(this._options.bits),o=this._children.get(n);return o instanceof r?o._findPlace(t):{bucket:this,pos:n,hash:t,existingChild:o}}async _findNewBucketAndPos(e){let t=await this._findPlace(e);if(t.existingChild!=null&&t.existingChild.key!==e){let n=new r(this._options,t.bucket,t.pos);t.bucket._putObjectAt(t.pos,n);let o=await n._findPlace(t.existingChild.hash);return o.bucket._putAt(o,t.existingChild.key,t.existingChild.value),n._findNewBucketAndPos(t.hash)}return t}_putAt(e,t,n){this._putObjectAt(e.pos,{key:t,value:n,hash:e.hash})}_putObjectAt(e,t){this._children.get(e)==null&&this._popCount++,this._children.set(e,t)}_delAt(e){if(e===-1)throw new Error("Invalid position");this._children.get(e)!=null&&this._popCount--,this._children.unset(e),this._level()}_level(){if(this._parent!=null&&this._popCount<=1)if(this._popCount===1){let e=this._children.find(RU);if(e!=null&&!(e instanceof r)){let t=e.hash;t.untake(this._options.bits);let n={pos:this._posAtParent,hash:t,bucket:this._parent};this._parent._putAt(n,e.key,e.value)}}else this._parent._delAt(this._posAtParent)}_at(e){return this._children.get(e)}};function RU(r){return!!r}function LU(r,e){return r.key}function DU(r){return r}async function __(r,e,t){let n=[];for(let o of r._children.compactArray())if(o instanceof Yr)await __(o,e,t);else{let i=await e(o);n.push({bitField:r._children.bitField(),children:i})}return t(n)}var NU=[255,254,252,248,240,224,192,128],OU=[1,3,7,15,31,63,127,255],c2=class{_value;_currentBytePos;_currentBitPos;constructor(e){this._value=e,this._currentBytePos=e.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(e){let t=e,n=0;for(;t>0&&this._haveBits();){let o=this._value[this._currentBytePos],i=this._currentBitPos+1,s=Math.min(i,t),a=BU(o,i-s,s);n=(n<<s)+a,t-=s,this._currentBitPos-=s,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return n}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function BU(r,e,t){let n=MU(e,t);return(r&n)>>>e}function MU(r,e){return NU[r]&OU[Math.min(e+r-1,7)]}function I_(r){function e(t){return t instanceof l2?t:new l2(t,r)}return e}var l2=class{_value;_hashFn;_depth;_availableBits;_currentBufferIndex;_buffers;constructor(e,t){if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=t,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let t=e;for(;this._availableBits<t;)await this._produceMoreBits();let n=0;for(;t>0;){let o=this._buffers[this._currentBufferIndex],i=Math.min(o.availableBits(),t),s=o.take(i);n=(n<<i)+s,t-=i,this._availableBits-=i,o.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let t=e;for(;t>0;){let n=this._buffers[this._currentBufferIndex],o=Math.min(n.totalBits()-n.availableBits(),t);n.untake(o),t-=o,this._availableBits+=o,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?ge([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new c2(t);this._buffers.push(n),this._availableBits+=n.availableBits()}};function Bc(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:I_(r.hashFn)};return new Yr(e)}var UU=async function(r){return(await ea.encode(r)).slice(0,8).reverse()},FU=async(r,e,t)=>{let n=(e.tableSize()-1).toString(16).length;await Promise.all(r.map(async o=>{if(o.Name==null)throw new Error("Unexpected Link without a Name");if(o.Name.length===n){let i=parseInt(o.Name,16);e._putObjectAt(i,new Yr({hash:t._options.hash,bits:t._options.bits},e,i));return}await t.put(o.Name.substring(2),!0)}))},T_=(r,e)=>r.toString(16).toUpperCase().padStart(e,"0").substring(0,e),HU=r=>{let e=r.bucket,t=[];for(;e._parent!=null;)t.push(e),e=e._parent;return t.push(e),t.reverse()},k_=async(r,e,t,n,o)=>{if(n==null){if(r.Data==null)throw new Ct("no data in PBNode");let d;try{d=ie.unmarshal(r.Data)}catch(f){throw new Ct(f.message)}if(d.type!=="hamt-sharded-directory")throw new Ct("not a HAMT");if(d.fanout==null)throw new Ct("missing fanout");let h=Bc({hashFn:UU,bits:Math.log2(Number(d.fanout))});n={rootBucket:h,hamtDepth:1,lastBucket:h}}let i=(n.lastBucket.tableSize()-1).toString(16).length;await FU(r.Links,n.lastBucket,n.rootBucket);let s=await n.rootBucket._findNewBucketAndPos(e),a=T_(s.pos,i),c=HU(s);c.length>n.hamtDepth&&(n.lastBucket=c[n.hamtDepth],a=T_(n.lastBucket._posAtParent,i));let l=r.Links.find(d=>{if(d.Name==null)return!1;let h=d.Name.substring(0,i),f=d.Name.substring(i);return!(h!==a||f!==""&&f!==e)});if(l==null)return;if(l.Name!=null&&l.Name.substring(i)===e)return l.Hash;n.hamtDepth++;let u=await t.get(l.Hash,o);return r=yt(u),k_(r,e,t,n,o)},C_=k_;var VU=(r,e,t,n,o,i,s)=>{async function*a(c={}){let l=c.offset??0,u=c.length??e.Links.length,d=e.Links.slice(l,u);c.onProgress?.(new M("unixfs:exporter:walk:directory",{cid:r})),yield*Pe(d,h=>Je(h,f=>async()=>{let p=f.Name??"",m=`${n}/${p}`;return(await o(f.Hash,p,m,[],i+1,s,c)).entry}),h=>qt(h,{ordered:!0,concurrency:c.blockReadConcurrency}),h=>$r(h,f=>f!=null))}return a},P_=VU;async function R_(r,e,t,n,o,i,s){if(e instanceof Uint8Array){let l=Js(e,n,o,i);t.push(l);return}if(e.Data==null)throw new Ct("no data in PBNode");let a;try{a=ie.unmarshal(e.Data)}catch(l){throw new Ct(l.message)}if(a.data!=null){let l=a.data,u=Js(l,n,o,i);t.push(u),n+=BigInt(u.byteLength)}let c=[];if(e.Links.length!==a.blockSizes.length)throw new Ct("Inconsistent block sizes and dag links");for(let l=0;l<e.Links.length;l++){let u=e.Links[l],d=n,h=d+a.blockSizes[l];if((o>=d&&o<h||i>=d&&i<=h||o<d&&i>h)&&c.push({link:u,blockStart:n}),n=h,n>i)break}await Pe(c,l=>Je(l,u=>async()=>{let d=await r.get(u.link.Hash,s);return{...u,block:d}}),l=>qt(l,{ordered:!0,concurrency:s.blockReadConcurrency}),async l=>{for await(let{link:u,block:d,blockStart:h}of l){let f;switch(u.Hash.code){case Le:f=yt(d);break;case $e:f=d;break;default:t.end(new Ct(`Unsupported codec: ${u.Hash.code}`));return}let p=new Cr({concurrency:1});p.on("error",m=>{t.end(m)}),p.add(async()=>{s.onProgress?.(new M("unixfs:exporter:walk:file",{cid:u.Hash})),await R_(r,f,t,h,o,i,s)}),await p.onIdle()}}),n>=i&&t.end()}var $U=(r,e,t,n,o,i,s)=>{async function*a(c={}){let l=t.fileSize();if(l===void 0)throw new Error("File was a directory");let{start:u,end:d}=Oc(l,c.offset,c.length);if(d===0n)return;let h=0n,f=d-u,p=Pt();c.onProgress?.(new M("unixfs:exporter:walk:file",{cid:r})),R_(s,e,p,0n,u,d,c).catch(m=>{p.end(m)});for await(let m of p)if(m!=null){if(h+=BigInt(m.byteLength),h>f)throw p.end(),new t2("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect");h===f&&p.end(),c.onProgress?.(new M("unixfs:exporter:progress:unixfs:file",{bytesRead:h,totalBytes:f,fileSize:l})),yield m}if(h<f)throw new r2("Traversed entire DAG but did not read enough bytes")}return a},I5=$U;var zU=(r,e,t,n,o,i,s)=>{function a(c={}){return c.onProgress?.(new M("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),L_(e,n,o,i,s,c)}return a};async function*L_(r,e,t,n,o,i){let s=r.Links;if(r.Data==null)throw new Ct("no data in PBNode");let a;try{a=ie.unmarshal(r.Data)}catch(u){throw new Ct(u.message)}if(a.fanout==null)throw new Ct("missing fanout");let c=(a.fanout-1n).toString(16).length,l=Pe(s,u=>Je(u,d=>async()=>{let h=d.Name!=null?d.Name.substring(c):null;if(h!=null&&h!==""){let f=await t(d.Hash,h,`${e}/${h}`,[],n+1,o,i);return{entries:f.entry==null?[]:[f.entry]}}else{let f=await o.get(d.Hash,i);return r=yt(f),i.onProgress?.(new M("unixfs:exporter:walk:hamt-sharded-directory",{cid:d.Hash})),{entries:L_(r,e,t,n,o,i)}}}),u=>qt(u,{ordered:!0,concurrency:i.blockReadConcurrency}));for await(let{entries:u}of l)yield*u}var D_=zU;var KU=(r,e)=>r.Links.find(n=>n.Name===e)?.Hash,qU={raw:I5,file:I5,directory:P_,"hamt-sharded-directory":D_,metadata:(r,e,t,n,o,i,s)=>()=>[],symlink:(r,e,t,n,o,i,s)=>()=>[]},GU=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=yt(c),u,d;if(e==null&&(e=r.toString()),l.Data==null)throw new Ct("no data in PBNode");try{u=ie.unmarshal(l.Data)}catch(f){throw new Ct(f.message)}if(t==null&&(t=e),n.length>0){let f;if(u?.type==="hamt-sharded-directory"?f=await C_(l,n[0],s):f=KU(l,n[0]),f==null)throw new fn("file does not exist");let p=n.shift(),m=`${t}/${p}`;d={cid:f,toResolve:n,name:p??"",path:m}}let h=qU[u.type](r,l,u,t,o,i,s);if(h==null)throw new fn("could not find content exporter");return u.isDirectory()?{entry:{type:"directory",name:e,path:t,cid:r,content:h,unixfs:u,depth:i,node:l,size:u.fileSize()},next:d}:{entry:{type:"file",name:e,path:t,cid:r,content:h,unixfs:u,depth:i,node:l,size:u.fileSize()},next:d}},N_=GU;var WU={[Le]:N_,[$e]:p_,[Pr]:u_,[Jn]:d_,[vt.code]:f_,[qn]:h_},O_=async(r,e,t,n,o,i,s)=>{let a=WU[r.code];if(a==null)throw new e2(`No resolver for code ${r.code}`);return a(r,e,t,n,O_,o,i,s)},B_=O_;var YU=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),XU=r=>{if(r instanceof Uint8Array)return{cid:O.decode(r),toResolve:[]};let e=O.asCID(r);if(e!=null)return{cid:e,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let t=YU(r);return{cid:O.parse(t[0]),toResolve:t.slice(1)}}throw new Jm(`Unknown path type ${r}`)};async function*Xu(r,e,t={}){let{cid:n,toResolve:o}=XU(r),i=n.toString(),s=i,a=o.length;for(;;){let c=await B_(n,i,s,o,a,e,t);if(c.entry==null&&c.next==null)throw new fn(`Could not resolve ${r}`);if(c.entry!=null&&(yield c.entry),c.next==null)return;o=c.next.toResolve,n=c.next.cid,i=c.next.name,s=c.next.path}}async function _t(r,e,t={}){let n=await Mi(Xu(r,e,t));if(n==null)throw new fn(`Could not resolve ${r}`);return n}async function*Mc(r,e,t={}){let n=await _t(r,e,t);if(n==null)return;if(yield n,n.type==="directory")for await(let i of o(n,t))yield i;async function*o(i,s){for await(let a of i.content(s))yield a,!(a instanceof Uint8Array)&&a.type==="directory"&&(yield*o(a,s))}}async function QU(r,e,t){let n=[],o;for await(let i of Xu(e,r,t))n.push(i.cid),o=i;if(o==null)throw new Lc("No terminal element found");return{ipfsRoots:n,terminalElement:o}}function T5(r){return r.type==="object"}async function M_({cid:r,path:e,resource:t,options:n,blockstore:o,log:i}){try{return await QU(o,`${r.toString()}/${e}`,n)}catch(s){return n?.signal?.throwIfAborted(),["ERR_NO_PROP","ERR_NO_TERMINAL_ELEMENT","ERR_NOT_FOUND"].includes(s.code)?Gm(t):(i.error("error walking path %s",e,s),Rc(t,"Error walking path"))}}var u2=class extends dt{codes=[Pr];canHandle({cid:e,accept:t,pathDetails:n}){return this.log("checking if we can handle %c with accept %s",e,t),n==null||!T5(n.terminalElement)||e.code!==Pr?!1:T5(n.terminalElement)}async handle(e){let{cid:t,path:n,resource:o,accept:i,pathDetails:s}=e;if(this.log.trace("fetching %c/%s",t,n),s==null)throw new Error("pathDetails is null");let a=s.ipfsRoots,l=s.terminalElement.node,u;if(i==="application/octet-stream"||i==="application/vnd.ipld.dag-cbor"||i==="application/cbor")u=l;else if(i==="application/vnd.ipld.dag-json")try{let f=mi(l);u=Rh(f)}catch(f){return this.log.error("could not transform %c to application/vnd.ipld.dag-json",f),Ho(o)}else try{u=a_(l)}catch(f){if(i==="application/json")return this.log('could not decode DAG-CBOR as JSON-safe, but the client sent "Accept: application/json"',f),Ho(o);this.log("could not decode DAG-CBOR as JSON-safe, falling back to `application/octet-stream`",f),u=l}let d=On(o,u),h=i??(u instanceof Uint8Array?"application/octet-stream":"application/json");return d.headers.set("content-type",h),jm(d,a),d}};function jU(r){return r[Symbol.asyncIterator]!=null}function ZU(r,e=1){return e=Number(e),jU(r)?async function*(){let t=[];if(e<1&&(e=1),e!==Math.round(e))throw new Error("Batch size must be an integer");for await(let n of r)for(t.push(n);t.length>=e;)yield t.slice(0,e),t=t.slice(e);for(;t.length>0;)yield t.slice(0,e),t=t.slice(e)}():function*(){let t=[];if(e<1&&(e=1),e!==Math.round(e))throw new Error("Batch size must be an integer");for(let n of r)for(t.push(n);t.length>=e;)yield t.slice(0,e),t=t.slice(e);for(;t.length>0;)yield t.slice(0,e),t=t.slice(e)}()}var d2=ZU;async function*Qu(r,e=1){for await(let t of d2(r,e)){let n=t.map(async o=>o().then(i=>({ok:!0,value:i}),i=>({ok:!1,err:i})));for(let o=0;o<n.length;o++){let i=await n[o];if(i.ok)yield i.value;else throw i.err}}}var JU=262144,ju=(r={})=>{let e=r.chunkSize??JU;return async function*(n){let o=new Z,i=0,s=!1;for await(let a of n)for(o.append(a),i+=a.length;i>=e;)if(yield o.slice(0,e),s=!0,e===o.length)o=new Z,i=0;else{let c=new Z;c.append(o.sublist(e)),o=c,i-=e}(!s||i>0)&&(yield o.subarray(0,i))}};var Un=async(r,e,t)=>{t.codec==null&&(t.codec=wt);let n=await ve.digest(r),o=O.create(t.cidVersion,t.codec.code,n);return await e.put(o,r,t),o};function U_(r){return async function*(t,n){let o=0n;for await(let i of t.content)yield async()=>{let s,a={codec:wt,cidVersion:r.cidVersion,onProgress:r.onProgress};r.rawLeaves?(a.codec=Sr,a.cidVersion=1):(s=new ie({type:r.leafType,data:i}),i=_e({Data:s.marshal(),Links:[]}));let c=await Un(i,n,a);return o+=BigInt(i.byteLength),r.onProgress?.(new M("unixfs:importer:progress:file:write",{bytesWritten:o,cid:c,path:t.path})),{cid:c,unixfs:s,size:BigInt(i.length),block:i}}}}var Zu=class r extends Error{static name="InvalidParametersError";static code="ERR_INVALID_PARAMS";name=r.name;code=r.code;constructor(e="Invalid parameters"){super(e)}};var Ui=class r extends Error{static name="InvalidContentError";static code="ERR_INVALID_CONTENT";name=r.name;code=r.code;constructor(e="Invalid content"){super(e)}};var F_=async(r,e,t)=>{let n=new ie({type:"directory",mtime:r.mtime,mode:r.mode}),o=_e(ct({Data:n.marshal()})),i=await Un(o,e,t),s=r.path;return{cid:i,path:s,unixfs:n,size:BigInt(o.length),originalPath:r.originalPath,block:o}};async function*eF(r,e,t){let n=-1,o;for await(let i of Qu(t.bufferImporter(r,e),t.blockWriteConcurrency)){if(n++,n===0){o={...i,single:!0};continue}else n===1&&o!=null&&(yield{...o,block:void 0,single:void 0},o=void 0);yield{...i,block:void 0}}o!=null&&(yield o)}function H_(r){return r.single===!0}var tF=(r,e,t)=>async function(o){if(o.length===1&&H_(o[0])&&t.reduceSingleLeafToSelf){let u=o[0],d=u.block;return H_(u)&&(r.mtime!==void 0||r.mode!==void 0)&&(u.unixfs=new ie({type:"file",mtime:r.mtime,mode:r.mode,data:u.block}),d={Data:u.unixfs.marshal(),Links:[]},u.block=_e(ct(d)),u.cid=await Un(u.block,e,{...t,cidVersion:t.cidVersion}),u.size=BigInt(u.block.length)),t.onProgress?.(new M("unixfs:importer:progress:file:layout",{cid:u.cid,path:u.originalPath})),{cid:u.cid,path:r.path,unixfs:u.unixfs,size:u.size,originalPath:u.originalPath}}let i=new ie({type:"file",mtime:r.mtime,mode:r.mode}),s=o.filter(u=>u.cid.code===$e&&u.size>0||u.unixfs!=null&&u.unixfs.data==null&&u.unixfs.fileSize()>0n?!0:!!u.unixfs?.data?.length).map(u=>u.cid.code===$e?(i.addBlockSize(u.size),{Name:"",Tsize:Number(u.size),Hash:u.cid}):(u.unixfs?.data==null?i.addBlockSize(u.unixfs?.fileSize()??0n):i.addBlockSize(BigInt(u.unixfs.data.length)),{Name:"",Tsize:Number(u.size),Hash:u.cid})),a={Data:i.marshal(),Links:s},c=_e(ct(a)),l=await Un(c,e,t);return t.onProgress?.(new M("unixfs:importer:progress:file:layout",{cid:l,path:r.originalPath})),{cid:l,path:r.path,unixfs:i,size:BigInt(c.length+a.Links.reduce((u,d)=>u+(d.Tsize??0),0)),originalPath:r.originalPath,block:c}},V_=async(r,e,t)=>t.layout(eF(r,e,t),tF(r,e,t));function rF(r){return Symbol.iterator in r}function nF(r){return Symbol.asyncIterator in r}function oF(r){try{if(r instanceof Uint8Array)return async function*(){yield r}();if(rF(r))return async function*(){yield*r}();if(nF(r))return r}catch{throw new Ui("Content was invalid")}throw new Ui("Content was invalid")}function $_(r){return async function*(t,n){for await(let o of t){let i;if(o.path!=null&&(i=o.path,o.path=o.path.split("/").filter(s=>s!=null&&s!==".").join("/")),iF(o)){let s={path:o.path,mtime:o.mtime,mode:o.mode,content:async function*(){let a=0n;for await(let c of r.chunker(r.chunkValidator(oF(o.content)))){let l=BigInt(c.byteLength);a+=l,r.onProgress?.(new M("unixfs:importer:progress:file:read",{bytesRead:a,chunkSize:l,path:o.path})),yield c}}(),originalPath:i};yield async()=>V_(s,n,r)}else if(o.path!=null){let s={path:o.path,mtime:o.mtime,mode:o.mode,originalPath:i};yield async()=>F_(s,n,r)}else throw new Error("Import candidate must have content or path or both")}}}function iF(r){return r.content!=null}var z_=()=>async function*(e){for await(let t of e){if(t.length===void 0)throw new Ui("Content was invalid");if(typeof t=="string"||t instanceof String)yield C(t.toString());else if(Array.isArray(t))yield Uint8Array.from(t);else if(t instanceof Uint8Array)yield t;else throw new Ui("Content was invalid")}};var sF=174;function Ju(r){let e=r?.maxChildrenPerNode??sF;return async function t(n,o){let i=[];for await(let s of d2(n,e))i.push(await o(s));return i.length>1?t(i,o):i[0]}}var ro=class{options;root;dir;path;dirty;flat;parent;parentKey;unixfs;mode;mtime;cid;size;nodeSize;constructor(e,t){this.options=t??{},this.root=e.root,this.dir=e.dir,this.path=e.path,this.dirty=e.dirty,this.flat=e.flat,this.parent=e.parent,this.parentKey=e.parentKey,this.unixfs=e.unixfs,this.mode=e.mode,this.mtime=e.mtime}},ed=O.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),td=O.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi");var ta=class extends ro{_children;constructor(e,t){super(e,t),this._children=new Map}async put(e,t){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,this._children.set(e,t)}async get(e){return Promise.resolve(this._children.get(e))}childCount(){return this._children.size}directChildrenCount(){return this.childCount()}onlyChild(){return this._children.values().next().value}async*eachChildSeries(){for(let[e,t]of this._children.entries())yield{key:e,child:t}}estimateNodeSize(){if(this.nodeSize!==void 0)return this.nodeSize;this.nodeSize=0;for(let[e,t]of this._children.entries())t.size!=null&&t.cid!=null&&(this.nodeSize+=e.length+(this.options.cidVersion===1?td.bytes.byteLength:ed.bytes.byteLength));return this.nodeSize}async*flush(e){let t=[];for(let[c,l]of this._children.entries()){let u=l;if(l instanceof ro)for await(let d of l.flush(e))u=d,yield d;u.size!=null&&u.cid!=null&&t.push({Name:c,Tsize:Number(u.size),Hash:u.cid})}let n=new ie({type:"directory",mtime:this.mtime,mode:this.mode}),o={Data:n.marshal(),Links:t},i=_e(ct(o)),s=await Un(i,e,this.options),a=i.length+o.Links.reduce((c,l)=>c+(l.Tsize??0),0);this.cid=s,this.size=a,yield{cid:s,unixfs:n,path:this.path,size:BigInt(a)}}};async function aF(r){return(await ea.encode(r)).slice(0,8).reverse()}var K_=BigInt(34),cF=8,k5=class extends ro{_bucket;constructor(e,t){super(e,t),this._bucket=Bc({hashFn:aF,bits:t.shardFanoutBits??cF})}async put(e,t){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,await this._bucket.put(e,t)}async get(e){return this._bucket.get(e)}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}async*eachChildSeries(){for await(let{key:e,value:t}of this._bucket.eachLeafSeries())yield{key:e,child:t}}estimateNodeSize(){return this.nodeSize!==void 0?this.nodeSize:(this.nodeSize=W_(this._bucket,this,this.options),this.nodeSize)}async*flush(e){for await(let t of G_(this._bucket,e,this,this.options))yield{...t,path:this.path}}},q_=k5;async function*G_(r,e,t,n){let o=r._children,i=(r.tableSize()-1).toString(16).length,s=[],a=0n;for(let p=0;p<o.length;p++){let m=o.get(p);if(m==null)continue;let g=p.toString(16).toUpperCase().padStart(i,"0");if(m instanceof Yr){let y;for await(let w of G_(m,e,null,n))y=w;if(y==null)throw new Error("Could not flush sharded directory, no subshard found");s.push({Name:g,Tsize:Number(y.size),Hash:y.cid}),a+=y.size}else if(lF(m.value)){let y=m.value,w;for await(let x of y.flush(e))w=x,yield w;if(w==null)throw new Error("Did not flush dir");let b=g+m.key;s.push({Name:b,Tsize:Number(w.size),Hash:w.cid}),a+=w.size}else{let y=m.value;if(y.cid==null)continue;let w=g+m.key,b=y.size;s.push({Name:w,Tsize:Number(b),Hash:y.cid}),a+=BigInt(b??0)}}let c=Uint8Array.from(o.bitField().reverse()),l=new ie({type:"hamt-sharded-directory",data:c,fanout:BigInt(r.tableSize()),hashType:K_,mtime:t?.mtime,mode:t?.mode}),u={Data:l.marshal(),Links:s},d=_e(ct(u)),h=await Un(d,e,n),f=BigInt(d.byteLength)+a;yield{cid:h,unixfs:l,size:f}}function lF(r){return typeof r.flush=="function"}function W_(r,e,t){let n=r._children,o=(r.tableSize()-1).toString(16).length,i=[];for(let l=0;l<n.length;l++){let u=n.get(l);if(u==null)continue;let d=l.toString(16).toUpperCase().padStart(o,"0");if(u instanceof Yr){let h=W_(u,null,t);i.push({Name:d,Tsize:Number(h),Hash:t.cidVersion===0?ed:td})}else if(typeof u.value.flush=="function"){let f=u.value.nodeSize();i.push({Name:d+u.key,Tsize:Number(f),Hash:t.cidVersion===0?ed:td})}else{let h=u.value;if(h.cid==null)continue;let f=d+u.key,p=h.size;i.push({Name:f,Tsize:Number(p),Hash:h.cid})}}let s=Uint8Array.from(n.bitField().reverse()),a=new ie({type:"hamt-sharded-directory",data:s,fanout:BigInt(r.tableSize()),hashType:K_,mtime:e?.mtime,mode:e?.mode});return _e(ct({Data:a.marshal(),Links:i})).length}async function C5(r,e,t,n){let o=e;e instanceof ta&&e.estimateNodeSize()>t&&(o=await uF(e,n));let i=o.parent;if(i!=null){if(o!==e){if(r!=null&&(r.parent=o),o.parentKey==null)throw new Error("No parent key found");await i.put(o.parentKey,o)}return C5(o,i,t,n)}return o}async function uF(r,e){let t=new q_({root:r.root,dir:!0,parent:r.parent,parentKey:r.parentKey,path:r.path,dirty:r.dirty,flat:!1,mtime:r.mtime,mode:r.mode},e);for await(let{key:n,child:o}of r.eachChildSeries())await t.put(n,o);return t}var Y_=(r="")=>r.split(/(?<!\\)\//).filter(Boolean);async function dF(r,e,t){let n=Y_(r.path??""),o=n.length-1,i=e,s="";for(let a=0;a<n.length;a++){let c=n[a];s+=`${s!==""?"/":""}${c}`;let l=a===o;if(i.dirty=!0,i.cid=void 0,i.size=void 0,l)await i.put(c,r),e=await C5(null,i,t.shardSplitThresholdBytes,t);else{let u=await i.get(c);(u==null||!(u instanceof ro))&&(u=new ta({root:!1,dir:!0,parent:i,parentKey:c,path:s,dirty:!0,flat:!0,mtime:u?.unixfs?.mtime,mode:u?.unixfs?.mode},t)),await i.put(c,u),i=u}}return e}async function*X_(r,e){if(!(r instanceof ro)){r.unixfs?.isDirectory()===!0&&(yield r);return}yield*r.flush(e)}function Q_(r){return async function*(t,n){let o=new ta({root:!0,dir:!0,path:"",dirty:!0,flat:!0},r),i,s=!1;for await(let a of t){if(a==null)continue;let c=`${a.originalPath??""}`.split("/")[0];c!=null&&c!==""&&(i==null?(i=c,s=!0):i!==c&&(s=!1)),o=await dF(a,o,r),a.unixfs?.isDirectory()!==!0&&(yield a)}if(r.wrapWithDirectory||s&&o.childCount()>1)yield*X_(o,n);else for await(let a of o.eachChildSeries())a!=null&&(yield*X_(a.child,n))}}async function*Fi(r,e,t={}){let n;Symbol.asyncIterator in r||Symbol.iterator in r?n=r:n=[r];let o=t.wrapWithDirectory??!1,i=t.shardSplitThresholdBytes??262144,s=t.shardFanoutBits??8,a=t.cidVersion??1,c=t.rawLeaves??!0,l=t.leafType??"file",u=t.fileImportConcurrency??50,d=t.blockWriteConcurrency??10,h=t.reduceSingleLeafToSelf??!0,f=t.chunker??ju(),p=t.chunkValidator??z_(),m=t.dagBuilder??$_({chunker:f,chunkValidator:p,wrapWithDirectory:o,layout:t.layout??Ju(),bufferImporter:t.bufferImporter??U_({cidVersion:a,rawLeaves:c,leafType:l,onProgress:t.onProgress}),blockWriteConcurrency:d,reduceSingleLeafToSelf:h,cidVersion:a,onProgress:t.onProgress}),g=t.treeBuilder??Q_({wrapWithDirectory:o,shardSplitThresholdBytes:i,shardFanoutBits:s,cidVersion:a,onProgress:t.onProgress});for await(let y of g(Qu(m(n,e),u),e))yield{cid:y.cid,path:y.path,unixfs:y.unixfs,size:y.size}}async function f2(r,e,t={}){let n=await nu(Fi([r],e,t));if(n==null)throw new Zu("Nothing imported");return n}async function j_(r,e,t={}){let n=await nu(Fi([r],e,t));if(n==null)throw new Zu("Nothing imported");return n}async function Z_(r,e,t={}){return f2({content:r},e,t)}async function J_(r,e,t={}){return f2({content:r},e,t)}var rd={cidVersion:1,rawLeaves:!0,layout:Ju({maxChildrenPerNode:1024}),chunker:ju({chunkSize:1048576})};async function*eI(r,e,t={}){yield*Fi(r,e,{...rd,...t})}async function tI(r,e,t={}){let{cid:n}=await Z_(r,e,{...rd,...t});return n}async function rI(r,e,t={}){let{cid:n}=await J_(r,e,{...rd,...t});return n}async function nI(r,e,t={}){let{cid:n}=await f2(r,e,{...rd,...t});return n}async function oI(r,e,t={}){let{cid:n}=await j_({...r,path:r.path??"-"},e,{...rd,...t});return n}var D5=xt(a2(),1);function p2(r){function e(t){return t instanceof h2?t:new h2(t,r)}return e}var h2=class{_value;_hashFn;_depth;_availableBits;_currentBufferIndex;_buffers;constructor(e,t){if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=t,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let t=e;for(;this._availableBits<t;)await this._produceMoreBits();let n=0;for(;t>0;){let o=this._buffers[this._currentBufferIndex],i=Math.min(o.availableBits(),t),s=o.take(i);n=(n<<i)+s,t-=i,this._availableBits-=i,o.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let t=e;for(;t>0;){let n=this._buffers[this._currentBufferIndex],o=Math.min(n.totalBits()-n.availableBits(),t);n.untake(o),t-=o,this._availableBits+=o,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?ge([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new P5(t);this._buffers.push(n),this._availableBits+=n.availableBits()}},fF=[255,254,252,248,240,224,192,128],hF=[1,3,7,15,31,63,127,255],P5=class{_value;_currentBytePos;_currentBitPos;constructor(e){this._value=e,this._currentBytePos=e.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(e){let t=e,n=0;for(;t>0&&this._haveBits();){let o=this._value[this._currentBytePos],i=this._currentBitPos+1,s=Math.min(i,t),a=pF(o,i-s,s);n=(n<<s)+a,t-=s,this._currentBitPos-=s,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return n}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function pF(r,e,t){let n=mF(e,t);return(r&n)>>>e}function mF(r,e){return fF[r]&hF[Math.min(e+r-1,7)]}var nd=BigInt(ea.code),ra=8;async function Uc(r){return(await ea.encode(r)).subarray(0,8).reverse()}var aI=xt(a2(),1);var Fn=async(r,e,t)=>{t.codec==null&&(t.codec=wt);let n=await ve.digest(r),o=O.create(t.cidVersion,t.codec.code,n);return await e.put(o,r,{...t,signal:t.signal}),o};var R5=class{options;root;dir;path;dirty;flat;parent;parentKey;unixfs;mode;mtime;cid;size;nodeSize;constructor(e,t){this.options=t??{},this.root=e.root,this.dir=e.dir,this.path=e.path,this.dirty=e.dirty,this.flat=e.flat,this.parent=e.parent,this.parentKey=e.parentKey,this.unixfs=e.unixfs,this.mode=e.mode,this.mtime=e.mtime}},m2=class extends R5{_bucket;constructor(e,t){super(e,t),this._bucket=Bc({hashFn:Uc,bits:8})}async put(e,t){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,await this._bucket.put(e,t)}async get(e){return this._bucket.get(e)}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}async*eachChildSeries(){for await(let{key:e,value:t}of this._bucket.eachLeafSeries())yield{key:e,child:t}}estimateNodeSize(){return this.nodeSize!==void 0?this.nodeSize:(this.nodeSize=sI(this._bucket,this,this.options),this.nodeSize)}async*flush(e){for await(let t of iI(this._bucket,e,this,this.options))yield{...t,path:this.path}}};async function*iI(r,e,t,n){let o=r._children,i=[],s=0n;for(let f=0;f<o.length;f++){let p=o.get(f);if(p==null)continue;let m=f.toString(16).toUpperCase().padStart(2,"0");if(p instanceof Yr){let g;for await(let y of iI(p,e,null,n))g=y;if(g==null)throw new Error("Could not flush sharded directory, no subshard found");i.push({Name:m,Tsize:Number(g.size),Hash:g.cid}),s+=g.size}else if(gF(p.value)){let g=p.value,y;for await(let b of g.flush(e))y=b,yield y;if(y==null)throw new Error("Did not flush dir");let w=m+p.key;i.push({Name:w,Tsize:Number(y.size),Hash:y.cid}),s+=y.size}else{let g=p.value;if(g.cid==null)continue;let y=m+p.key,w=g.size;i.push({Name:y,Tsize:Number(w),Hash:g.cid}),s+=BigInt(w??0)}}let a=Uint8Array.from(o.bitField().reverse()),c=new ie({type:"hamt-sharded-directory",data:a,fanout:BigInt(r.tableSize()),hashType:nd,mtime:t?.mtime,mode:t?.mode}),l={Data:c.marshal(),Links:i},u=_e(ct(l)),d=await Fn(u,e,n),h=BigInt(u.byteLength)+s;yield{cid:d,unixfs:c,size:h}}function gF(r){return typeof r.flush=="function"}function sI(r,e,t){let n=r._children,o=[];for(let c=0;c<n.length;c++){let l=n.get(c);if(l==null)continue;let u=c.toString(16).toUpperCase().padStart(2,"0");if(l instanceof Yr){let d=sI(l,null,t);o.push({Name:u,Tsize:Number(d),Hash:t.cidVersion===0?g2:y2})}else if(typeof l.value.flush=="function"){let h=l.value.nodeSize();o.push({Name:u+l.key,Tsize:Number(h),Hash:t.cidVersion===0?g2:y2})}else{let d=l.value;if(d.cid==null)continue;let h=u+l.key,f=d.size;o.push({Name:h,Tsize:Number(f),Hash:d.cid})}}let i=Uint8Array.from(n.bitField().reverse()),s=new ie({type:"hamt-sharded-directory",data:i,fanout:BigInt(r.tableSize()),hashType:nd,mtime:e?.mtime,mode:e?.mode});return _e(ct({Data:s.marshal(),Links:o})).length}var g2=O.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),y2=O.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi");var L5=xe("helia:unixfs:commands:utils:hamt-utils"),w2=r=>r.toString(16).toUpperCase().padStart(2,"0").substring(0,2),cI=async(r,e,t)=>{let n=new m2({root:!0,dir:!0,parent:void 0,parentKey:void 0,path:"",dirty:!0,flat:!1,mtime:t.mtime,mode:t.mode},t);for(let i=0;i<e.length;i++)await n._bucket.put(e[i].name,{size:e[i].size,cid:e[i].cid});let o=await Mi(n.flush(r));if(o==null)throw new Error("Flushing shard yielded no result");return o},b2=async(r,e,t)=>{let n=ie.unmarshal(r[0].node.Data??new Uint8Array(0)),o=BigInt(Math.pow(2,ra));r.reverse();let i,s;for(let a=0;a<r.length;a++){let c=a===r.length-1,l=r[a],u=Uint8Array.from(l.children.bitField().reverse()),d=new ie({type:"hamt-sharded-directory",data:u,fanout:o,hashType:nd});c&&(d.mtime=n.mtime,d.mode=n.mode),s={Data:d.marshal(),Links:l.node.Links};let h=_e(ct(s));if(i=await Fn(h,e,t),!c){let f=r[a+1];if(f==null)throw new Error("Was not operating on shard root but also had no parent?");L5("updating link in parent sub-shard with prefix %s",f.prefix),f.node.Links=f.node.Links.filter(p=>p.Name!==f.prefix),f.node.Links.push({Name:f.prefix,Hash:i,Tsize:l.node.Links.reduce((p,m)=>p+(m.Tsize??0),h.byteLength)})}}if(i==null||s==null)throw new Error("Noting persisted");return{cid:i,node:s}},x2=async(r,e,t,n)=>{let i=p2(Uc)(C(e)),s=[];for(;;){let a=await t.get(r,n),c=yt(a),l=new aI.default,u=await i.take(ra),d=w2(u);s.push({prefix:d,children:l,node:c});let h;for(let p of c.Links){let m=p.Name??"";if(m.length<2)throw new Error("Invalid HAMT - link name was too short");let g=parseInt(m.substring(0,2),16);l.set(g,!0),m.startsWith(d)&&(h=p)}if(h==null){L5("no link found with prefix %s for %s",d,e);break}let f=h.Name??"";if(f.length<2)throw new Error("Invalid HAMT - link name was too short");if(f.length===2){r=h.Hash,L5("descend into sub-shard with prefix %s",f);continue}break}return{path:s,hash:i}};async function E2(r,e,t,n){if(r.Data==null)throw new Error("DagPB node had no data");let o=ie.unmarshal(r.Data),i;if(o.type==="directory")i=yF(r);else if(o.type==="hamt-sharded-directory")i=await lI(r,0,t,e,n);else throw new Error("Can only estimate the size of directories or shards");return i>t}function yF(r){let e=0;for(let t of r.Links)e+=(t.Name??"").length,e+=t.Hash.version===1?y2.bytes.byteLength:g2.bytes.byteLength;return e}async function lI(r,e,t,n,o){if(e>t)return t;if(r.Data==null||!ie.unmarshal(r.Data).isDirectory())return e;for(let s of r.Links){let a=s.Name??"";if(a=a.substring(2),e+=a.length,e+=s.Hash.bytes.byteLength,s.Hash.code===Le){let c=await n.get(s.Hash,o),l=yt(c);e+=await lI(l,e,t,n,o)}}return e}var no=xe("helia:unixfs:components:utils:add-link");async function Fc(r,e,t,n){if(r.node.Data==null)throw new Wr("Invalid parent passed to addLink");if(ie.unmarshal(r.node.Data).type==="hamt-sharded-directory")return no("adding link to sharded directory"),xF(r,e,t,n);no(`adding ${e.Name} (${e.Hash}) to regular directory`);let i=await bF(r,e,t,n);if(await E2(i.node,t,n.shardSplitThresholdBytes,n)){no("converting directory to sharded directory");let s=await wF(i,t);i.cid=s.cid,i.node=yt(await t.get(s.cid,n))}return i}var wF=async(r,e)=>{if(r.node.Data==null)throw new Wr("Invalid parent passed to convertToShardedDirectory");let t=ie.unmarshal(r.node.Data),n=await cI(e,r.node.Links.map(o=>({name:o.Name??"",size:BigInt(o.Tsize??0),cid:o.Hash})),{mode:t.mode,mtime:t.mtime,cidVersion:r.cid.version});return no(`converted directory to sharded directory ${n.cid}`),n},bF=async(r,e,t,n)=>{let o=r.node.Links.filter(u=>{let d=u.Name===e.Name;if(d&&!n.allowOverwriting)throw new Gu;return!d});if(o.push(e),r.node.Data==null)throw new Er("Parent node with no data passed to addToDirectory");let i=ie.unmarshal(r.node.Data),s;if(i.mtime!=null){let u=Date.now(),d=Math.floor(u/1e3);i.mtime={secs:BigInt(d),nsecs:(u-d*1e3)*1e3},s=i.marshal()}else s=r.node.Data;r.node=ct({Data:s,Links:o});let a=_e(r.node),c=await ve.digest(a),l=O.create(r.cid.version,Le,c);return await t.put(l,a),{node:r.node,cid:l}},xF=async(r,e,t,n)=>{let{path:o,hash:i}=await x2(r.cid,e.Name,t,n),s=o[o.length-1];if(s==null)throw new Error("Invalid HAMT, could not generate path");let a=s.prefix,c=parseInt(a,16);no("next prefix for %s is %s",e.Name,a);let l=`${a}${e.Name}`,u=s.node.Links.find(d=>(d.Name??"").startsWith(a));if(u!=null)if(no("link %s was present in shard",l),u.Name===l){if(!n.allowOverwriting)throw new Gu;no("overwriting %s in subshard",e.Name),s.node.Links=s.node.Links.filter(d=>d.Name!==l),s.node.Links.push({Name:l,Hash:e.Hash,Tsize:e.Tsize})}else{if(u.Name?.length===2)throw new Error("Existing link was subshard?!");{no("prefix %s already exists, creating new subshard",a);let d=s.node.Links.findIndex(g=>g.Name?.startsWith(a)),h=s.node.Links.splice(d,1)[0],f=(h.Name??"").substring(2),m=p2(Uc)(C(f));for(let g=0;g<o.length;g++)await m.take(ra);for(;;){let g=await m.take(ra),y=w2(g);h.Name=`${y}${f}`;let w=await i.take(ra),b=w2(w);if(y===b){let A=new D5.default;A.set(w,!0),o.push({prefix:b,children:A,node:{Links:[]}});continue}let x=new D5.default;x.set(w,!0),x.set(g,!0),o.push({prefix:a,children:x,node:{Links:[h,{Name:`${b}${e.Name}`,Hash:e.Hash,Tsize:e.Tsize}]}});break}}}else no("link %s was not present in sub-shard",l),e.Name=l,s.node.Links.push(e),s.children.set(c,!0),no("adding %s to existing sub-shard",l);return b2(o,t,n)};async function Hi(r,e,t={}){let n=await _t(r,e,t);if(n.type!=="directory")throw new Bi(`${r.toString()} was not a UnixFS directory`);return{cid:r,node:n.node}}async function Hc(r,e,t,n){let o=await _t(r,t,n);if(o.type!=="directory"&&o.type!=="file"&&o.type!=="raw")throw new Gr(`${r.toString()} was not a UnixFS node`);return{Name:e,Tsize:o.node instanceof Uint8Array?o.node.byteLength:EF(o.node),Hash:r}}function EF(r){let e=r.Links.reduce((t,n)=>t+(n.Tsize??0),0);return _e(r).byteLength+e}var vF=xe("helia:unixfs:components:utils:resolve");async function oo(r,e,t,n){if(e==null||e==="")return{cid:r};let o=`/ipfs/${r}${e==null?"":`/${e}`}`,i=await Do(Xu(o,t,n));if(i.length===0)throw new Lc("Could not find path in directory");return vF("resolved %s to %c",e,r),{cid:i[i.length-1].cid,path:e,segments:i}}async function Vc(r,e,t,n){if(e.segments==null||e.segments.length===0)return r;let o=e.segments.pop();if(o==null)throw new Error("Insufficient segments");o.cid=r,e.segments.reverse();for(let i of e.segments){let[s,a]=await Promise.all([Hi(i.cid,t,n),Hc(o.cid,o.name,t,n)]);r=(await Fc(s,a,t,{...n,allowOverwriting:!0,cidVersion:r.version})).cid,i.cid=r,o=i}return r}var SF=ut.bind({ignoreUndefined:!0}),AF={};async function*uI(r,e,t={}){let n=SF(AF,t),o=await oo(r,n.path,e,n),i=await _t(o.cid,e,n);if(i.type!=="file"&&i.type!=="raw")throw new Zm;if(i.content==null)throw new Dc;yield*i.content(n)}var _F=ut.bind({ignoreUndefined:!0}),IF=xe("helia:unixfs:chmod"),TF={recursive:!1,shardSplitThresholdBytes:262144};async function dI(r,e,t,n={}){let o=_F(TF,n),i=await oo(r,o.path,t,n);if(IF("chmod %c %d",i.cid,e),o.recursive){let h=await Pe(async function*(){for await(let f of Mc(i.cid,t,n)){let p,m=[];if(f.type==="raw")p=new ie({type:"file",data:f.node});else if(f.type==="file"||f.type==="directory")p=f.unixfs,m=f.node.Links;else throw new Gr;p.mode=e;let g={Data:p.marshal(),Links:m};yield{path:f.path,content:g}}},f=>Fi(f,t,{...o,dagBuilder:async function*(p,m){for await(let g of p)yield async function(){let y=g.content,w=_e(y),b=await Fn(w,m,{...o,cidVersion:r.version});if(y.Data==null)throw new Er(`${b} had no data`);let x=ie.unmarshal(y.Data);return{cid:b,size:BigInt(w.length),path:g.path,unixfs:x}}}}),async f=>Mi(f));if(h==null)throw new Oi(`Could not chmod ${i.cid.toString()}`);return Vc(h.cid,i,t,o)}let s=await t.get(i.cid,n),a,c=[];if(i.cid.code===$e)a=new ie({type:"file",data:s});else{let h=yt(s);if(h.Data==null)throw new Er(`${i.cid.toString()} had no data`);c=h.Links,a=ie.unmarshal(h.Data)}a.mode=e;let l=_e({Data:a.marshal(),Links:c}),u=await ve.digest(l),d=O.create(i.cid.version,Le,u);return await t.put(d,l),Vc(d,i,t,o)}var kF=ut.bind({ignoreUndefined:!0}),CF=xe("helia:unixfs:cp"),PF={force:!1,shardSplitThresholdBytes:262144};async function fI(r,e,t,n,o={}){let i=kF(PF,o);if(t.includes("/"))throw new Wr("Name must not have slashes");let[s,a]=await Promise.all([Hi(e,n,i),Hc(r,t,n,i)]);return CF('Adding %c as "%s" to %c',r,t,e),(await Fc(s,a,n,{allowOverwriting:i.force,cidVersion:e.version,...i})).cid}var RF=ut.bind({ignoreUndefined:!0}),LF={};async function*hI(r,e,t={}){let n=RF(LF,t),o=await oo(r,n.path,e,n),i=await _t(o.cid,e);if(i.type==="file"||i.type==="raw"){yield i;return}if(i.content==null)throw new Dc;if(i.type!=="directory")throw new Bi;yield*i.content({offset:t.offset,length:t.length})}var DF=ut.bind({ignoreUndefined:!0}),pI=xe("helia:unixfs:mkdir"),NF={cidVersion:1,force:!1,shardSplitThresholdBytes:262144};async function mI(r,e,t,n={}){let o=DF(NF,n);if(e.includes("/"))throw new Wr("Path must not have slashes");if((await _t(r,t,n)).type!=="directory")throw new Bi(`${r.toString()} was not a UnixFS directory`);pI("creating %s",e);let a={Data:new ie({type:"directory",mode:o.mode,mtime:o.mtime}).marshal(),Links:[]},c=_e(a),l=await ve.digest(c),u=O.create(o.cidVersion,Le,l);await t.put(u,c);let[d,h]=await Promise.all([Hi(r,t,o),Hc(u,e,t,o)]);return pI("adding empty dir called %s to %c",e,r),(await Fc(d,h,t,{...o,allowOverwriting:o.force})).cid}var S2=xe("helia:unixfs:utils:remove-link");async function gI(r,e,t,n){if(r.node.Data==null)throw new Er("Parent node had no data");if(ie.unmarshal(r.node.Data).type==="hamt-sharded-directory"){S2(`removing ${e} from sharded directory`);let i=await BF(r,e,t,n);return await E2(i.node,t,n.shardSplitThresholdBytes,n)?i:(S2("converting shard to flat directory %c",r.cid),MF(i,t,n))}return S2(`removing link ${e} regular directory`),OF(r,e,t,n)}var OF=async(r,e,t,n)=>{r.node.Links=r.node.Links.filter(s=>s.Name!==e);let o=_e(r.node),i=await Fn(o,t,{...n,cidVersion:r.cid.version});return S2(`Updated regular directory ${i}`),{node:r.node,cid:i}},BF=async(r,e,t,n)=>{let{path:o}=await x2(r.cid,e,t,n),i=o[o.length-1];if(i==null)throw new Error("Invalid HAMT, could not generate path");let s=i.node.Links.filter(l=>(l.Name??"").substring(2)===e).map(l=>l.Name).pop();if(s==null)throw new Error("File not found");let a=s.substring(0,2),c=parseInt(a,16);if(i.node.Links=i.node.Links.filter(l=>l.Name!==s),i.children.unset(c),i.node.Links.length===1)for(;o.length!==1;){let l=o[o.length-1];if(l==null||l.node.Links.length>1)break;o.pop();let u=o[o.length-1];if(u==null)break;let d=l.node.Links[0];u.node.Links=u.node.Links.filter(h=>!(h.Name??"").startsWith(u.prefix)),u.node.Links.push({Hash:d.Hash,Name:`${u.prefix}${(d.Name??"").substring(2)}`,Tsize:d.Tsize})}return b2(o,t,n)},MF=async(r,e,t)=>{if(r.node.Data==null)throw new Wr("Invalid parent passed to convertToFlatDirectory");let n={Links:[]},o=await _t(r.cid,e);if(o.type!=="directory")throw new Error("Unexpected node type");for await(let c of o.content()){let l=0;c.node instanceof Uint8Array?l=c.node.byteLength:l=_e(c.node).length,n.Links.push({Hash:c.cid,Name:c.name,Tsize:l})}let i=ie.unmarshal(r.node.Data);n.Data=new ie({type:"directory",mode:i.mode,mtime:i.mtime}).marshal();let s=_e(ct(n));return{cid:await Fn(s,e,{codec:wt,cidVersion:r.cid.version,signal:t.signal}),node:n}};var UF=ut.bind({ignoreUndefined:!0}),FF=xe("helia:unixfs:rm"),HF={shardSplitThresholdBytes:262144};async function yI(r,e,t,n={}){let o=UF(HF,n);if(e.includes("/"))throw new Wr("Name must not have slashes");let i=await Hi(r,t,o);return FF("Removing %s from %c",e,r),(await gI(i,e,t,{...o,cidVersion:r.version})).cid}var VF=ut.bind({ignoreUndefined:!0}),$F=xe("helia:unixfs:stat"),zF={};async function wI(r,e,t={}){let n=VF(zF,t),o=await oo(r,t.path,e,n);$F("stat %c",o.cid);let i=await _t(o.cid,e,n);if(i.type!=="file"&&i.type!=="directory"&&i.type!=="raw")throw new Gr;let s=0n,a=0n,c=0n,l=0n,u=0,d,h,f=i.type,p;if(i.type==="raw"&&(s=BigInt(i.node.byteLength),a=BigInt(i.node.byteLength),c=BigInt(i.node.byteLength),l=BigInt(i.node.byteLength),u=1),i.type==="directory"&&(s=0n,a=BigInt(i.unixfs.marshal().byteLength),c=0n,l=a,u=1,d=i.unixfs.mode,h=i.unixfs.mtime,p=i.unixfs),i.type==="file"){let m=await bI(o.cid,e,n);s=i.unixfs.fileSize(),a=BigInt((i.node.Data?.byteLength??0)+i.node.Links.reduce((g,y)=>g+(y.Tsize??0),0)),c=BigInt(m.localFileSize),l=BigInt(m.localDagSize),u=m.blocks,d=i.unixfs.mode,h=i.unixfs.mtime,p=i.unixfs}return{cid:o.cid,mode:d,mtime:h,fileSize:s,dagSize:a,localFileSize:c,localDagSize:l,blocks:u,type:f,unixfs:p}}async function bI(r,e,t){let n={localFileSize:0,localDagSize:0,blocks:0};if(await e.has(r,t)){let o=await e.get(r,t);if(n.blocks++,n.localDagSize+=o.byteLength,r.code===$e)n.localFileSize+=o.byteLength;else if(r.code===Le){let i=yt(o);if(i.Links.length>0)for(let s of i.Links){let a=await bI(s.Hash,e,t);n.localFileSize+=a.localFileSize,n.localDagSize+=a.localDagSize,n.blocks+=a.blocks}else{if(i.Data==null)throw new Er(`PBNode ${r.toString()} had no data`);let s=ie.unmarshal(i.Data);if(s.data==null)throw new Er(`UnixFS node ${r.toString()} had no data`);n.localFileSize+=s.data.byteLength??0}}else throw new Oi(`${r.toString()} was neither DAG_PB nor RAW`)}return n}var KF=ut.bind({ignoreUndefined:!0}),qF=xe("helia:unixfs:touch"),GF={recursive:!1,shardSplitThresholdBytes:262144};async function xI(r,e,t={}){let n=KF(GF,t),o=await oo(r,n.path,e,n),i=n.mtime??{secs:BigInt(Math.round(Date.now()/1e3)),nsecs:0};if(qF("touch %c %o",o.cid,i),n.recursive){let h=await Pe(async function*(){for await(let f of Mc(o.cid,e)){let p,m;if(f.type==="raw")p=new ie({data:f.node}),m=[];else if(f.type==="file"||f.type==="directory")p=f.unixfs,m=f.node.Links;else throw new Gr;p.mtime=i;let g={Data:p.marshal(),Links:m};yield{path:f.path,content:g}}},f=>Fi(f,e,{...n,dagBuilder:async function*(p,m){for await(let g of p)yield async function(){let y=g.content,w=_e(y),b=await Fn(w,m,{...n,cidVersion:r.version});if(y.Data==null)throw new Er(`${b} had no data`);let x=ie.unmarshal(y.Data);return{cid:b,size:BigInt(w.length),path:g.path,unixfs:x}}}}),async f=>Mi(f));if(h==null)throw new Oi(`Could not chmod ${o.cid.toString()}`);return Vc(h.cid,o,e,n)}let s=await e.get(o.cid,t),a,c=[];if(o.cid.code===$e)a=new ie({data:s});else{let h=yt(s);if(c=h.Links,h.Data==null)throw new Er(`${o.cid.toString()} had no data`);a=ie.unmarshal(h.Data)}a.mtime=i;let l=_e({Data:a.marshal(),Links:c}),u=await ve.digest(l),d=O.create(o.cid.version,Le,u);return await e.put(d,l),Vc(d,o,e,n)}var A2=class{components;constructor(e){this.components=e}async*addAll(e,t={}){yield*eI(e,this.components.blockstore,t)}async addBytes(e,t={}){return tI(e,this.components.blockstore,t)}async addByteStream(e,t={}){return rI(e,this.components.blockstore,t)}async addFile(e,t={}){return nI(e,this.components.blockstore,t)}async addDirectory(e={},t={}){return oI(e,this.components.blockstore,t)}async*cat(e,t={}){yield*uI(e,this.components.blockstore,t)}async chmod(e,t,n={}){return dI(e,t,this.components.blockstore,n)}async cp(e,t,n,o={}){return fI(e,t,n,this.components.blockstore,o)}async*ls(e,t={}){yield*hI(e,this.components.blockstore,t)}async mkdir(e,t,n={}){return mI(e,t,this.components.blockstore,n)}async rm(e,t,n={}){return yI(e,t,this.components.blockstore,n)}async stat(e,t={}){return wI(e,this.components.blockstore,t)}async touch(e,t={}){return xI(e,this.components.blockstore,t)}};function EI(r){return new A2(r)}function vI(r,e){if(r==null)return;if(r instanceof Headers)return r.get(e)??void 0;if(Array.isArray(r))return r.find(([o])=>o.toLowerCase()===e.toLowerCase())?.[1];let t=Object.keys(r).find(n=>n.toLowerCase()===e.toLowerCase());if(t!=null)return r[t]}function SI(r,e,t){if((r??0)>(e??1/0))throw new qr("Invalid range: Range-start index is greater than range-end index.");if(r!=null&&(e??0)>=(t??1/0))throw new qr("Invalid range: Range-end index is greater than or equal to the size of the file.");if(r==null&&(e??0)>(t??1/0))throw new qr("Invalid range: Range-end index is greater than the size of the file.");if(r!=null&&r<0)throw new qr("Invalid range: Range-start index cannot be negative.");if(r!=null&&e!=null)return{byteSize:e-r+1,start:r,end:e};if(r==null&&e!=null)return t==null?{end:e}:e===t?{byteSize:t,start:0,end:t-1}:{byteSize:e,start:t-e,end:t-1};if(r!=null&&e==null){if(t==null)return{start:r};let n=t-1;return{byteSize:t-r,start:r,end:n}}return{byteSize:t,start:0,end:t!=null?t-1:0}}function WF(r){return typeof r=="string"?r.length:r instanceof ArrayBuffer||r instanceof Uint8Array?r.byteLength:r instanceof Blob?r.size:(r instanceof ReadableStream,null)}function YF(r){let e=r.match(/^bytes=(?<start>\d+)?-(?<end>\d+)?$/);if(e?.groups==null)throw new qr("Invalid range request");let{start:t,end:n}=e.groups;return{start:t,end:n}}var $c=class{headers;isRangeRequest;_fileSize;_body=null;rangeRequestHeader;log;requestRangeStart;requestRangeEnd;byteStart;byteEnd;byteSize;constructor(e,t){if(this.headers=t,this.log=e.forComponent("helia:verified-fetch:byte-range-context"),this.rangeRequestHeader=vI(this.headers,"Range"),this.rangeRequestHeader!=null){this.isRangeRequest=!0,this.log.trace("range request detected");try{let{start:n,end:o}=YF(this.rangeRequestHeader);this.requestRangeStart=n!=null?parseInt(n):null,this.requestRangeEnd=o!=null?parseInt(o):null}catch(n){this.log.error("error parsing range request header: %o",n),this.requestRangeStart=null,this.requestRangeEnd=null}this.setOffsetDetails()}else this.log.trace("no range request detected"),this.isRangeRequest=!1,this.requestRangeStart=null,this.requestRangeEnd=null}setBody(e){this._body=e,this.setFileSize(this._fileSize??WF(e)),this.log.trace("set request body with fileSize %o",this._fileSize)}getBody(){let e=this._body;if(e==null)return this.log.trace("body is null"),e;if(!this.isRangeRequest||!this.isValidRangeRequest)return this.log.trace("returning body unmodified for non-range, or invalid range, request"),e;let t=this.byteStart,n=this.byteEnd,o=this.byteSize;return t!=null||n!=null?(this.log.trace("returning body with byteStart=%o, byteEnd=%o, byteSize=%o",t,n,o),e instanceof ReadableStream?e:this.getSlicedBody(e)):(this.log.error("returning unmodified body for valid range request"),e)}getSlicedBody(e){let t=this.byteStart??0,n=this.byteEnd==null?void 0:this.byteEnd+1;return this.log.trace("returning body with offset %o and length %o",t,n),e.slice(t,n)}setFileSize(e){this._fileSize=e!=null?Number(e):null,this.log.trace("set _fileSize to %o",this._fileSize),this.setOffsetDetails()}getFileSize(){return this._fileSize}isValidByteStart(){return!(this.byteStart!=null&&(this.byteStart<0||this._fileSize!=null&&this.byteStart>=this._fileSize||this.byteEnd!=null&&this.byteStart>this.byteEnd))}isValidByteEnd(){return!(this.byteEnd!=null&&(this.byteEnd<0||this._fileSize!=null&&this.byteEnd>=this._fileSize||this.byteStart!=null&&this.byteEnd<this.byteStart))}get isValidRangeRequest(){if(!this.isRangeRequest)return!1;if(this.requestRangeStart==null&&this.requestRangeEnd==null)return this.log.trace("invalid range request, range request values not provided"),!1;if(!this.isValidByteStart())return this.log.trace("invalid range request, byteStart is less than 0 or greater than fileSize"),!1;if(!this.isValidByteEnd())return this.log.trace("invalid range request, byteEnd is less than 0 or greater than fileSize"),!1;if(this.requestRangeEnd!=null&&this.requestRangeStart!=null){if(this.requestRangeStart>this.requestRangeEnd)return this.log.trace("invalid range request, start is greater than end"),!1;if(this.requestRangeStart<0)return this.log.trace("invalid range request, start is less than 0"),!1;if(this.requestRangeEnd<0)return this.log.trace("invalid range request, end is less than 0"),!1}return this.byteEnd==null&&this.byteStart==null&&this.byteSize==null?(this.log.trace("invalid range request, could not calculate byteStart, byteEnd, or byteSize"),!1):!0}get offset(){return this.byteStart??0}get length(){return this.byteEnd!=null&&this.byteStart!=null&&this.byteStart===this.byteEnd?1:this.byteEnd!=null?this.byteEnd+1:this.byteSize!=null?this.byteSize-1:void 0}setOffsetDetails(){if(this.requestRangeStart==null&&this.requestRangeEnd==null){this.log.trace("requestRangeStart and requestRangeEnd are null");return}try{let{start:e,end:t,byteSize:n}=SI(this.requestRangeStart??void 0,this.requestRangeEnd??void 0,this._fileSize??void 0);this.log.trace("set byteStart to %o, byteEnd to %o, byteSize to %o",e,t,n),this.byteStart=e,this.byteEnd=t,this.byteSize=n}catch(e){this.log.error("error setting offset details: %o",e),this.byteStart=void 0,this.byteEnd=void 0,this.byteSize=void 0}}get contentRangeHeaderValue(){if(!this.isValidRangeRequest)throw this.log.error("cannot get contentRangeHeaderValue for invalid range request"),new qr("Invalid range request");return l_({byteStart:this.byteStart,byteEnd:this.byteEnd,byteSize:this._fileSize??void 0})}};async function AI(r,e,t,n){let o=t.forComponent("helia:verified-fetch:get-stream-from-async-iterable"),i=r[Symbol.asyncIterator](),{value:s,done:a}=await i.next();if(a===!0)throw o.error("no content found for path",e),new Xm;return{stream:new ReadableStream({async start(l){n?.onProgress?.(new M("verified-fetch:request:progress:chunk")),l.enqueue(s)},async pull(l){let{value:u,done:d}=await i.next();if(n?.signal?.aborted===!0){l.error(new Ut(n.signal.reason??"signal aborted by user")),l.close();return}if(d===!0){u!=null&&(n?.onProgress?.(new M("verified-fetch:request:progress:chunk")),l.enqueue(u)),l.close();return}n?.onProgress?.(new M("verified-fetch:request:progress:chunk")),l.enqueue(u)}}),firstChunk:s}}function _I(r){return r?.then!=null}async function _2({bytes:r,path:e,response:t,contentTypeParser:n,log:o,defaultContentType:i="application/octet-stream"}){let s;if(n!=null)try{let a=e.split("/").pop()?.trim();a=a===""?void 0:a;let c=n(r,a);if(_I(c)){let l=await c;l!=null&&(s=l)}else c!=null&&(s=c)}catch(a){o.error("error parsing content type",a)}o.trace('setting content type to "%s"',s??i),t.headers.set("content-type",s??i)}var I2=class extends dt{codes=[Le];canHandle({cid:e,accept:t,pathDetails:n}){return this.log("checking if we can handle %c with accept %s",e,t),n==null?!1:e.code===Le}getRedirectUrl(e){let{resource:t,path:n}=e;if(n===""?!t.toString().endsWith("/"):!n.endsWith("/"))try{let i=new URL(t.toString());return i.pathname.endsWith("/")?null:(i.pathname=`${i.pathname}/`,i.toString())}catch{return`${t.toString()}/`}return null}async handle(e){let{cid:t,options:n,withServerTiming:o=!1,pathDetails:i}=e,{handleServerTiming:s,contentTypeParser:a,helia:c,getBlockstore:l}=this.pluginOptions,u=this.log,d=e.resource,h=e.path,f=!1,p=new $c(this.pluginOptions.logger,n?.headers);if(i==null)throw new TypeError("Path details are required");let m=i.ipfsRoots,g=i.terminalElement,y=g.cid;if(g?.type==="directory"){let x=g.cid,A=this.getRedirectUrl(e);if(A!=null){if(u.trace("directory url normalization spec requires redirect..."),n?.redirect==="error")throw u('could not redirect to %s as redirect option was set to "error"',A),new TypeError("Failed to fetch");if(n?.redirect==="manual")return u("returning 301 permanent redirect to %s",A),qu(d,A);u("following redirect to %s",A),d=A,f=!0}let k="index.html";try{u.trace("found directory at %c/%s, looking for index.html",t,h);let v=await s("exporter-dir","",async()=>_t(`/ipfs/${x}/${k}`,c.blockstore,{signal:n?.signal,onProgress:n?.onProgress}),o);u.trace("found root file at %c/%s with cid %c",x,k,v.cid),h=k,y=v.cid}catch(v){this.log.error("error loading path %c/%s",x,k,v),n?.signal?.throwIfAborted(),e.isDirectory=!0,e.directoryEntries=[],this.log.trace("attempting to get directory entries because index.html was not found");let S=EI({...c,blockstore:l(e.cid,e.resource,n?.session??!0,n)});try{for await(let I of S.ls(x,{signal:n?.signal,onProgress:n?.onProgress}))e.directoryEntries.push(I);return null}catch(I){return u.error("error listing directory %c",x,I),qm("Unable to get directory contents")}}finally{n?.onProgress?.(new M("verified-fetch:request:end",{cid:x,path:k}))}}p.isRangeRequest&&p.isValidRangeRequest&&g.type==="file"&&(p.setFileSize(g.unixfs.fileSize()),u.trace("fileSize for rangeRequest %d",p.getFileSize()));let w=p.offset,b=p.length;u.trace("calling exporter for %c/%s with offset=%o & length=%o",y,h,w,b);try{let A=(await s("exporter-file","",async()=>_t(y,c.blockstore,{signal:n?.signal,onProgress:n?.onProgress}),o)).content({signal:n?.signal,onProgress:n?.onProgress,offset:w,length:b});u("got async iterator for %c/%s",t,h);let{stream:k,firstChunk:v}=await s("stream-and-chunk","",async()=>AI(A,h??"",this.pluginOptions.logger,{onProgress:n?.onProgress,signal:n?.signal}),o);p.setBody(k);let S=Wm(d,p.getBody(),{byteRangeContext:p,log:u},{redirected:f});return await s("set-content-type","",async()=>_2({bytes:v,path:h,response:S,contentTypeParser:a,log:u}),o),jm(S,m),S}catch(x){return n?.signal?.throwIfAborted(),u.error("error streaming %c/%s",t,h,x),p.isRangeRequest&&x.code==="ERR_INVALID_PARAMS"?Km(d):Rc(d.toString(),"Unable to stream content")}}};var T2=class extends dt{canHandle(e){this.log("checking if we can handle %c with accept %s",e.cid,e.accept);let{pathDetails:t,cid:n}=e;return t!=null?!1:n.code===Le||n.code===Pr}async handle(e){let{cid:t,resource:n,options:o,withServerTiming:i=!1}=e,{getBlockstore:s,handleServerTiming:a}=this.pluginOptions,c=s(t,n,o?.session??!0,o),l=await a("path-walking","",async()=>M_({...e,blockstore:c,log:this.log}),i);return e.modified++,l instanceof Response?(this.log.trace("path walking failed"),l.status===404?l:null):(e.pathDetails=l,null)}};function k2(r){return r.charAt(0)==="1"||r.charAt(0)==="Q"?Ue(r):or(O.parse(r))}var od=class extends Error{name="PluginError";code;fatal;details;response;constructor(e,t,n){super(t),this.code=e,this.fatal=n?.fatal??!1,this.details=n?.details,this.response=n?.response}},Vo=class extends od{name="PluginFatalError";constructor(e,t,n){super(e,t,{...n,fatal:!0}),this.name="PluginFatalError"}};var C2=class extends dt{codes=[];canHandle({cid:e,accept:t,query:n}){return this.log("checking if we can handle %c with accept %s",e,t),t==="application/vnd.ipfs.ipns-record"||n.format==="ipns-record"}async handle(e){let{resource:t,path:n,options:o}=e,{helia:i}=this.pluginOptions;if(e.reqFormat="ipns-record",n!==""||!(t.startsWith("ipns://")||t.includes(".ipns.")||t.includes("/ipns/")))throw this.log.error('invalid request for IPNS name "%s" and path "%s"',t,n),new Vo("ERR_INVALID_IPNS_NAME","Invalid IPNS name",{response:Ku(t,"Invalid IPNS name")});let s;try{let h;t.startsWith("ipns://")?h=t.replace("ipns://",""):t.includes("/ipns/")?h=t.split("/ipns/")[1].split("/")[0].split("?")[0]:h=t.split(".ipns.")[0].split("://")[1],this.log.trace('trying to parse peer id from "%s"',h),s=k2(h)}catch(h){throw this.log.error("could not parse peer id from IPNS url %s",t,h),new Vo("ERR_NO_PEER_ID_FOUND","could not parse peer id from url",{response:Ku(t,h)})}let a=ge([C("/ipns/"),s.toMultihash().bytes]),c=new Be("/dht/record/"+V(a,"base32"),!1),l=await i.datastore.get(c,o),u=tt.deserialize(l),d=On(t,u.value);return d.headers.set("content-type","application/vnd.ipfs.ipns-record"),d}};var P2=class extends dt{codes=[Jn,qn];canHandle({cid:e,accept:t}){return this.log("checking if we can handle %c with accept %s",e,t),t==="application/vnd.ipld.dag-json"&&e.code!==Pr?!0:Jn===e.code||qn===e.code}async handle(e){let{path:t,resource:n,cid:o,accept:i,options:s}=e,{getBlockstore:a}=this.pluginOptions,c=s?.session??!0;this.log.trace("fetching %c/%s",o,t);let l=e.pathDetails?.terminalElement.cid??e.cid,d=await a(l,n,c,s).get(l,s),h;if(i==="application/vnd.ipld.dag-cbor"||i==="application/cbor")try{let p=Ha(d);h=Ua(p)}catch(p){return this.log.error("could not transform %c to application/vnd.ipld.dag-cbor",p),Ho(n)}else h=d;let f=On(n,h);return f.headers.set("content-type",i??"application/json"),f}};var XF=["application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/octet-stream"];function QF({headers:r,accept:e}){let n=(e??new Headers(r).get("accept")??"").split(",").map(o=>o.split(";")[0]).map(o=>o.trim());for(let o of n){if(o==="*/*")return;if(XF.includes(o??""))return o}}var R2=class extends dt{codes=[$e,vt.code];canHandle({cid:e,accept:t,query:n}){return this.log("checking if we can handle %c with accept %s",e,t),t==="application/vnd.ipld.raw"||n.format==="raw"}async handle(e){let{path:t,resource:n,cid:o,accept:i,query:s,options:a}=e,{getBlockstore:c,contentTypeParser:l}=this.pluginOptions,u=a?.session??!0,d=this.log;if(i==="application/vnd.ipld.raw"||s.format==="raw"?(e.reqFormat="raw",e.query.download=!0,e.query.filename=e.query.filename??`${o.toString()}.bin`,d.trace("Set content disposition...")):d.trace("Did NOT setting content disposition..."),t!==""&&o.code===$e)throw d.trace("404-ing raw codec request for %c/%s",o,t),new Vo("ERR_RAW_PATHS_NOT_SUPPORTED","Raw codec does not support paths",{response:Gm(n,"Raw codec does not support paths")});let h=new $c(this.pluginOptions.logger,a?.headers),f=e.pathDetails?.terminalElement.cid??e.cid,m=await c(f,n,u,a).get(f,a);h.setBody(m);let g=Wm(n,h.getBody(),{byteRangeContext:h,log:d},{redirected:!1});return await _2({bytes:m,path:t,response:g,defaultContentType:QF({headers:a?.headers,accept:i}),contentTypeParser:l,log:d}),g}};var jF=({weak:r,reqFormat:e})=>e==="tar"||e==="car"||e==="ipns-record"||r===!0?"W/":"",ZF=({reqFormat:r})=>r==null?"":r==="tar"?".x-tar":`.${r}`;function L2({cid:r,reqFormat:e,weak:t,rangeStart:n,rangeEnd:o}){let i=jF({weak:t,reqFormat:e}),s=ZF({reqFormat:e});return(n!=null||o!=null)&&(s+=`.${n??"0"}-${o??"N"}`),`${i}"${r.toString()}${s}"`}var GAe=C("ustar\0","binary"),WAe=C("ustar ","binary"),YAe=C(" \0","binary");var PI=xt(TI(),1);function eH(r){return r[Symbol.asyncIterator]!=null}function tH(r){if(eH(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=ge([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return ge(e,t)}var kI=tH;var rH="0000000000000000000",nH="7777777777777777777",oH=48,iH=C("ustar\0","binary"),sH=C("00","binary"),aH=parseInt("7777",8),cH=257,lH=263,uH=function(r){switch(r){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72;default:return 0}},dH=function(r){let e=256;for(let t=0;t<148;t++)e+=r[t];for(let t=156;t<512;t++)e+=r[t];return e},Vi=function(r,e){let t=r.toString(8);return t.length>e?C(nH.slice(0,e)+" "):C(rH.slice(0,e-t.length)+t+" ")},N5=function(r){let e=C(r).byteLength,t=Math.floor(Math.log(e)/Math.log(10))+1;return e+t>=Math.pow(10,t)&&t++,`${e+t}${r}`};function CI(r){let e="";r.name!=null&&(e+=N5(" path="+r.name+`
75
+ `),t),t.log('handle: responded with "na" for "%s"',o)}}var VM=500,d5=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:o,close:i,abort:s,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.limits=e.limits,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=i,this._abort=s,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[Y5]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new hd("the connection is being closed");if(this.status==="closed")throw new na("the connection is closed");if(Array.isArray(e)||(e=[e]),this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new sa("Cannot open protocol stream on limited connection");let n=await this._newStream(e,t);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(VM);e={...e,signal:t}}try{this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this._abort(e),this.status="closed",this.timeline.close=Date.now())}};function OA(r){return new d5(r)}function zM(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return s5}function KM(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??a5}function BA(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Bm=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(e,t){this.components=e,this.connectionEncrypters=new Map,t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=new Map,t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new fm(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=de([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,o=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=await this.components.connectionManager.acceptIncomingConnection(e),!n)throw new hm("Connection denied");await this.shouldBlockConnection("denyInboundConnection",e),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(i){throw this.metrics.errors?.increment({inbound:!0}),i}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getPeerId(),o;n!=null&&(o=Ue(n),await this.shouldBlockConnection("denyOutboundConnection",o,e));let i="outbound";return t.initiator===!1&&(i="inbound"),await this._performUpgrade(e,i,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),n}}async _performUpgrade(e,t,n){let o,i,s,a,c;this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t);let l=e;if(n?.skipProtection!==!0){let u=this.components.connectionProtector;u!=null&&(e.log("protecting the %s connection",t),l=await u.protect(e,n))}try{if(o=l,n?.skipEncryption!==!0){n?.onProgress?.(new M(`upgrader:encrypt-${t}-connection`)),{conn:o,remotePeer:i,protocol:c}=await(t==="inbound"?this._encryptInbound(l,n):this._encryptOutbound(l,n));let u={...l,...o};await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",i,u)}else{let u=e.remoteAddr.getPeerId();if(u==null)throw new Ko(`${t} connection that skipped encryption must have a peer id`);let d=Ue(u);c="native",i=d}if(i.equals(this.components.peerId)){let u=new ia("Can not dial self");throw e.abort(u),u}if(s=o,n?.muxerFactory!=null)a=n.muxerFactory;else if(this.streamMuxers.size>0){n?.onProgress?.(new M(`upgrader:multiplex-${t}-connection`));let u=await(t==="inbound"?this._multiplexInbound({...l,...o},this.streamMuxers,n):this._multiplexOutbound({...l,...o},this.streamMuxers,n));a=u.muxerFactory,s=u.stream}}catch(u){throw e.log.error("failed to upgrade inbound connection %s %a - %e",t==="inbound"?"from":"to",e.remoteAddr,u),u}return await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",i,e),e.log("successfully upgraded %s connection",t),this._createConnection({cryptoProtocol:c,direction:t,maConn:e,upgradedConn:s,muxerFactory:a,remotePeer:i,limits:n?.limits})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:o,upgradedConn:i,remotePeer:s,muxerFactory:a,limits:c}=e,l,u,d;a!=null&&(l=a.createStreamMuxer({direction:n,onIncomingStream:p=>{d!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),g=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);let{stream:y,protocol:w}=await Uu(p,m,{signal:g,log:p.log,yieldBytes:!1});if(d==null)return;d.log("incoming stream opened on %s",w);let b=zM(w,this.components.registrar);if(BA(w,"inbound",d)===b){let A=new yd(`Too many inbound protocol streams for protocol "${w}" - limit ${b}`);throw p.abort(A),A}p.source=y.source,p.sink=y.sink,p.protocol=w,y.closeWrite!=null&&(p.closeWrite=y.closeWrite),y.closeRead!=null&&(p.closeRead=y.closeRead),y.close!=null&&(p.close=y.close),await this.components.peerStore.merge(s,{protocols:[w]}),this.components.metrics?.trackProtocolStream(p,d),this._onStream({connection:d,stream:p,protocol:w})}).catch(async m=>{d.log.error("error handling incoming stream id %s - %e",p.id,m),p.timeline.close==null&&await p.close()})}}),u=async(p,m={})=>{if(l==null)throw new Ws("Connection is not multiplexed");d.log.trace("starting new stream for protocols %s",p);let g=await l.newStream();d.log.trace("started new stream %s for protocols %s",g.id,p);try{if(m.signal==null){g.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p);let A=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);m={...m,signal:A}}g.log.trace("selecting protocol from protocols %s",p);let{stream:y,protocol:w}=await Bu(g,p,{...m,log:g.log,yieldBytes:!0});g.log.trace("selected protocol %s",w);let b=KM(w,this.components.registrar,m),x=BA(w,"outbound",d);if(x>=b){let A=new Go(`Too many outbound protocol streams for protocol "${w}" - ${x}/${b}`);throw g.abort(A),A}return await this.components.peerStore.merge(s,{protocols:[w]}),g.source=y.source,g.sink=y.sink,g.protocol=w,y.closeWrite!=null&&(g.closeWrite=y.closeWrite),y.closeRead!=null&&(g.closeRead=y.closeRead),y.close!=null&&(g.close=y.close),this.components.metrics?.trackProtocolStream(g,d),g}catch(y){throw d.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",n==="inbound"?"from":"to",e.maConn.remoteAddr,p,y),g.timeline.close==null&&g.abort(y),y}},Promise.all([l.sink(i.source),i.sink(l.source)]).catch(p=>{d.log.error("error piping data through muxer - %e",p)}));let h=o.timeline;o.timeline=new Proxy(h,{set:(...p)=>(p[1]==="close"&&p[2]!=null&&h.close==null&&(async()=>{try{d.status==="open"&&await d.close()}catch(m){d.log.error("error closing connection after timeline close %e",m)}finally{this.events.safeDispatchEvent("connection:close",{detail:d})}})().catch(m=>{d.log.error("error thrown while dispatching connection:close event %e",m)}),Reflect.set(...p))}),o.timeline.upgraded=Date.now();let f=()=>{throw new Ws("Connection is not multiplexed")};return d=OA({remoteAddr:o.remoteAddr,remotePeer:s,status:"open",direction:n,timeline:o.timeline,multiplexer:l?.protocol,encryption:t,limits:c,logger:this.components.logger,newStream:u??f,getStreams:()=>l?.streams??[],close:async p=>{await l?.close(p),await o.close(p)},abort:p=>{o.abort(p),l?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:d}),d.__maConnTimeline=h,d}_onStream(e){let{connection:t,stream:n,protocol:o}=e,{handler:i,options:s}=this.components.registrar.getHandler(o);if(t.limits!=null&&s.runOnLimitedConnection!==!0)throw new sa("Cannot open protocol stream on limited connection");i({connection:t,stream:n})}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let{stream:o,protocol:i}=await Uu(e,n,{...t,log:e.log}),s=this.connectionEncrypters.get(i);if(s==null)throw new Ys(`no crypto module found for ${i}`);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,i),{...await s.secureInbound(o,t),protocol:i}}catch(o){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,o),new Ys(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:i}=await Bu(e,n,{...t,log:e.log,yieldBytes:!0}),s=this.connectionEncrypters.get(i);if(s==null)throw new Ys(`no crypto module found for ${i}`);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,i),{...await s.secureOutbound(o,t),protocol:i}}catch(o){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,o),new Ys(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let{stream:i,protocol:s}=await Bu(e,o,{...n,log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",s);let a=t.get(s);return{stream:i,muxerFactory:a}}catch(i){throw e.log.error("error multiplexing outbound connection",i),new Ws(String(i))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{let{stream:i,protocol:s}=await Uu(e,o,{...n,log:e.log}),a=t.get(s);return{stream:i,muxerFactory:a}}catch(i){throw e.log.error("error multiplexing inbound connection",i),new Ws(String(i))}}};var Mm=class extends ye{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new ye,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=n(l),d=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||d},this.peerId=e.peerId,this.logger=e.logger??ui(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??q0,i=e.nodeInfo?.version??K0,s=this.components=pA({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:i,userAgent:e.nodeInfo?.userAgent??G0(o,i)},logger:this.logger,events:t,datastore:e.datastore??new Bs,connectionGater:gA(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",aA(s,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),s.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(d=>d.multiaddr)};s.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(s)),this.components.upgrader=new Bm(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new Cm(this.components,e.transportManager)),this.configureComponent("connectionManager",new Sm(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Am(this.components,e.connectionMonitor)),this.configureComponent("registrar",new km(this.components)),this.configureComponent("addressManager",new nm(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Im(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new _m(this.components,{routers:c})),this.configureComponent("randomWalk",new Tm(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",h=>{this.#e(h)})}),e.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let u=e.services[l],d=u(this.components);if(d==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=d,this.configureComponent(l,d),d[Vn]!=null&&(this.log("registering service %s for content routing",l),c.push(d[Vn])),d[$n]!=null&&(this.log("registering service %s for peer routing",l),a.push(d[$n])),d[$i]!=null&&(this.log("registering service %s for peer discovery",l),d[$i].addEventListener?.("peer",h=>{this.#e(h)}))}mA(s)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new gr;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new D("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new D("no protocols were provided to open a stream");return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){yi(e)&&(e=Ue(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let s=await this.peerStore.get(e);if(s.id.publicKey!=null)return s.id.publicKey}catch(s){if(s.name!=="NotFoundError")throw s}let n=ge([C("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),i=gt(o);return await this.peerStore.patch(e,{publicKey:i}),i}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function Um(r={}){r.privateKey??=await Gf("Ed25519");let e=new Mm({...await rA(r),peerId:f9(r.privateKey)});return r.start!==!1&&await e.start(),e}async function MA(r){let e=r.libp2p??{};e.privateKey==null&&r.datastore!=null&&(e.privateKey=await H8(r.datastore,r.keychain));let t=Lu(e);return t.datastore=t.datastore??r.datastore,await Um({...t,...e,start:!1})}async function UA(r={}){let e=r.datastore??new Bs,t=r.blockstore??new du,n;qM(r.libp2p)?n=r.libp2p:n=await MA({...r,libp2p:{dns:r.dns,...r.libp2p,start:void 0},datastore:e});let o=new _p({...r,libp2p:n,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[Jl(),Kl()],routers:r.routers??[k6(n),I6()],metrics:n.metrics});return r.start!==!1&&await o.start(),o}function qM(r){return r==null?!1:["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"].every(t=>typeof r[t]=="function")}function FA(){let r=Lu();r.start=!1,r.addresses={listen:[]},r.transports=[H0(),z0()],r.peerDiscovery=[];let e={dcutr:r.services.dcutr,identify:r.services.identify,keychain:r.services.keychain,ping:r.services.ping};return{...r,start:!1,services:e}}var Cc=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,VA=new Set,f5=typeof process=="object"&&process?process:{},$A=(r,e,t,n)=>{typeof f5.emitWarning=="function"?f5.emitWarning(r,e,t,n):console.error(`[${t}] ${e}: ${r}`)},Fm=globalThis.AbortController,HA=globalThis.AbortSignal;if(typeof Fm>"u"){HA=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,o){this._onabort.push(o)}},Fm=class{constructor(){e()}signal=new HA;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let o of this.signal._onabort)o(n);this.signal.onabort?.(n)}}};let r=f5.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{r&&(r=!1,$A("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var GM=r=>!VA.has(r),f7e=Symbol("type"),Di=r=>r&&r===Math.floor(r)&&r>0&&isFinite(r),zA=r=>Di(r)?r<=Math.pow(2,8)?Uint8Array:r<=Math.pow(2,16)?Uint16Array:r<=Math.pow(2,32)?Uint32Array:r<=Number.MAX_SAFE_INTEGER?Pc:null:null,Pc=class extends Array{constructor(e){super(e),this.fill(0)}},h5=class r{heap;length;static#e=!1;static create(e){let t=zA(e);if(!t)return[];r.#e=!0;let n=new r(e,t);return r.#e=!1,n}constructor(e,t){if(!r.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},Hm=class r{#e;#r;#n;#c;#m;#A;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#g;#o;#s;#t;#f;#l;#h;#u;#b;#d;#x;#E;#y;#w;#_;#p;static unsafeExposeInternals(e){return{starts:e.#E,ttls:e.#y,sizes:e.#x,keyMap:e.#o,keyList:e.#s,valList:e.#t,next:e.#f,prev:e.#l,get head(){return e.#h},get tail(){return e.#u},free:e.#b,isBackgroundFetch:t=>e.#a(t),backgroundFetch:(t,n,o,i)=>e.#O(t,n,o,i),moveToTail:t=>e.#L(t),indexes:t=>e.#I(t),rindexes:t=>e.#T(t),isStale:t=>e.#S(t)}}get max(){return this.#e}get maxSize(){return this.#r}get calculatedSize(){return this.#g}get size(){return this.#i}get fetchMethod(){return this.#m}get memoMethod(){return this.#A}get dispose(){return this.#n}get disposeAfter(){return this.#c}constructor(e){let{max:t=0,ttl:n,ttlResolution:o=1,ttlAutopurge:i,updateAgeOnGet:s,updateAgeOnHas:a,allowStale:c,dispose:l,disposeAfter:u,noDisposeOnSet:d,noUpdateTTL:h,maxSize:f=0,maxEntrySize:p=0,sizeCalculation:m,fetchMethod:g,memoMethod:y,noDeleteOnFetchRejection:w,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:x,allowStaleOnFetchAbort:A,ignoreFetchAbort:k}=e;if(t!==0&&!Di(t))throw new TypeError("max option must be a nonnegative integer");let v=t?zA(t):Array;if(!v)throw new Error("invalid max value: "+t);if(this.#e=t,this.#r=f,this.maxEntrySize=p||this.#r,this.sizeCalculation=m,this.sizeCalculation){if(!this.#r&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(y!==void 0&&typeof y!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#A=y,g!==void 0&&typeof g!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#m=g,this.#_=!!g,this.#o=new Map,this.#s=new Array(t).fill(void 0),this.#t=new Array(t).fill(void 0),this.#f=new v(t),this.#l=new v(t),this.#h=0,this.#u=0,this.#b=h5.create(t),this.#i=0,this.#g=0,typeof l=="function"&&(this.#n=l),typeof u=="function"?(this.#c=u,this.#d=[]):(this.#c=void 0,this.#d=void 0),this.#w=!!this.#n,this.#p=!!this.#c,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!h,this.noDeleteOnFetchRejection=!!w,this.allowStaleOnFetchRejection=!!x,this.allowStaleOnFetchAbort=!!A,this.ignoreFetchAbort=!!k,this.maxEntrySize!==0){if(this.#r!==0&&!Di(this.#r))throw new TypeError("maxSize must be a positive integer if specified");if(!Di(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#V()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!a,this.ttlResolution=Di(o)||o===0?o:1,this.ttlAutopurge=!!i,this.ttl=n||0,this.ttl){if(!Di(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#C()}if(this.#e===0&&this.ttl===0&&this.#r===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#r){let S="LRU_CACHE_UNBOUNDED";GM(S)&&(VA.add(S),$A("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",S,r))}}getRemainingTTL(e){return this.#o.has(e)?1/0:0}#C(){let e=new Pc(this.#e),t=new Pc(this.#e);this.#y=e,this.#E=t,this.#B=(i,s,a=Cc.now())=>{if(t[i]=s!==0?a:0,e[i]=s,s!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#S(i)&&this.#k(this.#s[i],"expire")},s+1);c.unref&&c.unref()}},this.#P=i=>{t[i]=e[i]!==0?Cc.now():0},this.#v=(i,s)=>{if(e[s]){let a=e[s],c=t[s];if(!a||!c)return;i.ttl=a,i.start=c,i.now=n||o();let l=i.now-c;i.remainingTTL=a-l}};let n=0,o=()=>{let i=Cc.now();if(this.ttlResolution>0){n=i;let s=setTimeout(()=>n=0,this.ttlResolution);s.unref&&s.unref()}return i};this.getRemainingTTL=i=>{let s=this.#o.get(i);if(s===void 0)return 0;let a=e[s],c=t[s];if(!a||!c)return 1/0;let l=(n||o())-c;return a-l},this.#S=i=>{let s=t[i],a=e[i];return!!a&&!!s&&(n||o())-s>a}}#P=()=>{};#v=()=>{};#B=()=>{};#S=()=>!1;#V(){let e=new Pc(this.#e);this.#g=0,this.#x=e,this.#R=t=>{this.#g-=e[t],e[t]=0},this.#M=(t,n,o,i)=>{if(this.#a(n))return 0;if(!Di(o))if(i){if(typeof i!="function")throw new TypeError("sizeCalculation must be a function");if(o=i(n,t),!Di(o))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return o},this.#D=(t,n,o)=>{if(e[t]=n,this.#r){let i=this.#r-e[t];for(;this.#g>i;)this.#N(!0)}this.#g+=e[t],o&&(o.entrySize=n,o.totalCalculatedSize=this.#g)}}#R=e=>{};#D=(e,t,n)=>{};#M=(e,t,n,o)=>{if(n||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#I({allowStale:e=this.allowStale}={}){if(this.#i)for(let t=this.#u;!(!this.#U(t)||((e||!this.#S(t))&&(yield t),t===this.#h));)t=this.#l[t]}*#T({allowStale:e=this.allowStale}={}){if(this.#i)for(let t=this.#h;!(!this.#U(t)||((e||!this.#S(t))&&(yield t),t===this.#u));)t=this.#f[t]}#U(e){return e!==void 0&&this.#o.get(this.#s[e])===e}*entries(){for(let e of this.#I())this.#t[e]!==void 0&&this.#s[e]!==void 0&&!this.#a(this.#t[e])&&(yield[this.#s[e],this.#t[e]])}*rentries(){for(let e of this.#T())this.#t[e]!==void 0&&this.#s[e]!==void 0&&!this.#a(this.#t[e])&&(yield[this.#s[e],this.#t[e]])}*keys(){for(let e of this.#I()){let t=this.#s[e];t!==void 0&&!this.#a(this.#t[e])&&(yield t)}}*rkeys(){for(let e of this.#T()){let t=this.#s[e];t!==void 0&&!this.#a(this.#t[e])&&(yield t)}}*values(){for(let e of this.#I())this.#t[e]!==void 0&&!this.#a(this.#t[e])&&(yield this.#t[e])}*rvalues(){for(let e of this.#T())this.#t[e]!==void 0&&!this.#a(this.#t[e])&&(yield this.#t[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(let n of this.#I()){let o=this.#t[n],i=this.#a(o)?o.__staleWhileFetching:o;if(i!==void 0&&e(i,this.#s[n],this))return this.get(this.#s[n],t)}}forEach(e,t=this){for(let n of this.#I()){let o=this.#t[n],i=this.#a(o)?o.__staleWhileFetching:o;i!==void 0&&e.call(t,i,this.#s[n],this)}}rforEach(e,t=this){for(let n of this.#T()){let o=this.#t[n],i=this.#a(o)?o.__staleWhileFetching:o;i!==void 0&&e.call(t,i,this.#s[n],this)}}purgeStale(){let e=!1;for(let t of this.#T({allowStale:!0}))this.#S(t)&&(this.#k(this.#s[t],"expire"),e=!0);return e}info(e){let t=this.#o.get(e);if(t===void 0)return;let n=this.#t[t],o=this.#a(n)?n.__staleWhileFetching:n;if(o===void 0)return;let i={value:o};if(this.#y&&this.#E){let s=this.#y[t],a=this.#E[t];if(s&&a){let c=s-(Cc.now()-a);i.ttl=c,i.start=Date.now()}}return this.#x&&(i.size=this.#x[t]),i}dump(){let e=[];for(let t of this.#I({allowStale:!0})){let n=this.#s[t],o=this.#t[t],i=this.#a(o)?o.__staleWhileFetching:o;if(i===void 0||n===void 0)continue;let s={value:i};if(this.#y&&this.#E){s.ttl=this.#y[t];let a=Cc.now()-this.#E[t];s.start=Math.floor(Date.now()-a)}this.#x&&(s.size=this.#x[t]),e.unshift([n,s])}return e}load(e){this.clear();for(let[t,n]of e){if(n.start){let o=Date.now()-n.start;n.start=Cc.now()-o}this.set(t,n.value,n)}}set(e,t,n={}){if(t===void 0)return this.delete(e),this;let{ttl:o=this.ttl,start:i,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:c}=n,{noUpdateTTL:l=this.noUpdateTTL}=n,u=this.#M(e,t,n.size||0,a);if(this.maxEntrySize&&u>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#k(e,"set"),this;let d=this.#i===0?void 0:this.#o.get(e);if(d===void 0)d=this.#i===0?this.#u:this.#b.length!==0?this.#b.pop():this.#i===this.#e?this.#N(!1):this.#i,this.#s[d]=e,this.#t[d]=t,this.#o.set(e,d),this.#f[this.#u]=d,this.#l[d]=this.#u,this.#u=d,this.#i++,this.#D(d,u,c),c&&(c.set="add"),l=!1;else{this.#L(d);let h=this.#t[d];if(t!==h){if(this.#_&&this.#a(h)){h.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=h;f!==void 0&&!s&&(this.#w&&this.#n?.(f,e,"set"),this.#p&&this.#d?.push([f,e,"set"]))}else s||(this.#w&&this.#n?.(h,e,"set"),this.#p&&this.#d?.push([h,e,"set"]));if(this.#R(d),this.#D(d,u,c),this.#t[d]=t,c){c.set="replace";let f=h&&this.#a(h)?h.__staleWhileFetching:h;f!==void 0&&(c.oldValue=f)}}else c&&(c.set="update")}if(o!==0&&!this.#y&&this.#C(),this.#y&&(l||this.#B(d,o,i),c&&this.#v(c,d)),!s&&this.#p&&this.#d){let h=this.#d,f;for(;f=h?.shift();)this.#c?.(...f)}return this}pop(){try{for(;this.#i;){let e=this.#t[this.#h];if(this.#N(!0),this.#a(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#p&&this.#d){let e=this.#d,t;for(;t=e?.shift();)this.#c?.(...t)}}}#N(e){let t=this.#h,n=this.#s[t],o=this.#t[t];return this.#_&&this.#a(o)?o.__abortController.abort(new Error("evicted")):(this.#w||this.#p)&&(this.#w&&this.#n?.(o,n,"evict"),this.#p&&this.#d?.push([o,n,"evict"])),this.#R(t),e&&(this.#s[t]=void 0,this.#t[t]=void 0,this.#b.push(t)),this.#i===1?(this.#h=this.#u=0,this.#b.length=0):this.#h=this.#f[t],this.#o.delete(n),this.#i--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:o}=t,i=this.#o.get(e);if(i!==void 0){let s=this.#t[i];if(this.#a(s)&&s.__staleWhileFetching===void 0)return!1;if(this.#S(i))o&&(o.has="stale",this.#v(o,i));else return n&&this.#P(i),o&&(o.has="hit",this.#v(o,i)),!0}else o&&(o.has="miss");return!1}peek(e,t={}){let{allowStale:n=this.allowStale}=t,o=this.#o.get(e);if(o===void 0||!n&&this.#S(o))return;let i=this.#t[o];return this.#a(i)?i.__staleWhileFetching:i}#O(e,t,n,o){let i=t===void 0?void 0:this.#t[t];if(this.#a(i))return i;let s=new Fm,{signal:a}=n;a?.addEventListener("abort",()=>s.abort(a.reason),{signal:s.signal});let c={signal:s.signal,options:n,context:o},l=(m,g=!1)=>{let{aborted:y}=s.signal,w=n.ignoreFetchAbort&&m!==void 0;if(n.status&&(y&&!g?(n.status.fetchAborted=!0,n.status.fetchError=s.signal.reason,w&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),y&&!w&&!g)return d(s.signal.reason);let b=f;return this.#t[t]===f&&(m===void 0?b.__staleWhileFetching?this.#t[t]=b.__staleWhileFetching:this.#k(e,"fetch"):(n.status&&(n.status.fetchUpdated=!0),this.set(e,m,c.options))),m},u=m=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=m),d(m)),d=m=>{let{aborted:g}=s.signal,y=g&&n.allowStaleOnFetchAbort,w=y||n.allowStaleOnFetchRejection,b=w||n.noDeleteOnFetchRejection,x=f;if(this.#t[t]===f&&(!b||x.__staleWhileFetching===void 0?this.#k(e,"fetch"):y||(this.#t[t]=x.__staleWhileFetching)),w)return n.status&&x.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),x.__staleWhileFetching;if(x.__returned===x)throw m},h=(m,g)=>{let y=this.#m?.(e,i,c);y&&y instanceof Promise&&y.then(w=>m(w===void 0?void 0:w),g),s.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(m(void 0),n.allowStaleOnFetchAbort&&(m=w=>l(w,!0)))})};n.status&&(n.status.fetchDispatched=!0);let f=new Promise(h).then(l,u),p=Object.assign(f,{__abortController:s,__staleWhileFetching:i,__returned:void 0});return t===void 0?(this.set(e,p,{...c.options,status:void 0}),t=this.#o.get(e)):this.#t[t]=p,p}#a(e){if(!this.#_)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof Fm}async fetch(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:h=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:m,forceRefresh:g=!1,status:y,signal:w}=t;if(!this.#_)return y&&(y.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:o,noDeleteOnStaleGet:i,status:y});let b={allowStale:n,updateAgeOnGet:o,noDeleteOnStaleGet:i,ttl:s,noDisposeOnSet:a,size:c,sizeCalculation:l,noUpdateTTL:u,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:h,allowStaleOnFetchAbort:p,ignoreFetchAbort:f,status:y,signal:w},x=this.#o.get(e);if(x===void 0){y&&(y.fetch="miss");let A=this.#O(e,x,b,m);return A.__returned=A}else{let A=this.#t[x];if(this.#a(A)){let $=n&&A.__staleWhileFetching!==void 0;return y&&(y.fetch="inflight",$&&(y.returnedStale=!0)),$?A.__staleWhileFetching:A.__returned=A}let k=this.#S(x);if(!g&&!k)return y&&(y.fetch="hit"),this.#L(x),o&&this.#P(x),y&&this.#v(y,x),A;let v=this.#O(e,x,b,m),I=v.__staleWhileFetching!==void 0&&n;return y&&(y.fetch=k?"stale":"refresh",I&&k&&(y.returnedStale=!0)),I?v.__staleWhileFetching:v.__returned=v}}async forceFetch(e,t={}){let n=await this.fetch(e,t);if(n===void 0)throw new Error("fetch() returned undefined");return n}memo(e,t={}){let n=this.#A;if(!n)throw new Error("no memoMethod provided to constructor");let{context:o,forceRefresh:i,...s}=t,a=this.get(e,s);if(!i&&a!==void 0)return a;let c=n(e,a,{options:s,context:o});return this.set(e,c,s),c}get(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:s}=t,a=this.#o.get(e);if(a!==void 0){let c=this.#t[a],l=this.#a(c);return s&&this.#v(s,a),this.#S(a)?(s&&(s.get="stale"),l?(s&&n&&c.__staleWhileFetching!==void 0&&(s.returnedStale=!0),n?c.__staleWhileFetching:void 0):(i||this.#k(e,"expire"),s&&n&&(s.returnedStale=!0),n?c:void 0)):(s&&(s.get="hit"),l?c.__staleWhileFetching:(this.#L(a),o&&this.#P(a),c))}else s&&(s.get="miss")}#F(e,t){this.#l[t]=e,this.#f[e]=t}#L(e){e!==this.#u&&(e===this.#h?this.#h=this.#f[e]:this.#F(this.#l[e],this.#f[e]),this.#F(this.#u,e),this.#u=e)}delete(e){return this.#k(e,"delete")}#k(e,t){let n=!1;if(this.#i!==0){let o=this.#o.get(e);if(o!==void 0)if(n=!0,this.#i===1)this.#H(t);else{this.#R(o);let i=this.#t[o];if(this.#a(i)?i.__abortController.abort(new Error("deleted")):(this.#w||this.#p)&&(this.#w&&this.#n?.(i,e,t),this.#p&&this.#d?.push([i,e,t])),this.#o.delete(e),this.#s[o]=void 0,this.#t[o]=void 0,o===this.#u)this.#u=this.#l[o];else if(o===this.#h)this.#h=this.#f[o];else{let s=this.#l[o];this.#f[s]=this.#f[o];let a=this.#f[o];this.#l[a]=this.#l[o]}this.#i--,this.#b.push(o)}}if(this.#p&&this.#d?.length){let o=this.#d,i;for(;i=o?.shift();)this.#c?.(...i)}return n}clear(){return this.#H("delete")}#H(e){for(let t of this.#T({allowStale:!0})){let n=this.#t[t];if(this.#a(n))n.__abortController.abort(new Error("deleted"));else{let o=this.#s[t];this.#w&&this.#n?.(n,o,e),this.#p&&this.#d?.push([n,o,e])}}if(this.#o.clear(),this.#t.fill(void 0),this.#s.fill(void 0),this.#y&&this.#E&&(this.#y.fill(0),this.#E.fill(0)),this.#x&&this.#x.fill(0),this.#h=0,this.#u=0,this.#b.length=0,this.#g=0,this.#i=0,this.#p&&this.#d){let t=this.#d,n;for(;n=t?.shift();)this.#c?.(...n)}}};var g5=xt(Vm(),1);var y5=40;function w5(r,e){if(!r.length)throw new Error("Unexpected end of data");let t=g5.default.decode(r);return e.seek(g5.default.decode.bytes),t}function b5(r){let e=new DataView(r.buffer,r.byteOffset,r.byteLength),t=0;return{version:2,characteristics:[e.getBigUint64(t,!0),e.getBigUint64(t+=8,!0)],dataOffset:Number(e.getBigUint64(t+=8,!0)),dataSize:Number(e.getBigUint64(t+=8,!0)),indexOffset:Number(e.getBigUint64(t+=8,!0))}}var Ni={Null:r=>r===null?r:void 0,Int:r=>Number.isInteger(r)?r:void 0,Float:r=>typeof r=="number"&&Number.isFinite(r)?r:void 0,String:r=>typeof r=="string"?r:void 0,Bool:r=>typeof r=="boolean"?r:void 0,Bytes:r=>r instanceof Uint8Array?r:void 0,Link:r=>r!==null&&typeof r=="object"&&r.asCID===r?r:void 0,List:r=>Array.isArray(r)?r:void 0,Map:r=>r!==null&&typeof r=="object"&&r.asCID!==r&&!Array.isArray(r)&&!(r instanceof Uint8Array)?r:void 0},Fu={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":Ni.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(Ni.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=Fu["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let o=e;o<r.length;o++){let i=r[o];if(i=Fu["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:Ni.Int,CarV1HeaderOrV2Pragma:r=>{if(Ni.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let o=0;o<e.length;o++){let[i,s]=e[o];switch(i){case"roots":{let a=Fu["CarV1HeaderOrV2Pragma > roots (anon)"](r[i]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=Fu.Int(r[i]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},Hu={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":Ni.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(Ni.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=Hu["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let o=e;o<r.length;o++){let i=r[o];if(i=Hu["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:Ni.Int,CarV1HeaderOrV2Pragma:r=>{if(Ni.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let o=0;o<e.length;o++){let[i,s]=e[o];switch(i){case"roots":{let a=Hu["CarV1HeaderOrV2Pragma > roots (anon)"](s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=Hu.Int(s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},x5={toTyped:Fu.CarV1HeaderOrV2Pragma,toRepresentation:Hu.CarV1HeaderOrV2Pragma};var k7e=q3();var lU=xt(Vm(),1);var D7e=[new F(E.map,2),new F(E.string,"version"),new F(E.uint,1),new F(E.string,"roots")],N7e=new F(E.tag,42);async function E5(r,e){let t=w5(await r.upTo(8),r);if(t===0)throw new Error("Invalid CAR header (zero length)");let n=await r.exactly(t,!0),o=mi(n);if(x5.toTyped(o)===void 0)throw new Error("Invalid CAR header format");if(o.version!==1&&o.version!==2||e!==void 0&&o.version!==e)throw new Error(`Invalid CAR version: ${o.version}${e!==void 0?` (expected ${e})`:""}`);if(o.version===1){if(!Array.isArray(o.roots))throw new Error("Invalid CAR header format");return o}if(o.roots!==void 0)throw new Error("Invalid CAR header format");let i=b5(await r.exactly(y5,!0));r.seek(i.dataOffset-r.pos);let s=await E5(r,1);return Object.assign(s,i)}function Vu(r){let e=0;return{async upTo(t){return r.subarray(e,e+Math.min(t,r.length-e))},async exactly(t,n=!1){if(t>r.length-e)throw new Error("Unexpected end of data");let o=r.subarray(e,e+t);return n&&(e+=t),o},seek(t){e+=t},get pos(){return e}}}var v5=xt(Vm(),1),t_=1;function S5(r){let e=Ua({version:t_,roots:r}),t=v5.default.encode(e.length),n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function r_(r){return{async setRoots(e){let t=S5(e);await r.write(t)},async writeBlock(e){let{cid:t,bytes:n}=e;await r.write(new Uint8Array(v5.default.encode(t.bytes.length+n.length))),await r.write(t.bytes),n.length&&await r.write(n)},async close(){await r.end()},version(){return t_}}}function $m(){}function n_(){let r=[],e=null,t=$m,n=!1,o=null,i=$m,s=()=>(e||(e=new Promise(l=>{t=()=>{e=null,t=$m,l()}})),e),a={write(l){r.push(l);let u=s();return i(),u},async end(){n=!0;let l=s();i(),await l}},c={async next(){let l=r.shift();return l?(r.length===0&&t(),{done:!1,value:l}):n?(t(),{done:!0,value:void 0}):(o||(o=new Promise(u=>{i=()=>(o=null,i=$m,u(c.next()))})),o)}};return{writer:a,iterator:c}}var $u=class r{constructor(e,t){this._encoder=t,this._mutex=t.setRoots(e),this._ended=!1}async put(e){if(!(e.bytes instanceof Uint8Array)||!e.cid)throw new TypeError("Can only write {cid, bytes} objects");if(this._ended)throw new Error("Already closed");let t=O.asCID(e.cid);if(!t)throw new TypeError("Can only write {cid, bytes} objects");return this._mutex=this._mutex.then(()=>this._encoder.writeBlock({cid:t,bytes:e.bytes})),this._mutex}async close(){if(this._ended)throw new Error("Already closed");return await this._mutex,this._ended=!0,this._encoder.close()}version(){return this._encoder.version()}static create(e){e=hU(e);let{encoder:t,iterator:n}=o_(),o=new r(e,t),i=new zm(n);return{writer:o,out:i}}static createAppender(){let{encoder:e,iterator:t}=o_();e.setRoots=()=>Promise.resolve();let n=new r([],e),o=new zm(t);return{writer:n,out:o}}static async updateRootsInBytes(e,t){let n=Vu(e);await E5(n);let o=S5(t);if(Number(n.pos)!==o.length)throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${n.pos} bytes, new header is ${o.length} bytes)`);return e.set(o,0),e}},zm=class{constructor(e){this._iterator=e}[Symbol.asyncIterator](){if(this._iterating)throw new Error("Multiple iterator not supported");return this._iterating=!0,this._iterator}};function o_(){let r=n_(),{writer:e,iterator:t}=r;return{encoder:r_(e),iterator:t}}function hU(r){if(r===void 0)return[];if(!Array.isArray(r)){let t=O.asCID(r);if(!t)throw new TypeError("roots must be a single CID or an array of CIDs");return[t]}let e=[];for(let t of r){let n=O.asCID(t);if(!n)throw new TypeError("roots must be a single CID or an array of CIDs");e.push(n)}return e}var pU=1,A5=class{components;constructor(e,t){this.components=e}async import(e,t){await Lt(this.components.blockstore.putMany(Je(e.blocks(),({cid:n,bytes:o})=>({cid:n,block:o})),t))}async export(e,t,n){let o=J(),i=Array.isArray(e)?e:[e],s=new Cr({concurrency:pU});s.on("idle",()=>{o.resolve()}),s.on("error",a=>{s.clear(),o.reject(a)});for(let a of i)s.add(async()=>{await this.#e(a,s,async(c,l)=>{n?.blockFilter?.has(c.multihash.bytes)!==!0&&(n?.blockFilter?.add(c.multihash.bytes),await t.put({cid:c,bytes:l}))},n)}).catch(()=>{});try{await o.promise}finally{await t.close()}}async*stream(e,t){let{writer:n,out:o}=$u.create(e);this.export(e,n,t).catch(()=>{});for await(let i of o)yield i}async#e(e,t,n,o){let i=await this.components.getCodec(e.code),s=await this.components.blockstore.get(e,o);await n(e,s);let a=Eh({bytes:s,cid:e,codec:i});for await(let[,c]of a.links())t.add(async()=>{await this.#e(c,t,n,o)})}};function i_(r,e={}){return new A5(r,e)}function zu(r,e={}){let t=ac(r),n={_cancelled:!1,async start(){this._cancelled=!1},async pull(o){try{let{value:i,done:s}=await t.next();if(this._cancelled)return;if(s===!0){o.close();return}o.enqueue(i)}catch(i){o.error(i)}},cancel(){this._cancelled=!0}};return new globalThis.ReadableStream(n,e)}function _5(r,e,t){Object.defineProperty(r,e,{enumerable:!0,configurable:!1,set:()=>{},get:()=>t})}function Uo(r,e){_5(r,"type",e)}function Fo(r,e){_5(r,"url",e)}function s_(r){_5(r,"redirected",!0)}function On(r,e,t){let n=new Response(e,{...t??{},status:200,statusText:"OK"});return t?.redirected===!0&&s_(n),Uo(n,"basic"),Fo(n,r),n.headers.set("Accept-Ranges","bytes"),n}function Rc(r,e,t){let n=new Response(e,{...t??{},status:502,statusText:"Bad Gateway"});return Uo(n,"basic"),Fo(n,r),n}function qm(r,e,t){let n=new Response(e,{...t??{},status:501,statusText:"Not Implemented"});return n.headers.set("X-Content-Type-Options","nosniff"),Uo(n,"basic"),Fo(n,r),n}function Ho(r,e,t){let n=new Response(e,{...t??{},status:406,statusText:"Not Acceptable"});return Uo(n,"basic"),Fo(n,r),n}function Gm(r,e,t){let n=new Response(e,{...t??{},status:404,statusText:"Not Found"});return Uo(n,"basic"),Fo(n,r),n}function Ku(r,e,t){e instanceof Error&&(e=e.message);let n=new Response(e,{...t??{},status:400,statusText:"Bad Request"});return Uo(n,"basic"),Fo(n,r),n}function qu(r,e,t){let n=new Response(null,{...t??{},status:301,statusText:"Moved Permanently",headers:{...t?.headers??{},location:e}});return Uo(n,"basic"),Fo(n,r),n}function Wm(r,e,{byteRangeContext:t,log:n},o){if(!t.isRangeRequest)return On(r,e,o);if(!t.isValidRangeRequest)return Km(r,e,o);let i;try{i=new Response(e,{...o??{},status:206,statusText:"Partial Content",headers:{...o?.headers??{},"content-range":t.contentRangeHeaderValue}})}catch(s){return n?.error("failed to create range response",s),Km(r,e,o)}return o?.redirected===!0&&s_(i),Uo(i,"basic"),Fo(i,r),i.headers.set("Accept-Ranges","bytes"),i}function Km(r,e,t){let n=new Response(e,{...t??{},status:416,statusText:"Requested Range Not Satisfiable"});return Uo(n,"basic"),Fo(n,r),n}var dt=class{codes=[];log;pluginOptions;constructor(e){let t=this.constructor.name.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();this.log=e.logger.forComponent(t),this.pluginOptions=e}canHandle(e){throw new Error("Not implemented")}async handle(e){throw new Error("Not implemented")}};var Ym=class extends dt{canHandle(e){return this.log("checking if we can handle %c with accept %s",e.cid,e.accept),e.accept?.startsWith("application/vnd.ipld.car")===!0||e.query.format==="car"}async handle(e){let{options:t}=e,{getBlockstore:n,helia:o}=this.pluginOptions;e.reqFormat="car",e.query.download=!0,e.query.filename=e.query.filename??`${e.cid.toString()}.car`;let i=n(e.cid,e.resource,t?.session??!0,t),s=i_({blockstore:i,getCodec:o.getCodec}),a=zu(s.stream(e.cid,t)),c=On(e.resource,a);return c.headers.set("content-type","application/vnd.ipld.car; version=1"),c}};function a_(r){let e=wr(r,{allowIndefinite:!1,coerceUndefinedToNull:!1,allowNaN:!1,allowInfinity:!1,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,allowBigInt:!1});return new TextDecoder().decode($l(e))}var qr=class extends Error{static name="InvalidRangeError";constructor(e="Invalid range request"){super(e),this.name="InvalidRangeError"}},Xm=class extends Error{static name="NoContentError";constructor(e="No content found"){super(e),this.name="NoContentError"}},Qm=class extends Error{static name="SubdomainNotSupportedError";constructor(e="Subdomain not supported"){super(e),this.name="SubdomainNotSupportedError"}};function c_({ttl:r,protocol:e,response:t}){if(t.headers.has("cache-control"))return;let n;e==="ipfs"?n="public, max-age=29030400, immutable":r==null?n="public, max-age=300":n=`public, max-age=${r}`,t.headers.set("cache-control",n)}function l_({byteStart:r,byteEnd:e,byteSize:t}){let n=t??"*";if((e??0)>=(t??1/0))throw new qr("Invalid range: Range-end index is greater than or equal to the size of the file.");if((r??0)>=(t??1/0))throw new qr("Invalid range: Range-start index is greater than or equal to the size of the file.");if(r!=null&&e==null)return t==null?`bytes */${n}`:`bytes ${r}-${t-1}/${t}`;if(r==null&&e!=null){if(t==null)return`bytes */${n}`;let o=t-1;return`bytes ${o-e+1}-${o}/${t}`}return r==null&&e==null?`bytes */${n}`:`bytes ${r}-${e}/${n}`}function jm(r,e){e!=null&&r.headers.set("X-Ipfs-Roots",e.map(t=>t.toV1().toString()).join(","))}var Bn=class extends Error{name;code;constructor(e,t,n){super(e),this.name=t,this.code=n}},Gr=class extends Bn{constructor(e="not a Unixfs node"){super(e,"NotUnixFSError","ERR_NOT_UNIXFS")}},Er=class extends Bn{constructor(e="invalid PBNode"){super(e,"InvalidPBNodeError","ERR_INVALID_PBNODE")}},Oi=class extends Bn{constructor(e="unknown error"){super(e,"InvalidPBNodeError","ERR_UNKNOWN_ERROR")}},Gu=class extends Bn{constructor(e="path already exists"){super(e,"AlreadyExistsError","ERR_ALREADY_EXISTS")}},Lc=class extends Bn{constructor(e="path does not exist"){super(e,"DoesNotExistError","ERR_DOES_NOT_EXIST")}},Dc=class extends Bn{constructor(e="no content"){super(e,"NoContentError","ERR_NO_CONTENT")}},Zm=class extends Bn{constructor(e="not a file"){super(e,"NotAFileError","ERR_NOT_A_FILE")}},Bi=class extends Bn{constructor(e="not a directory"){super(e,"NotADirectoryError","ERR_NOT_A_DIRECTORY")}},Wr=class extends Bn{constructor(e="invalid parameters"){super(e,"InvalidParametersError","ERR_INVALID_PARAMETERS")}};function mU(r){return r[Symbol.asyncIterator]!=null}function gU(r){if(mU(r))return(async()=>{let t;for await(let n of r)t=n;return t})();let e;for(let t of r)e=t;return e}var Mi=gU;var Jm=class r extends Error{static name="BadPathError";static code="ERR_BAD_PATH";name=r.name;code=r.code;constructor(e="Bad path"){super(e)}},fn=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not found"){super(e)}},e2=class r extends Error{static name="NoResolverError";static code="ERR_NO_RESOLVER";name=r.name;code=r.code;constructor(e="No resolver"){super(e)}},Ct=class r extends Error{static name="NotUnixFSError";static code="ERR_NOT_UNIXFS";name=r.name;code=r.code;constructor(e="Not UnixFS"){super(e)}},t2=class r extends Error{static name="OverReadError";static code="ERR_OVER_READ";name=r.name;code=r.code;constructor(e="Over read"){super(e)}},r2=class r extends Error{static name="UnderReadError";static code="ERR_UNDER_READ";name=r.name;code=r.code;constructor(e="Under read"){super(e)}},n2=class r extends Error{static name="NoPropError";static code="ERR_NO_PROP";name=r.name;code=r.code;constructor(e="No Property found"){super(e)}},Zs=class r extends Error{static name="InvalidParametersError";static code="ERR_INVALID_PARAMS";name=r.name;code=r.code;constructor(e="Invalid parameters"){super(e)}};function Nc(r,e,t,n,o,i,s){let a=r,c=o;for(;i.length>0;){let l=i[0];if(l in a){i.shift(),c=`${c}/${l}`;let u=O.asCID(a[l]);if(u!=null)return{entry:{type:"object",name:n,path:o,cid:t,node:e,depth:s,size:BigInt(e.length),content:async function*(){yield r}},next:{cid:u,name:l,path:c,toResolve:i}};a=a[l]}else throw new n2(`No property named ${l} found in node ${t}`)}return{entry:{type:"object",name:n,path:o,cid:t,node:e,depth:s,size:BigInt(e.length),content:async function*(){yield r}}}}var yU=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=mi(c);return Nc(l,c,r,e,t,n,i)},u_=yU;var wU=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=Ha(c);return Nc(l,c,r,e,t,n,i)},d_=wU;function bU(r,e,t,n){let o=BigInt(r.length),i=BigInt(e+o);return t>=i||n<e?new Uint8Array(0):(n>=e&&n<i&&(r=r.subarray(0,Number(n-e))),t>=e&&t<i&&(r=r.subarray(Number(t-e))),r)}var Js=bU;var xU=(r,e=0,t=r)=>{let n=BigInt(r),o=BigInt(e??0),i=BigInt(t);if(i!==n&&(i=o+i),i>n&&(i=n),o<0n)throw new Zs("Offset must be greater than or equal to 0");if(o>n)throw new Zs("Offset must be less than the file size");if(i<0n)throw new Zs("Length must be greater than or equal to 0");if(i>n)throw new Zs("Length must be less than the file size");return{start:o,end:i}},Oc=xU;var EU=r=>{async function*e(t={}){let{start:n,end:o}=Oc(r.length,t.offset,t.length),i=Js(r,0n,n,o);t.onProgress?.(new M("unixfs:exporter:progress:identity",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return e},vU=async(r,e,t,n,o,i,s,a)=>{if(n.length>0)throw new fn(`No link named ${t} found in raw node ${r}`);let c=we(r.multihash.bytes);return{entry:{type:"identity",name:e,path:t,cid:r,content:EU(c.digest),depth:i,size:BigInt(c.digest.length),node:c.digest}}},f_=vU;var SU=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=bg(c);return Nc(l,c,r,e,t,n,i)},h_=SU;var AU=r=>{async function*e(t={}){let{start:n,end:o}=Oc(r.length,t.offset,t.length),i=Js(r,0n,n,o);t.onProgress?.(new M("unixfs:exporter:progress:raw",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return e},_U=async(r,e,t,n,o,i,s,a)=>{if(n.length>0)throw new fn(`No link named ${t} found in raw node ${r}`);let c=await s.get(r,a);return{entry:{type:"raw",name:e,path:t,cid:r,content:AU(c),depth:i,size:BigInt(c.length),node:c}}},p_=_U;var Wu=class r extends Error{static name="InvalidTypeError";static code="ERR_INVALID_TYPE";name=r.name;code=r.code;constructor(e="Invalid type"){super(e)}};var Mn;(function(r){let e;(function(o){o.Raw="Raw",o.Directory="Directory",o.File="File",o.Metadata="Metadata",o.Symlink="Symlink",o.HAMTShard="HAMTShard"})(e=r.DataType||(r.DataType={}));let t;(function(o){o[o.Raw=0]="Raw",o[o.Directory=1]="Directory",o[o.File=2]="File",o[o.Metadata=3]="Metadata",o[o.Symlink=4]="Symlink",o[o.HAMTShard=5]="HAMTShard"})(t||(t={})),function(o){o.codec=()=>Ke(t)}(e=r.DataType||(r.DataType={}));let n;r.codec=()=>(n==null&&(n=re((o,i,s={})=>{if(s.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),r.DataType.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),o.filesize!=null&&(i.uint32(24),i.uint64(o.filesize)),o.blocksizes!=null)for(let a of o.blocksizes)i.uint32(32),i.uint64(a);o.hashType!=null&&(i.uint32(40),i.uint64(o.hashType)),o.fanout!=null&&(i.uint32(48),i.uint64(o.fanout)),o.mode!=null&&(i.uint32(56),i.uint32(o.mode)),o.mtime!=null&&(i.uint32(66),o2.codec().encode(o.mtime,i)),s.lengthDelimited!==!1&&i.ldelim()},(o,i)=>{let s={blocksizes:[]},a=i==null?o.len:o.pos+i;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:s.Type=r.DataType.codec().decode(o);break;case 2:s.Data=o.bytes();break;case 3:s.filesize=o.uint64();break;case 4:s.blocksizes.push(o.uint64());break;case 5:s.hashType=o.uint64();break;case 6:s.fanout=o.uint64();break;case 7:s.mode=o.uint32();break;case 8:s.mtime=o2.codec().decode(o,o.uint32());break;default:o.skipType(c&7);break}}return s})),n),r.encode=o=>te(o,r.codec()),r.decode=o=>ee(o,r.codec())})(Mn||(Mn={}));var o2;(function(r){let e;r.codec=()=>(e==null&&(e=re((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Seconds!=null&&(n.uint32(8),n.int64(t.Seconds)),t.FractionalNanoseconds!=null&&(n.uint32(21),n.fixed32(t.FractionalNanoseconds)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let s=t.uint32();switch(s>>>3){case 1:o.Seconds=t.int64();break;case 2:o.FractionalNanoseconds=t.fixed32();break;default:t.skipType(s&7);break}}return o})),e),r.encode=t=>te(t,r.codec()),r.decode=t=>ee(t,r.codec())})(o2||(o2={}));var m_;(function(r){let e;r.codec=()=>(e==null&&(e=re((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.MimeType!=null&&(n.uint32(10),n.string(t.MimeType)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let s=t.uint32();switch(s>>>3){case 1:o.MimeType=t.string();break;default:t.skipType(s&7);break}}return o})),e),r.encode=t=>te(t,r.codec()),r.decode=t=>ee(t,r.codec())})(m_||(m_={}));var g_={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},IU=["directory","hamt-sharded-directory"],y_=parseInt("0644",8),w_=parseInt("0755",8),ie=class r{static unmarshal(e){let t=Mn.decode(e),n=new r({type:g_[t.Type!=null?t.Type.toString():"File"],data:t.Data,blockSizes:t.blocksizes,mode:t.mode,mtime:t.mtime!=null?{secs:t.mtime.Seconds??0n,nsecs:t.mtime.FractionalNanoseconds}:void 0,fanout:t.fanout});return n._originalMode=t.mode??0,n}type;data;blockSizes;hashType;fanout;mtime;_mode;_originalMode;constructor(e={type:"file"}){let{type:t,data:n,blockSizes:o,hashType:i,fanout:s,mtime:a,mode:c}=e;if(t!=null&&!Object.values(g_).includes(t))throw new Wu("Type: "+t+" is not valid");this.type=t??"file",this.data=n,this.hashType=i,this.fanout=s,this.blockSizes=o??[],this._originalMode=0,this.mode=c,this.mtime=a}set mode(e){e==null?this._mode=this.isDirectory()?w_:y_:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return IU.includes(this.type)}addBlockSize(e){this.blockSizes.push(e)}removeBlockSize(e){this.blockSizes.splice(e,1)}fileSize(){if(this.isDirectory())return 0n;let e=0n;return this.blockSizes.forEach(t=>{e+=t}),this.data!=null&&(e+=BigInt(this.data.length)),e}marshal(){let e;switch(this.type){case"raw":e=Mn.DataType.Raw;break;case"directory":e=Mn.DataType.Directory;break;case"file":e=Mn.DataType.File;break;case"metadata":e=Mn.DataType.Metadata;break;case"symlink":e=Mn.DataType.Symlink;break;case"hamt-sharded-directory":e=Mn.DataType.HAMTShard;break;default:throw new Wu(`Type: ${e} is not valid`)}let t=this.data;(this.data==null||this.data.length===0)&&(t=void 0);let n;this.mode!=null&&(n=this._originalMode&4294963200|(this.mode??0),n===y_&&!this.isDirectory()&&(n=void 0),n===w_&&this.isDirectory()&&(n=void 0));let o;return this.mtime!=null&&(o={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),Mn.encode({Type:e,Data:t,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:n,mtime:o})}};var s2=xt(E_(),1);function TU(r){let e=new Array(4);for(let t=0;t<4;t++)e[t]=r&255,r=r>>8;return new Uint8Array(e)}var wwe=ji({name:"murmur3-32",code:35,encode:r=>TU(s2.default.x86.hash32(r))}),ea=ji({name:"murmur3-128",code:34,encode:r=>Xi.fromHex(s2.default.x64.hash128(r))}),bwe=ji({name:"murmur3-x64-64",code:34,encode:r=>Xi.fromHex(s2.default.x64.hash128(r)).subarray(0,8)});var A_=xt(a2(),1);var Yr=class r{_options;_popCount;_parent;_posAtParent;_children;key;constructor(e,t,n=0){this._options=e,this._popCount=0,this._parent=t,this._posAtParent=n,this._children=new A_.default,this.key=null}async put(e,t){let n=await this._findNewBucketAndPos(e);n.bucket._putAt(n,e,t)}async get(e){let t=await this._findChild(e);if(t!=null)return t.value}async del(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);n!=null&&n.key===e&&t.bucket._delAt(t.pos)}leafCount(){return this._children.compactArray().reduce((t,n)=>n instanceof r?t+n.leafCount():t+1,0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){let e=this._children.compactArray();for(let t of e)t instanceof r?yield*t.eachLeafSeries():yield t}serialize(e,t){let n=[];return t(this._children.reduce((o,i,s)=>(i!=null&&(i instanceof r?o.push(i.serialize(e,t)):o.push(e(i,s))),o),n))}async asyncTransform(e,t){return __(this,e,t)}toJSON(){return this.serialize(LU,DU)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);if(!(n instanceof r)&&n!=null&&n.key===e)return n}async _findPlace(e){let t=this._options.hash(typeof e=="string"?C(e):e),n=await t.take(this._options.bits),o=this._children.get(n);return o instanceof r?o._findPlace(t):{bucket:this,pos:n,hash:t,existingChild:o}}async _findNewBucketAndPos(e){let t=await this._findPlace(e);if(t.existingChild!=null&&t.existingChild.key!==e){let n=new r(this._options,t.bucket,t.pos);t.bucket._putObjectAt(t.pos,n);let o=await n._findPlace(t.existingChild.hash);return o.bucket._putAt(o,t.existingChild.key,t.existingChild.value),n._findNewBucketAndPos(t.hash)}return t}_putAt(e,t,n){this._putObjectAt(e.pos,{key:t,value:n,hash:e.hash})}_putObjectAt(e,t){this._children.get(e)==null&&this._popCount++,this._children.set(e,t)}_delAt(e){if(e===-1)throw new Error("Invalid position");this._children.get(e)!=null&&this._popCount--,this._children.unset(e),this._level()}_level(){if(this._parent!=null&&this._popCount<=1)if(this._popCount===1){let e=this._children.find(RU);if(e!=null&&!(e instanceof r)){let t=e.hash;t.untake(this._options.bits);let n={pos:this._posAtParent,hash:t,bucket:this._parent};this._parent._putAt(n,e.key,e.value)}}else this._parent._delAt(this._posAtParent)}_at(e){return this._children.get(e)}};function RU(r){return!!r}function LU(r,e){return r.key}function DU(r){return r}async function __(r,e,t){let n=[];for(let o of r._children.compactArray())if(o instanceof Yr)await __(o,e,t);else{let i=await e(o);n.push({bitField:r._children.bitField(),children:i})}return t(n)}var NU=[255,254,252,248,240,224,192,128],OU=[1,3,7,15,31,63,127,255],c2=class{_value;_currentBytePos;_currentBitPos;constructor(e){this._value=e,this._currentBytePos=e.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(e){let t=e,n=0;for(;t>0&&this._haveBits();){let o=this._value[this._currentBytePos],i=this._currentBitPos+1,s=Math.min(i,t),a=BU(o,i-s,s);n=(n<<s)+a,t-=s,this._currentBitPos-=s,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return n}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function BU(r,e,t){let n=MU(e,t);return(r&n)>>>e}function MU(r,e){return NU[r]&OU[Math.min(e+r-1,7)]}function I_(r){function e(t){return t instanceof l2?t:new l2(t,r)}return e}var l2=class{_value;_hashFn;_depth;_availableBits;_currentBufferIndex;_buffers;constructor(e,t){if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=t,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let t=e;for(;this._availableBits<t;)await this._produceMoreBits();let n=0;for(;t>0;){let o=this._buffers[this._currentBufferIndex],i=Math.min(o.availableBits(),t),s=o.take(i);n=(n<<i)+s,t-=i,this._availableBits-=i,o.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let t=e;for(;t>0;){let n=this._buffers[this._currentBufferIndex],o=Math.min(n.totalBits()-n.availableBits(),t);n.untake(o),t-=o,this._availableBits+=o,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?ge([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new c2(t);this._buffers.push(n),this._availableBits+=n.availableBits()}};function Bc(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:I_(r.hashFn)};return new Yr(e)}var UU=async function(r){return(await ea.encode(r)).slice(0,8).reverse()},FU=async(r,e,t)=>{let n=(e.tableSize()-1).toString(16).length;await Promise.all(r.map(async o=>{if(o.Name==null)throw new Error("Unexpected Link without a Name");if(o.Name.length===n){let i=parseInt(o.Name,16);e._putObjectAt(i,new Yr({hash:t._options.hash,bits:t._options.bits},e,i));return}await t.put(o.Name.substring(2),!0)}))},T_=(r,e)=>r.toString(16).toUpperCase().padStart(e,"0").substring(0,e),HU=r=>{let e=r.bucket,t=[];for(;e._parent!=null;)t.push(e),e=e._parent;return t.push(e),t.reverse()},k_=async(r,e,t,n,o)=>{if(n==null){if(r.Data==null)throw new Ct("no data in PBNode");let d;try{d=ie.unmarshal(r.Data)}catch(f){throw new Ct(f.message)}if(d.type!=="hamt-sharded-directory")throw new Ct("not a HAMT");if(d.fanout==null)throw new Ct("missing fanout");let h=Bc({hashFn:UU,bits:Math.log2(Number(d.fanout))});n={rootBucket:h,hamtDepth:1,lastBucket:h}}let i=(n.lastBucket.tableSize()-1).toString(16).length;await FU(r.Links,n.lastBucket,n.rootBucket);let s=await n.rootBucket._findNewBucketAndPos(e),a=T_(s.pos,i),c=HU(s);c.length>n.hamtDepth&&(n.lastBucket=c[n.hamtDepth],a=T_(n.lastBucket._posAtParent,i));let l=r.Links.find(d=>{if(d.Name==null)return!1;let h=d.Name.substring(0,i),f=d.Name.substring(i);return!(h!==a||f!==""&&f!==e)});if(l==null)return;if(l.Name!=null&&l.Name.substring(i)===e)return l.Hash;n.hamtDepth++;let u=await t.get(l.Hash,o);return r=yt(u),k_(r,e,t,n,o)},C_=k_;var VU=(r,e,t,n,o,i,s)=>{async function*a(c={}){let l=c.offset??0,u=c.length??e.Links.length,d=e.Links.slice(l,u);c.onProgress?.(new M("unixfs:exporter:walk:directory",{cid:r})),yield*Pe(d,h=>Je(h,f=>async()=>{let p=f.Name??"",m=`${n}/${p}`;return(await o(f.Hash,p,m,[],i+1,s,c)).entry}),h=>qt(h,{ordered:!0,concurrency:c.blockReadConcurrency}),h=>$r(h,f=>f!=null))}return a},P_=VU;async function R_(r,e,t,n,o,i,s){if(e instanceof Uint8Array){let l=Js(e,n,o,i);t.push(l);return}if(e.Data==null)throw new Ct("no data in PBNode");let a;try{a=ie.unmarshal(e.Data)}catch(l){throw new Ct(l.message)}if(a.data!=null){let l=a.data,u=Js(l,n,o,i);t.push(u),n+=BigInt(u.byteLength)}let c=[];if(e.Links.length!==a.blockSizes.length)throw new Ct("Inconsistent block sizes and dag links");for(let l=0;l<e.Links.length;l++){let u=e.Links[l],d=n,h=d+a.blockSizes[l];if((o>=d&&o<h||i>=d&&i<=h||o<d&&i>h)&&c.push({link:u,blockStart:n}),n=h,n>i)break}await Pe(c,l=>Je(l,u=>async()=>{let d=await r.get(u.link.Hash,s);return{...u,block:d}}),l=>qt(l,{ordered:!0,concurrency:s.blockReadConcurrency}),async l=>{for await(let{link:u,block:d,blockStart:h}of l){let f;switch(u.Hash.code){case Le:f=yt(d);break;case $e:f=d;break;default:t.end(new Ct(`Unsupported codec: ${u.Hash.code}`));return}let p=new Cr({concurrency:1});p.on("error",m=>{t.end(m)}),p.add(async()=>{s.onProgress?.(new M("unixfs:exporter:walk:file",{cid:u.Hash})),await R_(r,f,t,h,o,i,s)}),await p.onIdle()}}),n>=i&&t.end()}var $U=(r,e,t,n,o,i,s)=>{async function*a(c={}){let l=t.fileSize();if(l===void 0)throw new Error("File was a directory");let{start:u,end:d}=Oc(l,c.offset,c.length);if(d===0n)return;let h=0n,f=d-u,p=Pt();c.onProgress?.(new M("unixfs:exporter:walk:file",{cid:r})),R_(s,e,p,0n,u,d,c).catch(m=>{p.end(m)});for await(let m of p)if(m!=null){if(h+=BigInt(m.byteLength),h>f)throw p.end(),new t2("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect");h===f&&p.end(),c.onProgress?.(new M("unixfs:exporter:progress:unixfs:file",{bytesRead:h,totalBytes:f,fileSize:l})),yield m}if(h<f)throw new r2("Traversed entire DAG but did not read enough bytes")}return a},I5=$U;var zU=(r,e,t,n,o,i,s)=>{function a(c={}){return c.onProgress?.(new M("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),L_(e,n,o,i,s,c)}return a};async function*L_(r,e,t,n,o,i){let s=r.Links;if(r.Data==null)throw new Ct("no data in PBNode");let a;try{a=ie.unmarshal(r.Data)}catch(u){throw new Ct(u.message)}if(a.fanout==null)throw new Ct("missing fanout");let c=(a.fanout-1n).toString(16).length,l=Pe(s,u=>Je(u,d=>async()=>{let h=d.Name!=null?d.Name.substring(c):null;if(h!=null&&h!==""){let f=await t(d.Hash,h,`${e}/${h}`,[],n+1,o,i);return{entries:f.entry==null?[]:[f.entry]}}else{let f=await o.get(d.Hash,i);return r=yt(f),i.onProgress?.(new M("unixfs:exporter:walk:hamt-sharded-directory",{cid:d.Hash})),{entries:L_(r,e,t,n,o,i)}}}),u=>qt(u,{ordered:!0,concurrency:i.blockReadConcurrency}));for await(let{entries:u}of l)yield*u}var D_=zU;var KU=(r,e)=>r.Links.find(n=>n.Name===e)?.Hash,qU={raw:I5,file:I5,directory:P_,"hamt-sharded-directory":D_,metadata:(r,e,t,n,o,i,s)=>()=>[],symlink:(r,e,t,n,o,i,s)=>()=>[]},GU=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=yt(c),u,d;if(e==null&&(e=r.toString()),l.Data==null)throw new Ct("no data in PBNode");try{u=ie.unmarshal(l.Data)}catch(f){throw new Ct(f.message)}if(t==null&&(t=e),n.length>0){let f;if(u?.type==="hamt-sharded-directory"?f=await C_(l,n[0],s):f=KU(l,n[0]),f==null)throw new fn("file does not exist");let p=n.shift(),m=`${t}/${p}`;d={cid:f,toResolve:n,name:p??"",path:m}}let h=qU[u.type](r,l,u,t,o,i,s);if(h==null)throw new fn("could not find content exporter");return u.isDirectory()?{entry:{type:"directory",name:e,path:t,cid:r,content:h,unixfs:u,depth:i,node:l,size:u.fileSize()},next:d}:{entry:{type:"file",name:e,path:t,cid:r,content:h,unixfs:u,depth:i,node:l,size:u.fileSize()},next:d}},N_=GU;var WU={[Le]:N_,[$e]:p_,[Pr]:u_,[Jn]:d_,[vt.code]:f_,[qn]:h_},O_=async(r,e,t,n,o,i,s)=>{let a=WU[r.code];if(a==null)throw new e2(`No resolver for code ${r.code}`);return a(r,e,t,n,O_,o,i,s)},B_=O_;var YU=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),XU=r=>{if(r instanceof Uint8Array)return{cid:O.decode(r),toResolve:[]};let e=O.asCID(r);if(e!=null)return{cid:e,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let t=YU(r);return{cid:O.parse(t[0]),toResolve:t.slice(1)}}throw new Jm(`Unknown path type ${r}`)};async function*Xu(r,e,t={}){let{cid:n,toResolve:o}=XU(r),i=n.toString(),s=i,a=o.length;for(;;){let c=await B_(n,i,s,o,a,e,t);if(c.entry==null&&c.next==null)throw new fn(`Could not resolve ${r}`);if(c.entry!=null&&(yield c.entry),c.next==null)return;o=c.next.toResolve,n=c.next.cid,i=c.next.name,s=c.next.path}}async function _t(r,e,t={}){let n=await Mi(Xu(r,e,t));if(n==null)throw new fn(`Could not resolve ${r}`);return n}async function*Mc(r,e,t={}){let n=await _t(r,e,t);if(n==null)return;if(yield n,n.type==="directory")for await(let i of o(n,t))yield i;async function*o(i,s){for await(let a of i.content(s))yield a,!(a instanceof Uint8Array)&&a.type==="directory"&&(yield*o(a,s))}}async function QU(r,e,t){let n=[],o;for await(let i of Xu(e,r,t))n.push(i.cid),o=i;if(o==null)throw new Lc("No terminal element found");return{ipfsRoots:n,terminalElement:o}}function T5(r){return r.type==="object"}async function M_({cid:r,path:e,resource:t,options:n,blockstore:o,log:i}){try{return await QU(o,`${r.toString()}/${e}`,n)}catch(s){return n?.signal?.throwIfAborted(),["ERR_NO_PROP","ERR_NO_TERMINAL_ELEMENT","ERR_NOT_FOUND"].includes(s.code)?Gm(t):(i.error("error walking path %s",e,s),Rc(t,"Error walking path"))}}var u2=class extends dt{codes=[Pr];canHandle({cid:e,accept:t,pathDetails:n}){return this.log("checking if we can handle %c with accept %s",e,t),n==null||!T5(n.terminalElement)||e.code!==Pr?!1:T5(n.terminalElement)}async handle(e){let{cid:t,path:n,resource:o,accept:i,pathDetails:s}=e;if(this.log.trace("fetching %c/%s",t,n),s==null)throw new Error("pathDetails is null");let a=s.ipfsRoots,l=s.terminalElement.node,u;if(i==="application/octet-stream"||i==="application/vnd.ipld.dag-cbor"||i==="application/cbor")u=l;else if(i==="application/vnd.ipld.dag-json")try{let f=mi(l);u=Rh(f)}catch(f){return this.log.error("could not transform %c to application/vnd.ipld.dag-json",f),Ho(o)}else try{u=a_(l)}catch(f){if(i==="application/json")return this.log('could not decode DAG-CBOR as JSON-safe, but the client sent "Accept: application/json"',f),Ho(o);this.log("could not decode DAG-CBOR as JSON-safe, falling back to `application/octet-stream`",f),u=l}let d=On(o,u),h=i??(u instanceof Uint8Array?"application/octet-stream":"application/json");return d.headers.set("content-type",h),jm(d,a),d}};function jU(r){return r[Symbol.asyncIterator]!=null}function ZU(r,e=1){return e=Number(e),jU(r)?async function*(){let t=[];if(e<1&&(e=1),e!==Math.round(e))throw new Error("Batch size must be an integer");for await(let n of r)for(t.push(n);t.length>=e;)yield t.slice(0,e),t=t.slice(e);for(;t.length>0;)yield t.slice(0,e),t=t.slice(e)}():function*(){let t=[];if(e<1&&(e=1),e!==Math.round(e))throw new Error("Batch size must be an integer");for(let n of r)for(t.push(n);t.length>=e;)yield t.slice(0,e),t=t.slice(e);for(;t.length>0;)yield t.slice(0,e),t=t.slice(e)}()}var d2=ZU;async function*Qu(r,e=1){for await(let t of d2(r,e)){let n=t.map(async o=>o().then(i=>({ok:!0,value:i}),i=>({ok:!1,err:i})));for(let o=0;o<n.length;o++){let i=await n[o];if(i.ok)yield i.value;else throw i.err}}}var JU=262144,ju=(r={})=>{let e=r.chunkSize??JU;return async function*(n){let o=new Z,i=0,s=!1;for await(let a of n)for(o.append(a),i+=a.length;i>=e;)if(yield o.slice(0,e),s=!0,e===o.length)o=new Z,i=0;else{let c=new Z;c.append(o.sublist(e)),o=c,i-=e}(!s||i>0)&&(yield o.subarray(0,i))}};var Un=async(r,e,t)=>{t.codec==null&&(t.codec=wt);let n=await ve.digest(r),o=O.create(t.cidVersion,t.codec.code,n);return await e.put(o,r,t),o};function U_(r){return async function*(t,n){let o=0n;for await(let i of t.content)yield async()=>{let s,a={codec:wt,cidVersion:r.cidVersion,onProgress:r.onProgress};r.rawLeaves?(a.codec=Sr,a.cidVersion=1):(s=new ie({type:r.leafType,data:i}),i=_e({Data:s.marshal(),Links:[]}));let c=await Un(i,n,a);return o+=BigInt(i.byteLength),r.onProgress?.(new M("unixfs:importer:progress:file:write",{bytesWritten:o,cid:c,path:t.path})),{cid:c,unixfs:s,size:BigInt(i.length),block:i}}}}var Zu=class r extends Error{static name="InvalidParametersError";static code="ERR_INVALID_PARAMS";name=r.name;code=r.code;constructor(e="Invalid parameters"){super(e)}};var Ui=class r extends Error{static name="InvalidContentError";static code="ERR_INVALID_CONTENT";name=r.name;code=r.code;constructor(e="Invalid content"){super(e)}};var F_=async(r,e,t)=>{let n=new ie({type:"directory",mtime:r.mtime,mode:r.mode}),o=_e(ct({Data:n.marshal()})),i=await Un(o,e,t),s=r.path;return{cid:i,path:s,unixfs:n,size:BigInt(o.length),originalPath:r.originalPath,block:o}};async function*eF(r,e,t){let n=-1,o;for await(let i of Qu(t.bufferImporter(r,e),t.blockWriteConcurrency)){if(n++,n===0){o={...i,single:!0};continue}else n===1&&o!=null&&(yield{...o,block:void 0,single:void 0},o=void 0);yield{...i,block:void 0}}o!=null&&(yield o)}function H_(r){return r.single===!0}var tF=(r,e,t)=>async function(o){if(o.length===1&&H_(o[0])&&t.reduceSingleLeafToSelf){let u=o[0],d=u.block;return H_(u)&&(r.mtime!==void 0||r.mode!==void 0)&&(u.unixfs=new ie({type:"file",mtime:r.mtime,mode:r.mode,data:u.block}),d={Data:u.unixfs.marshal(),Links:[]},u.block=_e(ct(d)),u.cid=await Un(u.block,e,{...t,cidVersion:t.cidVersion}),u.size=BigInt(u.block.length)),t.onProgress?.(new M("unixfs:importer:progress:file:layout",{cid:u.cid,path:u.originalPath})),{cid:u.cid,path:r.path,unixfs:u.unixfs,size:u.size,originalPath:u.originalPath}}let i=new ie({type:"file",mtime:r.mtime,mode:r.mode}),s=o.filter(u=>u.cid.code===$e&&u.size>0||u.unixfs!=null&&u.unixfs.data==null&&u.unixfs.fileSize()>0n?!0:!!u.unixfs?.data?.length).map(u=>u.cid.code===$e?(i.addBlockSize(u.size),{Name:"",Tsize:Number(u.size),Hash:u.cid}):(u.unixfs?.data==null?i.addBlockSize(u.unixfs?.fileSize()??0n):i.addBlockSize(BigInt(u.unixfs.data.length)),{Name:"",Tsize:Number(u.size),Hash:u.cid})),a={Data:i.marshal(),Links:s},c=_e(ct(a)),l=await Un(c,e,t);return t.onProgress?.(new M("unixfs:importer:progress:file:layout",{cid:l,path:r.originalPath})),{cid:l,path:r.path,unixfs:i,size:BigInt(c.length+a.Links.reduce((u,d)=>u+(d.Tsize??0),0)),originalPath:r.originalPath,block:c}},V_=async(r,e,t)=>t.layout(eF(r,e,t),tF(r,e,t));function rF(r){return Symbol.iterator in r}function nF(r){return Symbol.asyncIterator in r}function oF(r){try{if(r instanceof Uint8Array)return async function*(){yield r}();if(rF(r))return async function*(){yield*r}();if(nF(r))return r}catch{throw new Ui("Content was invalid")}throw new Ui("Content was invalid")}function $_(r){return async function*(t,n){for await(let o of t){let i;if(o.path!=null&&(i=o.path,o.path=o.path.split("/").filter(s=>s!=null&&s!==".").join("/")),iF(o)){let s={path:o.path,mtime:o.mtime,mode:o.mode,content:async function*(){let a=0n;for await(let c of r.chunker(r.chunkValidator(oF(o.content)))){let l=BigInt(c.byteLength);a+=l,r.onProgress?.(new M("unixfs:importer:progress:file:read",{bytesRead:a,chunkSize:l,path:o.path})),yield c}}(),originalPath:i};yield async()=>V_(s,n,r)}else if(o.path!=null){let s={path:o.path,mtime:o.mtime,mode:o.mode,originalPath:i};yield async()=>F_(s,n,r)}else throw new Error("Import candidate must have content or path or both")}}}function iF(r){return r.content!=null}var z_=()=>async function*(e){for await(let t of e){if(t.length===void 0)throw new Ui("Content was invalid");if(typeof t=="string"||t instanceof String)yield C(t.toString());else if(Array.isArray(t))yield Uint8Array.from(t);else if(t instanceof Uint8Array)yield t;else throw new Ui("Content was invalid")}};var sF=174;function Ju(r){let e=r?.maxChildrenPerNode??sF;return async function t(n,o){let i=[];for await(let s of d2(n,e))i.push(await o(s));return i.length>1?t(i,o):i[0]}}var ro=class{options;root;dir;path;dirty;flat;parent;parentKey;unixfs;mode;mtime;cid;size;nodeSize;constructor(e,t){this.options=t??{},this.root=e.root,this.dir=e.dir,this.path=e.path,this.dirty=e.dirty,this.flat=e.flat,this.parent=e.parent,this.parentKey=e.parentKey,this.unixfs=e.unixfs,this.mode=e.mode,this.mtime=e.mtime}},ed=O.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),td=O.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi");var ta=class extends ro{_children;constructor(e,t){super(e,t),this._children=new Map}async put(e,t){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,this._children.set(e,t)}async get(e){return Promise.resolve(this._children.get(e))}childCount(){return this._children.size}directChildrenCount(){return this.childCount()}onlyChild(){return this._children.values().next().value}async*eachChildSeries(){for(let[e,t]of this._children.entries())yield{key:e,child:t}}estimateNodeSize(){if(this.nodeSize!==void 0)return this.nodeSize;this.nodeSize=0;for(let[e,t]of this._children.entries())t.size!=null&&t.cid!=null&&(this.nodeSize+=e.length+(this.options.cidVersion===1?td.bytes.byteLength:ed.bytes.byteLength));return this.nodeSize}async*flush(e){let t=[];for(let[c,l]of this._children.entries()){let u=l;if(l instanceof ro)for await(let d of l.flush(e))u=d,yield d;u.size!=null&&u.cid!=null&&t.push({Name:c,Tsize:Number(u.size),Hash:u.cid})}let n=new ie({type:"directory",mtime:this.mtime,mode:this.mode}),o={Data:n.marshal(),Links:t},i=_e(ct(o)),s=await Un(i,e,this.options),a=i.length+o.Links.reduce((c,l)=>c+(l.Tsize??0),0);this.cid=s,this.size=a,yield{cid:s,unixfs:n,path:this.path,size:BigInt(a)}}};async function aF(r){return(await ea.encode(r)).slice(0,8).reverse()}var K_=BigInt(34),cF=8,k5=class extends ro{_bucket;constructor(e,t){super(e,t),this._bucket=Bc({hashFn:aF,bits:t.shardFanoutBits??cF})}async put(e,t){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,await this._bucket.put(e,t)}async get(e){return this._bucket.get(e)}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}async*eachChildSeries(){for await(let{key:e,value:t}of this._bucket.eachLeafSeries())yield{key:e,child:t}}estimateNodeSize(){return this.nodeSize!==void 0?this.nodeSize:(this.nodeSize=W_(this._bucket,this,this.options),this.nodeSize)}async*flush(e){for await(let t of G_(this._bucket,e,this,this.options))yield{...t,path:this.path}}},q_=k5;async function*G_(r,e,t,n){let o=r._children,i=(r.tableSize()-1).toString(16).length,s=[],a=0n;for(let p=0;p<o.length;p++){let m=o.get(p);if(m==null)continue;let g=p.toString(16).toUpperCase().padStart(i,"0");if(m instanceof Yr){let y;for await(let w of G_(m,e,null,n))y=w;if(y==null)throw new Error("Could not flush sharded directory, no subshard found");s.push({Name:g,Tsize:Number(y.size),Hash:y.cid}),a+=y.size}else if(lF(m.value)){let y=m.value,w;for await(let x of y.flush(e))w=x,yield w;if(w==null)throw new Error("Did not flush dir");let b=g+m.key;s.push({Name:b,Tsize:Number(w.size),Hash:w.cid}),a+=w.size}else{let y=m.value;if(y.cid==null)continue;let w=g+m.key,b=y.size;s.push({Name:w,Tsize:Number(b),Hash:y.cid}),a+=BigInt(b??0)}}let c=Uint8Array.from(o.bitField().reverse()),l=new ie({type:"hamt-sharded-directory",data:c,fanout:BigInt(r.tableSize()),hashType:K_,mtime:t?.mtime,mode:t?.mode}),u={Data:l.marshal(),Links:s},d=_e(ct(u)),h=await Un(d,e,n),f=BigInt(d.byteLength)+a;yield{cid:h,unixfs:l,size:f}}function lF(r){return typeof r.flush=="function"}function W_(r,e,t){let n=r._children,o=(r.tableSize()-1).toString(16).length,i=[];for(let l=0;l<n.length;l++){let u=n.get(l);if(u==null)continue;let d=l.toString(16).toUpperCase().padStart(o,"0");if(u instanceof Yr){let h=W_(u,null,t);i.push({Name:d,Tsize:Number(h),Hash:t.cidVersion===0?ed:td})}else if(typeof u.value.flush=="function"){let f=u.value.nodeSize();i.push({Name:d+u.key,Tsize:Number(f),Hash:t.cidVersion===0?ed:td})}else{let h=u.value;if(h.cid==null)continue;let f=d+u.key,p=h.size;i.push({Name:f,Tsize:Number(p),Hash:h.cid})}}let s=Uint8Array.from(n.bitField().reverse()),a=new ie({type:"hamt-sharded-directory",data:s,fanout:BigInt(r.tableSize()),hashType:K_,mtime:e?.mtime,mode:e?.mode});return _e(ct({Data:a.marshal(),Links:i})).length}async function C5(r,e,t,n){let o=e;e instanceof ta&&e.estimateNodeSize()>t&&(o=await uF(e,n));let i=o.parent;if(i!=null){if(o!==e){if(r!=null&&(r.parent=o),o.parentKey==null)throw new Error("No parent key found");await i.put(o.parentKey,o)}return C5(o,i,t,n)}return o}async function uF(r,e){let t=new q_({root:r.root,dir:!0,parent:r.parent,parentKey:r.parentKey,path:r.path,dirty:r.dirty,flat:!1,mtime:r.mtime,mode:r.mode},e);for await(let{key:n,child:o}of r.eachChildSeries())await t.put(n,o);return t}var Y_=(r="")=>r.split(/(?<!\\)\//).filter(Boolean);async function dF(r,e,t){let n=Y_(r.path??""),o=n.length-1,i=e,s="";for(let a=0;a<n.length;a++){let c=n[a];s+=`${s!==""?"/":""}${c}`;let l=a===o;if(i.dirty=!0,i.cid=void 0,i.size=void 0,l)await i.put(c,r),e=await C5(null,i,t.shardSplitThresholdBytes,t);else{let u=await i.get(c);(u==null||!(u instanceof ro))&&(u=new ta({root:!1,dir:!0,parent:i,parentKey:c,path:s,dirty:!0,flat:!0,mtime:u?.unixfs?.mtime,mode:u?.unixfs?.mode},t)),await i.put(c,u),i=u}}return e}async function*X_(r,e){if(!(r instanceof ro)){r.unixfs?.isDirectory()===!0&&(yield r);return}yield*r.flush(e)}function Q_(r){return async function*(t,n){let o=new ta({root:!0,dir:!0,path:"",dirty:!0,flat:!0},r),i,s=!1;for await(let a of t){if(a==null)continue;let c=`${a.originalPath??""}`.split("/")[0];c!=null&&c!==""&&(i==null?(i=c,s=!0):i!==c&&(s=!1)),o=await dF(a,o,r),a.unixfs?.isDirectory()!==!0&&(yield a)}if(r.wrapWithDirectory||s&&o.childCount()>1)yield*X_(o,n);else for await(let a of o.eachChildSeries())a!=null&&(yield*X_(a.child,n))}}async function*Fi(r,e,t={}){let n;Symbol.asyncIterator in r||Symbol.iterator in r?n=r:n=[r];let o=t.wrapWithDirectory??!1,i=t.shardSplitThresholdBytes??262144,s=t.shardFanoutBits??8,a=t.cidVersion??1,c=t.rawLeaves??!0,l=t.leafType??"file",u=t.fileImportConcurrency??50,d=t.blockWriteConcurrency??10,h=t.reduceSingleLeafToSelf??!0,f=t.chunker??ju(),p=t.chunkValidator??z_(),m=t.dagBuilder??$_({chunker:f,chunkValidator:p,wrapWithDirectory:o,layout:t.layout??Ju(),bufferImporter:t.bufferImporter??U_({cidVersion:a,rawLeaves:c,leafType:l,onProgress:t.onProgress}),blockWriteConcurrency:d,reduceSingleLeafToSelf:h,cidVersion:a,onProgress:t.onProgress}),g=t.treeBuilder??Q_({wrapWithDirectory:o,shardSplitThresholdBytes:i,shardFanoutBits:s,cidVersion:a,onProgress:t.onProgress});for await(let y of g(Qu(m(n,e),u),e))yield{cid:y.cid,path:y.path,unixfs:y.unixfs,size:y.size}}async function f2(r,e,t={}){let n=await nu(Fi([r],e,t));if(n==null)throw new Zu("Nothing imported");return n}async function j_(r,e,t={}){let n=await nu(Fi([r],e,t));if(n==null)throw new Zu("Nothing imported");return n}async function Z_(r,e,t={}){return f2({content:r},e,t)}async function J_(r,e,t={}){return f2({content:r},e,t)}var rd={cidVersion:1,rawLeaves:!0,layout:Ju({maxChildrenPerNode:1024}),chunker:ju({chunkSize:1048576})};async function*eI(r,e,t={}){yield*Fi(r,e,{...rd,...t})}async function tI(r,e,t={}){let{cid:n}=await Z_(r,e,{...rd,...t});return n}async function rI(r,e,t={}){let{cid:n}=await J_(r,e,{...rd,...t});return n}async function nI(r,e,t={}){let{cid:n}=await f2(r,e,{...rd,...t});return n}async function oI(r,e,t={}){let{cid:n}=await j_({...r,path:r.path??"-"},e,{...rd,...t});return n}var D5=xt(a2(),1);function p2(r){function e(t){return t instanceof h2?t:new h2(t,r)}return e}var h2=class{_value;_hashFn;_depth;_availableBits;_currentBufferIndex;_buffers;constructor(e,t){if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=t,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let t=e;for(;this._availableBits<t;)await this._produceMoreBits();let n=0;for(;t>0;){let o=this._buffers[this._currentBufferIndex],i=Math.min(o.availableBits(),t),s=o.take(i);n=(n<<i)+s,t-=i,this._availableBits-=i,o.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let t=e;for(;t>0;){let n=this._buffers[this._currentBufferIndex],o=Math.min(n.totalBits()-n.availableBits(),t);n.untake(o),t-=o,this._availableBits+=o,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?ge([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new P5(t);this._buffers.push(n),this._availableBits+=n.availableBits()}},fF=[255,254,252,248,240,224,192,128],hF=[1,3,7,15,31,63,127,255],P5=class{_value;_currentBytePos;_currentBitPos;constructor(e){this._value=e,this._currentBytePos=e.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(e){let t=e,n=0;for(;t>0&&this._haveBits();){let o=this._value[this._currentBytePos],i=this._currentBitPos+1,s=Math.min(i,t),a=pF(o,i-s,s);n=(n<<s)+a,t-=s,this._currentBitPos-=s,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return n}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function pF(r,e,t){let n=mF(e,t);return(r&n)>>>e}function mF(r,e){return fF[r]&hF[Math.min(e+r-1,7)]}var nd=BigInt(ea.code),ra=8;async function Uc(r){return(await ea.encode(r)).subarray(0,8).reverse()}var aI=xt(a2(),1);var Fn=async(r,e,t)=>{t.codec==null&&(t.codec=wt);let n=await ve.digest(r),o=O.create(t.cidVersion,t.codec.code,n);return await e.put(o,r,{...t,signal:t.signal}),o};var R5=class{options;root;dir;path;dirty;flat;parent;parentKey;unixfs;mode;mtime;cid;size;nodeSize;constructor(e,t){this.options=t??{},this.root=e.root,this.dir=e.dir,this.path=e.path,this.dirty=e.dirty,this.flat=e.flat,this.parent=e.parent,this.parentKey=e.parentKey,this.unixfs=e.unixfs,this.mode=e.mode,this.mtime=e.mtime}},m2=class extends R5{_bucket;constructor(e,t){super(e,t),this._bucket=Bc({hashFn:Uc,bits:8})}async put(e,t){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,await this._bucket.put(e,t)}async get(e){return this._bucket.get(e)}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}async*eachChildSeries(){for await(let{key:e,value:t}of this._bucket.eachLeafSeries())yield{key:e,child:t}}estimateNodeSize(){return this.nodeSize!==void 0?this.nodeSize:(this.nodeSize=sI(this._bucket,this,this.options),this.nodeSize)}async*flush(e){for await(let t of iI(this._bucket,e,this,this.options))yield{...t,path:this.path}}};async function*iI(r,e,t,n){let o=r._children,i=[],s=0n;for(let f=0;f<o.length;f++){let p=o.get(f);if(p==null)continue;let m=f.toString(16).toUpperCase().padStart(2,"0");if(p instanceof Yr){let g;for await(let y of iI(p,e,null,n))g=y;if(g==null)throw new Error("Could not flush sharded directory, no subshard found");i.push({Name:m,Tsize:Number(g.size),Hash:g.cid}),s+=g.size}else if(gF(p.value)){let g=p.value,y;for await(let b of g.flush(e))y=b,yield y;if(y==null)throw new Error("Did not flush dir");let w=m+p.key;i.push({Name:w,Tsize:Number(y.size),Hash:y.cid}),s+=y.size}else{let g=p.value;if(g.cid==null)continue;let y=m+p.key,w=g.size;i.push({Name:y,Tsize:Number(w),Hash:g.cid}),s+=BigInt(w??0)}}let a=Uint8Array.from(o.bitField().reverse()),c=new ie({type:"hamt-sharded-directory",data:a,fanout:BigInt(r.tableSize()),hashType:nd,mtime:t?.mtime,mode:t?.mode}),l={Data:c.marshal(),Links:i},u=_e(ct(l)),d=await Fn(u,e,n),h=BigInt(u.byteLength)+s;yield{cid:d,unixfs:c,size:h}}function gF(r){return typeof r.flush=="function"}function sI(r,e,t){let n=r._children,o=[];for(let c=0;c<n.length;c++){let l=n.get(c);if(l==null)continue;let u=c.toString(16).toUpperCase().padStart(2,"0");if(l instanceof Yr){let d=sI(l,null,t);o.push({Name:u,Tsize:Number(d),Hash:t.cidVersion===0?g2:y2})}else if(typeof l.value.flush=="function"){let h=l.value.nodeSize();o.push({Name:u+l.key,Tsize:Number(h),Hash:t.cidVersion===0?g2:y2})}else{let d=l.value;if(d.cid==null)continue;let h=u+l.key,f=d.size;o.push({Name:h,Tsize:Number(f),Hash:d.cid})}}let i=Uint8Array.from(n.bitField().reverse()),s=new ie({type:"hamt-sharded-directory",data:i,fanout:BigInt(r.tableSize()),hashType:nd,mtime:e?.mtime,mode:e?.mode});return _e(ct({Data:s.marshal(),Links:o})).length}var g2=O.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),y2=O.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi");var L5=xe("helia:unixfs:commands:utils:hamt-utils"),w2=r=>r.toString(16).toUpperCase().padStart(2,"0").substring(0,2),cI=async(r,e,t)=>{let n=new m2({root:!0,dir:!0,parent:void 0,parentKey:void 0,path:"",dirty:!0,flat:!1,mtime:t.mtime,mode:t.mode},t);for(let i=0;i<e.length;i++)await n._bucket.put(e[i].name,{size:e[i].size,cid:e[i].cid});let o=await Mi(n.flush(r));if(o==null)throw new Error("Flushing shard yielded no result");return o},b2=async(r,e,t)=>{let n=ie.unmarshal(r[0].node.Data??new Uint8Array(0)),o=BigInt(Math.pow(2,ra));r.reverse();let i,s;for(let a=0;a<r.length;a++){let c=a===r.length-1,l=r[a],u=Uint8Array.from(l.children.bitField().reverse()),d=new ie({type:"hamt-sharded-directory",data:u,fanout:o,hashType:nd});c&&(d.mtime=n.mtime,d.mode=n.mode),s={Data:d.marshal(),Links:l.node.Links};let h=_e(ct(s));if(i=await Fn(h,e,t),!c){let f=r[a+1];if(f==null)throw new Error("Was not operating on shard root but also had no parent?");L5("updating link in parent sub-shard with prefix %s",f.prefix),f.node.Links=f.node.Links.filter(p=>p.Name!==f.prefix),f.node.Links.push({Name:f.prefix,Hash:i,Tsize:l.node.Links.reduce((p,m)=>p+(m.Tsize??0),h.byteLength)})}}if(i==null||s==null)throw new Error("Noting persisted");return{cid:i,node:s}},x2=async(r,e,t,n)=>{let i=p2(Uc)(C(e)),s=[];for(;;){let a=await t.get(r,n),c=yt(a),l=new aI.default,u=await i.take(ra),d=w2(u);s.push({prefix:d,children:l,node:c});let h;for(let p of c.Links){let m=p.Name??"";if(m.length<2)throw new Error("Invalid HAMT - link name was too short");let g=parseInt(m.substring(0,2),16);l.set(g,!0),m.startsWith(d)&&(h=p)}if(h==null){L5("no link found with prefix %s for %s",d,e);break}let f=h.Name??"";if(f.length<2)throw new Error("Invalid HAMT - link name was too short");if(f.length===2){r=h.Hash,L5("descend into sub-shard with prefix %s",f);continue}break}return{path:s,hash:i}};async function E2(r,e,t,n){if(r.Data==null)throw new Error("DagPB node had no data");let o=ie.unmarshal(r.Data),i;if(o.type==="directory")i=yF(r);else if(o.type==="hamt-sharded-directory")i=await lI(r,0,t,e,n);else throw new Error("Can only estimate the size of directories or shards");return i>t}function yF(r){let e=0;for(let t of r.Links)e+=(t.Name??"").length,e+=t.Hash.version===1?y2.bytes.byteLength:g2.bytes.byteLength;return e}async function lI(r,e,t,n,o){if(e>t)return t;if(r.Data==null||!ie.unmarshal(r.Data).isDirectory())return e;for(let s of r.Links){let a=s.Name??"";if(a=a.substring(2),e+=a.length,e+=s.Hash.bytes.byteLength,s.Hash.code===Le){let c=await n.get(s.Hash,o),l=yt(c);e+=await lI(l,e,t,n,o)}}return e}var no=xe("helia:unixfs:components:utils:add-link");async function Fc(r,e,t,n){if(r.node.Data==null)throw new Wr("Invalid parent passed to addLink");if(ie.unmarshal(r.node.Data).type==="hamt-sharded-directory")return no("adding link to sharded directory"),xF(r,e,t,n);no(`adding ${e.Name} (${e.Hash}) to regular directory`);let i=await bF(r,e,t,n);if(await E2(i.node,t,n.shardSplitThresholdBytes,n)){no("converting directory to sharded directory");let s=await wF(i,t);i.cid=s.cid,i.node=yt(await t.get(s.cid,n))}return i}var wF=async(r,e)=>{if(r.node.Data==null)throw new Wr("Invalid parent passed to convertToShardedDirectory");let t=ie.unmarshal(r.node.Data),n=await cI(e,r.node.Links.map(o=>({name:o.Name??"",size:BigInt(o.Tsize??0),cid:o.Hash})),{mode:t.mode,mtime:t.mtime,cidVersion:r.cid.version});return no(`converted directory to sharded directory ${n.cid}`),n},bF=async(r,e,t,n)=>{let o=r.node.Links.filter(u=>{let d=u.Name===e.Name;if(d&&!n.allowOverwriting)throw new Gu;return!d});if(o.push(e),r.node.Data==null)throw new Er("Parent node with no data passed to addToDirectory");let i=ie.unmarshal(r.node.Data),s;if(i.mtime!=null){let u=Date.now(),d=Math.floor(u/1e3);i.mtime={secs:BigInt(d),nsecs:(u-d*1e3)*1e3},s=i.marshal()}else s=r.node.Data;r.node=ct({Data:s,Links:o});let a=_e(r.node),c=await ve.digest(a),l=O.create(r.cid.version,Le,c);return await t.put(l,a),{node:r.node,cid:l}},xF=async(r,e,t,n)=>{let{path:o,hash:i}=await x2(r.cid,e.Name,t,n),s=o[o.length-1];if(s==null)throw new Error("Invalid HAMT, could not generate path");let a=s.prefix,c=parseInt(a,16);no("next prefix for %s is %s",e.Name,a);let l=`${a}${e.Name}`,u=s.node.Links.find(d=>(d.Name??"").startsWith(a));if(u!=null)if(no("link %s was present in shard",l),u.Name===l){if(!n.allowOverwriting)throw new Gu;no("overwriting %s in subshard",e.Name),s.node.Links=s.node.Links.filter(d=>d.Name!==l),s.node.Links.push({Name:l,Hash:e.Hash,Tsize:e.Tsize})}else{if(u.Name?.length===2)throw new Error("Existing link was subshard?!");{no("prefix %s already exists, creating new subshard",a);let d=s.node.Links.findIndex(g=>g.Name?.startsWith(a)),h=s.node.Links.splice(d,1)[0],f=(h.Name??"").substring(2),m=p2(Uc)(C(f));for(let g=0;g<o.length;g++)await m.take(ra);for(;;){let g=await m.take(ra),y=w2(g);h.Name=`${y}${f}`;let w=await i.take(ra),b=w2(w);if(y===b){let A=new D5.default;A.set(w,!0),o.push({prefix:b,children:A,node:{Links:[]}});continue}let x=new D5.default;x.set(w,!0),x.set(g,!0),o.push({prefix:a,children:x,node:{Links:[h,{Name:`${b}${e.Name}`,Hash:e.Hash,Tsize:e.Tsize}]}});break}}}else no("link %s was not present in sub-shard",l),e.Name=l,s.node.Links.push(e),s.children.set(c,!0),no("adding %s to existing sub-shard",l);return b2(o,t,n)};async function Hi(r,e,t={}){let n=await _t(r,e,t);if(n.type!=="directory")throw new Bi(`${r.toString()} was not a UnixFS directory`);return{cid:r,node:n.node}}async function Hc(r,e,t,n){let o=await _t(r,t,n);if(o.type!=="directory"&&o.type!=="file"&&o.type!=="raw")throw new Gr(`${r.toString()} was not a UnixFS node`);return{Name:e,Tsize:o.node instanceof Uint8Array?o.node.byteLength:EF(o.node),Hash:r}}function EF(r){let e=r.Links.reduce((t,n)=>t+(n.Tsize??0),0);return _e(r).byteLength+e}var vF=xe("helia:unixfs:components:utils:resolve");async function oo(r,e,t,n){if(e==null||e==="")return{cid:r};let o=`/ipfs/${r}${e==null?"":`/${e}`}`,i=await Do(Xu(o,t,n));if(i.length===0)throw new Lc("Could not find path in directory");return vF("resolved %s to %c",e,r),{cid:i[i.length-1].cid,path:e,segments:i}}async function Vc(r,e,t,n){if(e.segments==null||e.segments.length===0)return r;let o=e.segments.pop();if(o==null)throw new Error("Insufficient segments");o.cid=r,e.segments.reverse();for(let i of e.segments){let[s,a]=await Promise.all([Hi(i.cid,t,n),Hc(o.cid,o.name,t,n)]);r=(await Fc(s,a,t,{...n,allowOverwriting:!0,cidVersion:r.version})).cid,i.cid=r,o=i}return r}var SF=ut.bind({ignoreUndefined:!0}),AF={};async function*uI(r,e,t={}){let n=SF(AF,t),o=await oo(r,n.path,e,n),i=await _t(o.cid,e,n);if(i.type!=="file"&&i.type!=="raw")throw new Zm;if(i.content==null)throw new Dc;yield*i.content(n)}var _F=ut.bind({ignoreUndefined:!0}),IF=xe("helia:unixfs:chmod"),TF={recursive:!1,shardSplitThresholdBytes:262144};async function dI(r,e,t,n={}){let o=_F(TF,n),i=await oo(r,o.path,t,n);if(IF("chmod %c %d",i.cid,e),o.recursive){let h=await Pe(async function*(){for await(let f of Mc(i.cid,t,n)){let p,m=[];if(f.type==="raw")p=new ie({type:"file",data:f.node});else if(f.type==="file"||f.type==="directory")p=f.unixfs,m=f.node.Links;else throw new Gr;p.mode=e;let g={Data:p.marshal(),Links:m};yield{path:f.path,content:g}}},f=>Fi(f,t,{...o,dagBuilder:async function*(p,m){for await(let g of p)yield async function(){let y=g.content,w=_e(y),b=await Fn(w,m,{...o,cidVersion:r.version});if(y.Data==null)throw new Er(`${b} had no data`);let x=ie.unmarshal(y.Data);return{cid:b,size:BigInt(w.length),path:g.path,unixfs:x}}}}),async f=>Mi(f));if(h==null)throw new Oi(`Could not chmod ${i.cid.toString()}`);return Vc(h.cid,i,t,o)}let s=await t.get(i.cid,n),a,c=[];if(i.cid.code===$e)a=new ie({type:"file",data:s});else{let h=yt(s);if(h.Data==null)throw new Er(`${i.cid.toString()} had no data`);c=h.Links,a=ie.unmarshal(h.Data)}a.mode=e;let l=_e({Data:a.marshal(),Links:c}),u=await ve.digest(l),d=O.create(i.cid.version,Le,u);return await t.put(d,l),Vc(d,i,t,o)}var kF=ut.bind({ignoreUndefined:!0}),CF=xe("helia:unixfs:cp"),PF={force:!1,shardSplitThresholdBytes:262144};async function fI(r,e,t,n,o={}){let i=kF(PF,o);if(t.includes("/"))throw new Wr("Name must not have slashes");let[s,a]=await Promise.all([Hi(e,n,i),Hc(r,t,n,i)]);return CF('Adding %c as "%s" to %c',r,t,e),(await Fc(s,a,n,{allowOverwriting:i.force,cidVersion:e.version,...i})).cid}var RF=ut.bind({ignoreUndefined:!0}),LF={};async function*hI(r,e,t={}){let n=RF(LF,t),o=await oo(r,n.path,e,n),i=await _t(o.cid,e);if(i.type==="file"||i.type==="raw"){yield i;return}if(i.content==null)throw new Dc;if(i.type!=="directory")throw new Bi;yield*i.content({offset:t.offset,length:t.length})}var DF=ut.bind({ignoreUndefined:!0}),pI=xe("helia:unixfs:mkdir"),NF={cidVersion:1,force:!1,shardSplitThresholdBytes:262144};async function mI(r,e,t,n={}){let o=DF(NF,n);if(e.includes("/"))throw new Wr("Path must not have slashes");if((await _t(r,t,n)).type!=="directory")throw new Bi(`${r.toString()} was not a UnixFS directory`);pI("creating %s",e);let a={Data:new ie({type:"directory",mode:o.mode,mtime:o.mtime}).marshal(),Links:[]},c=_e(a),l=await ve.digest(c),u=O.create(o.cidVersion,Le,l);await t.put(u,c);let[d,h]=await Promise.all([Hi(r,t,o),Hc(u,e,t,o)]);return pI("adding empty dir called %s to %c",e,r),(await Fc(d,h,t,{...o,allowOverwriting:o.force})).cid}var S2=xe("helia:unixfs:utils:remove-link");async function gI(r,e,t,n){if(r.node.Data==null)throw new Er("Parent node had no data");if(ie.unmarshal(r.node.Data).type==="hamt-sharded-directory"){S2(`removing ${e} from sharded directory`);let i=await BF(r,e,t,n);return await E2(i.node,t,n.shardSplitThresholdBytes,n)?i:(S2("converting shard to flat directory %c",r.cid),MF(i,t,n))}return S2(`removing link ${e} regular directory`),OF(r,e,t,n)}var OF=async(r,e,t,n)=>{r.node.Links=r.node.Links.filter(s=>s.Name!==e);let o=_e(r.node),i=await Fn(o,t,{...n,cidVersion:r.cid.version});return S2(`Updated regular directory ${i}`),{node:r.node,cid:i}},BF=async(r,e,t,n)=>{let{path:o}=await x2(r.cid,e,t,n),i=o[o.length-1];if(i==null)throw new Error("Invalid HAMT, could not generate path");let s=i.node.Links.filter(l=>(l.Name??"").substring(2)===e).map(l=>l.Name).pop();if(s==null)throw new Error("File not found");let a=s.substring(0,2),c=parseInt(a,16);if(i.node.Links=i.node.Links.filter(l=>l.Name!==s),i.children.unset(c),i.node.Links.length===1)for(;o.length!==1;){let l=o[o.length-1];if(l==null||l.node.Links.length>1)break;o.pop();let u=o[o.length-1];if(u==null)break;let d=l.node.Links[0];u.node.Links=u.node.Links.filter(h=>!(h.Name??"").startsWith(u.prefix)),u.node.Links.push({Hash:d.Hash,Name:`${u.prefix}${(d.Name??"").substring(2)}`,Tsize:d.Tsize})}return b2(o,t,n)},MF=async(r,e,t)=>{if(r.node.Data==null)throw new Wr("Invalid parent passed to convertToFlatDirectory");let n={Links:[]},o=await _t(r.cid,e);if(o.type!=="directory")throw new Error("Unexpected node type");for await(let c of o.content()){let l=0;c.node instanceof Uint8Array?l=c.node.byteLength:l=_e(c.node).length,n.Links.push({Hash:c.cid,Name:c.name,Tsize:l})}let i=ie.unmarshal(r.node.Data);n.Data=new ie({type:"directory",mode:i.mode,mtime:i.mtime}).marshal();let s=_e(ct(n));return{cid:await Fn(s,e,{codec:wt,cidVersion:r.cid.version,signal:t.signal}),node:n}};var UF=ut.bind({ignoreUndefined:!0}),FF=xe("helia:unixfs:rm"),HF={shardSplitThresholdBytes:262144};async function yI(r,e,t,n={}){let o=UF(HF,n);if(e.includes("/"))throw new Wr("Name must not have slashes");let i=await Hi(r,t,o);return FF("Removing %s from %c",e,r),(await gI(i,e,t,{...o,cidVersion:r.version})).cid}var VF=ut.bind({ignoreUndefined:!0}),$F=xe("helia:unixfs:stat"),zF={};async function wI(r,e,t={}){let n=VF(zF,t),o=await oo(r,t.path,e,n);$F("stat %c",o.cid);let i=await _t(o.cid,e,n);if(i.type!=="file"&&i.type!=="directory"&&i.type!=="raw")throw new Gr;let s=0n,a=0n,c=0n,l=0n,u=0,d,h,f=i.type,p;if(i.type==="raw"&&(s=BigInt(i.node.byteLength),a=BigInt(i.node.byteLength),c=BigInt(i.node.byteLength),l=BigInt(i.node.byteLength),u=1),i.type==="directory"&&(s=0n,a=BigInt(i.unixfs.marshal().byteLength),c=0n,l=a,u=1,d=i.unixfs.mode,h=i.unixfs.mtime,p=i.unixfs),i.type==="file"){let m=await bI(o.cid,e,n);s=i.unixfs.fileSize(),a=BigInt((i.node.Data?.byteLength??0)+i.node.Links.reduce((g,y)=>g+(y.Tsize??0),0)),c=BigInt(m.localFileSize),l=BigInt(m.localDagSize),u=m.blocks,d=i.unixfs.mode,h=i.unixfs.mtime,p=i.unixfs}return{cid:o.cid,mode:d,mtime:h,fileSize:s,dagSize:a,localFileSize:c,localDagSize:l,blocks:u,type:f,unixfs:p}}async function bI(r,e,t){let n={localFileSize:0,localDagSize:0,blocks:0};if(await e.has(r,t)){let o=await e.get(r,t);if(n.blocks++,n.localDagSize+=o.byteLength,r.code===$e)n.localFileSize+=o.byteLength;else if(r.code===Le){let i=yt(o);if(i.Links.length>0)for(let s of i.Links){let a=await bI(s.Hash,e,t);n.localFileSize+=a.localFileSize,n.localDagSize+=a.localDagSize,n.blocks+=a.blocks}else{if(i.Data==null)throw new Er(`PBNode ${r.toString()} had no data`);let s=ie.unmarshal(i.Data);if(s.data==null)throw new Er(`UnixFS node ${r.toString()} had no data`);n.localFileSize+=s.data.byteLength??0}}else throw new Oi(`${r.toString()} was neither DAG_PB nor RAW`)}return n}var KF=ut.bind({ignoreUndefined:!0}),qF=xe("helia:unixfs:touch"),GF={recursive:!1,shardSplitThresholdBytes:262144};async function xI(r,e,t={}){let n=KF(GF,t),o=await oo(r,n.path,e,n),i=n.mtime??{secs:BigInt(Math.round(Date.now()/1e3)),nsecs:0};if(qF("touch %c %o",o.cid,i),n.recursive){let h=await Pe(async function*(){for await(let f of Mc(o.cid,e)){let p,m;if(f.type==="raw")p=new ie({data:f.node}),m=[];else if(f.type==="file"||f.type==="directory")p=f.unixfs,m=f.node.Links;else throw new Gr;p.mtime=i;let g={Data:p.marshal(),Links:m};yield{path:f.path,content:g}}},f=>Fi(f,e,{...n,dagBuilder:async function*(p,m){for await(let g of p)yield async function(){let y=g.content,w=_e(y),b=await Fn(w,m,{...n,cidVersion:r.version});if(y.Data==null)throw new Er(`${b} had no data`);let x=ie.unmarshal(y.Data);return{cid:b,size:BigInt(w.length),path:g.path,unixfs:x}}}}),async f=>Mi(f));if(h==null)throw new Oi(`Could not chmod ${o.cid.toString()}`);return Vc(h.cid,o,e,n)}let s=await e.get(o.cid,t),a,c=[];if(o.cid.code===$e)a=new ie({data:s});else{let h=yt(s);if(c=h.Links,h.Data==null)throw new Er(`${o.cid.toString()} had no data`);a=ie.unmarshal(h.Data)}a.mtime=i;let l=_e({Data:a.marshal(),Links:c}),u=await ve.digest(l),d=O.create(o.cid.version,Le,u);return await e.put(d,l),Vc(d,o,e,n)}var A2=class{components;constructor(e){this.components=e}async*addAll(e,t={}){yield*eI(e,this.components.blockstore,t)}async addBytes(e,t={}){return tI(e,this.components.blockstore,t)}async addByteStream(e,t={}){return rI(e,this.components.blockstore,t)}async addFile(e,t={}){return nI(e,this.components.blockstore,t)}async addDirectory(e={},t={}){return oI(e,this.components.blockstore,t)}async*cat(e,t={}){yield*uI(e,this.components.blockstore,t)}async chmod(e,t,n={}){return dI(e,t,this.components.blockstore,n)}async cp(e,t,n,o={}){return fI(e,t,n,this.components.blockstore,o)}async*ls(e,t={}){yield*hI(e,this.components.blockstore,t)}async mkdir(e,t,n={}){return mI(e,t,this.components.blockstore,n)}async rm(e,t,n={}){return yI(e,t,this.components.blockstore,n)}async stat(e,t={}){return wI(e,this.components.blockstore,t)}async touch(e,t={}){return xI(e,this.components.blockstore,t)}};function EI(r){return new A2(r)}function vI(r,e){if(r==null)return;if(r instanceof Headers)return r.get(e)??void 0;if(Array.isArray(r))return r.find(([o])=>o.toLowerCase()===e.toLowerCase())?.[1];let t=Object.keys(r).find(n=>n.toLowerCase()===e.toLowerCase());if(t!=null)return r[t]}function SI(r,e,t){if((r??0)>(e??1/0))throw new qr("Invalid range: Range-start index is greater than range-end index.");if(r!=null&&(e??0)>=(t??1/0))throw new qr("Invalid range: Range-end index is greater than or equal to the size of the file.");if(r==null&&(e??0)>(t??1/0))throw new qr("Invalid range: Range-end index is greater than the size of the file.");if(r!=null&&r<0)throw new qr("Invalid range: Range-start index cannot be negative.");if(r!=null&&e!=null)return{byteSize:e-r+1,start:r,end:e};if(r==null&&e!=null)return t==null?{end:e}:e===t?{byteSize:t,start:0,end:t-1}:{byteSize:e,start:t-e,end:t-1};if(r!=null&&e==null){if(t==null)return{start:r};let n=t-1;return{byteSize:t-r,start:r,end:n}}return{byteSize:t,start:0,end:t!=null?t-1:0}}function WF(r){return typeof r=="string"?r.length:r instanceof ArrayBuffer||r instanceof Uint8Array?r.byteLength:r instanceof Blob?r.size:(r instanceof ReadableStream,null)}function YF(r){let e=r.match(/^bytes=(?<start>\d+)?-(?<end>\d+)?$/);if(e?.groups==null)throw new qr("Invalid range request");let{start:t,end:n}=e.groups;return{start:t,end:n}}var $c=class{headers;isRangeRequest;_fileSize;_body=null;rangeRequestHeader;log;requestRangeStart;requestRangeEnd;byteStart;byteEnd;byteSize;constructor(e,t){if(this.headers=t,this.log=e.forComponent("helia:verified-fetch:byte-range-context"),this.rangeRequestHeader=vI(this.headers,"Range"),this.rangeRequestHeader!=null){this.isRangeRequest=!0,this.log.trace("range request detected");try{let{start:n,end:o}=YF(this.rangeRequestHeader);this.requestRangeStart=n!=null?parseInt(n):null,this.requestRangeEnd=o!=null?parseInt(o):null}catch(n){this.log.error("error parsing range request header: %o",n),this.requestRangeStart=null,this.requestRangeEnd=null}this.setOffsetDetails()}else this.log.trace("no range request detected"),this.isRangeRequest=!1,this.requestRangeStart=null,this.requestRangeEnd=null}setBody(e){this._body=e,this.setFileSize(this._fileSize??WF(e)),this.log.trace("set request body with fileSize %o",this._fileSize)}getBody(){let e=this._body;if(e==null)return this.log.trace("body is null"),e;if(!this.isRangeRequest||!this.isValidRangeRequest)return this.log.trace("returning body unmodified for non-range, or invalid range, request"),e;let t=this.byteStart,n=this.byteEnd,o=this.byteSize;return t!=null||n!=null?(this.log.trace("returning body with byteStart=%o, byteEnd=%o, byteSize=%o",t,n,o),e instanceof ReadableStream?e:this.getSlicedBody(e)):(this.log.error("returning unmodified body for valid range request"),e)}getSlicedBody(e){let t=this.byteStart??0,n=this.byteEnd==null?void 0:this.byteEnd+1;return this.log.trace("returning body with offset %o and length %o",t,n),e.slice(t,n)}setFileSize(e){this._fileSize=e!=null?Number(e):null,this.log.trace("set _fileSize to %o",this._fileSize),this.setOffsetDetails()}getFileSize(){return this._fileSize}isValidByteStart(){return!(this.byteStart!=null&&(this.byteStart<0||this._fileSize!=null&&this.byteStart>=this._fileSize||this.byteEnd!=null&&this.byteStart>this.byteEnd))}isValidByteEnd(){return!(this.byteEnd!=null&&(this.byteEnd<0||this._fileSize!=null&&this.byteEnd>=this._fileSize||this.byteStart!=null&&this.byteEnd<this.byteStart))}get isValidRangeRequest(){if(!this.isRangeRequest)return!1;if(this.requestRangeStart==null&&this.requestRangeEnd==null)return this.log.trace("invalid range request, range request values not provided"),!1;if(!this.isValidByteStart())return this.log.trace("invalid range request, byteStart is less than 0 or greater than fileSize"),!1;if(!this.isValidByteEnd())return this.log.trace("invalid range request, byteEnd is less than 0 or greater than fileSize"),!1;if(this.requestRangeEnd!=null&&this.requestRangeStart!=null){if(this.requestRangeStart>this.requestRangeEnd)return this.log.trace("invalid range request, start is greater than end"),!1;if(this.requestRangeStart<0)return this.log.trace("invalid range request, start is less than 0"),!1;if(this.requestRangeEnd<0)return this.log.trace("invalid range request, end is less than 0"),!1}return this.byteEnd==null&&this.byteStart==null&&this.byteSize==null?(this.log.trace("invalid range request, could not calculate byteStart, byteEnd, or byteSize"),!1):!0}get offset(){return this.byteStart??0}get length(){return this.byteEnd!=null&&this.byteStart!=null&&this.byteStart===this.byteEnd?1:this.byteEnd!=null?this.byteEnd+1:this.byteSize!=null?this.byteSize-1:void 0}setOffsetDetails(){if(this.requestRangeStart==null&&this.requestRangeEnd==null){this.log.trace("requestRangeStart and requestRangeEnd are null");return}try{let{start:e,end:t,byteSize:n}=SI(this.requestRangeStart??void 0,this.requestRangeEnd??void 0,this._fileSize??void 0);this.log.trace("set byteStart to %o, byteEnd to %o, byteSize to %o",e,t,n),this.byteStart=e,this.byteEnd=t,this.byteSize=n}catch(e){this.log.error("error setting offset details: %o",e),this.byteStart=void 0,this.byteEnd=void 0,this.byteSize=void 0}}get contentRangeHeaderValue(){if(!this.isValidRangeRequest)throw this.log.error("cannot get contentRangeHeaderValue for invalid range request"),new qr("Invalid range request");return l_({byteStart:this.byteStart,byteEnd:this.byteEnd,byteSize:this._fileSize??void 0})}};async function AI(r,e,t,n){let o=t.forComponent("helia:verified-fetch:get-stream-from-async-iterable"),i=r[Symbol.asyncIterator](),{value:s,done:a}=await i.next();if(a===!0)throw o.error("no content found for path",e),new Xm;return{stream:new ReadableStream({async start(l){n?.onProgress?.(new M("verified-fetch:request:progress:chunk")),l.enqueue(s)},async pull(l){let{value:u,done:d}=await i.next();if(n?.signal?.aborted===!0){l.error(new Ut(n.signal.reason??"signal aborted by user")),l.close();return}if(d===!0){u!=null&&(n?.onProgress?.(new M("verified-fetch:request:progress:chunk")),l.enqueue(u)),l.close();return}n?.onProgress?.(new M("verified-fetch:request:progress:chunk")),l.enqueue(u)}}),firstChunk:s}}function _I(r){return r?.then!=null}async function _2({bytes:r,path:e,response:t,contentTypeParser:n,log:o,defaultContentType:i="application/octet-stream"}){let s;if(n!=null)try{let a=e.split("/").pop()?.trim();a=a===""?void 0:a;let c=n(r,a);if(_I(c)){let l=await c;l!=null&&(s=l)}else c!=null&&(s=c);o.trace("contentTypeParser returned %s",s)}catch(a){o.error("error parsing content type",a)}o.trace('setting content type to "%s"',s??i),t.headers.set("content-type",s??i)}var I2=class extends dt{codes=[Le];canHandle({cid:e,accept:t,pathDetails:n}){return this.log("checking if we can handle %c with accept %s",e,t),n==null?!1:e.code===Le}getRedirectUrl(e){let{resource:t,path:n}=e;if(n===""?!t.toString().endsWith("/"):!n.endsWith("/"))try{let i=new URL(t.toString());return i.pathname.endsWith("/")?null:(i.pathname=`${i.pathname}/`,i.toString())}catch{return`${t.toString()}/`}return null}async handle(e){let{cid:t,options:n,withServerTiming:o=!1,pathDetails:i}=e,{handleServerTiming:s,contentTypeParser:a,helia:c,getBlockstore:l}=this.pluginOptions,u=this.log,d=e.resource,h=e.path,f=!1,p=new $c(this.pluginOptions.logger,n?.headers);if(i==null)throw new TypeError("Path details are required");let m=i.ipfsRoots,g=i.terminalElement,y=g.cid;if(g?.type==="directory"){let x=g.cid,A=this.getRedirectUrl(e);if(A!=null){if(u.trace("directory url normalization spec requires redirect..."),n?.redirect==="error")throw u('could not redirect to %s as redirect option was set to "error"',A),new TypeError("Failed to fetch");if(n?.redirect==="manual")return u("returning 301 permanent redirect to %s",A),qu(d,A);u("following redirect to %s",A),d=A,f=!0}let k="index.html";try{u.trace("found directory at %c/%s, looking for index.html",t,h);let v=await s("exporter-dir","",async()=>_t(`/ipfs/${x}/${k}`,c.blockstore,{signal:n?.signal,onProgress:n?.onProgress}),o);u.trace("found root file at %c/%s with cid %c",x,k,v.cid),h=k,y=v.cid}catch(v){this.log.error("error loading path %c/%s",x,k,v),n?.signal?.throwIfAborted(),e.isDirectory=!0,e.directoryEntries=[],this.log.trace("attempting to get directory entries because index.html was not found");let S=EI({...c,blockstore:l(e.cid,e.resource,n?.session??!0,n)});try{for await(let I of S.ls(x,{signal:n?.signal,onProgress:n?.onProgress}))e.directoryEntries.push(I);return null}catch(I){return u.error("error listing directory %c",x,I),qm("Unable to get directory contents")}}finally{n?.onProgress?.(new M("verified-fetch:request:end",{cid:x,path:k}))}}p.isRangeRequest&&p.isValidRangeRequest&&g.type==="file"&&(p.setFileSize(g.unixfs.fileSize()),u.trace("fileSize for rangeRequest %d",p.getFileSize()));let w=p.offset,b=p.length;u.trace("calling exporter for %c/%s with offset=%o & length=%o",y,h,w,b);try{let A=(await s("exporter-file","",async()=>_t(y,c.blockstore,{signal:n?.signal,onProgress:n?.onProgress}),o)).content({signal:n?.signal,onProgress:n?.onProgress,offset:w,length:b});u("got async iterator for %c/%s",t,h);let{stream:k,firstChunk:v}=await s("stream-and-chunk","",async()=>AI(A,h??"",this.pluginOptions.logger,{onProgress:n?.onProgress,signal:n?.signal}),o);p.setBody(k);let S=Wm(d,p.getBody(),{byteRangeContext:p,log:u},{redirected:f});return await s("set-content-type","",async()=>_2({bytes:v,path:h,response:S,contentTypeParser:a,log:u}),o),jm(S,m),S}catch(x){return n?.signal?.throwIfAborted(),u.error("error streaming %c/%s",t,h,x),p.isRangeRequest&&x.code==="ERR_INVALID_PARAMS"?Km(d):Rc(d.toString(),"Unable to stream content")}}};var T2=class extends dt{canHandle(e){this.log("checking if we can handle %c with accept %s",e.cid,e.accept);let{pathDetails:t,cid:n}=e;return t!=null?!1:n.code===Le||n.code===Pr}async handle(e){let{cid:t,resource:n,options:o,withServerTiming:i=!1}=e,{getBlockstore:s,handleServerTiming:a}=this.pluginOptions,c=s(t,n,o?.session??!0,o),l=await a("path-walking","",async()=>M_({...e,blockstore:c,log:this.log}),i);return e.modified++,l instanceof Response?(this.log.trace("path walking failed"),l.status===404?l:null):(e.pathDetails=l,null)}};function k2(r){return r.charAt(0)==="1"||r.charAt(0)==="Q"?Ue(r):or(O.parse(r))}var od=class extends Error{name="PluginError";code;fatal;details;response;constructor(e,t,n){super(t),this.code=e,this.fatal=n?.fatal??!1,this.details=n?.details,this.response=n?.response}},Vo=class extends od{name="PluginFatalError";constructor(e,t,n){super(e,t,{...n,fatal:!0}),this.name="PluginFatalError"}};var C2=class extends dt{codes=[];canHandle({cid:e,accept:t,query:n}){return this.log("checking if we can handle %c with accept %s",e,t),t==="application/vnd.ipfs.ipns-record"||n.format==="ipns-record"}async handle(e){let{resource:t,path:n,options:o}=e,{helia:i}=this.pluginOptions;if(e.reqFormat="ipns-record",n!==""||!(t.startsWith("ipns://")||t.includes(".ipns.")||t.includes("/ipns/")))throw this.log.error('invalid request for IPNS name "%s" and path "%s"',t,n),new Vo("ERR_INVALID_IPNS_NAME","Invalid IPNS name",{response:Ku(t,"Invalid IPNS name")});let s;try{let h;t.startsWith("ipns://")?h=t.replace("ipns://",""):t.includes("/ipns/")?h=t.split("/ipns/")[1].split("/")[0].split("?")[0]:h=t.split(".ipns.")[0].split("://")[1],this.log.trace('trying to parse peer id from "%s"',h),s=k2(h)}catch(h){throw this.log.error("could not parse peer id from IPNS url %s",t,h),new Vo("ERR_NO_PEER_ID_FOUND","could not parse peer id from url",{response:Ku(t,h)})}let a=ge([C("/ipns/"),s.toMultihash().bytes]),c=new Be("/dht/record/"+V(a,"base32"),!1),l=await i.datastore.get(c,o),u=tt.deserialize(l),d=On(t,u.value);return d.headers.set("content-type","application/vnd.ipfs.ipns-record"),d}};var P2=class extends dt{codes=[Jn,qn];canHandle({cid:e,accept:t}){return this.log("checking if we can handle %c with accept %s",e,t),t==="application/vnd.ipld.dag-json"&&e.code!==Pr?!0:Jn===e.code||qn===e.code}async handle(e){let{path:t,resource:n,cid:o,accept:i,options:s}=e,{getBlockstore:a}=this.pluginOptions,c=s?.session??!0;this.log.trace("fetching %c/%s",o,t);let l=e.pathDetails?.terminalElement.cid??e.cid,d=await a(l,n,c,s).get(l,s),h;if(i==="application/vnd.ipld.dag-cbor"||i==="application/cbor")try{let p=Ha(d);h=Ua(p)}catch(p){return this.log.error("could not transform %c to application/vnd.ipld.dag-cbor",p),Ho(n)}else h=d;let f=On(n,h);return f.headers.set("content-type",i??"application/json"),f}};var XF=["application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/octet-stream"];function QF({headers:r,accept:e}){let n=(e??new Headers(r).get("accept")??"").split(",").map(o=>o.split(";")[0]).map(o=>o.trim());for(let o of n){if(o==="*/*")return;if(XF.includes(o??""))return o}}var R2=class extends dt{codes=[$e,vt.code];canHandle({cid:e,accept:t,query:n}){return this.log("checking if we can handle %c with accept %s",e,t),t==="application/vnd.ipld.raw"||n.format==="raw"}async handle(e){let{path:t,resource:n,cid:o,accept:i,query:s,options:a}=e,{getBlockstore:c,contentTypeParser:l}=this.pluginOptions,u=a?.session??!0,d=this.log;if(i==="application/vnd.ipld.raw"||s.format==="raw"?(e.reqFormat="raw",e.query.download=!0,e.query.filename=e.query.filename??`${o.toString()}.bin`,d.trace("Set content disposition...")):d.trace("Did NOT setting content disposition..."),t!==""&&o.code===$e)throw d.trace("404-ing raw codec request for %c/%s",o,t),new Vo("ERR_RAW_PATHS_NOT_SUPPORTED","Raw codec does not support paths",{response:Gm(n,"Raw codec does not support paths")});let h=new $c(this.pluginOptions.logger,a?.headers),f=e.pathDetails?.terminalElement.cid??e.cid,m=await c(f,n,u,a).get(f,a);h.setBody(m);let g=Wm(n,h.getBody(),{byteRangeContext:h,log:d},{redirected:!1});return await _2({bytes:m,path:t,response:g,defaultContentType:QF({headers:a?.headers,accept:i}),contentTypeParser:l,log:d}),g}};var jF=({weak:r,reqFormat:e})=>e==="tar"||e==="car"||e==="ipns-record"||r===!0?"W/":"",ZF=({reqFormat:r})=>r==null?"":r==="tar"?".x-tar":`.${r}`;function L2({cid:r,reqFormat:e,weak:t,rangeStart:n,rangeEnd:o}){let i=jF({weak:t,reqFormat:e}),s=ZF({reqFormat:e});return(n!=null||o!=null)&&(s+=`.${n??"0"}-${o??"N"}`),`${i}"${r.toString()}${s}"`}var GAe=C("ustar\0","binary"),WAe=C("ustar ","binary"),YAe=C(" \0","binary");var PI=xt(TI(),1);function eH(r){return r[Symbol.asyncIterator]!=null}function tH(r){if(eH(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=ge([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return ge(e,t)}var kI=tH;var rH="0000000000000000000",nH="7777777777777777777",oH=48,iH=C("ustar\0","binary"),sH=C("00","binary"),aH=parseInt("7777",8),cH=257,lH=263,uH=function(r){switch(r){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72;default:return 0}},dH=function(r){let e=256;for(let t=0;t<148;t++)e+=r[t];for(let t=156;t<512;t++)e+=r[t];return e},Vi=function(r,e){let t=r.toString(8);return t.length>e?C(nH.slice(0,e)+" "):C(rH.slice(0,e-t.length)+t+" ")},N5=function(r){let e=C(r).byteLength,t=Math.floor(Math.log(e)/Math.log(10))+1;return e+t>=Math.pow(10,t)&&t++,`${e+t}${r}`};function CI(r){let e="";r.name!=null&&(e+=N5(" path="+r.name+`
76
76
  `)),r.linkname!=null&&(e+=N5(" linkpath="+r.linkname+`
77
77
  `));let t=r.pax;if(t!=null)for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e+=N5(" "+n+"="+t[n]+`
78
78
  `));return C(e)}function D2(r){let e=new Uint8Array(512),t=r.name,n="";if(r.typeflag===5&&t[t.length-1]!=="/"&&(t+="/"),C(t).byteLength!==t.length)return null;for(;C(t).byteLength>100;){let o=t.indexOf("/");if(o===-1)return null;n+=n!==""?"/"+t.slice(0,o):t.slice(0,o),t=t.slice(o+1)}return C(t).byteLength>100||C(n).byteLength>155||r.linkname!=null&&C(r.linkname).byteLength>100?null:(e.set(C(t),0),e.set(Vi(r.mode&aH,6),100),e.set(Vi(r.uid,6),108),e.set(Vi(r.gid,6),116),e.set(Vi(r.size,11),124),e.set(Vi(r.mtime.getTime()/1e3|0,11),136),e[156]=oH+uH(r.type),r.linkname!=null&&e.set(C(r.linkname),157),e.set(iH,cH),e.set(sH,lH),r.uname!=null&&e.set(C(r.uname),265),r.gname!=null&&e.set(C(r.gname),297),e.set(Vi(r.devmajor??0,6),329),e.set(Vi(r.devminor??0,6),337),n!=null&&e.set(C(n),345),e.set(Vi(dH(e),6),148),e)}var{S_IFMT:hH,S_IFBLK:pH,S_IFCHR:mH,S_IFDIR:gH,S_IFIFO:yH,S_IFLNK:wH}=PI.default,bH=parseInt("755",8),xH=parseInt("644",8),RI=new Uint8Array(1024);function EH(r=0){switch(r&hH){case pH:return"block-device";case mH:return"character-device";case gH:return"directory";case yH:return"fifo";case wH:return"symlink";default:return"file"}}function B5(r){return r&=511,r!==0?RI.subarray(0,512-r):new Uint8Array(0)}function O5(r){if(r.pax==null){let e=D2(r);if(e!=null)return e}return vH(r)}function vH(r){let e=CI(r),t={name:"PaxHeader",mode:r.mode,uid:r.uid,gid:r.gid,size:e.length,mtime:r.mtime,type:"pax-header",linkname:r.linkname,uname:r.uname,gname:r.gname,devmajor:r.devmajor,devminor:r.devminor};return new Z(D2(t)??new Uint8Array(0),e,B5(e.length),D2({...t,size:r.size,type:r.type})??new Uint8Array(0)).subarray()}function N2(){return async function*(r){for await(let{header:e,body:t}of r){let n={...e,size:e.type==="symlink"?0:e.size??0,type:e.type??EH(e.mode),mode:e.mode??(e.type==="directory"?bH:xH),uid:e.uid??0,gid:e.gid??0,mtime:e.mtime??new Date};if(typeof t=="string"&&(t=C(t)),t instanceof Uint8Array||Xr(t)){n.size=t.length,yield O5(n),yield Xr(t)?t.subarray():t,yield B5(n.size);continue}if(n.type==="symlink"&&n.linkname==null){if(t==null)throw new Error("type was symlink but no linkname or body specified");n.linkname=V(await kI(t)),yield O5(n);continue}if(yield O5(n),n.type!=="file"&&n.type!=="contiguous-file")continue;let o=0;for await(let i of t??[])o+=i.length,yield Xr(i)?i.subarray():i;if(o!==n.size)throw new Error(`size mismatch, wrote ${o} of ${n.size} bytes`);yield B5(n.size)}yield RI}}var SH=["file","raw","directory"];function AH(r){let e,t;return(r.type==="file"||r.type==="directory")&&(e=r.unixfs.mode,t=r.unixfs.mtime!=null?new Date(Number(r.unixfs.mtime.secs*1000n)):void 0),{name:r.path,mode:e,mtime:t,size:Number(r.size),type:r.type==="directory"?"directory":"file"}}function LI(r){if(!SH.includes(r.type))throw new Gr(`${r.type} is not a UnixFS node`);let e={header:AH(r)};return(r.type==="file"||r.type==="raw")&&(e.body=r.content()),e}async function*DI(r,e,t){let n=await _t(r,e,t);if(n.type==="file"||n.type==="raw"){yield*Pe([LI(n)],N2());return}if(n.type==="directory"){yield*Pe(Mc(r,e,t),o=>Je(o,i=>LI(i)),N2());return}throw new Gr("Not a UnixFS node")}var O2=class extends dt{codes=[];canHandle({cid:e,accept:t,query:n}){return this.log("checking if we can handle %c with accept %s",e,t),t==="application/x-tar"||n.format==="tar"}async handle(e){let{cid:t,path:n,resource:o,options:i,pathDetails:s}=e,{getBlockstore:a}=this.pluginOptions,c=s?.terminalElement.cid??t;if(c.code!==Le&&c.code!==$e)return Ho("only UnixFS data can be returned in a TAR file");e.reqFormat="tar",e.query.download=!0,e.query.filename=e.query.filename??`${c.toString()}.tar`;let l=a(c,o,i?.session,i),u=zu(DI(`/ipfs/${t}/${n}`,l,i)),d=On(o,u);return d.headers.set("content-type","application/x-tar"),d.headers.set("etag",L2({cid:c,reqFormat:e.reqFormat,weak:!0})),d}};function NI(r){let e=_H(r);return e===r?`filename="${r}"`:`filename="${e}"; filename*=UTF-8''${encodeURIComponent(r)}`}function _H(r){return r.replace(/[^\x00-\x7F]/g,"_")}var IH={[Pr]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car"],[Jn]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car"],[qn]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car"],[Le]:["application/octet-stream","application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car","application/x-tar"],[$e]:["application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.dag-json","application/vnd.ipld.car","application/x-tar"]};function OI(r,e){let t=IH[r.code];if(e!=null)return TH(e,t)}function TH(r,e){let t=r.split(",").map(n=>{let o=n.trim().split(";");return{mimeType:`${o[0]}`.trim(),weight:kH(o[1])}}).sort((n,o)=>n.weight===o.weight?0:n.weight>o.weight?-1:1).map(n=>n.mimeType);for(let n of t)for(let o of e)if(n.includes(o)||n==="*/*"||n.startsWith("*/")&&o.split("/")[1]===n.split("/")[1]||n.endsWith("/*")&&o.split("/")[0]===n.split("/")[0])return o}function kH(r){if(r!=null&&(r=r.trim()),r?.startsWith("q=")!==!0)return 1;let e=parseFloat(r.replace("q=",""));return isNaN(e)?0:e}var B2={raw:"application/vnd.ipld.raw",car:"application/vnd.ipld.car","dag-json":"application/vnd.ipld.dag-json","dag-cbor":"application/vnd.ipld.dag-cbor",json:"application/json",cbor:"application/cbor","ipns-record":"application/vnd.ipfs.ipns-record",tar:"application/x-tar"};function BI(r){if(r!=null)return B2[r]}function M5(r){let e=r.get("accept");return!!(e!=null&&Object.values(B2).includes(e))}function U5(r){let e=r?.format;return!!(e!=null&&Object.keys(B2).includes(e))}function MI({query:r,headers:e}){return M5(e)||U5(r)}function UI({query:r,headers:e,logger:t}){let n=t.forComponent("helia:verified-fetch:get-resolved-accept-header"),o=new Headers(e),i=o.get("accept")??void 0;if(i!=null&&n('incoming accept header "%s"',i),!MI({query:r,headers:o}))return n("no explicit IPLD content-type requested, returning incoming accept header %s",i),i;let s=BI(r?.format);r?.format!=null&&n('incoming query format "%s", mapped to %s',r.format,s);let a=i;return!M5(o)&&U5(r)&&(n("accept header not recognized, but query format provided, setting accept header to %s",s),a=s),n('resolved accept header to "%s"',a),a}async function id(r,e,t){let n=performance.now();try{let o=await t(),s=(performance.now()-n).toFixed(1),a=`${r};dur=${s};desc="${e}"`;return{result:o,header:a,error:null}}catch(o){let s=(performance.now()-n).toFixed(1),a=`${r};dur=${s};desc="${e}"`;return{result:null,error:o,header:a}}}var FI=xt(B3(),1),M2=class{lru;constructor(e){this.lru=(0,FI.default)(e)}get(e){let t=this.lru.get(e);if(t!=null){if(t.expire!=null&&t.expire<Date.now()){this.lru.remove(e);return}return t.value}}set(e,t,n){this.lru.set(e,{value:t,expire:Date.now()+n})}has(e){return this.get(e)!=null}remove(e){this.lru.remove(e)}clear(){this.lru.clear()}};var HI=new M2(1e3),CH=/^(?<protocol>ip[fn]s):\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,PH=/^\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,RH=/^https?:\/\/(.*[^/])\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,LH=/^https?:\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\.(?<protocol>ip[fn]s)\.([^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/;function DH(r){let e=r?.protocol;if(e==null)return!1;let t=r?.cidOrPeerIdOrDnsLink;if(t==null)return!1;let n=r?.path,o=r?.queryString;return["ipns","ipfs"].includes(e)&&typeof t=="string"&&(n==null||typeof n=="string")&&(o==null||typeof o=="string")}function sd(r){for(let e of[LH,CH,RH,PH]){let t=r.match(e);if(DH(t?.groups))return t.groups}throw new TypeError(`Invalid URL: ${r}, please use ipfs://, ipns://, or gateway URLs only`)}function NH(r){if(r==null)return;let e=r.answer?.TTL,t=r.record?.ttl,n=t!=null?Number(t/BigInt(1e9)):void 0;return e??n}var OH=/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;function BH(r){return OH.test(r)&&r.includes("-")&&!r.includes(".")}function MH(r){return r.replace(/--/g,"%").replace(/-/g,".").replace(/%/g,"-")}async function VI({urlString:r,ipns:e,logger:t,withServerTiming:n=!1},o){let i=t.forComponent("helia:verified-fetch:parse-url-string"),{protocol:s,cidOrPeerIdOrDnsLink:a,path:c,queryString:l}=sd(r),u,d,h=[],f,p=[];if(s==="ipfs")try{u=O.parse(a)}catch(y){i.error(y),h.push(new TypeError("Invalid CID for ipfs://<cid> URL"))}else if(f=HI.get(a),f!=null)u=f.cid,d=f.path,i.trace("resolved %s to %c from cache",a,u);else{i.trace("Attempting to resolve PeerId for %s",a);let y;try{if(y=k2(a),y.publicKey==null)throw new TypeError("cidOrPeerIdOrDnsLink contains no public key");if(n){let w=await id("ipns.resolve",`Resolve IPNS name ${a}`,e.resolve.bind(null,y.publicKey,o));if(p.push(w),w.error!=null)throw w.error;f=w.result}else f=await e.resolve(y.publicKey,o);u=f?.cid,d=f?.path,i.trace("resolved %s to %c",a,u)}catch(w){o?.signal?.throwIfAborted(),y==null?(i.error('could not parse PeerId string "%s"',a,w),h.push(new TypeError(`Could not parse PeerId in ipns url "${a}", ${w.message}`))):(i.error("could not resolve PeerId %c",y,w),h.push(new TypeError(`Could not resolve PeerId "${a}", ${w.message}`)))}if(u==null){let w=a;BH(a)&&(w=MH(a),i.trace('decoded dnslink from "%s" to "%s"',a,w)),i.trace("Attempting to resolve DNSLink for %s",w);try{if(n){let b=await id("ipns.resolveDNSLink",`Resolve DNSLink ${w}`,e.resolveDNSLink.bind(e,w,o));if(p.push(b),b.error!=null)throw b.error;f=b.result}else f=await e.resolveDNSLink(w,o);u=f?.cid,d=f?.path,i.trace("resolved %s to %c",w,u)}catch(b){o?.signal?.throwIfAborted(),i.error('could not resolve DnsLink for "%s"',a,b),h.push(b)}}}if(u==null)throw h.length===1?h[0]:new AggregateError(h,`Invalid resource. Cannot determine CID from URL "${r}"`);let m=NH(f);f!=null&&(m=m??60*2,i.trace("caching %s resolved to %s with TTL: %s",a,u,m),HI.set(a,f,m*1e3));let g={};if(l!=null&&l.length>0){let y=l.split("&");for(let w of y){let[b,x]=w.split("=");g[b]=decodeURIComponent(x)}g.download!=null&&(g.download=g.download==="true"),g.filename!=null&&(g.filename=g.filename.toString())}return{protocol:s,cid:u,path:UH(d,c??""),query:g,ttl:m,ipfsPath:`/${s}/${a}${c!=null&&c!==""?`/${c}`:""}`,serverTimings:p}}function UH(r,e){let t="";return r!=null&&(t+=r),e.length>0&&(t=`${t.length>0?`${t}/`:t}${e}`),t=t.replace(/\/(\/)+/g,"/"),t.startsWith("/")&&(t=t.substring(1)),t.split("/").map(decodeURIComponent).join("/")}function $I(r){return r.match(/\.[a-zA-Z0-9]{1,4}$/)!=null||r.endsWith("/")?r:`${r}/`}async function zI({resource:r,options:e,logger:t,cid:n,fetch:o=globalThis.fetch}){let i=t.forComponent("helia:verified-fetch:get-redirect-response");if(typeof r!="string"||e==null||["ipfs://","ipns://"].some(u=>r.startsWith(u)))return null;let s=new Headers(e?.headers),a=s.get("x-forwarded-host"),c=s.get("host");if(s.get("x-forwarded-for")==null&&a==null&&c==null)return i.trace("no redirect info found in headers"),null;i.trace("checking for redirect info");try{let u=sd(r),d=new URL(r),h=a??d.host,f=new URL(d);if(u.protocol==="ipfs"&&n.version===0?f.host=`${n.toV1()}.ipfs.${h}`:f.host=`${u.cidOrPeerIdOrDnsLink}.${u.protocol}.${h}`,c?.includes(u.protocol)===!0&&f.host.includes(c))return i.trace("request was for a subdomain already, not setting location header"),null;if(c!=null&&!f.host.includes(c))return i.trace("host header is not the same as the subdomain url host, not setting location header"),null;if(d.host===f.host)return i.trace("req url is the same as the subdomain url, not setting location header"),null;f.pathname=$I(d.pathname.replace(`/${u.cidOrPeerIdOrDnsLink}`,"").replace(`/${u.protocol}`,"")),i.trace("subdomain url %s",f.href);let p=new URL(d,`${d.protocol}//${h}`);p.pathname=$I(d.pathname),i.trace("path url %s",p.href);try{let m=await o(f,{method:"HEAD"});if(m.ok)return i("subdomain supported, redirecting to subdomain"),qu(r.toString(),f.href);throw i("subdomain not supported, subdomain failed with status %s %s",m.status,m.statusText),new Qm("subdomain not supported")}catch(m){return i("subdomain not supported",m),p.href===d.href?(i("path url is the same as the request url, not setting location header"),null):qu(r.toString(),p.href)}}catch(u){i.error("error setting location header for x-forwarded-host",u)}return null}async function KI(r,{ipns:e,logger:t},{withServerTiming:n=!1,...o}={withServerTiming:!1}){if(typeof r=="string")return VI({urlString:r,ipns:e,logger:t,withServerTiming:n},o);let i=O.asCID(r);if(i!=null)return{cid:i,protocol:"ipfs",path:"",query:{},ipfsPath:`/ipfs/${i.toString()}`,ttl:29030400,serverTimings:[]};throw new TypeError(`Invalid resource. Cannot determine CID from resource: ${r}`)}function qI(r){let e=O.asCID(r);if(e!=null)return`ipfs://${e}`;try{return`ipfs://${O.parse(r.toString())}`}catch{}let{protocol:t,cidOrPeerIdOrDnsLink:n}=sd(r.toString());return`${t}://${n}`}var FH=100,HH=60*1e3;function VH(r){if(r==null)return;let e;return r?.signal===null?e=void 0:e=r?.signal,{...r,signal:e}}var U2=class{helia;ipns;log;contentTypeParser;blockstoreSessions;serverTimingHeaders=[];withServerTiming;plugins=[];constructor({helia:e,ipns:t},n){this.helia=e,this.log=e.logger.forComponent("helia:verified-fetch"),this.ipns=t??Kx(e),this.contentTypeParser=n?.contentTypeParser,this.blockstoreSessions=new Hm({max:n?.sessionCacheSize??FH,ttl:n?.sessionTTLms??HH,dispose:a=>{a.close()}}),this.withServerTiming=n?.withServerTiming??!1;let o={...n,logger:A9("helia:verified-fetch"),getBlockstore:(a,c,l,u)=>this.getBlockstore(a,c,l,u),handleServerTiming:async(a,c,l)=>this.handleServerTiming(a,c,l,this.withServerTiming),helia:e,contentTypeParser:this.contentTypeParser},i=[new T2(o),new C2(o),new Ym(o),new R2(o),new O2(o),new P2(o),new u2(o),new I2(o)],s=n?.plugins?.map(a=>a(o))??[];if(s.length>0){let a=new Map(i.map(l=>[l.constructor.name,l])),c=new Map(s.map(l=>[l.constructor.name,l]));this.plugins=i.map(l=>c.get(l.constructor.name)??l),this.plugins.push(...s.filter(l=>!a.has(l.constructor.name)))}else this.plugins=i;this.log.trace("created VerifiedFetch instance")}getBlockstore(e,t,n=!0,o={}){let i=qI(t);if(!n)return this.helia.blockstore;let s=this.blockstoreSessions.get(i);return s==null&&(s=this.helia.blockstore.createSession(e,o),this.blockstoreSessions.set(i,s)),s}async handleServerTiming(e,t,n,o){if(!o)return n();let{error:i,result:s,header:a}=await id(e,t,n);if(this.serverTimingHeaders.push(a),i!=null)throw i;return s}handleFinalResponse(e,{query:t,cid:n,reqFormat:o,ttl:i,protocol:s,ipfsPath:a}={}){if(this.serverTimingHeaders.length>0){let l=this.serverTimingHeaders.join(", ");e.headers.set("Server-Timing",l),this.serverTimingHeaders=[]}let c;return this.log.trace("checking for content disposition"),t?.download===!0?c="attachment":this.log.trace("download not requested"),t?.filename!=null?(c==null&&(c="inline"),c=`${c}; ${NI(t.filename)}`):this.log.trace("no filename specified in query"),c!=null?e.headers.set("Content-Disposition",c):this.log.trace("no content disposition specified"),n!=null&&e.headers.get("etag")==null&&e.headers.set("etag",L2({cid:n,reqFormat:o,weak:!1})),s!=null&&c_({response:e,ttl:i,protocol:s}),a!=null&&e.headers.set("X-Ipfs-Path",a),e}async runPluginPipeline(e,t=3){let n,o=0,i=new Set,s=e.modified;for(;o<t;){this.log(`Starting pipeline pass #${o+1}`),o++;let a=this.plugins.filter(u=>!i.has(u.constructor.name)).filter(u=>u.canHandle(e));if(a.length===0){this.log.trace("No plugins can handle the current context.. checking by CID code");let u=this.plugins.filter(d=>d.codes.includes(e.cid.code));if(u.length>0)a.push(...u);else{this.log.trace("No plugins found that can handle request by CID code; exiting pipeline.");break}}this.log.trace("Plugins ready to handle request: ",a.map(u=>u.constructor.name).join(", "));let c=!1,l=!1;for(let u of a){try{this.log.trace("Invoking plugin:",u.constructor.name),i.add(u.constructor.name);let d=await u.handle(e);if(d!=null){n=d,l=!0;break}}catch(d){if(e.options?.signal?.throwIfAborted(),this.log.error("Error in plugin:",u.constructor.name,d),d.name==="PluginFatalError")return d.response??Rc(e.resource,"Failed to fetch")}finally{let d=e.modified;c=d!==s,c&&(s=d)}if(n!=null){this.log.trace("Plugin produced final response:",u.constructor.name);break}}if(l&&n!=null)break;if(!c){this.log.trace("No context changes and no final response; exiting pipeline.");break}}return n}async fetch(e,t){this.log("fetch %s",e);let n=VH(t),o=n?.withServerTiming??this.withServerTiming;n?.onProgress?.(new M("verified-fetch:request:start",{resource:e}));let i,s,a,c,l,u;try{let y=await this.handleServerTiming("parse-resource","",async()=>KI(e,{ipns:this.ipns,logger:this.helia.logger},{withServerTiming:o,...n}),o);i=y.cid,s=y.path,a=y.query,c=y.ttl,l=y.protocol,u=y.ipfsPath,this.serverTimingHeaders.push(...y.serverTimings.map(({header:w})=>w))}catch(y){return n?.signal?.throwIfAborted(),this.log.error("error parsing resource %s",e,y),this.handleFinalResponse(Ku(e.toString(),y))}n?.onProgress?.(new M("verified-fetch:request:resolve",{cid:i,path:s}));let d=UI({query:a,headers:n?.headers,logger:this.helia.logger}),h=OI(i,d);if(this.log("output type %s",h),d!=null&&h==null)return this.handleFinalResponse(Ho(e.toString()));let f=h?.split(";")[0]??"application/octet-stream",p=await zI({resource:e,options:n,logger:this.helia.logger,cid:i});if(p!=null)return this.handleFinalResponse(p);let m={cid:i,path:s,resource:e.toString(),accept:h,query:a,options:n,withServerTiming:o,onProgress:n?.onProgress,modified:0};this.log.trace('finding handler for cid code "%s" and response content type "%s"',i.code,f);let g=await this.runPluginPipeline(m);return n?.onProgress?.(new M("verified-fetch:request:end",{cid:i,path:s})),this.handleFinalResponse(g??qm(e.toString()),{query:{...a,...m.query},cid:i,reqFormat:m.reqFormat,ttl:c,protocol:l,ipfsPath:u})}async start(){await this.helia.start()}async stop(){await this.helia.stop()}};var ad,F2=async function(e,t){return ad==null&&(ad=await F5()),ad(e,t)};F2.start=async function(){await ad?.start()};F2.stop=async function(){await ad?.stop()};function $H(r){return"ipfs-_blank"}function zH(r,e){let t;try{let n=new URL(e.globalData.gatewayURL),o=e.globalData.dnsLink?"inbrowser.dev":n.host,i=o;o.includes(".ipfs.")?i=o.split(".ipfs.")[1]:o.includes(".ipns.")&&(i=o.split(".ipns.")[1]),t=`${n.protocol}//${i}/ipfs/${r.hash}?filename=${r.name}`}catch{t=`ipfs://${r.hash}`}return`<a class="ipfs-hash" translate="no" href="${t}">${r.shortHash}</a>`}function KH(r){return r.path!=null?`Index of <a href="${`${r.globalData.gatewayURL}/${r.path}`}">${r.name}</a>`:`Index of ${r.name} ${r.path}`}function qH(r){return r.listing.map(e=>`<div class="type-icon">
@@ -1 +1 @@
1
- {"version":3,"file":"set-content-type.d.ts","sourceRoot":"","sources":["../../../src/utils/set-content-type.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,mBAAmB,CAAA;AAC/C,OAAO,EAAE,KAAK,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAGpD,MAAM,WAAW,qBAAqB;IACpC,KAAK,EAAE,UAAU,CAAA;IACjB,IAAI,EAAE,MAAM,CAAA;IACZ,QAAQ,EAAE,QAAQ,CAAA;IAClB,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAC3B,iBAAiB,EAAE,iBAAiB,GAAG,SAAS,CAAA;IAChD,GAAG,EAAE,MAAM,CAAA;CACZ;AAED,wBAAsB,cAAc,CAAE,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,iBAAiB,EAAE,GAAG,EAAE,kBAA+C,EAAE,EAAE,qBAAqB,GAAG,OAAO,CAAC,IAAI,CAAC,CAwB9K"}
1
+ {"version":3,"file":"set-content-type.d.ts","sourceRoot":"","sources":["../../../src/utils/set-content-type.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,mBAAmB,CAAA;AAC/C,OAAO,EAAE,KAAK,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAGpD,MAAM,WAAW,qBAAqB;IACpC,KAAK,EAAE,UAAU,CAAA;IACjB,IAAI,EAAE,MAAM,CAAA;IACZ,QAAQ,EAAE,QAAQ,CAAA;IAClB,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAC3B,iBAAiB,EAAE,iBAAiB,GAAG,SAAS,CAAA;IAChD,GAAG,EAAE,MAAM,CAAA;CACZ;AAED,wBAAsB,cAAc,CAAE,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,iBAAiB,EAAE,GAAG,EAAE,kBAA+C,EAAE,EAAE,qBAAqB,GAAG,OAAO,CAAC,IAAI,CAAC,CAyB9K"}
@@ -17,6 +17,7 @@ export async function setContentType({ bytes, path, response, contentTypeParser,
17
17
  else if (parsed != null) {
18
18
  contentType = parsed;
19
19
  }
20
+ log.trace('contentTypeParser returned %s', contentType);
20
21
  }
21
22
  catch (err) {
22
23
  log.error('error parsing content type', err);
@@ -1 +1 @@
1
- {"version":3,"file":"set-content-type.js","sourceRoot":"","sources":["../../../src/utils/set-content-type.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,MAAM,mBAAmB,CAAA;AAC/C,OAAO,EAA0B,MAAM,aAAa,CAAA;AACpD,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAA;AAW5C,MAAM,CAAC,KAAK,UAAU,cAAc,CAAE,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,iBAAiB,EAAE,GAAG,EAAE,kBAAkB,GAAG,0BAA0B,EAAyB;IAC7J,IAAI,WAA+B,CAAA;IAEnC,IAAI,iBAAiB,IAAI,IAAI,EAAE,CAAC;QAC9B,IAAI,CAAC;YACH,IAAI,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,IAAI,EAAE,CAAA;YAC5C,QAAQ,GAAG,QAAQ,KAAK,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,QAAQ,CAAA;YACjD,MAAM,MAAM,GAAG,iBAAiB,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;YAEjD,IAAI,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC;gBACtB,MAAM,MAAM,GAAG,MAAM,MAAM,CAAA;gBAE3B,IAAI,MAAM,IAAI,IAAI,EAAE,CAAC;oBACnB,WAAW,GAAG,MAAM,CAAA;gBACtB,CAAC;YACH,CAAC;iBAAM,IAAI,MAAM,IAAI,IAAI,EAAE,CAAC;gBAC1B,WAAW,GAAG,MAAM,CAAA;YACtB,CAAC;QACH,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,GAAG,CAAC,KAAK,CAAC,4BAA4B,EAAE,GAAG,CAAC,CAAA;QAC9C,CAAC;IACH,CAAC;IACD,GAAG,CAAC,KAAK,CAAC,8BAA8B,EAAE,WAAW,IAAI,kBAAkB,CAAC,CAAA;IAC5E,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE,WAAW,IAAI,kBAAkB,CAAC,CAAA;AACzE,CAAC"}
1
+ {"version":3,"file":"set-content-type.js","sourceRoot":"","sources":["../../../src/utils/set-content-type.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,MAAM,mBAAmB,CAAA;AAC/C,OAAO,EAA0B,MAAM,aAAa,CAAA;AACpD,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAA;AAW5C,MAAM,CAAC,KAAK,UAAU,cAAc,CAAE,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,iBAAiB,EAAE,GAAG,EAAE,kBAAkB,GAAG,0BAA0B,EAAyB;IAC7J,IAAI,WAA+B,CAAA;IAEnC,IAAI,iBAAiB,IAAI,IAAI,EAAE,CAAC;QAC9B,IAAI,CAAC;YACH,IAAI,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,IAAI,EAAE,CAAA;YAC5C,QAAQ,GAAG,QAAQ,KAAK,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,QAAQ,CAAA;YACjD,MAAM,MAAM,GAAG,iBAAiB,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;YAEjD,IAAI,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC;gBACtB,MAAM,MAAM,GAAG,MAAM,MAAM,CAAA;gBAE3B,IAAI,MAAM,IAAI,IAAI,EAAE,CAAC;oBACnB,WAAW,GAAG,MAAM,CAAA;gBACtB,CAAC;YACH,CAAC;iBAAM,IAAI,MAAM,IAAI,IAAI,EAAE,CAAC;gBAC1B,WAAW,GAAG,MAAM,CAAA;YACtB,CAAC;YACD,GAAG,CAAC,KAAK,CAAC,+BAA+B,EAAE,WAAW,CAAC,CAAA;QACzD,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,GAAG,CAAC,KAAK,CAAC,4BAA4B,EAAE,GAAG,CAAC,CAAA;QAC9C,CAAC;IACH,CAAC;IACD,GAAG,CAAC,KAAK,CAAC,8BAA8B,EAAE,WAAW,IAAI,kBAAkB,CAAC,CAAA;IAC5E,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE,WAAW,IAAI,kBAAkB,CAAC,CAAA;AACzE,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@helia/verified-fetch",
3
- "version": "2.5.3",
3
+ "version": "2.5.4",
4
4
  "description": "A fetch-like API for obtaining verified & trustless IPFS content on the web",
5
5
  "license": "Apache-2.0 OR MIT",
6
6
  "homepage": "https://github.com/ipfs/helia-verified-fetch/tree/main/packages/verified-fetch#readme",
@@ -29,6 +29,7 @@ export async function setContentType ({ bytes, path, response, contentTypeParser
29
29
  } else if (parsed != null) {
30
30
  contentType = parsed
31
31
  }
32
+ log.trace('contentTypeParser returned %s', contentType)
32
33
  } catch (err) {
33
34
  log.error('error parsing content type', err)
34
35
  }