@helia/verified-fetch 5.0.0 → 5.0.2
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 +3 -3
- package/dist/index.min.js.map +3 -3
- package/dist/src/plugins/plugin-handle-ipns-record.js +2 -2
- package/dist/src/plugins/plugin-handle-ipns-record.js.map +1 -1
- package/dist/src/url-resolver.js +2 -2
- package/dist/src/url-resolver.js.map +1 -1
- package/dist/src/utils/get-e-tag.d.ts +4 -7
- package/dist/src/utils/get-e-tag.d.ts.map +1 -1
- package/dist/src/utils/get-e-tag.js +9 -3
- package/dist/src/utils/get-e-tag.js.map +1 -1
- package/dist/src/verified-fetch.d.ts.map +1 -1
- package/dist/src/verified-fetch.js +2 -1
- package/dist/src/verified-fetch.js.map +1 -1
- package/package.json +1 -1
- package/src/plugins/plugin-handle-ipns-record.ts +2 -2
- package/src/url-resolver.ts +2 -2
- package/src/utils/get-e-tag.ts +13 -10
- package/src/verified-fetch.ts +2 -1
package/dist/index.min.js
CHANGED
|
@@ -110,13 +110,13 @@ a=ice-pwd:`+e+t)}catch{}return r}var tS=D("libp2p-webrtc-noise:");function $B(r,
|
|
|
110
110
|
`)}var V5=class{log;metrics;components;init;certificate;privateKey;emitter;renewCertificateTask;constructor(e,t={}){if(this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,this.emitter=new _e,t.certificateLifespan!=null&&t.certificateRenewalThreshold!=null&&t.certificateRenewalThreshold>=t.certificateLifespan)throw new O("Certificate renewal threshold must be less than certificate lifespan");e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[ma]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Ve]=["@libp2p/transport"];async start(){this.certificate=await this.getCertificate()}async stop(){this.renewCertificateTask!=null&&clearTimeout(this.renewCertificateTask),this.certificate=void 0}async dial(e,t){this.log("dial %a",e),t.signal.throwIfAborted();let n,o=e.getComponents().findLast(c=>c.code===421)?.value;o!=null&&(n=ze(o));let i=JD(),{peerConnection:s,muxerFactory:a}=await KB("client",i,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},dataChannel:this.init.dataChannel});try{return await HB(s,a,i,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:t.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:t.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(c){throw s.close(),c}}createListener(e){if(this.certificate==null)throw new Wn;return new K5(this.components,{...this.init,...e,certificate:this.certificate,emitter:this.emitter})}listenFilter(e){return e.filter(Hp.exactMatch)}dialFilter(e){return this.listenFilter(e)}async getCertificate(e){if(kQ(this.init.certificate))return this.log("using provided TLS certificate"),this.init.certificate;let t=await this.loadOrCreatePrivateKey(),{pem:n,certhash:o}=await this.loadOrCreateCertificate(t,e);return{privateKey:await VB(t),pem:n,certhash:o}}async loadOrCreatePrivateKey(){if(this.privateKey!=null)return this.privateKey;let e=this.init.certificateKeychainName??zD,t=this.getKeychain();try{if(t==null)throw this.log("no keychain configured - not checking for stored private key"),new Ye;this.log.trace("checking for stored private key"),this.privateKey=await t.exportKey(e)}catch(n){if(n.name!=="NotFoundError")throw n;this.log.trace("generating private key"),this.privateKey=await df("ECDSA","P-256"),t!=null?(this.log.trace("storing private key"),await t.importKey(e,this.privateKey)):this.log("no keychain configured - not storing private key")}return this.privateKey}async loadOrCreateCertificate(e,t){if(this.certificate!=null&&t!==!0)return this.certificate;let n,o=new ot(this.init.certificateDatastoreKey??qD),i=await gg(e);try{if(t===!0)throw this.log.trace("forcing renewal of TLS certificate"),new Ye;this.log.trace("checking for stored TLS certificate"),n=await this.loadCertificate(o,i)}catch(a){if(a.name!=="NotFoundError")throw a;this.log.trace("generating new TLS certificate"),n=await this.createCertificate(o,i)}let s=n.notAfter.getTime()-(this.init.certificateRenewalThreshold??iv)-Date.now();return s<0&&(s=100),this.log("will renew TLS certificate after %d ms",s),this.renewCertificateTask=setTimeout(()=>{this.log("renewing TLS certificate"),this.getCertificate(!0).then(a=>{this.certificate=a,this.emitter.safeDispatchEvent("certificate:renew",{detail:a})}).catch(a=>{this.log.error("could not renew certificate - %e",a)})},s),{pem:n.toString("pem"),certhash:Lc.encode((await At.digest(new Uint8Array(n.rawData))).bytes)}}async loadCertificate(e,t){let n=await this.components.datastore.get(e),o=new nh(n),i=o.notAfter.getTime()-(this.init.certificateRenewalThreshold??iv);if(Date.now()>i)throw this.log("stored TLS certificate has expired"),new Ye;this.log("loaded certificate, expires in %d ms",i);let s=await o.publicKey.export(crypto),a=await crypto.subtle.exportKey("raw",s),c=await crypto.subtle.exportKey("raw",t.publicKey);if(!me(new Uint8Array(a,0,a.byteLength),new Uint8Array(c,0,c.byteLength)))throw this.log("stored TLS certificate public key did not match public key from private key"),new Ye;return this.log("loaded certificate, expiry time is %o",i),o}async createCertificate(e,t){let n=new Date,o=new Date(Date.now()+(this.init.certificateLifespan??jD));n.setMilliseconds(0),o.setMilliseconds(0);let i=await H5.createSelfSigned({serialNumber:(BigInt(Math.random().toString().replace(".",""))*100000n).toString(16),name:"CN=example.com, C=US, L=CA, O=example, ST=CA",notBefore:n,notAfter:o,keys:t,extensions:[new eh(!1,void 0,!0)]},crypto);return this.getKeychain()!=null?(this.log.trace("storing TLS certificate"),await this.components.datastore.put(e,D(i.toString("pem")))):this.log("no keychain is configured so not storing TLS certificate since the private key will not be reused"),i}getKeychain(){try{return this.components.keychain}catch{}}};function kQ(r){return r==null?!1:typeof r.privateKey=="string"&&typeof r.pem=="string"&&typeof r.certhash=="string"}function q5(r){return e=>new V5(e,r)}function qB(r){return e=>new M6(e,r)}function zB(){throw new Error("WebSocket Servers can not be created in the browser!")}var PQ=1024*1024*4,RQ=10,rS=class extends Ia{websocket;maxBufferedAmount;checkBufferedAmountTask;constructor(e){super(e),this.websocket=e.websocket,this.maxBufferedAmount=e.maxBufferedAmount??PQ,this.checkBufferedAmountTask=Rf(this.checkBufferedAmount.bind(this),e.bufferedAmountPollInterval??RQ),this.websocket.addEventListener("close",t=>{if(this.log('closed - code %d, reason "%s", wasClean %s',t.code,t.reason,t.wasClean),this.checkBufferedAmountTask.stop(),!t.wasClean){this.onRemoteReset();return}this.onTransportClosed()},{once:!0}),this.websocket.addEventListener("message",t=>{try{let n;if(typeof t.data=="string")n=D(t.data);else if(t.data instanceof ArrayBuffer)n=new Uint8Array(t.data,0,t.data.byteLength);else{this.abort(new Error("Incorrect binary type"));return}this.onData(n)}catch(n){this.log.error("error receiving data - %e",n)}})}sendData(e){for(let n of e)this.websocket.send(n);let t=this.websocket.bufferedAmount<this.maxBufferedAmount;return t||this.checkBufferedAmountTask.start(),{sentBytes:e.byteLength,canSendMore:t}}sendReset(){this.websocket.close(1006)}async sendClose(e){this.websocket.close(),e?.signal?.throwIfAborted()}sendPause(){}sendResume(){}checkBufferedAmount(){this.log("buffered amount now %d",this.websocket.bufferedAmount),this.websocket.bufferedAmount===0&&(this.checkBufferedAmountTask.stop(),this.safeDispatchEvent("drain"))}};function jB(r){return new rS(r)}var nS=class{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[ma]=!0;[Symbol.toStringTag]="@libp2p/websockets";[Ve]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=jB({websocket:await this._connect(e,t),remoteAddr:e,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:websockets:connection"),maxBufferedAmount:this.init.maxBufferedAmount,bufferedAmountPollInterval:this.init.bufferedAmountPollInterval});this.log("new outbound connection %s",n.remoteAddr);let o=await t.upgrader.upgradeOutbound(n,t);return this.log("outbound connection %s upgraded",n.remoteAddr),o}async _connect(e,t){t?.signal?.throwIfAborted();let n=$a(e);this.log("create websocket connection to %s",n);let o=new WebSocket(n);o.binaryType="arraybuffer";try{t.onProgress?.(new Y("websockets:open-connection")),await Ze(o,"open",t)}catch(i){if(t.signal?.aborted)throw this.metrics?.dialerEvents.increment({abort:!0}),new Mu(`Could not connect to ${n}`);this.metrics?.dialerEvents.increment({error:!0});try{o.close()}catch{}throw i}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),o}createListener(e){return zB({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e.filter(t=>Ms.exactMatch(t)||bl.exactMatch(t))}dialFilter(e){return this.listenFilter(e)}};function z5(r={}){return e=>new nS(e,r)}var oS=gt(Ey(),1);function j5(r,e){let t=e.map((n,o)=>({record:so(n),index:o}));return t.sort((n,o)=>{let i=n.record.sequence,s=o.record.sequence;if(i>s)return-1;if(i<s)return 1;if(n.record.validityType===Tn.ValidityType.EOL&&o.record.validityType===Tn.ValidityType.EOL){let a=oS.default.fromString(n.record.validity).toDate(),c=oS.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var WB="6.0.14",GB="helia";var XB={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dnsaddr/va1.bootstrap.libp2p.io/p2p/12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function m0(r={}){let e=`${GB}/${WB} ${A3()}`;return{privateKey:r.privateKey,dns:r.dns,nodeInfo:{userAgent:e},addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[tO(),qB(),q5(),z5()],connectionEncrypters:[t4()],streamMuxers:[FR(),DD()],peerDiscovery:[qR(XB)],services:{autoNAT:VR(),dcutr:oO(),delegatedRouting:()=>wk("https://delegated-ipfs.dev",p9()),dht:ID({clientMode:!0,validators:{ipns:Sl},selectors:{ipns:j5}}),identify:XO(),identifyPush:YO(),keychain:G3(r.keychain),ping:UD(),http:VO()}}}async function YB(r){let e=r.libp2p??{};e.privateKey==null&&r.datastore!=null&&(e.privateKey=await eb(r.datastore,r.keychain));let t=m0(e);return t.datastore=t.datastore??r.datastore,await _3({...t,...e,start:!1})}async function QB(r={}){let e=r.datastore??new Al,t=r.blockstore??new Xp,n;return uP(r.libp2p)?n=r.libp2p:n=await YB({...r,libp2p:{dns:r.dns,...r.libp2p,start:void 0},datastore:e}),{...r,libp2p:n,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[Vp(),Fp()],routers:r.routers??[Gp(n),Wp()],metrics:n.metrics}}async function ZB(r={}){let e=await QB(r),t=new ay(e);return e.start!==!1&&await t.start(),t}function JB(){let r=m0();r.start=!1,r.addresses={listen:[]},r.transports=[q5(),z5()],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 oh=class extends Map{#t=0;#e=new Map;#r=new Map;#s;#c;#a;constructor(e={}){if(super(),!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if(typeof e.maxAge=="number"&&e.maxAge===0)throw new TypeError("`maxAge` must be a number greater than 0");this.#s=e.maxSize,this.#c=e.maxAge||Number.POSITIVE_INFINITY,this.#a=e.onEviction}get __oldCache(){return this.#r}#l(e){if(typeof this.#a=="function")for(let[t,n]of e)this.#a(t,n.value)}#n(e,t){return typeof t.expiry=="number"&&t.expiry<=Date.now()?(typeof this.#a=="function"&&this.#a(e,t.value),this.delete(e)):!1}#d(e,t){if(this.#n(e,t)===!1)return t.value}#u(e,t){return t.expiry?this.#d(e,t):t.value}#f(e,t){let n=t.get(e);return this.#u(e,n)}#o(e,t){this.#e.set(e,t),this.#t++,this.#t>=this.#s&&(this.#t=0,this.#l(this.#r),this.#r=this.#e,this.#e=new Map)}#h(e,t){this.#r.delete(e),this.#o(e,t)}*#i(){for(let e of this.#r){let[t,n]=e;this.#e.has(t)||this.#n(t,n)===!1&&(yield e)}for(let e of this.#e){let[t,n]=e;this.#n(t,n)===!1&&(yield e)}}get(e){if(this.#e.has(e)){let t=this.#e.get(e);return this.#u(e,t)}if(this.#r.has(e)){let t=this.#r.get(e);if(this.#n(e,t)===!1)return this.#h(e,t),t.value}}set(e,t,{maxAge:n=this.#c}={}){let o=typeof n=="number"&&n!==Number.POSITIVE_INFINITY?Date.now()+n:void 0;return this.#e.has(e)?this.#e.set(e,{value:t,expiry:o}):this.#o(e,{value:t,expiry:o}),this}has(e){return this.#e.has(e)?!this.#n(e,this.#e.get(e)):this.#r.has(e)?!this.#n(e,this.#r.get(e)):!1}peek(e){if(this.#e.has(e))return this.#f(e,this.#e);if(this.#r.has(e))return this.#f(e,this.#r)}expiresIn(e){let t=this.#e.get(e)??this.#r.get(e);if(t)return t.expiry?t.expiry-Date.now():Number.POSITIVE_INFINITY}delete(e){let t=this.#e.delete(e);return t&&this.#t--,this.#r.delete(e)||t}clear(){this.#e.clear(),this.#r.clear(),this.#t=0}resize(e){if(!(e&&e>0))throw new TypeError("`maxSize` must be a number greater than 0");let t=[...this.#i()],n=t.length-e;n<0?(this.#e=new Map(t),this.#r=new Map,this.#t=t.length):(n>0&&this.#l(t.slice(0,n)),this.#r=new Map(t.slice(n)),this.#e=new Map,this.#t=0),this.#s=e}evict(e=1){let t=Number(e);if(!t||t<=0)return;let n=[...this.#i()],o=Math.trunc(Math.min(t,Math.max(n.length-1,0)));o<=0||(this.#l(n.slice(0,o)),this.#r=new Map(n.slice(o)),this.#e=new Map,this.#t=0)}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let e of this.#e){let[t,n]=e;this.#n(t,n)===!1&&(yield[t,n.value])}for(let e of this.#r){let[t,n]=e;this.#e.has(t)||this.#n(t,n)===!1&&(yield[t,n.value])}}*entriesDescending(){let e=[...this.#e];for(let t=e.length-1;t>=0;--t){let n=e[t],[o,i]=n;this.#n(o,i)===!1&&(yield[o,i.value])}e=[...this.#r];for(let t=e.length-1;t>=0;--t){let n=e[t],[o,i]=n;this.#e.has(o)||this.#n(o,i)===!1&&(yield[o,i.value])}}*entriesAscending(){for(let[e,t]of this.#i())yield[e,t.value]}get size(){if(!this.#t)return this.#r.size;let e=0;for(let t of this.#r.keys())this.#e.has(t)||e++;return Math.min(this.#t+e,this.#s)}get maxSize(){return this.#s}get maxAge(){return this.#c}entries(){return this.entriesAscending()}forEach(e,t=this){for(let[n,o]of this.entriesAscending())e.call(t,o,n,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}};var W5=class extends Error{static name="DNSLinkNotFoundError";constructor(e="DNSLink not found"){super(e),this.name="DNSLinkNotFoundError"}},ih=class extends Error{static name="InvalidNamespaceError";constructor(e="Invalid namespace"){super(e),this.name="InvalidNamespaceError"}};var eM=(r,e)=>{let[,t,n,...o]=r.split("/");if(t!=="ipfs")throw new ih(`Namespace ${t} was not "ipfs"`);return{namespace:"ipfs",cid:Z.parse(n),path:o.length>0?`/${o.join("/")}`:"",answer:e}};var tM=(r,e)=>{let[,t,n,...o]=r.split("/");if(t!=="ipns")throw new ih(`Namespace ${t} was not "ipns"`);try{return{namespace:"ipns",peerId:ze(n),path:o.length>0?`/${o.join("/")}`:"",answer:e}}catch{return{namespace:"dnslink",value:n,path:o.length>0?`/${o.join("/")}`:"",answer:e}}};var G5=class{dns;log;namespaces;cache;cacheMaxAnswers;constructor(e,t={}){this.dns=e.dns,this.log=e.logger.forComponent("helia:dnslink"),this.namespaces={ipfs:eM,ipns:tM,...t.namespaces},this.cache=new oh({maxSize:t.cacheSize??1e3,maxAge:t.cacheMaxAge??3e4}),this.cacheMaxAnswers=t.cacheMaxAnswers??10}async resolve(e,t={}){if(t.nocache!==!0){let s=this.cache.get(e);if(s!=null){let a=[...s.values()];if(a.length>0)return a}}let n=await this.recursiveResolveDomain(e,t.maxRecursiveDepth??dI,t),o=new oh({maxSize:this.cacheMaxAnswers});n.forEach((s,a)=>{o.set(a,s,{maxAge:s.answer.TTL*1e3})});let i=n.reduce((s,a)=>{let c=a.answer.TTL*1e3;return c>s?c:s},0);return this.cache.maxAge<i&&(i=this.cache.maxAge),this.cache.set(e,o,{maxAge:i}),n}async recursiveResolveDomain(e,t,n={}){if(t===0)throw new Error("recursion limit exceeded");e.startsWith("_dnslink.")||(e=`_dnslink.${e}`);try{return await this.recursiveResolveDnslink(e,t,n)}catch(o){if(o.code!=="ENOTFOUND"&&o.code!=="ENODATA"&&o.name!=="DNSLinkNotFoundError"&&o.name!=="NotFoundError")throw o;return e.startsWith("_dnslink.")?e=e.replace("_dnslink.",""):e=`_dnslink.${e}`,this.recursiveResolveDnslink(e,t,n)}}async recursiveResolveDnslink(e,t,n={}){if(t===0)throw new Error("recursion limit exceeded");this.log("query %s for TXT and CNAME records",e);let i=((await this.dns.query(e,{...n,types:[Zr.TXT]}))?.Answer??[]).sort((l,f)=>l.data.localeCompare(f.data));this.log("found %d TXT records for %s",i.length,e);let s=[];for(let l of i)try{let f=l.data;if(f.startsWith('"')&&f.endsWith('"')&&(f=f.substring(1,f.length-1)),!f.startsWith("dnslink="))continue;this.log("%s TXT %s",l.name,f),f=f.replace("dnslink=","");let[,u,h]=f.split("/");if(u==="dnslink"){s.push(...await this.recursiveResolveDomain(h,t-1,n));continue}let d=this.namespaces[u];if(d==null){this.log('unknown protocol "%s" in DNSLink record for domain: %s',u,e);continue}let m=d(f,l);if(m.namespace==="dnslink"){s.push(...await this.recursiveResolveDomain(m.value,t-1,n));continue}s.push(d(f,l))}catch(f){this.log.error("could not parse DNS link record for domain %s, %s - %e",e,l.data,f)}if(s.length>0)return s;this.log("no DNSLink records found for %s, falling back to CNAME",e);let c=((await this.dns.query(e,{...n,types:[Zr.CNAME]}))?.Answer??[]).sort((l,f)=>l.data.localeCompare(f.data));this.log("found %d CNAME records for %s",c.length,e);for(let l of c)try{return await this.recursiveResolveDomain(l.data,t-1,n)}catch(f){this.log.error("domain %s cname %s had no DNSLink records - %e",e,l.data,f)}throw new W5(`No DNSLink records found for domain: ${e}`)}};function rM(r,e={}){return new G5(r,e)}var nM=BigInt(6e4)*5000000n;var X5=class extends Error{static name="RecordsFailedValidationError";constructor(e="Records failed validation"){super(e),this.name="RecordsFailedValidationError"}},Y5=class extends Error{static name="UnsupportedMultibasePrefixError";constructor(e="Unsupported multibase prefix"){super(e),this.name="UnsupportedMultibasePrefixError"}},Q5=class extends Error{static name="UnsupportedMultihashCodecError";constructor(e="Unsupported multihash codec"){super(e),this.name="UnsupportedMultihashCodecError"}},Z5=class extends Error{static name="InvalidValueError";constructor(e="Invalid value"){super(e),this.name="InvalidValueError"}};var g0=class extends Error{static name="RecordNotFoundError";name="RecordNotFoundError"};var OQ=114,iS=0,sS=18;function aS(r,e){return r.code===e}var J5="/dht/record/",DQ="/ipns/metadata/";function y0(r){return new ot(J5+H(r,"base32"),!1)}function e8(r){return new ot(DQ+H(r,"base32"),!1)}function NQ(r){return r?.asCID===r}function oM(r){if(!NQ(r))return!1;if(r.code!==OQ)throw new O(`CID codec ${r.code} was not libp2p-key`);if(r.multihash.code!==iS&&r.multihash.code!==sS)throw new O(`Multihash algorithm codec ${r.multihash.code} was not Identity or SHA256 hash`);return!0}var iM={[rn.prefix]:rn,[Qe.prefix]:Qe},t8=class{routers;localStore;log;constructor(e,t){this.log=e.logger.forComponent("helia:ipns"),this.localStore=t.localStore,this.routers=t.routers}async resolve(e,t={}){let n=XS(e)||Vr(e)?e.toMultihash():oM(e)?e.multihash:e,o=El(n),i=await this.#e(o,t);return{...await this.#t(i.value,t),record:i}}async#t(e,t={}){let n=e.split("/");try{let o=n[1];if(o==="ipns"){let i=n[2],s=i.substring(0,1),a;if(s==="1"||s==="Q")a=Qe.decode(`z${i}`);else if(iM[s]!=null)a=iM[s].decode(i);else throw new Y5(`Unsupported multibase prefix "${s}"`);let c;try{c=qe(a)}catch{c=Z.decode(a).multihash}if(!aS(c,iS)&&!aS(c,sS))throw new Q5(`Unsupported multihash codec "${c.code}"`);let{cid:l}=await this.resolve(c,t),f=n.slice(3).join("/");return{cid:l,path:f===""?void 0:f}}else if(o==="ipfs"){let i=Z.parse(n[2]),s=n.slice(3).join("/");return{cid:i,path:s===""?void 0:s}}}catch(o){this.log.error("error parsing ipfs path - %e",o)}throw this.log.error("invalid ipfs path %s",e),new Z5("Invalid value")}async#e(e,t={}){let n=[];if(await this.localStore.has(e,t))if(this.log("record is present in the cache"),t.nocache!==!0)try{let{record:c,created:l}=await this.localStore.get(e,t);this.log("record retrieved from cache"),await Sl(e,c),this.log("record was valid");let f=so(c),u=Number((f.ttl??nM)/1000000n);if(l.getTime()+u>Date.now())return this.log("record TTL was valid"),f;if(t.offline===!0)return this.log("record TTL has been reached but we are resolving offline-only, returning record"),f;this.log("record TTL has been reached, searching routing for updates"),n.push(c)}catch(c){this.log("cached record was invalid - %e",c),await this.localStore.delete(e,t)}else this.log("ignoring local cache due to nocache=true option");if(t.offline===!0)throw new g0("Record was not present in the cache or has expired");this.log("did not have record locally");let i=0,s=[];if(await Promise.all(this.routers.map(async c=>{let l;try{l=await c.get(e,{...t,validate:!1})}catch(f){this.log.error("error finding IPNS record using router %s - %e",c.toString(),f),s.push(f);return}try{await Sl(e,l),n.push(l)}catch(f){i++,this.log.error("error validating IPNS record from router %s - %e",c.toString(),f)}})),n.length===0)throw i>0?new X5(`${i>1?`${i} records`:"Record"} found for routing key ${i>1?"were":"was"} invalid`):new g0("Could not find record for routing key");let a=n[j5(e,n)];return await this.localStore.put(e,a,t),so(a)}};var w0;(function(r){let e;r.codec=()=>(e==null&&(e=ve((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.keyName!=null&&t.keyName!==""&&(n.uint32(10),n.string(t.keyName)),t.lifetime!=null&&t.lifetime!==0&&(n.uint32(16),n.uint32(t.lifetime)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={keyName:"",lifetime:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.keyName=t.string();break}case 2:{i.lifetime=t.uint32();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>xe(t,r.codec(),n)})(w0||(w0={}));function sM(r,e){return{async put(t,n,o={}){try{let i=y0(t);try{let c=await r.get(i),l=Bt.deserialize(c);if(me(l.value,n))return}catch(c){if(c.name!=="NotFoundError")throw c}let s=new Bt(t,n,new Date);o.onProgress?.(new Y("ipns:routing:datastore:put"));let a=r.batch();a.put(i,s.serialize()),o.metadata!=null&&a.put(e8(t),w0.encode(o.metadata)),await a.commit(o)}catch(i){throw o.onProgress?.(new Y("ipns:routing:datastore:error",i)),i}},async get(t,n={}){try{let o=y0(t);n.onProgress?.(new Y("ipns:routing:datastore:get"));let i=await r.get(o,n),s=Bt.deserialize(i);return{record:s.value,created:s.timeReceived}}catch(o){throw n.onProgress?.(new Y("ipns:routing:datastore:error",o)),o}},async has(t,n={}){let o=y0(t);return r.has(o,n)},async delete(t,n){let o=y0(t),i=r.batch();i.delete(o),i.delete(e8(t)),await i.commit(n)},async*list(t={}){try{t.onProgress?.(new Y("ipns:routing:datastore:list"));for await(let{key:n,value:o}of r.query({prefix:J5},t))try{let i=Bt.deserialize(o),a=n.toString().substring(J5.length),c=D(a,"base32"),l=e8(c),f;try{let u=await r.get(l,t);f=w0.decode(u)}catch(u){e.error("Error deserializing metadata for %s - %e",a,u)}yield{routingKey:c,metadata:f,record:i.value,created:i.timeReceived}}catch(i){e.error("Error deserializing record - %e",i)}}catch(n){throw t.onProgress?.(new Y("ipns:routing:datastore:error",n)),n}}}}var cS=class{routing;constructor(e){this.routing=e}async put(e,t,n={}){try{await this.routing.put(e,t,n)}catch(o){throw n.onProgress?.(new Y("ipns:routing:helia:error",o)),o}}async get(e,t={}){try{return await this.routing.get(e,t)}catch(n){throw t.onProgress?.(new Y("ipns:routing:helia:error",n)),n}}toString(){return"HeliaRouting()"}};function lS(r){return new cS(r)}var uS=class{localStore;constructor(e){this.localStore=e}async put(e,t,n){await this.localStore.put(e,t,n)}async get(e,t){let{record:n}=await this.localStore.get(e,t);return n}toString(){return"LocalStoreRouting()"}};function aM(r){return new uS(r)}function cM(r,e={}){let t=sM(r.datastore,r.logger.forComponent("helia:ipns:local-store")),n=[aM(t),lS(r.routing),...e.routers??[]];return new t8(r,{routers:n,localStore:t})}var hS=gt(r8(),1);var pS=40;function mS(r,e){if(!r.length)throw new Error("Unexpected end of data");let t=hS.default.decode(r);return e.seek(hS.default.decode.bytes),t}function gS(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 Tc={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},x0={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":Tc.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(Tc.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=x0["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=x0["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:Tc.Int,CarV1HeaderOrV2Pragma:r=>{if(Tc.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=x0["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=x0.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}},b0={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":Tc.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(Tc.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=b0["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=b0["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:Tc.Int,CarV1HeaderOrV2Pragma:r=>{if(Tc.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=b0["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=b0.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}},yS={toTyped:x0.CarV1HeaderOrV2Pragma,toRepresentation:b0.CarV1HeaderOrV2Pragma};var nQe=sx();var QQ=gt(r8(),1);var cQe=[new j(A.map,2),new j(A.string,"version"),new j(A.uint,1),new j(A.string,"roots")],lQe=new j(A.tag,42);async function wS(r,e){let t=mS(await r.upTo(8),r);if(t===0)throw new Error("Invalid CAR header (zero length)");let n=await r.exactly(t,!0),o=ci(n);if(yS.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=gS(await r.exactly(pS,!0));r.seek(i.dataOffset-r.pos);let s=await wS(r,1);return Object.assign(s,i)}function v0(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 xS=gt(r8(),1),bM=1;function bS(r){let e=hn({version:bM,roots:r}),t=xS.default.encode(e.length),n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function vM(r){return{async setRoots(e){let t=bS(e);await r.write(t)},async writeBlock(e){let{cid:t,bytes:n}=e;await r.write(new Uint8Array(xS.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 bM}}}function n8(){}function EM(){let r=[],e=null,t=n8,n=!1,o=null,i=n8,s=()=>(e||(e=new Promise(l=>{t=()=>{e=null,t=n8,l()}})),e),a={write(l){r.push(l);let f=s();return i(),f},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(f=>{i=()=>(o=null,i=n8,f(c.next()))})),o)}};return{writer:a,iterator:c}}var E0=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=Z.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=tZ(e);let{encoder:t,iterator:n}=SM(),o=new r(e,t),i=new o8(n);return{writer:o,out:i}}static createAppender(){let{encoder:e,iterator:t}=SM();e.setRoots=()=>Promise.resolve();let n=new r([],e),o=new o8(t);return{writer:n,out:o}}static async updateRootsInBytes(e,t){let n=v0(e);await wS(n);let o=bS(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}},o8=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 SM(){let r=EM(),{writer:e,iterator:t}=r;return{encoder:vM(e),iterator:t}}function tZ(r){if(r===void 0)return[];if(!Array.isArray(r)){let t=Z.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=Z.asCID(t);if(!n)throw new TypeError("roots must be a single CID or an array of CIDs");e.push(n)}return e}var sh=class{walker;constructor(e){this.walker=e?.walker}async*export(e,t,n,o){let i,s={blockstore:t,getCodec:n};this.walker!=null?i=this.walker(s):i=iy()(s);for await(let a of i.walk(e,o))yield a.block}};var i8=class{components;log;constructor(e){this.components=e,this.log=e.logger.forComponent("helia:car")}async import(e,t){await Xr(this.components.blockstore.putMany(Kt(e.blocks(),({cid:n,bytes:o})=>({cid:n,bytes:o})),t))}async*export(e,t){let n=Array.isArray(e)?e:[e],{writer:o,out:i}=E0.create(n),s=i[Symbol.asyncIterator](),a=new AbortController;for(this._export(n,o,t).catch(c=>{this.log.error("error during streaming export - %e",c),a.abort(c)});;){let{done:c,value:l}=await nt(s.next(),a.signal);if(a.signal.aborted)throw a.signal.reason;if(l!=null&&(yield l),c===!0)break}}async _export(e,t,n){let o=n?.traversal;for(let i of e){if(i.multihash.code===0)continue;let s=n?.exporter??(i.code===112?new ah:new sh),a=i,c=!1;if(o!=null){for await(let{cid:l,bytes:f}of o.traverse(a,this.components.blockstore,this.components.getCodec,n))if(this.log.trace("next CID on path to %c is %c",i,l),a=l,i.equals(l)&&(c=!0),c||n?.includeTraversalBlocks===!0){if(n?.blockFilter?.has(l.multihash.bytes)===!0)continue;n?.blockFilter?.add(l.multihash.bytes),await t.put({cid:l,bytes:f})}}for await(let{cid:l,bytes:f}of s.export(a,this.components.blockstore,this.components.getCodec,n))n?.blockFilter?.has(l.multihash.bytes)!==!0&&l.multihash.code!==0&&(c&&l.equals(a)||(n?.blockFilter?.add(l.multihash.bytes),await t.put({cid:l,bytes:f})))}await t.close()}};var S0=class{async*export(e,t,n,o){let i=await Ge(t.get(e,o));yield Ma({cid:e,bytes:i,codec:await n(e.code)})}};var A0=class r extends Error{static name="InvalidTypeError";static code="ERR_INVALID_TYPE";name=r.name;code=r.code;constructor(e="Invalid type"){super(e)}},s8=class r extends Error{static name="InvalidUnixFSMessageError";static code="ERR_INVALID_MESSAGE";name=r.name;code=r.code;constructor(e="Invalid message"){super(e)}};var Ai;(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=()=>wt(t)})(e=r.DataType||(r.DataType={}));let n;r.codec=()=>(n==null&&(n=ve((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),a8.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=a8.codec().decode(o,o.uint32());break;default:o.skipType(c&7);break}}return s})),n),r.encode=o=>be(o,r.codec()),r.decode=o=>xe(o,r.codec())})(Ai||(Ai={}));var a8;(function(r){let e;r.codec=()=>(e==null&&(e=ve((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=>be(t,r.codec()),r.decode=t=>xe(t,r.codec())})(a8||(a8={}));var _M;(function(r){let e;r.codec=()=>(e==null&&(e=ve((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=>be(t,r.codec()),r.decode=t=>xe(t,r.codec())})(_M||(_M={}));var TM={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},nZ=["directory","hamt-sharded-directory"],CM=parseInt("0644",8),IM=parseInt("0755",8),kM=BigInt(1024),$n=class r{static unmarshal(e){let t=Ai.decode(e);if(t.fanout!=null&&t.fanout>kM)throw new s8(`Fanout size was too large - ${t.fanout} > ${kM}`);let n=new r({type:TM[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(TM).includes(t))throw new A0("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()?IM:CM:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return nZ.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=Ai.DataType.Raw;break;case"directory":e=Ai.DataType.Directory;break;case"file":e=Ai.DataType.File;break;case"metadata":e=Ai.DataType.Metadata;break;case"symlink":e=Ai.DataType.Symlink;break;case"hamt-sharded-directory":e=Ai.DataType.HAMTShard;break;default:throw new A0(`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===CM&&!this.isDirectory()&&(n=void 0),n===IM&&this.isDirectory()&&(n=void 0));let o;return this.mtime!=null&&(o={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),Ai.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 _0=class extends Error{static code="ERR_NOT_UNIXFS";static message="Not a UnixFS node";static name="NotUnixFSError";code="ERR_NOT_UNIXFS";message="Not a UnixFS node";name="NotUnixFSError"},c8=class extends Error{static name="NotDescendantError";name="NotDescendantError"},l8=class extends Error{static name="InvalidTraversalError";name="InvalidTraversalError"};function iZ(r){return r.cid.code===85}function sZ(r){return r.cid.code===112}function aZ(r){if(iZ(r))return!0;if(sZ(r)&&r.value.Data!=null){let e=$n.unmarshal(r.value.Data);return e.type==="file"||e.type==="raw"}else throw new _0("Encountered non raw/dag-pb CID in UnixFS DAG")}var ah=class{options;constructor(e){this.options=e}async*export(e,t,n,o){if(e.code!==112&&e.code!==85)throw new _0("Target CID was not UnixFS - use the SubGraphExporter to export arbitrary graphs");let i=$f()({blockstore:t,getCodec:n}),s=this.options?.offset??0,a=this.options?.length??1/0,c=this.options?.listingOnly??!1;if(s<0)throw new O("Offset cannot be negative");if(a<0)throw new O("Length cannot be negative");let l,f=new AbortController,u=Re([f.signal,o?.signal]);f.signal;function h(d,m){if(l==null&&(l=aZ(m)),!l){let F=m.value.Links.find(M=>M.Hash.equals(d)),V=$n.unmarshal(m.value.Data??new Uint8Array);return V.type==="directory"?!c:V.type==="hamt-sharded-directory"&&c?F?.Name?.length===2:!0}let y=m.value.Links.findIndex(F=>F.Hash.equals(d)),w=$n.unmarshal(m.value.Data??new Uint8Array),x=s,E=x+a,v=Number([...w.blockSizes].slice(0,y).reduce((F,V)=>F+V,0n)),I=v+Number(w.blockSizes[y]);return x>=v&&x<I||E>=v&&E<I||x<=v&&E>=I}try{for await(let d of i.walk(e,{...o,includeChild:h,signal:u}))yield d.block}finally{f.abort(),u.clear()}}};var u8=class{path;constructor(e){this.path=e}async*traverse(e,t,n,o){if(!this.path.some(s=>s.equals(e)))throw new l8(`CIDPath traversal must include ${e}`);let i;for(let s of this.path){if(i!=null){let l=!1;for(let[,f]of i.links())if(f.equals(s)){l=!0;break}if(!l)throw new c8(`${s} is not a child of ${i.cid}`)}let a=await Ge(t.get(s,o)),c=Ma({cid:s,bytes:a,codec:await n(s.code)});i=c,yield c}}};function cZ(r){return r[Symbol.asyncIterator]!=null}function lZ(r){if(cZ(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 PM=lZ;var f8=class r extends Error{static name="BadPathError";static code="ERR_BAD_PATH";name=r.name;code=r.code;constructor(e="Bad path"){super(e)}},qo=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not found"){super(e)}},d8=class r extends Error{static name="NoResolverError";static code="ERR_NO_RESOLVER";name=r.name;code=r.code;constructor(e="No resolver"){super(e)}},sr=class r extends Error{static name="NotUnixFSError";static code="ERR_NOT_UNIXFS";name=r.name;code=r.code;constructor(e="Not UnixFS"){super(e)}},h8=class r extends Error{static name="OverReadError";static code="ERR_OVER_READ";name=r.name;code=r.code;constructor(e="Over read"){super(e)}},p8=class r extends Error{static name="UnderReadError";static code="ERR_UNDER_READ";name=r.name;code=r.code;constructor(e="Under read"){super(e)}},m8=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)}},ca=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 ch(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 f=Z.asCID(a[l]);if(f!=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:f,name:l,path:c,toResolve:i}};a=a[l]}else throw new m8(`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 uZ=async(r,e,t,n,o,i,s,a)=>{let c=await Ge(s.get(r,a)),l=ci(c);return ch(l,c,r,e,t,n,i)},RM=uZ;var fZ=async(r,e,t,n,o,i,s,a)=>{let c=await Ge(s.get(r,a)),l=gl(c);return ch(l,c,r,e,t,n,i)},OM=fZ;function dZ(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 Cu=dZ;var hZ=(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 ca("Offset must be greater than or equal to 0");if(o>n)throw new ca("Offset must be less than the file size");if(i<0n)throw new ca("Length must be greater than or equal to 0");if(i>n)throw new ca("Length must be less than the file size");return{start:o,end:i}},lh=hZ;var pZ=r=>{async function*e(t={}){let{start:n,end:o}=lh(r.length,t.offset,t.length),i=Cu(r,0n,n,o);t.onProgress?.(new Y("unixfs:exporter:progress:identity",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return e},mZ=async(r,e,t,n,o,i,s,a)=>{if(n.length>0)throw new qo(`No link named ${t} found in raw node ${r}`);let c=qe(r.multihash.bytes);return{entry:{type:"identity",name:e,path:t,cid:r,content:pZ(c.digest),depth:i,size:BigInt(c.digest.length),node:c.digest}}},DM=mZ;var gZ=async(r,e,t,n,o,i,s,a)=>{let c=await Ge(s.get(r,a)),l=zu(c);return ch(l,c,r,e,t,n,i)},NM=gZ;var yZ=r=>{async function*e(t={}){let{start:n,end:o}=lh(r.length,t.offset,t.length),i=Cu(r,0n,n,o);t.onProgress?.(new Y("unixfs:exporter:progress:raw",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return e},wZ=async(r,e,t,n,o,i,s,a)=>{if(n.length>0)throw new qo(`No link named ${t} found in raw node ${r}`);let c=await Ge(s.get(r,a));return{entry:{type:"raw",name:e,path:t,cid:r,content:yZ(c),depth:i,size:BigInt(c.length),node:c}}},LM=wZ;var y8=gt(UM(),1);function xZ(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 QZe=ps({name:"murmur3-32",code:35,encode:r=>xZ(y8.default.x86.hash32(r))}),FM=ps({name:"murmur3-128",code:34,encode:r=>Dc.fromHex(y8.default.x64.hash128(r))}),ZZe=ps({name:"murmur3-x64-64",code:34,encode:r=>Dc.fromHex(y8.default.x64.hash128(r)).subarray(0,8)});var VM=gt(KM(),1);var Iu=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 VM.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 qM(this,e,t)}toJSON(){return this.serialize(AZ,_Z)}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"?D(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(SZ);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 SZ(r){return!!r}function AZ(r,e){return r.key}function _Z(r){return r}async function qM(r,e,t){let n=[];for(let o of r._children.compactArray())if(o instanceof Iu)await qM(o,e,t);else{let i=await e(o);n.push({bitField:r._children.bitField(),children:i})}return t(n)}var TZ=[255,254,252,248,240,224,192,128],CZ=[1,3,7,15,31,63,127,255],w8=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=IZ(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 IZ(r,e,t){let n=kZ(e,t);return(r&n)>>>e}function kZ(r,e){return TZ[r]&CZ[Math.min(e+r-1,7)]}function zM(r){function e(t){return t instanceof x8?t:new x8(t,r)}return e}var x8=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?dt([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new w8(t);this._buffers.push(n),this._availableBits+=n.availableBits()}};function jM(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:zM(r.hashFn)};return new Iu(e)}var PZ=async function(r){return(await FM.encode(r)).slice(0,8).reverse()},RZ=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 Iu({hash:t._options.hash,bits:t._options.bits},e,i));return}await t.put(o.Name.substring(2),!0)}))},WM=(r,e)=>r.toString(16).toUpperCase().padStart(e,"0").substring(0,e),OZ=r=>{let e=r.bucket,t=[];for(;e._parent!=null;)t.push(e),e=e._parent;return t.push(e),t.reverse()},GM=async(r,e,t,n,o)=>{if(n==null){if(r.Data==null)throw new sr("no data in PBNode");let u;try{u=$n.unmarshal(r.Data)}catch(d){throw new sr(d.message)}if(u.type!=="hamt-sharded-directory")throw new sr("not a HAMT");if(u.fanout==null)throw new sr("missing fanout");let h=jM({hashFn:PZ,bits:Math.log2(Number(u.fanout))});n={rootBucket:h,hamtDepth:1,lastBucket:h}}let i=(n.lastBucket.tableSize()-1).toString(16).length;await RZ(r.Links,n.lastBucket,n.rootBucket);let s=await n.rootBucket._findNewBucketAndPos(e),a=WM(s.pos,i),c=OZ(s);c.length>n.hamtDepth&&(n.lastBucket=c[n.hamtDepth],a=WM(n.lastBucket._posAtParent,i));let l=r.Links.find(u=>{if(u.Name==null)return!1;let h=u.Name.substring(0,i),d=u.Name.substring(i);return!(h!==a||d!==""&&d!==e)});if(l==null)return;if(l.Name!=null&&l.Name.substring(i)===e)return l.Hash;n.hamtDepth++;let f=await Ge(t.get(l.Hash,o));return r=_n(f),GM(r,e,t,n,o)},XM=GM;function uh(r){return r?.extended===!1}var DZ=(r,e,t,n,o,i,s)=>{async function*a(c={}){let l=c.offset??0,f=c.length??e.Links.length,u=e.Links.slice(l,f);c.onProgress?.(new Y("unixfs:exporter:walk:directory",{cid:r})),yield*ln(u,h=>Kt(h,d=>async()=>{let m=d.Name??"",y=`${n}/${m}`;return uh(c)?{cid:d.Hash,name:m,path:y}:(await o(d.Hash,m,y,[],i+1,s,c)).entry}),h=>gn(h,{ordered:!0,concurrency:c.blockReadConcurrency}),h=>pn(h,d=>d!=null))}return a},YM=DZ;async function QM(r,e,t,n,o,i,s){if(e instanceof Uint8Array){let l=Cu(e,n,o,i);t.push(l);return}if(e.Data==null)throw new sr("no data in PBNode");let a;try{a=$n.unmarshal(e.Data)}catch(l){throw new sr(l.message)}if(a.data!=null){let l=a.data,f=Cu(l,n,o,i);t.push(f),n+=BigInt(f.byteLength)}let c=[];if(e.Links.length!==a.blockSizes.length)throw new sr("Inconsistent block sizes and dag links");for(let l=0;l<e.Links.length;l++){let f=e.Links[l],u=n,h=u+a.blockSizes[l];if((o>=u&&o<h||i>=u&&i<=h||o<u&&i>h)&&c.push({link:f,blockStart:n}),n=h,n>i)break}await ln(c,l=>Kt(l,f=>async()=>{let u=await Ge(r.get(f.link.Hash,s));return{...f,block:u}}),l=>gn(l,{ordered:!0,concurrency:s.blockReadConcurrency}),async l=>{for await(let{link:f,block:u,blockStart:h}of l){let d;switch(f.Hash.code){case pt:d=_n(u);break;case rt:d=u;break;default:t.end(new sr(`Unsupported codec: ${f.Hash.code}`));return}let m=new Ds({concurrency:1});m.on("error",y=>{t.end(y)}),m.add(async()=>{s.onProgress?.(new Y("unixfs:exporter:walk:file",{cid:f.Hash})),await QM(r,d,t,h,o,i,s)}),await m.onIdle()}}),n>=i&&t.end()}var NZ=(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:f,end:u}=lh(l,c.offset,c.length);if(u===0n)return;let h=0n,d=u-f,m=ur();c.onProgress?.(new Y("unixfs:exporter:walk:file",{cid:r})),QM(s,e,m,0n,f,u,c).catch(y=>{m.end(y)});for await(let y of m)if(y!=null){if(h+=BigInt(y.byteLength),h>d)throw m.end(),new h8("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect");h===d&&m.end(),c.onProgress?.(new Y("unixfs:exporter:progress:unixfs:file",{bytesRead:h,totalBytes:d,fileSize:l})),yield y}if(h<d)throw new p8("Traversed entire DAG but did not read enough bytes")}return a},vS=NZ;var LZ=(r,e,t,n,o,i,s)=>{function a(c={}){return c.onProgress?.(new Y("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),ZM(e,n,o,i,s,c)}return a};async function*ZM(r,e,t,n,o,i){let s=r.Links;if(r.Data==null)throw new sr("no data in PBNode");let a;try{a=$n.unmarshal(r.Data)}catch(f){throw new sr(f.message)}if(a.fanout==null)throw new sr("missing fanout");let c=(a.fanout-1n).toString(16).length,l=ln(s,f=>Kt(f,u=>async()=>{let h=u.Name!=null?u.Name.substring(c):null;if(h!=null&&h!==""){let d=`${e}/${h}`;return uh(i)?{entries:[{cid:u.Hash,name:h,path:d}]}:{entries:[(await t(u.Hash,h,d,[],n+1,o,i)).entry].filter(Boolean)}}else{let d=await Ge(o.get(u.Hash,i));return r=_n(d),i.onProgress?.(new Y("unixfs:exporter:walk:hamt-sharded-directory",{cid:u.Hash})),{entries:ZM(r,e,t,n,o,i)}}}),f=>gn(f,{ordered:!0,concurrency:i.blockReadConcurrency}));for await(let{entries:f}of l)yield*f}var JM=LZ;var BZ=(r,e)=>r.Links.find(n=>n.Name===e)?.Hash,MZ={raw:vS,file:vS,directory:YM,"hamt-sharded-directory":JM,metadata:(r,e,t,n,o,i,s)=>()=>[],symlink:(r,e,t,n,o,i,s)=>()=>[]},UZ=async(r,e,t,n,o,i,s,a)=>{if(uh(a)&&n.length===0)return{entry:{cid:r,name:e,path:t}};let c=await Ge(s.get(r,a)),l;try{l=_n(c)}catch(d){throw new sr(d.message)}let f,u;if(e==null&&(e=r.toString()),l.Data==null)throw new sr("no data in PBNode");try{f=$n.unmarshal(l.Data)}catch(d){throw new sr(d.message)}if(t==null&&(t=e),n.length>0){let d;if(f?.type==="hamt-sharded-directory"?d=await XM(l,n[0],s):d=BZ(l,n[0]),d==null)throw new qo("file does not exist");let m=n.shift(),y=`${t}/${m}`;u={cid:d,toResolve:n,name:m??"",path:y}}let h=MZ[f.type](r,l,f,t,o,i,s);if(h==null)throw new qo("could not find content exporter");return f.isDirectory()?{entry:{type:"directory",name:e,path:t,cid:r,content:h,unixfs:f,depth:i,node:l,size:f.fileSize()},next:u}:{entry:{type:"file",name:e,path:t,cid:r,content:h,unixfs:f,depth:i,node:l,size:f.fileSize()},next:u}},eU=UZ;var FZ={[pt]:eU,[rt]:LM,[fr]:RM,[dr]:OM,[$t.code]:DM,[lr]:NM},tU=async(r,e,t,n,o,i,s)=>{let a=FZ[r.code];if(a==null)throw new d8(`No resolver for code ${r.code}`);return a(r,e,t,n,tU,o,i,s)},rU=tU;var $Z=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),HZ=r=>{if(r instanceof Uint8Array)return{cid:Z.decode(r),toResolve:[]};let e=Z.asCID(r);if(e!=null)return{cid:e,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let t=$Z(r);return{cid:Z.parse(t[0]),toResolve:t.slice(1)}}throw new f8(`Unknown path type ${r}`)};async function*ES(r,e,t={}){let{cid:n,toResolve:o}=HZ(r),i=n.toString(),s=i,a=o.length;for(;;){let c=await rU(n,i,s,o,a,e,t);if(c.entry==null&&c.next==null)throw new qo(`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 C0(r,e,t={}){let n=await PM(ES(r,e,t));if(n==null)throw new qo(`Could not resolve ${r}`);return n}async function*nU(r,e,t={}){let n=await C0(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))}}function oU(r){return new i8(r)}var yo="application/vnd.ipld.dag-cbor",wo="application/cbor",xo="application/vnd.ipld.dag-json",bo="application/json",En="application/vnd.ipld.raw",Kr="application/octet-stream",ku="application/vnd.ipfs.ipns-record",Pu="application/vnd.ipld.car",fh="application/x-tar",I0="application/vnd.ipld.dag-pb",dh={mediaType:Kr,codecs:[rt,lr,dr,81,fr,pt],immutable:!0,extension:".bin",etag:"",disposition:"attachment"},KZ={mediaType:yo,codecs:[fr,81,dr,lr,pt,rt],immutable:!0,extension:".cbor",etag:".dag-cbor",disposition:"attachment"},VZ={mediaType:wo,codecs:[81,fr,dr,lr,pt,rt],immutable:!0,extension:".cbor",etag:".cbor",disposition:"attachment"},qZ={mediaType:xo,codecs:[dr,lr,fr,81,pt,rt],immutable:!0,extension:".json",etag:".dag-json",disposition:"inline"},zZ={mediaType:bo,codecs:[lr,dr,fr,81,pt,rt],immutable:!0,extension:".json",etag:".json",disposition:"inline"},b8={mediaType:En,codecs:[rt,lr,dr,81,fr,pt],immutable:!0,extension:".raw",etag:".raw",disposition:"attachment"},k0={mediaType:ku,codecs:[],immutable:!1,extension:".bin",etag:".bin",disposition:"attachment"},P0={mediaType:Pu,codecs:[rt,lr,dr,81,fr,pt],immutable:!1,extension:".car",etag:".car",disposition:"attachment"},jZ={mediaType:fh,codecs:[rt,pt],immutable:!1,extension:".x-tar",etag:".x-tar",disposition:"attachment"},iU=[KZ,VZ,qZ,zZ,b8,k0,P0,jZ,dh];function sU(r){return iU.find(e=>e.mediaType===r)}function R0(r){return r==null?[]:iU.filter(e=>e.codecs.includes(r.code)).sort((e,t)=>{let n=e.codecs.indexOf(r.code),o=t.codecs.indexOf(r.code);return n<o?-1:o<n?1:0})}function aU(r="ipfs:",e){let t=R0(e);return r==="ipfs:"&&t.length===0&&(t=[b8,dh]),r==="ipns:"&&t.push(k0),t}function zo(r){if(r==null)throw new O("Cannot get filename for Content-Disposition header - filename argument was missing");let e=WZ(r);return e===r?`filename="${r}"`:`filename="${e}"; filename*=UTF-8''${encodeURIComponent(r)}`}function WZ(r){return r.replace(/[^\x00-\x7F]/g,"_")}var Hn=class extends Error{static name="InvalidRangeError";constructor(e="Invalid range request"){super(e),this.name="InvalidRangeError"}};function cU({offset:r,length:e}){return{offset:Number(r),length:Number(e)}}function SS(r,e,t){if(r=BigInt(r),e!=null){if(e=BigInt(e),e<0n)throw new Hn("Range start cannot be negative");if(e>=r)throw new Hn("Range start cannot be larger than total bytes")}if(t!=null){if(t=BigInt(t),(t>0n?t:-t)>=r)throw new Hn("Range end cannot be larger than total bytes");if(t<0n)if(e==null)e=r+t,t=r-1n;else throw new Hn("Range end cannot be negative");t+=1n}return cU(uU(r,e,t))}function lU(r,e){r=BigInt(r);let t=(e??"0:*").split(":"),n=BigInt(t[0]),o=t[1]==="*"?r:BigInt(t[1]);return cU(uU(r,n,o))}function uU(r,e=0n,t=r){if(e>=0n)return t>=0n?{offset:e,length:t-e}:{offset:e,length:r-e+t};let n=r+e;return Math.abs(Number(e))>Number(r)&&(n=0n),t>=0n?{offset:n,length:t-n}:{offset:n,length:r-n+t}}function fU({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 AS(r,e,t){e!=null&&(e=BigInt(e)),t!=null&&(t=BigInt(t));let n=BigInt(r);if((t??0n)>=n)throw new Hn("Invalid range: Range-end index is greater than or equal to the size of the file.");if((e??0n)>=n)throw new Hn("Invalid range: Range-start index is greater than or equal to the size of the file.");let o="*";if(e==null)t!=null&&(t<0n?o=`${n+t}-${n-1n}`:o=`0-${t}`);else if(t==null){let i="*";r!=null&&(i=`${n-1n}`),o=`${e}-${i}`}else o=`${e}-${t}`;return`bytes ${o}/${n}`}function _S(r,e,t){Object.defineProperty(r,e,{enumerable:!0,configurable:!1,set:()=>{},get:()=>t})}function jo(r,e){r.type!==e&&_S(r,"type",e)}function Wo(r,e){e=e.toString();let t=e.indexOf("#");t>-1&&(e=e.substring(0,t)),r.url!==e&&_S(r,"url",e)}function dU(r){_S(r,"redirected",!0)}function _i(r,e,t){let n=new Response(e,{...t??{},status:200,statusText:"OK"});return t?.redirected===!0&&dU(n),jo(n,"basic"),Wo(n,r),n}function O0(r,e,t){let n=new Response(e,{...t??{},status:500,statusText:"Internal Server Error"});return n.headers.set("X-Content-Type-Options","nosniff"),jo(n,"basic"),Wo(n,r),n}function hU(r,e,t){let n=new Response(e,{...t??{},status:504,statusText:"Gateway Timeout"});return jo(n,"basic"),Wo(n,r),n}function hh(r,e,t){let n=new Response(e,{...t??{},status:502,statusText:"Bad Gateway"});return jo(n,"basic"),Wo(n,r),n}function TS(r,e,t){let n=new Response(e,{...t??{},status:501,statusText:"Not Implemented"});return n.headers.set("X-Content-Type-Options","nosniff"),jo(n,"basic"),Wo(n,r),n}function ss(r,e,t){let n=new Headers(t?.headers);n.set("content-type","application/json");let o=new Response(JSON.stringify({acceptable:e.map(i=>i.mediaType)}),{...t??{},status:406,statusText:"Not Acceptable",headers:n});return jo(o,"basic"),Wo(o,r),o}function CS(r,e,t){let n=new Response(e,{...t??{},status:404,statusText:"Not Found"});return jo(n,"basic"),Wo(n,r),n}function GZ(r){return Array.isArray(r)&&r.every(e=>e instanceof Error)}function Kn(r,e,t){let n,o;GZ(e)?(n=e[e.length-1].stack,o=e.map(a=>({message:a.message,stack:a.stack??""}))):e instanceof Error&&(n=e.stack,o=[{message:e.message,stack:e.stack??""}]);let i=JSON.stringify({stack:n,errors:o}),s=new Response(i,{status:400,statusText:"Bad Request",...t??{},headers:{...t?.headers??{},"Content-Type":"application/json"}});return jo(s,"basic"),Wo(s,r),s}function pU(r,e,t){let n=new Response(null,{...t??{},status:301,statusText:"Moved Permanently",headers:{...t?.headers??{},location:e}});return jo(n,"basic"),Wo(n,r),n}function v8(r,e,t,n,o){let i;if(t.ranges.length===1)i=XZ(r,e,t.ranges[0],n,o);else if(t.ranges.length>1)i=YZ(r,e,t,n,o);else return E8(r,n);return o?.redirected===!0&&dU(i),jo(i,"basic"),Wo(i,r),i}function XZ(r,e,t,n,o){try{let i=new Headers(o?.headers),{offset:s,length:a}=SS(n,t.start,t.end);i.set("content-length",`${a}`),i.set("content-range",AS(n,t.start,t.end));let c=Lo(e(s,a));return new Response(c,{...o??{},status:206,statusText:"Partial Content",headers:i})}catch(i){return i.name==="InvalidRangeError"?E8(r,n,o):O0(r,"",o)}}function YZ(r,e,t,n,o){let i=new Headers(o?.headers),s=i.get("content-type");if(s==null)throw new Error("Content-Type header must be set");i.delete("content-type");let a=0n,c=t.ranges.map(({start:u,end:h})=>{let d=D([`--${t.multipartBoundary}`,`Content-Type: ${s}`,`Content-Range: ${AS(n,u,h)}`,"",""].join(`\r
|
|
111
111
|
`));return a+=BigInt(d.byteLength)+(BigInt(h??n)-BigInt(u??0)),d}),l=D([`--${t.multipartBoundary}--`,""].join(`\r
|
|
112
112
|
`));a+=BigInt(l.byteLength),i.set("content-length",`${a}`),i.set("content-type",`multipart/byteranges; boundary=${t.multipartBoundary}`);let f=Lo((async function*(){for(let u=0;u<c.length;u++){yield c[u];let{offset:h,length:d}=SS(n,t.ranges[u].start,t.ranges[u].end);yield*e(h,d),yield D(`\r
|
|
113
|
-
`)}yield l})());return new Response(f,{...o??{},status:206,statusText:"Partial Content",headers:i})}function E8(r,e,t){let n=new Headers(t?.headers);e!=null&&n.set("content-range",`bytes */${e}`);let o=new Response("Range Not Satisfiable",{...t,headers:n,status:416,statusText:"Range Not Satisfiable"});return jo(o,"basic"),Wo(o,r),o}function mU(r,e){let t=new Headers(e?.headers),n=new Response("Precondition Failed",{...e,headers:t,status:412,statusText:"Precondition Failed"});return jo(n,"basic"),Wo(n,r),n}var Vn=class{pluginOptions;_log;get log(){return this._log==null&&(this._log=this.pluginOptions.logger.newScope(this.id)),this._log}constructor(e){this.pluginOptions=e}};function QZ(r){return`${r.replace(/\/ipfs\//,"").replace(/\/ipns\//,"").replace(/\/+$/g,"").replace(/\//g,"_")}.car`}function ZZ({url:r}){let e=r.searchParams.get("dag-scope");return e==="all"||e==="entity"||e==="block"?e:r.searchParams.has("entity-bytes")?"entity":"all"}var S8=class extends Vn{id="car-plugin";canHandle({accept:e}){return e.some(t=>t.contentType.mediaType===Pu)}async handle(e){let{options:t,url:n,accept:o,resource:i,blockstore:s,range:a,ipfsRoots:c,terminalElement:l}=e;if(a!=null)return Kn(i,new Error("Range requests are not supported for CAR files"));let f=o.filter(v=>v.contentType.mediaType===Pu).pop();if(f==null)return Kn(i,new Error("Could not find CAR media type in accept header"));let u=f.options.order==="dfs"||n.searchParams.get("car-order")==="dfs"?"dfs":"unk",h=f.options.dups!=="n"&&n.searchParams.get("car-dups")!=="n";if(f.options.version==="2"||n.searchParams.get("car-version")==="2")return ss(i,[P0]);let d=this.pluginOptions.helia,m=oU({blockstore:s,getCodec:d.getCodec,logger:d.logger}),y={...t,includeTraversalBlocks:!0};h||(y.blockFilter=br(1024)),c.length>1&&(y.traversal=new u8(c));let w=ZZ(e),x=l.cid;if(w==="block")y.exporter=new S0;else if(w==="entity")if(x.code===pt){let v={listingOnly:!0},I=lU(l.size,n.searchParams.get("entity-bytes"));v.offset=I.offset,v.length=I.length,y.exporter=new ah(v)}else y.exporter=new S0;else y.exporter=new sh({walker:u==="dfs"?$f():sy()});let E=Lo(m.export(x,y));return _i(i,E,{headers:{"content-type":`${Pu}; version=1; order=${u}; dups=${h?"y":"n"}`,"content-disposition":`attachment; ${zo(n.searchParams.get("filename")??QZ(`/ipfs/${n.hostname}${n.pathname}`))}`,"x-content-type-options":"nosniff","accept-ranges":"none"}})}};var JZ={[fr]:{[bo]:r=>Po(ci(r)),[xo]:r=>Po(ci(r)),[yo]:r=>r,[wo]:r=>r,[En]:r=>r,[Kr]:r=>r},81:{[bo]:r=>Po(ci(r)),[xo]:r=>Po(ci(r)),[yo]:r=>r,[wo]:r=>r,[En]:r=>r,[Kr]:r=>r},[dr]:{[wo]:r=>hn(gl(r)),[yo]:r=>hn(gl(r)),[xo]:r=>r,[bo]:r=>r,[En]:r=>r,[Kr]:r=>r},[lr]:{[wo]:r=>hn(zu(r)),[yo]:r=>hn(zu(r)),[xo]:r=>r,[bo]:r=>r,[En]:r=>r,[Kr]:r=>r},[pt]:{[wo]:r=>hn(_n(r)),[yo]:r=>hn(_n(r)),[bo]:r=>Po(_n(r)),[xo]:r=>Po(_n(r)),[En]:r=>r,[Kr]:r=>r},[rt]:{[wo]:r=>hn(r),[yo]:r=>hn(r),[bo]:r=>r,[xo]:r=>Po(r),[En]:r=>r,[Kr]:r=>r},[$t.code]:{[wo]:r=>hn(r),[yo]:r=>hn(r),[bo]:r=>Po(r),[xo]:r=>Po(r),[En]:r=>r,[Kr]:r=>r}};function gU(r,e,t){if(t.length===0)return{contentType:R0(r)[0],output:e};for(let n of t){let o=JZ[r.code]?.[n.contentType.mediaType];if(o!=null)return{contentType:n.contentType,output:o(e)}}throw new Error(`Could not convert ${r} to any of ${t.map(n=>n.contentType.mediaType).join(", ")}`)}var A8=class extends Vn{id="ipld-plugin";codes=[81,fr,dr,lr,rt,pt,$t.code];canHandle({terminalElement:e,accept:t}){let n=this.codes.includes(e.cid.code),o=t.length===0||t.some(i=>i.contentType.mediaType===wo||i.contentType.mediaType===yo||i.contentType.mediaType===bo||i.contentType.mediaType===xo||i.contentType.mediaType===En||i.contentType.mediaType===Kr);return n&&o}async handle(e){let{url:t,resource:n,accept:o,ipfsRoots:i,terminalElement:s,blockstore:a,options:c}=e;this.log.trace("fetching %c/%s",s.cid,t.pathname);let l;s.node==null?l=await Ge(a.get(s.cid,c)):s.type==="object"||s.type==="raw"||s.type==="identity"?l=s.node:l=Xx(s.node);let f;try{let h=gU(s.cid,l,o);l=h.output,f=h.contentType}catch(h){return this.log.error("could not decode object from block - %e",h),ss(n,R0(s.cid))}let u={"content-length":`${l.byteLength}`,"content-type":f.mediaType,"content-disposition":`${t.searchParams.get("download")==="true"?"attachment":f.disposition}; ${zo(t.searchParams.get("filename")??`${s.cid}${f.extension}`)}`,"x-ipfs-roots":i.map(h=>h.toV1()).join(","),"x-content-type-options":"nosniff","accept-ranges":"bytes"};return e.range!=null?v8(n,async function*(h,d){yield l.subarray(h,h+d)},e.range,l.byteLength,{headers:u}):_i(n,l,{headers:u})}};var _8=class extends Vn{id="ipns-record-plugin";codes=[];canHandle({accept:e}){return e.some(t=>t.contentType.mediaType===ku)}async handle(e){let{resource:t,url:n,options:o,range:i}=e,{ipnsResolver:s}=this.pluginOptions;if(n.pathname!==""||n.protocol!=="ipns:")return this.log.error('invalid request for IPNS name "%s" and path "%s"',
|
|
113
|
+
`)}yield l})());return new Response(f,{...o??{},status:206,statusText:"Partial Content",headers:i})}function E8(r,e,t){let n=new Headers(t?.headers);e!=null&&n.set("content-range",`bytes */${e}`);let o=new Response("Range Not Satisfiable",{...t,headers:n,status:416,statusText:"Range Not Satisfiable"});return jo(o,"basic"),Wo(o,r),o}function mU(r,e){let t=new Headers(e?.headers),n=new Response("Precondition Failed",{...e,headers:t,status:412,statusText:"Precondition Failed"});return jo(n,"basic"),Wo(n,r),n}var Vn=class{pluginOptions;_log;get log(){return this._log==null&&(this._log=this.pluginOptions.logger.newScope(this.id)),this._log}constructor(e){this.pluginOptions=e}};function QZ(r){return`${r.replace(/\/ipfs\//,"").replace(/\/ipns\//,"").replace(/\/+$/g,"").replace(/\//g,"_")}.car`}function ZZ({url:r}){let e=r.searchParams.get("dag-scope");return e==="all"||e==="entity"||e==="block"?e:r.searchParams.has("entity-bytes")?"entity":"all"}var S8=class extends Vn{id="car-plugin";canHandle({accept:e}){return e.some(t=>t.contentType.mediaType===Pu)}async handle(e){let{options:t,url:n,accept:o,resource:i,blockstore:s,range:a,ipfsRoots:c,terminalElement:l}=e;if(a!=null)return Kn(i,new Error("Range requests are not supported for CAR files"));let f=o.filter(v=>v.contentType.mediaType===Pu).pop();if(f==null)return Kn(i,new Error("Could not find CAR media type in accept header"));let u=f.options.order==="dfs"||n.searchParams.get("car-order")==="dfs"?"dfs":"unk",h=f.options.dups!=="n"&&n.searchParams.get("car-dups")!=="n";if(f.options.version==="2"||n.searchParams.get("car-version")==="2")return ss(i,[P0]);let d=this.pluginOptions.helia,m=oU({blockstore:s,getCodec:d.getCodec,logger:d.logger}),y={...t,includeTraversalBlocks:!0};h||(y.blockFilter=br(1024)),c.length>1&&(y.traversal=new u8(c));let w=ZZ(e),x=l.cid;if(w==="block")y.exporter=new S0;else if(w==="entity")if(x.code===pt){let v={listingOnly:!0},I=lU(l.size,n.searchParams.get("entity-bytes"));v.offset=I.offset,v.length=I.length,y.exporter=new ah(v)}else y.exporter=new S0;else y.exporter=new sh({walker:u==="dfs"?$f():sy()});let E=Lo(m.export(x,y));return _i(i,E,{headers:{"content-type":`${Pu}; version=1; order=${u}; dups=${h?"y":"n"}`,"content-disposition":`attachment; ${zo(n.searchParams.get("filename")??QZ(`/ipfs/${n.hostname}${n.pathname}`))}`,"x-content-type-options":"nosniff","accept-ranges":"none"}})}};var JZ={[fr]:{[bo]:r=>Po(ci(r)),[xo]:r=>Po(ci(r)),[yo]:r=>r,[wo]:r=>r,[En]:r=>r,[Kr]:r=>r},81:{[bo]:r=>Po(ci(r)),[xo]:r=>Po(ci(r)),[yo]:r=>r,[wo]:r=>r,[En]:r=>r,[Kr]:r=>r},[dr]:{[wo]:r=>hn(gl(r)),[yo]:r=>hn(gl(r)),[xo]:r=>r,[bo]:r=>r,[En]:r=>r,[Kr]:r=>r},[lr]:{[wo]:r=>hn(zu(r)),[yo]:r=>hn(zu(r)),[xo]:r=>r,[bo]:r=>r,[En]:r=>r,[Kr]:r=>r},[pt]:{[wo]:r=>hn(_n(r)),[yo]:r=>hn(_n(r)),[bo]:r=>Po(_n(r)),[xo]:r=>Po(_n(r)),[En]:r=>r,[Kr]:r=>r},[rt]:{[wo]:r=>hn(r),[yo]:r=>hn(r),[bo]:r=>r,[xo]:r=>Po(r),[En]:r=>r,[Kr]:r=>r},[$t.code]:{[wo]:r=>hn(r),[yo]:r=>hn(r),[bo]:r=>Po(r),[xo]:r=>Po(r),[En]:r=>r,[Kr]:r=>r}};function gU(r,e,t){if(t.length===0)return{contentType:R0(r)[0],output:e};for(let n of t){let o=JZ[r.code]?.[n.contentType.mediaType];if(o!=null)return{contentType:n.contentType,output:o(e)}}throw new Error(`Could not convert ${r} to any of ${t.map(n=>n.contentType.mediaType).join(", ")}`)}var A8=class extends Vn{id="ipld-plugin";codes=[81,fr,dr,lr,rt,pt,$t.code];canHandle({terminalElement:e,accept:t}){let n=this.codes.includes(e.cid.code),o=t.length===0||t.some(i=>i.contentType.mediaType===wo||i.contentType.mediaType===yo||i.contentType.mediaType===bo||i.contentType.mediaType===xo||i.contentType.mediaType===En||i.contentType.mediaType===Kr);return n&&o}async handle(e){let{url:t,resource:n,accept:o,ipfsRoots:i,terminalElement:s,blockstore:a,options:c}=e;this.log.trace("fetching %c/%s",s.cid,t.pathname);let l;s.node==null?l=await Ge(a.get(s.cid,c)):s.type==="object"||s.type==="raw"||s.type==="identity"?l=s.node:l=Xx(s.node);let f;try{let h=gU(s.cid,l,o);l=h.output,f=h.contentType}catch(h){return this.log.error("could not decode object from block - %e",h),ss(n,R0(s.cid))}let u={"content-length":`${l.byteLength}`,"content-type":f.mediaType,"content-disposition":`${t.searchParams.get("download")==="true"?"attachment":f.disposition}; ${zo(t.searchParams.get("filename")??`${s.cid}${f.extension}`)}`,"x-ipfs-roots":i.map(h=>h.toV1()).join(","),"x-content-type-options":"nosniff","accept-ranges":"bytes"};return e.range!=null?v8(n,async function*(h,d){yield l.subarray(h,h+d)},e.range,l.byteLength,{headers:u}):_i(n,l,{headers:u})}};var _8=class extends Vn{id="ipns-record-plugin";codes=[];canHandle({accept:e}){return e.some(t=>t.contentType.mediaType===ku)}async handle(e){let{resource:t,url:n,options:o,range:i}=e,{ipnsResolver:s}=this.pluginOptions;if(n.pathname!==""&&n.pathname!=="/"||n.protocol!=="ipns:")return this.log.error('invalid request for IPNS name "%s" and path "%s"',n,n.pathname),Kn(t,new Error("Invalid IPNS name"));if(i!=null)return Kn(t,new Error("Range requests are not supported for IPNS records"));let a;try{this.log.trace('trying to parse peer id from "%s"',n.hostname),a=ze(n.hostname)}catch(f){return this.log.error("could not parse peer id from IPNS url %s",t,f),Kn(t,f)}let c=await s.resolve(a,o),l=vl(c.record);return _i(t,l,{headers:{"content-length":`${l.byteLength}`,"content-type":k0.mediaType,"content-disposition":`attachment; ${zo(n.searchParams.get("filename")??`${a}${k0.extension}`)}`,"x-ipfs-roots":c.cid.toV1().toString(),"cache-control":`public, max-age=${Number((c.record.ttl??0n)/BigInt(1e9))}`,"accept-ranges":"none"}})}};var T8=class extends Error{name;code;constructor(e,t,n){super(e),this.name=t,this.code=n}},Ru=class extends T8{constructor(e="not a Unixfs node"){super(e,"NotUnixFSError","ERR_NOT_UNIXFS")}};var C8=class extends T8{constructor(e="path does not exist"){super(e,"DoesNotExistError","ERR_DOES_NOT_EXIST")}};var Att=D("ustar\0","binary"),_tt=D("ustar ","binary"),Ttt=D(" \0","binary");var bU=gt(wU(),1);var tJ="0000000000000000000",rJ="7777777777777777777",nJ=48,oJ=D("ustar\0","binary"),iJ=D("00","binary"),sJ=parseInt("7777",8),aJ=257,cJ=263,lJ=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}},uJ=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},Cc=function(r,e){let t=r.toString(8);return t.length>e?D(rJ.slice(0,e)+" "):D(tJ.slice(0,e-t.length)+t+" ")},IS=function(r){let e=D(r).byteLength,t=Math.floor(Math.log(e)/Math.log(10))+1;return e+t>=Math.pow(10,t)&&t++,`${e+t}${r}`};function xU(r){let e="";r.name!=null&&(e+=IS(" path="+r.name+`
|
|
114
114
|
`)),r.linkname!=null&&(e+=IS(" linkpath="+r.linkname+`
|
|
115
115
|
`));let t=r.pax;if(t!=null)for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e+=IS(" "+n+"="+t[n]+`
|
|
116
|
-
`));return D(e)}function I8(r){let e=new Uint8Array(512),t=r.name,n="";if(r.typeflag===5&&t[t.length-1]!=="/"&&(t+="/"),D(t).byteLength!==t.length)return null;for(;D(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 D(t).byteLength>100||D(n).byteLength>155||r.linkname!=null&&D(r.linkname).byteLength>100?null:(e.set(D(t),0),e.set(Cc(r.mode&sJ,6),100),e.set(Cc(r.uid,6),108),e.set(Cc(r.gid,6),116),e.set(Cc(r.size,11),124),e.set(Cc(r.mtime.getTime()/1e3|0,11),136),e[156]=nJ+lJ(r.type),r.linkname!=null&&e.set(D(r.linkname),157),e.set(oJ,aJ),e.set(iJ,cJ),r.uname!=null&&e.set(D(r.uname),265),r.gname!=null&&e.set(D(r.gname),297),e.set(Cc(r.devmajor??0,6),329),e.set(Cc(r.devminor??0,6),337),n!=null&&e.set(D(n),345),e.set(Cc(uJ(e),6),148),e)}var{S_IFMT:dJ,S_IFBLK:hJ,S_IFCHR:pJ,S_IFDIR:mJ,S_IFIFO:gJ,S_IFLNK:yJ}=bU.default,wJ=parseInt("755",8),xJ=parseInt("644",8),vU=new Uint8Array(1024);function bJ(r=0){switch(r&dJ){case hJ:return"block-device";case pJ:return"character-device";case mJ:return"directory";case gJ:return"fifo";case yJ:return"symlink";default:return"file"}}function PS(r){return r&=511,r!==0?vU.subarray(0,512-r):new Uint8Array(0)}function kS(r){if(r.pax==null){let e=I8(r);if(e!=null)return e}return vJ(r)}function vJ(r){let e=xU(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 se(I8(t)??new Uint8Array(0),e,PS(e.length),I8({...t,size:r.size,type:r.type})??new Uint8Array(0)).subarray()}function k8(){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??bJ(e.mode),mode:e.mode??(e.type==="directory"?wJ:xJ),uid:e.uid??0,gid:e.gid??0,mtime:e.mtime??new Date};if(typeof t=="string"&&(t=D(t)),t instanceof Uint8Array||Eo(t)){n.size=t.length,yield kS(n),yield Eo(t)?t.subarray():t,yield PS(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=H(await Ge(t)),yield kS(n);continue}if(yield kS(n),n.type!=="file"&&n.type!=="contiguous-file")continue;let o=0;for await(let i of t??[])o+=i.length,yield Eo(i)?i.subarray():i;if(o!==n.size)throw new Error(`size mismatch, wrote ${o} of ${n.size} bytes`);yield PS(n.size)}yield vU}}var EJ=["file","raw","directory"];function SJ(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 EU(r){if(!EJ.includes(r.type))throw new Ru(`${r.type} is not a UnixFS node`);let e={header:SJ(r)};return(r.type==="file"||r.type==="raw")&&(e.body=r.content()),e}async function*SU(r,e,t){let n=await C0(r,e,t);if(n.type==="file"||n.type==="raw"){yield*ln([EU(n)],k8());return}if(n.type==="directory"){yield*ln(nU(r,e,t),o=>Kt(o,i=>EU(i)),k8());return}throw new Ru("Not a UnixFS node")}var P8=class extends Vn{id="tar-plugin";codes=[];canHandle({accept:e}){return e.some(t=>t.contentType.mediaType===fh)}async handle(e){let{terminalElement:t,url:n,resource:o,options:i,blockstore:s,range:a}=e;if(t.cid.code!==pt&&t.cid.code!==rt)return Kn(o,new Ru("Only UnixFS data can be returned in a TAR file"));if(a!=null)return Kn(o,new Error("Range requests are not supported for TAR files"));let c=Lo(SU(`/ipfs/${t.cid}${n.pathname}`,s,i));return _i(o,c,{headers:{"content-type":fh,"content-disposition":`attachment; ${zo(n.searchParams.get("filename")??`${t.cid.toString()}.tar`)}`,"accept-ranges":"none"}})}};function AJ(r,e,t){let n;try{n=new URL(r)}catch{n=e}if(t?.type==="directory"&&!n.pathname.endsWith("/"))return n.pathname+="/",n.toString()}var R8=class extends Vn{id="unixfs-plugin";codes=[pt,rt];canHandle({terminalElement:e,accept:t}){let n=this.codes.includes(e.cid.code),o=t.length===0||t.some(i=>i.contentType.mediaType===Kr||i.contentType.mediaType===I0);return n&&o}async handle(e){let{url:t,resource:n,terminalElement:o,ipfsRoots:i}=e,s=t.searchParams.get("filename")??o.name,a;if(o.type==="directory"){let c=AJ(n,t,o);if(c!=null){if(this.log.trace("directory url normalization spec requires redirect"),e.options?.redirect==="error")throw this.log('could not redirect to %s as redirect option was set to "error"',c),new TypeError("Failed to fetch");if(e.options?.redirect==="manual")return this.log("returning 301 permanent redirect to %s",c),pU(e.resource,c);this.log("following redirect to %s",c),n=c,a=!0}let l=o.cid;if(e.options?.supportDirectoryIndexes!==!1){let u="index.html";try{this.log.trace("found directory at %c/%s, looking for index.html",l,t.pathname);let h=await e.serverTiming.time("exporter-dir","",C0(`/ipfs/${l}/${u}`,e.blockstore,e.options));return h.type==="directory"||h.type==="object"?hh(n,"Unable to stream content"):(s=u,this.log.trace("found directory index at %c/%s with cid %c",l,u,h.cid),await this.streamFile(n,h,s,a,e.range,e.options))}catch(h){if(h.name!=="NotFoundError")throw this.log.error("error loading path %c/%s - %e",l,u,h),h}}let f=await Ge(e.blockstore.get(l,e.options));return _i(n,f,{headers:{"content-type":I0,"content-length":`${f.byteLength}`,"content-disposition":`${t.searchParams.get("download")==="true"?"attachment":"inline"}; ${zo(`${l}.dir`)}`,"x-ipfs-roots":i.map(u=>u.toV1()).join(","),"accept-ranges":"bytes"},redirected:a})}else return o.type==="file"||o.type==="raw"||o.type==="identity"?(this.log("streaming file"),this.streamFile(n,o,s,a,e.range,e.options)):(this.log.error("cannot stream terminal element type %s",o.type),hh(n,"Unable to stream content"))}async streamFile(e,t,n,o,i,s){let a=Kr;return i==null&&(a=await this.detectContentType(t,n,s)),i!=null?v8(e,(c,l)=>t.content({...s??{},offset:c,length:l}),i,t.size,{headers:{"content-type":a,"content-disposition":`inline; ${zo(n)}`,"x-ipfs-roots":t.cid.toString(),"accept-ranges":"bytes"},redirected:o}):_i(e,Lo(t.content(s)),{headers:{"content-type":a,"content-length":`${t.size}`,"content-disposition":`inline; ${zo(n)}`,"x-ipfs-roots":t.cid.toString(),"accept-ranges":"bytes"},redirected:o})}async detectContentType(e,t,n){let o;if(e.type==="raw"||e.type==="identity"?o=e.node:o=await Py(e.content(n)),o==null)throw new Error("stream ended before first block was read");let i;if(this.pluginOptions.contentTypeParser!=null)try{let s=this.pluginOptions.contentTypeParser(o,t);if(yf(s)){let a=await s;a!=null&&(i=a)}else s!=null&&(i=s);this.log.trace("contentTypeParser returned %s for file with name %s",i,t)}catch(s){this.log.error("error parsing content type - %e",s)}return i??Kr}};var D0=class extends Map{#t=0;#e=new Map;#r=new Map;#s;#c;#a;constructor(e={}){if(super(),!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if(typeof e.maxAge=="number"&&e.maxAge===0)throw new TypeError("`maxAge` must be a number greater than 0");this.#s=e.maxSize,this.#c=e.maxAge||Number.POSITIVE_INFINITY,this.#a=e.onEviction}get __oldCache(){return this.#r}#l(e){if(typeof this.#a=="function")for(let[t,n]of e)this.#a(t,n.value)}#n(e,t){return typeof t.expiry=="number"&&t.expiry<=Date.now()?(typeof this.#a=="function"&&this.#a(e,t.value),this.delete(e)):!1}#d(e,t){if(this.#n(e,t)===!1)return t.value}#u(e,t){return t.expiry?this.#d(e,t):t.value}#f(e,t){let n=t.get(e);return this.#u(e,n)}#o(e,t){this.#e.set(e,t),this.#t++,this.#t>=this.#s&&(this.#t=0,this.#l(this.#r),this.#r=this.#e,this.#e=new Map)}#h(e,t){this.#r.delete(e),this.#o(e,t)}*#i(){for(let e of this.#r){let[t,n]=e;this.#e.has(t)||this.#n(t,n)===!1&&(yield e)}for(let e of this.#e){let[t,n]=e;this.#n(t,n)===!1&&(yield e)}}get(e){if(this.#e.has(e)){let t=this.#e.get(e);return this.#u(e,t)}if(this.#r.has(e)){let t=this.#r.get(e);if(this.#n(e,t)===!1)return this.#h(e,t),t.value}}set(e,t,{maxAge:n=this.#c}={}){let o=typeof n=="number"&&n!==Number.POSITIVE_INFINITY?Date.now()+n:void 0;return this.#e.has(e)?this.#e.set(e,{value:t,expiry:o}):this.#o(e,{value:t,expiry:o}),this}has(e){return this.#e.has(e)?!this.#n(e,this.#e.get(e)):this.#r.has(e)?!this.#n(e,this.#r.get(e)):!1}peek(e){if(this.#e.has(e))return this.#f(e,this.#e);if(this.#r.has(e))return this.#f(e,this.#r)}expiresIn(e){let t=this.#e.get(e)??this.#r.get(e);if(t)return t.expiry?t.expiry-Date.now():Number.POSITIVE_INFINITY}delete(e){let t=this.#e.delete(e);return t&&this.#t--,this.#r.delete(e)||t}clear(){this.#e.clear(),this.#r.clear(),this.#t=0}resize(e){if(!(e&&e>0))throw new TypeError("`maxSize` must be a number greater than 0");let t=[...this.#i()],n=t.length-e;n<0?(this.#e=new Map(t),this.#r=new Map,this.#t=t.length):(n>0&&this.#l(t.slice(0,n)),this.#r=new Map(t.slice(n)),this.#e=new Map,this.#t=0),this.#s=e}evict(e=1){let t=Number(e);if(!t||t<=0)return;let n=[...this.#i()],o=Math.trunc(Math.min(t,Math.max(n.length-1,0)));o<=0||(this.#l(n.slice(0,o)),this.#r=new Map(n.slice(o)),this.#e=new Map,this.#t=0)}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let e of this.#e){let[t,n]=e;this.#n(t,n)===!1&&(yield[t,n.value])}for(let e of this.#r){let[t,n]=e;this.#e.has(t)||this.#n(t,n)===!1&&(yield[t,n.value])}}*entriesDescending(){let e=[...this.#e];for(let t=e.length-1;t>=0;--t){let n=e[t],[o,i]=n;this.#n(o,i)===!1&&(yield[o,i.value])}e=[...this.#r];for(let t=e.length-1;t>=0;--t){let n=e[t],[o,i]=n;this.#e.has(o)||this.#n(o,i)===!1&&(yield[o,i.value])}}*entriesAscending(){for(let[e,t]of this.#i())yield[e,t.value]}get size(){if(!this.#t)return this.#r.size;let e=0;for(let t of this.#r.keys())this.#e.has(t)||e++;return Math.min(this.#t+e,this.#s)}get maxSize(){return this.#s}get maxAge(){return this.#c}entries(){return this.entriesAscending()}forEach(e,t=this){for(let[n,o]of this.entriesAscending())e.call(t,o,n,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}};var _J=/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;function AU(r){return _J.test(r)&&r.includes("-")&&!r.includes(".")}function _U(r){return r.replace(/--/g,"%").replace(/-/g,".").replace(/%/g,"-")}function TU(r){if(!r.startsWith("/ipfs/")&&!r.startsWith("/ipns/"))throw new O(`Path ${r} did not start with /ipfs/ or /ipns/`);let e=r.indexOf("#"),t="";e>-1&&(t=r.substring(e),r=r.substring(0,e));let n=r.indexOf("?"),o="";n>-1&&(o=r.substring(n),r=r.substring(0,n));let i=r.substring(1,5),s=r.substring(6);return`https://example.org/${i}/${s}${o}${t}`}function CU(r){if(!r.startsWith("ipfs://")&&!r.startsWith("ipns://"))throw new O(`URL ${r} did not start with ipfs:// or ipns://`);let e=r.substring(0,4),t=r.substring(7);return`https://example.org/${e}/${t}`}var TJ=/^(?<cidOrPeerIdOrDnsLink>[^/?]+)\.(?<protocol>ip[fn]s)\.([^/?]+)$/,CJ=114;function IJ(r){let e=r?.protocol;return!(e!=="ipfs"&&e!=="ipns"||r?.cidOrPeerIdOrDnsLink==null)}function kJ(r,e){let t=e.toLowerCase().indexOf(r);return t===-1?r:e.substring(t,t+r.length)}function PJ(r){if(r instanceof URL)return r;if((r.startsWith("/ipfs/")||r.startsWith("/ipns/"))&&(r=TU(r)),(r.startsWith("ipfs://")||r.startsWith("ipns://"))&&(r=CU(r)),r.startsWith("http://")||r.startsWith("https://"))return new URL(r);throw new O(`Invalid URL: ${r}`)}function RJ(r){let e=PJ(r),t=e.hostname.match(TJ);if(IJ(t?.groups)){let n=t.groups;n.protocol==="ipns"&&AU(n.cidOrPeerIdOrDnsLink)&&(n.cidOrPeerIdOrDnsLink=_U(n.cidOrPeerIdOrDnsLink));let o=kJ(n.cidOrPeerIdOrDnsLink,r),i=new URL(`not-${r}`);return new URL(`${n.protocol}://${o}${i.pathname}${e.search}${e.hash}`)}if(e.pathname.startsWith("/ipfs/")){let o=e.pathname.substring(6).split("/").shift();if(o==null)throw new O(`Path gateway URL ${r} had no CID`);return new URL(`ipfs://${o}${e.pathname.replace(`/ipfs/${o}`,"")}${e.search}${e.hash}`)}if(e.pathname.startsWith("/ipns/")){let o=e.pathname.substring(6).split("/").shift();if(o==null)throw new O(`Path gateway URL ${r} had no name`);return new URL(`ipns://${o}${e.pathname.replace(`/ipns/${o}`,"")}${e.search}${e.hash}`)}throw new TypeError(`Invalid URL: ${r}, please use ipfs://, ipns://, or gateway URLs only`)}function O8(r){let e=RJ(r);if(e.protocol==="ipns:")try{ze(e.hostname)}catch{e.protocol="dnslink:"}if(e.protocol==="ipfs:"){let t=Z.parse(e.hostname);if(t.code===CJ)return new URL(`ipns://${oo(t)}${e.pathname}${e.search}${e.hash}`)}return e}function IU(r){let e=Z.asCID(r);if(e!=null)return`ipfs://${e}`;try{return`ipfs://${Z.parse(r.toString())}`}catch{}let{protocol:t,host:n}=O8(r.toString());return`${t}//${n}`}var ph=class{headers;constructor(){this.headers=[]}getHeader(){return this.headers.join(",")}async time(e,t,n){let o=performance.now();try{return await n}finally{let s=(performance.now()-o).toFixed(1);this.headers.push(`${e};dur=${s};desc="${t}"`)}}};var OJ=29030400,DJ=[81,lr,rt],NJ=[pt,fr,dr,rt];function kU(r,e,t){return{name:e.toString(),path:e.toString(),depth:0,type:r,node:t,cid:e,size:BigInt(t.byteLength),content:async function*(){yield t}}}var D8=class{components;blockstoreSessions;constructor(e,t={}){this.components=e,this.blockstoreSessions=new D0({maxSize:t.sessionCacheSize??100,maxAge:t.sessionTTLms??6e4,onEviction:(n,o)=>{o.close()}})}async resolve(e,t=new ph,n={}){if(e.protocol==="ipfs:")return this.resolveIPFSPath(e,t,n);if(e.protocol==="ipns:")return this.resolveIPNSName(e,t,n);if(e.protocol==="dnslink:")return this.resolveDNSLink(e,t,n);throw new ca(`Invalid resource. Unsupported protocol in URL, must be ipfs:, ipns:, or dnslink: ${e}`)}getBlockstore(e,t={}){if(t.session===!1)return this.components.helia.blockstore;let n=IU(e),o=this.blockstoreSessions.get(n);return o==null&&(o=this.components.helia.blockstore.createSession(e,t),this.blockstoreSessions.set(n,o)),o}async resolveDNSLink(e,t,n){let i=(await t.time("dnsLink.resolve",`Resolve DNSLink ${e.hostname}`,this.components.dnsLink.resolve(e.hostname,n)))?.[0];if(i==null)throw new TypeError(`Invalid resource. Cannot resolve DNSLink from domain: ${e.hostname}`);if(i.namespace==="ipns")return this.resolveIPNSName(e,t,n);if(i.namespace!=="ipfs")throw new TypeError(`Invalid resource. Unexpected DNSLink namespace ${i.namespace} from domain: ${domain}`);i.path!=null&&e.pathname;let s=new URL(`ipfs://${i.cid}/${e.pathname}`);return{...await this.resolveIPFSPath(s,t,n),url:e,ttl:i.answer.TTL}}async resolveIPNSName(e,t,n){let o=ze(e.hostname),i=await t.time("ipns.resolve",`Resolve IPNS name ${o}`,this.components.ipnsResolver.resolve(o,n));i.path!=null&&e.pathname;let s=new URL(`ipfs://${i.cid}/${e.pathname}`);return{...await this.resolveIPFSPath(s,t,n),url:e,ttl:Number((i.record.ttl??0n)/BigInt(1e9))}}async resolveIPFSPath(e,t,n){let o=await t.time("ipfs.resolve","",this.walkPath(e,n));return{...o,url:e,ttl:OJ,blockstore:o.blockstore}}async walkPath(e,t={}){let n=Z.parse(e.hostname),o=this.getBlockstore(n,t);if(NJ.includes(n.code)){let s=[],a,c=LJ(e);for await(let l of ES(c,o,{...t,offline:t.onlyIfCached===!0,extended:t.isRawBlockRequest!==!0}))s.push(l.cid),a=l;if(a==null)throw new C8("No terminal element found");return{ipfsRoots:s,terminalElement:a,blockstore:o}}let i;return n.multihash.code===0?i=n.multihash.digest:i=await Ge(o.get(n,t)),DJ.includes(n.code)?{ipfsRoots:[n],terminalElement:kU("object",n,i),blockstore:o}:{ipfsRoots:[n],terminalElement:kU("raw",n,i),blockstore:o}}};function LJ(r){return`/ipfs/${r.hostname}${decodeURI(r.pathname)}`}var OU=gt(PU(),1);var OS={128:"\u20AC",130:"\u201A",131:"\u0192",132:"\u201E",133:"\u2026",134:"\u2020",135:"\u2021",136:"\u02C6",137:"\u2030",138:"\u0160",139:"\u2039",140:"\u0152",142:"\u017D",145:"\u2018",146:"\u2019",147:"\u201C",148:"\u201D",149:"\u2022",150:"\u2013",151:"\u2014",152:"\u02DC",153:"\u2122",154:"\u0161",155:"\u203A",156:"\u0153",158:"\u017E",159:"\u0178"},BJ={};for(let[r,e]of Object.entries(OS))BJ[e]=Number.parseInt(r);function RU(r,e="utf-8"){switch(e.toLowerCase()){case"utf-8":case"utf8":return typeof globalThis.TextDecoder<"u"?new globalThis.TextDecoder("utf-8").decode(r):MJ(r);case"utf-16le":return UJ(r);case"ascii":return FJ(r);case"latin1":case"iso-8859-1":return $J(r);case"windows-1252":return HJ(r);default:throw new RangeError(`Encoding '${e}' not supported`)}}function MJ(r){let e="",t=0;for(;t<r.length;){let n=r[t++];if(n<128)e+=String.fromCharCode(n);else if(n<224){let o=r[t++]&63;e+=String.fromCharCode((n&31)<<6|o)}else if(n<240){let o=r[t++]&63,i=r[t++]&63;e+=String.fromCharCode((n&15)<<12|o<<6|i)}else{let o=r[t++]&63,i=r[t++]&63,s=r[t++]&63,a=(n&7)<<18|o<<12|i<<6|s;a-=65536,e+=String.fromCharCode(55296+(a>>10&1023),56320+(a&1023))}}return e}function UJ(r){let e="";for(let t=0;t<r.length;t+=2)e+=String.fromCharCode(r[t]|r[t+1]<<8);return e}function FJ(r){return String.fromCharCode(...r.map(e=>e&127))}function $J(r){return String.fromCharCode(...r)}function HJ(r){let e="";for(let t of r)t>=128&&t<=159&&OS[t]?e+=OS[t]:e+=String.fromCharCode(t);return e}function qn(r){return new DataView(r.buffer,r.byteOffset)}var DU={len:1,get(r,e){return qn(r).getUint8(e)},put(r,e,t){return qn(r).setUint8(e,t),e+1}},Ut={len:2,get(r,e){return qn(r).getUint16(e,!0)},put(r,e,t){return qn(r).setUint16(e,t,!0),e+2}},mh={len:2,get(r,e){return qn(r).getUint16(e)},put(r,e,t){return qn(r).setUint16(e,t),e+2}};var Yt={len:4,get(r,e){return qn(r).getUint32(e,!0)},put(r,e,t){return qn(r).setUint32(e,t,!0),e+4}},NU={len:4,get(r,e){return qn(r).getUint32(e)},put(r,e,t){return qn(r).setUint32(e,t),e+4}};var LU={len:4,get(r,e){return qn(r).getInt32(e)},put(r,e,t){return qn(r).setInt32(e,t),e+4}};var BU={len:8,get(r,e){return qn(r).getBigUint64(e,!0)},put(r,e,t){return qn(r).setBigUint64(e,t,!0),e+8}};var zn=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){let n=e.subarray(t,t+this.len);return RU(n,this.encoding)}};var VJ="End-Of-Stream",kt=class extends Error{constructor(){super(VJ),this.name="EndOfStreamError"}},Ou=class extends Error{constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var Du=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let n=await this.read(e,t);return this.peekQueue.push(e.subarray(0,n)),n}async read(e,t=!1){if(e.length===0)return 0;let n=this.readFromPeekBuffer(e);if(this.endOfStream||(n+=await this.readRemainderFromStream(e.subarray(n),t)),n===0&&!t)throw new kt;return n}readFromPeekBuffer(e){let t=e.length,n=0;for(;this.peekQueue.length>0&&t>0;){let o=this.peekQueue.pop();if(!o)throw new Error("peekData should be defined");let i=Math.min(o.length,t);e.set(o.subarray(0,i),n),n+=i,t-=i,i<o.length&&this.peekQueue.push(o.subarray(i))}return n}async readRemainderFromStream(e,t){let n=0;for(;n<e.length&&!this.endOfStream;){if(this.interrupted)throw new Ou;let o=await this.readFromStream(e.subarray(n),t);if(o===0)break;n+=o}if(!t&&n<e.length)throw new kt;return n}};var N8=class extends Du{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}};var N0=class extends N8{async readFromStream(e,t){if(e.length===0)return 0;let n=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return n.done&&(this.endOfStream=n.done),n.value?(e.set(n.value),n.value.length):0}};var gh=class extends Du{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let n=Math.min(t.length,e.length);return e.set(t.subarray(0,n)),n<t.length?this.buffer=t.subarray(n):this.buffer=null,n}async readFromStream(e,t){if(e.length===0)return 0;let n=0;for(this.buffer&&(n+=this.writeChunk(e,this.buffer));n<e.length&&!this.endOfStream;){let o=await this.reader.read();if(o.done){this.endOfStream=!0;break}o.value&&(n+=this.writeChunk(e.subarray(n),o.value))}if(!t&&n===0&&this.endOfStream)throw new kt;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function DS(r){try{let e=r.getReader({mode:"byob"});return e instanceof ReadableStreamDefaultReader?new gh(e):new N0(e)}catch(e){if(e instanceof TypeError)return new gh(r.getReader());throw e}}var ua=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener("abort",()=>{this.abort()})}async readToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.readBuffer(n,{position:t})<e.len)throw new kt;return e.get(n,0)}async peekToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.peekBuffer(n,{position:t})<e.len)throw new kt;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new kt;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new kt;return e.get(this.numBuffer,0)}async ignore(e){if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}};var zJ=256e3,L8=class extends ua{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let n=this.normalizeOptions(e,t),o=n.position-this.position;if(o>0)return await this.ignore(o),this.readBuffer(e,t);if(o<0)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");if(n.length===0)return 0;let i=await this.streamReader.read(e.subarray(0,n.length),n.mayBeLess);if(this.position+=i,(!t||!t.mayBeLess)&&i<n.length)throw new kt;return i}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),o=0;if(n.position){let i=n.position-this.position;if(i>0){let s=new Uint8Array(n.length+i);return o=await this.peekBuffer(s,{mayBeLess:n.mayBeLess}),e.set(s.subarray(i)),o-i}if(i<0)throw new Error("Cannot peek from a negative offset in a stream")}if(n.length>0){try{o=await this.streamReader.peek(e.subarray(0,n.length),n.mayBeLess)}catch(i){if(t?.mayBeLess&&i instanceof kt)return 0;throw i}if(!n.mayBeLess&&o<n.length)throw new kt}return o}async ignore(e){let t=Math.min(zJ,e),n=new Uint8Array(t),o=0;for(;o<e;){let i=e-o,s=await this.readBuffer(n,{length:Math.min(t,i)});if(s<0)return s;o+=s}return o}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}};var B8=class extends ua{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),o=Math.min(this.uint8Array.length-n.position,n.length);if(!n.mayBeLess&&o<n.length)throw new kt;return e.set(this.uint8Array.subarray(n.position,n.position+o)),o}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};var M8=class extends ua{constructor(e,t){super(t),this.blob=e,this.fileInfo={...t?.fileInfo??{},size:e.size,mimeType:e.type}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),o=Math.min(this.blob.size-n.position,n.length);if(!n.mayBeLess&&o<n.length)throw new kt;let i=await this.blob.slice(n.position,n.position+o).arrayBuffer();return e.set(new Uint8Array(i)),o}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function MU(r,e){let t=DS(r),n=e??{},o=n.onClose;return n.onClose=async()=>{if(await t.close(),o)return o()},new L8(t,n)}function UU(r,e){return new B8(r,e)}function FU(r,e){return new M8(r,e)}var GU=gt(qU(),1);var Lu={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},NS={get(r){return{signature:Yt.get(r,0),compressedSize:Yt.get(r,8),uncompressedSize:Yt.get(r,12)}},len:16},zU={get(r){let e=Ut.get(r,6);return{signature:Yt.get(r,0),minVersion:Ut.get(r,4),dataDescriptor:!!(e&8),compressedMethod:Ut.get(r,8),compressedSize:Yt.get(r,18),uncompressedSize:Yt.get(r,22),filenameLength:Ut.get(r,26),extraFieldLength:Ut.get(r,28),filename:null}},len:30},jU={get(r){return{signature:Yt.get(r,0),nrOfThisDisk:Ut.get(r,4),nrOfThisDiskWithTheStart:Ut.get(r,6),nrOfEntriesOnThisDisk:Ut.get(r,8),nrOfEntriesOfSize:Ut.get(r,10),sizeOfCd:Yt.get(r,12),offsetOfStartOfCd:Yt.get(r,16),zipFileCommentLength:Ut.get(r,20)}},len:22},WU={get(r){let e=Ut.get(r,8);return{signature:Yt.get(r,0),minVersion:Ut.get(r,6),dataDescriptor:!!(e&8),compressedMethod:Ut.get(r,10),compressedSize:Yt.get(r,20),uncompressedSize:Yt.get(r,24),filenameLength:Ut.get(r,28),extraFieldLength:Ut.get(r,30),fileCommentLength:Ut.get(r,32),relativeOffsetOfLocalHeader:Yt.get(r,42),filename:null}},len:46};function XU(r){let e=new Uint8Array(Yt.len);return Yt.put(e,0,r),e}var as=(0,GU.default)("tokenizer:inflate"),LS=256*1024,iee=XU(Lu.DataDescriptor),$8=XU(Lu.EndOfCentralDirectory),L0=class r{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(LS)}async isZip(){return await this.peekSignature()===Lu.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(Yt)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16*1024,e.fileInfo.size),n=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(n,{position:e.fileInfo.size-t});for(let o=n.length-4;o>=0;o--)if(n[o]===$8[0]&&n[o+1]===$8[1]&&n[o+2]===$8[2]&&n[o+3]===$8[3])return e.fileInfo.size-t+o;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){as("Cannot reading central-directory without random-read support");return}as("Reading central-directory...");let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){as("Central-directory 32-bit signature found");let n=await this.tokenizer.readToken(jU,t),o=[];this.tokenizer.setPosition(n.offsetOfStartOfCd);for(let i=0;i<n.nrOfEntriesOfSize;++i){let s=await this.tokenizer.readToken(WU);if(s.signature!==Lu.CentralFileHeader)throw new Error("Expected Central-File-Header signature");s.filename=await this.tokenizer.readToken(new zn(s.filenameLength,"utf-8")),await this.tokenizer.ignore(s.extraFieldLength),await this.tokenizer.ignore(s.fileCommentLength),o.push(s),as(`Add central-directory file-entry: n=${i+1}/${o.length}: filename=${o[i].filename}`)}return this.tokenizer.setPosition(e),o}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let n=!1;do{let o=await this.readLocalFileHeader();if(!o)break;let i=e(o);n=!!i.stop;let s;if(await this.tokenizer.ignore(o.extraFieldLength),o.dataDescriptor&&o.compressedSize===0){let a=[],c=LS;as("Compressed-file-size unknown, scanning for next data-descriptor-signature....");let l=-1;for(;l<0&&c===LS;){c=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),l=see(this.syncBuffer.subarray(0,c),iee);let f=l>=0?l:c;if(i.handler){let u=new Uint8Array(f);await this.tokenizer.readBuffer(u),a.push(u)}else await this.tokenizer.ignore(f)}as(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),i.handler&&await this.inflate(o,aee(a),i.handler)}else i.handler?(as(`Reading compressed-file-data: ${o.compressedSize} bytes`),s=new Uint8Array(o.compressedSize),await this.tokenizer.readBuffer(s),await this.inflate(o,s,i.handler)):(as(`Ignoring compressed-file-data: ${o.compressedSize} bytes`),await this.tokenizer.ignore(o.compressedSize));if(as(`Reading data-descriptor at pos=${this.tokenizer.position}`),o.dataDescriptor&&(await this.tokenizer.readToken(NS)).signature!==134695760)throw new Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-NS.len}`)}while(!n)}async iterateOverCentralDirectory(e,t){for(let n of e){let o=t(n);if(o.handler){this.tokenizer.setPosition(n.relativeOffsetOfLocalHeader);let i=await this.readLocalFileHeader();if(i){await this.tokenizer.ignore(i.extraFieldLength);let s=new Uint8Array(n.compressedSize);await this.tokenizer.readBuffer(s),await this.inflate(i,s,o.handler)}}if(o.stop)break}}async inflate(e,t,n){if(e.compressedMethod===0)return n(t);if(e.compressedMethod!==8)throw new Error(`Unsupported ZIP compression method: ${e.compressedMethod}`);as(`Decompress filename=${e.filename}, compressed-size=${t.length}`);let o=await r.decompressDeflateRaw(t);return n(o)}static async decompressDeflateRaw(e){let t=new ReadableStream({start(i){i.enqueue(e),i.close()}}),n=new DecompressionStream("deflate-raw"),o=t.pipeThrough(n);try{let s=await new Response(o).arrayBuffer();return new Uint8Array(s)}catch(i){let s=i instanceof Error?`Failed to deflate ZIP entry: ${i.message}`:"Unknown decompression error in ZIP entry";throw new TypeError(s)}}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(Yt);if(e===Lu.LocalFileHeader){let t=await this.tokenizer.readToken(zU);return t.filename=await this.tokenizer.readToken(new zn(t.filenameLength,"utf-8")),t}if(e===Lu.CentralFileHeader)return!1;throw e===3759263696?new Error("Encrypted ZIP"):new Error("Unexpected signature")}};function see(r,e){let t=r.length,n=e.length;if(n>t)return-1;for(let o=0;o<=t-n;o++){let i=!0;for(let s=0;s<n;s++)if(r[o+s]!==e[s]){i=!1;break}if(i)return o}return-1}function aee(r){let e=r.reduce((o,i)=>o+i.length,0),t=new Uint8Array(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var B0=class{constructor(e){this.tokenizer=e}inflate(){let e=this.tokenizer;return new ReadableStream({async pull(t){let n=new Uint8Array(1024),o=await e.readBuffer(n,{mayBeLess:!0});if(o===0){t.close();return}t.enqueue(n.subarray(0,o))}}).pipeThrough(new DecompressionStream("gzip"))}};var Qnt={utf8:new globalThis.TextDecoder("utf8")};var Znt=new globalThis.TextEncoder;var Jnt=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function BS(r){let{byteLength:e}=r;if(e===6)return r.getUint16(0)*2**32+r.getUint32(2);if(e===5)return r.getUint8(0)*2**32+r.getUint32(1);if(e===4)return r.getUint32(0);if(e===3)return r.getUint8(0)*2**16+r.getUint16(1);if(e===2)return r.getUint16(0);if(e===1)return r.getUint8(0)}function YU(r,e){if(e==="utf-16le"){let t=[];for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);t.push(o&255,o>>8&255)}return t}if(e==="utf-16be"){let t=[];for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);t.push(o>>8&255,o&255)}return t}return[...r].map(t=>t.charCodeAt(0))}function QU(r,e=0){let t=Number.parseInt(new zn(6).get(r,148).replace(/\0.*$/,"").trim(),8);if(Number.isNaN(t))return!1;let n=256;for(let o=e;o<e+148;o++)n+=r[o];for(let o=e+156;o<e+512;o++)n+=r[o];return t===n}var ZU={get:(r,e)=>r[e+3]&127|r[e+2]<<7|r[e+1]<<14|r[e]<<21,len:4};var JU=["jpg","png","apng","gif","webp","flif","xcf","cr2","cr3","orf","arw","dng","nef","rw2","raf","tif","bmp","icns","jxr","psd","indd","zip","tar","rar","gz","bz2","7z","dmg","mp4","mid","mkv","webm","mov","avi","mpg","mp2","mp3","m4a","oga","ogg","ogv","opus","flac","wav","spx","amr","pdf","epub","elf","macho","exe","swf","rtf","wasm","woff","woff2","eot","ttf","otf","ttc","ico","flv","ps","xz","sqlite","nes","crx","xpi","cab","deb","ar","rpm","Z","lz","cfb","mxf","mts","blend","bpg","docx","pptx","xlsx","3gp","3g2","j2c","jp2","jpm","jpx","mj2","aif","qcp","odt","ods","odp","xml","mobi","heic","cur","ktx","ape","wv","dcm","ics","glb","pcap","dsf","lnk","alias","voc","ac3","m4v","m4p","m4b","f4v","f4p","f4b","f4a","mie","asf","ogm","ogx","mpc","arrow","shp","aac","mp1","it","s3m","xm","skp","avif","eps","lzh","pgp","asar","stl","chm","3mf","zst","jxl","vcf","jls","pst","dwg","parquet","class","arj","cpio","ace","avro","icc","fbx","vsdx","vtt","apk","drc","lz4","potx","xltx","dotx","xltm","ott","ots","otp","odg","otg","xlsm","docm","dotm","potm","pptm","jar","rm","ppsm","ppsx","tar.gz","reg","dat"],eF=["image/jpeg","image/png","image/gif","image/webp","image/flif","image/x-xcf","image/x-canon-cr2","image/x-canon-cr3","image/tiff","image/bmp","image/vnd.ms-photo","image/vnd.adobe.photoshop","application/x-indesign","application/epub+zip","application/x-xpinstall","application/vnd.ms-powerpoint.slideshow.macroenabled.12","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.spreadsheet","application/vnd.oasis.opendocument.presentation","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.openxmlformats-officedocument.presentationml.slideshow","application/zip","application/x-tar","application/x-rar-compressed","application/gzip","application/x-bzip2","application/x-7z-compressed","application/x-apple-diskimage","application/vnd.apache.arrow.file","video/mp4","audio/midi","video/matroska","video/webm","video/quicktime","video/vnd.avi","audio/wav","audio/qcelp","audio/x-ms-asf","video/x-ms-asf","application/vnd.ms-asf","video/mpeg","video/3gpp","audio/mpeg","audio/mp4","video/ogg","audio/ogg","audio/ogg; codecs=opus","application/ogg","audio/flac","audio/ape","audio/wavpack","audio/amr","application/pdf","application/x-elf","application/x-mach-binary","application/x-msdownload","application/x-shockwave-flash","application/rtf","application/wasm","font/woff","font/woff2","application/vnd.ms-fontobject","font/ttf","font/otf","font/collection","image/x-icon","video/x-flv","application/postscript","application/eps","application/x-xz","application/x-sqlite3","application/x-nintendo-nes-rom","application/x-google-chrome-extension","application/vnd.ms-cab-compressed","application/x-deb","application/x-unix-archive","application/x-rpm","application/x-compress","application/x-lzip","application/x-cfb","application/x-mie","application/mxf","video/mp2t","application/x-blender","image/bpg","image/j2c","image/jp2","image/jpx","image/jpm","image/mj2","audio/aiff","application/xml","application/x-mobipocket-ebook","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/icns","image/ktx","application/dicom","audio/x-musepack","text/calendar","text/vcard","text/vtt","model/gltf-binary","application/vnd.tcpdump.pcap","audio/x-dsf","application/x.ms.shortcut","application/x.apple.alias","audio/x-voc","audio/vnd.dolby.dd-raw","audio/x-m4a","image/apng","image/x-olympus-orf","image/x-sony-arw","image/x-adobe-dng","image/x-nikon-nef","image/x-panasonic-rw2","image/x-fujifilm-raf","video/x-m4v","video/3gpp2","application/x-esri-shape","audio/aac","audio/x-it","audio/x-s3m","audio/x-xm","video/MP1S","video/MP2P","application/vnd.sketchup.skp","image/avif","application/x-lzh-compressed","application/pgp-encrypted","application/x-asar","model/stl","application/vnd.ms-htmlhelp","model/3mf","image/jxl","application/zstd","image/jls","application/vnd.ms-outlook","image/vnd.dwg","application/vnd.apache.parquet","application/java-vm","application/x-arj","application/x-cpio","application/x-ace-compressed","application/avro","application/vnd.iccprofile","application/x.autodesk.fbx","application/vnd.visio","application/vnd.android.package-archive","application/vnd.google.draco","application/x-lz4","application/vnd.openxmlformats-officedocument.presentationml.template","application/vnd.openxmlformats-officedocument.spreadsheetml.template","application/vnd.openxmlformats-officedocument.wordprocessingml.template","application/vnd.ms-excel.template.macroenabled.12","application/vnd.oasis.opendocument.text-template","application/vnd.oasis.opendocument.spreadsheet-template","application/vnd.oasis.opendocument.presentation-template","application/vnd.oasis.opendocument.graphics","application/vnd.oasis.opendocument.graphics-template","application/vnd.ms-excel.sheet.macroenabled.12","application/vnd.ms-word.document.macroenabled.12","application/vnd.ms-word.template.macroenabled.12","application/vnd.ms-powerpoint.template.macroenabled.12","application/vnd.ms-powerpoint.presentation.macroenabled.12","application/java-archive","application/vnd.rn-realmedia","application/x-ms-regedit","application/x-ft-windows-registry-hive"];var MS=4100;async function tF(r,e){return new FS(e).fromBuffer(r)}function US(r){switch(r=r.toLowerCase(),r){case"application/epub+zip":return{ext:"epub",mime:r};case"application/vnd.oasis.opendocument.text":return{ext:"odt",mime:r};case"application/vnd.oasis.opendocument.text-template":return{ext:"ott",mime:r};case"application/vnd.oasis.opendocument.spreadsheet":return{ext:"ods",mime:r};case"application/vnd.oasis.opendocument.spreadsheet-template":return{ext:"ots",mime:r};case"application/vnd.oasis.opendocument.presentation":return{ext:"odp",mime:r};case"application/vnd.oasis.opendocument.presentation-template":return{ext:"otp",mime:r};case"application/vnd.oasis.opendocument.graphics":return{ext:"odg",mime:r};case"application/vnd.oasis.opendocument.graphics-template":return{ext:"otg",mime:r};case"application/vnd.openxmlformats-officedocument.presentationml.slideshow":return{ext:"ppsx",mime:r};case"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":return{ext:"xlsx",mime:r};case"application/vnd.ms-excel.sheet.macroenabled":return{ext:"xlsm",mime:"application/vnd.ms-excel.sheet.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.spreadsheetml.template":return{ext:"xltx",mime:r};case"application/vnd.ms-excel.template.macroenabled":return{ext:"xltm",mime:"application/vnd.ms-excel.template.macroenabled.12"};case"application/vnd.ms-powerpoint.slideshow.macroenabled":return{ext:"ppsm",mime:"application/vnd.ms-powerpoint.slideshow.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.document":return{ext:"docx",mime:r};case"application/vnd.ms-word.document.macroenabled":return{ext:"docm",mime:"application/vnd.ms-word.document.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.template":return{ext:"dotx",mime:r};case"application/vnd.ms-word.template.macroenabledtemplate":return{ext:"dotm",mime:"application/vnd.ms-word.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.template":return{ext:"potx",mime:r};case"application/vnd.ms-powerpoint.template.macroenabled":return{ext:"potm",mime:"application/vnd.ms-powerpoint.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.presentation":return{ext:"pptx",mime:r};case"application/vnd.ms-powerpoint.presentation.macroenabled":return{ext:"pptm",mime:"application/vnd.ms-powerpoint.presentation.macroenabled.12"};case"application/vnd.ms-visio.drawing":return{ext:"vsdx",mime:"application/vnd.visio"};case"application/vnd.ms-package.3dmanufacturing-3dmodel+xml":return{ext:"3mf",mime:"model/3mf"};default:}}function cs(r,e,t){t={offset:0,...t};for(let[n,o]of e.entries())if(t.mask){if(o!==(t.mask[n]&r[n+t.offset]))return!1}else if(o!==r[n+t.offset])return!1;return!0}var FS=class{constructor(e){this.options={mpegOffsetTolerance:0,...e},this.detectors=[...e?.customDetectors??[],{id:"core",detect:this.detectConfident},{id:"core.imprecise",detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:e?.signal}}async fromTokenizer(e){let t=e.position;for(let n of this.detectors){let o=await n.detect(e);if(o)return o;if(t!==e.position)return}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t?.length>1)return this.fromTokenizer(UU(t,this.tokenizerOptions))}async fromBlob(e){let t=FU(e,this.tokenizerOptions);try{return await this.fromTokenizer(t)}finally{await t.close()}}async fromStream(e){let t=MU(e,this.tokenizerOptions);try{return await this.fromTokenizer(t)}finally{await t.close()}}async toDetectionStream(e,t){let{sampleSize:n=MS}=t,o,i,s=e.getReader({mode:"byob"});try{let{value:l,done:f}=await s.read(new Uint8Array(n));if(i=l,!f&&l)try{o=await this.fromBuffer(l.subarray(0,n))}catch(u){if(!(u instanceof kt))throw u;o=void 0}i=l}finally{s.releaseLock()}let a=new TransformStream({async start(l){l.enqueue(i)},transform(l,f){f.enqueue(l)}}),c=e.pipeThrough(a);return c.fileType=o,c}check(e,t){return cs(this.buffer,e,t)}checkString(e,t){return this.check(YU(e,t?.encoding),t)}detectConfident=async e=>{if(this.buffer=new Uint8Array(MS),e.fileInfo.size===void 0&&(e.fileInfo.size=Number.MAX_SAFE_INTEGER),this.tokenizer=e,await e.peekBuffer(this.buffer,{length:32,mayBeLess:!0}),this.check([66,77]))return{ext:"bmp",mime:"image/bmp"};if(this.check([11,119]))return{ext:"ac3",mime:"audio/vnd.dolby.dd-raw"};if(this.check([120,1]))return{ext:"dmg",mime:"application/x-apple-diskimage"};if(this.check([77,90]))return{ext:"exe",mime:"application/x-msdownload"};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString("PS-Adobe-",{offset:2})&&this.checkString(" EPSF-",{offset:14})?{ext:"eps",mime:"application/eps"}:{ext:"ps",mime:"application/postscript"};if(this.check([31,160])||this.check([31,157]))return{ext:"Z",mime:"application/x-compress"};if(this.check([199,113]))return{ext:"cpio",mime:"application/x-cpio"};if(this.check([96,234]))return{ext:"arj",mime:"application/x-arj"};if(this.check([239,187,191]))return this.tokenizer.ignore(3),this.detectConfident(e);if(this.check([71,73,70]))return{ext:"gif",mime:"image/gif"};if(this.check([73,73,188]))return{ext:"jxr",mime:"image/vnd.ms-photo"};if(this.check([31,139,8])){let n=new B0(e).inflate(),o=!0;try{let i;try{i=await this.fromStream(n)}catch{o=!1}if(i&&i.ext==="tar")return{ext:"tar.gz",mime:"application/gzip"}}finally{o&&await n.cancel()}return{ext:"gz",mime:"application/gzip"}}if(this.check([66,90,104]))return{ext:"bz2",mime:"application/x-bzip2"};if(this.checkString("ID3")){await e.ignore(6);let t=await e.readToken(ZU);return e.position+t>e.fileInfo.size?{ext:"mp3",mime:"audio/mpeg"}:(await e.ignore(t),this.fromTokenizer(e))}if(this.checkString("MP+"))return{ext:"mpc",mime:"audio/x-musepack"};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:"swf",mime:"application/x-shockwave-flash"};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:"jls",mime:"image/jls"}:{ext:"jpg",mime:"image/jpeg"};if(this.check([79,98,106,1]))return{ext:"avro",mime:"application/avro"};if(this.checkString("FLIF"))return{ext:"flif",mime:"image/flif"};if(this.checkString("8BPS"))return{ext:"psd",mime:"image/vnd.adobe.photoshop"};if(this.checkString("MPCK"))return{ext:"mpc",mime:"audio/x-musepack"};if(this.checkString("FORM"))return{ext:"aif",mime:"audio/aiff"};if(this.checkString("icns",{offset:0}))return{ext:"icns",mime:"image/icns"};if(this.check([80,75,3,4])){let t;return await new L0(e).unzip(n=>{switch(n.filename){case"META-INF/mozilla.rsa":return t={ext:"xpi",mime:"application/x-xpinstall"},{stop:!0};case"META-INF/MANIFEST.MF":return t={ext:"jar",mime:"application/java-archive"},{stop:!0};case"mimetype":return{async handler(o){let i=new TextDecoder("utf-8").decode(o).trim();t=US(i)},stop:!0};case"[Content_Types].xml":return{async handler(o){let i=new TextDecoder("utf-8").decode(o),s=i.indexOf('.main+xml"');if(s===-1){let a="application/vnd.ms-package.3dmanufacturing-3dmodel+xml";i.includes(`ContentType="${a}"`)&&(t=US(a))}else{i=i.slice(0,Math.max(0,s));let a=i.lastIndexOf('"'),c=i.slice(Math.max(0,a+1));t=US(c)}},stop:!0};default:return/classes\d*\.dex/.test(n.filename)?(t={ext:"apk",mime:"application/vnd.android.package-archive"},{stop:!0}):{}}}).catch(n=>{if(!(n instanceof kt))throw n}),t??{ext:"zip",mime:"application/zip"}}if(this.checkString("OggS")){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),cs(t,[79,112,117,115,72,101,97,100])?{ext:"opus",mime:"audio/ogg; codecs=opus"}:cs(t,[128,116,104,101,111,114,97])?{ext:"ogv",mime:"video/ogg"}:cs(t,[1,118,105,100,101,111,0])?{ext:"ogm",mime:"video/ogg"}:cs(t,[127,70,76,65,67])?{ext:"oga",mime:"audio/ogg"}:cs(t,[83,112,101,101,120,32,32])?{ext:"spx",mime:"audio/ogg"}:cs(t,[1,118,111,114,98,105,115])?{ext:"ogg",mime:"audio/ogg"}:{ext:"ogx",mime:"application/ogg"}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:"zip",mime:"application/zip"};if(this.checkString("MThd"))return{ext:"mid",mime:"audio/midi"};if(this.checkString("wOFF")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff",mime:"font/woff"};if(this.checkString("wOF2")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff2",mime:"font/woff2"};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:"pcap",mime:"application/vnd.tcpdump.pcap"};if(this.checkString("DSD "))return{ext:"dsf",mime:"audio/x-dsf"};if(this.checkString("LZIP"))return{ext:"lz",mime:"application/x-lzip"};if(this.checkString("fLaC"))return{ext:"flac",mime:"audio/flac"};if(this.check([66,80,71,251]))return{ext:"bpg",mime:"image/bpg"};if(this.checkString("wvpk"))return{ext:"wv",mime:"audio/wavpack"};if(this.checkString("%PDF"))return{ext:"pdf",mime:"application/pdf"};if(this.check([0,97,115,109]))return{ext:"wasm",mime:"application/wasm"};if(this.check([73,73])){let t=await this.readTiffHeader(!1);if(t)return t}if(this.check([77,77])){let t=await this.readTiffHeader(!0);if(t)return t}if(this.checkString("MAC "))return{ext:"ape",mime:"audio/ape"};if(this.check([26,69,223,163])){async function t(){let a=await e.peekNumber(DU),c=128,l=0;for(;(a&c)===0&&c!==0;)++l,c>>=1;let f=new Uint8Array(l+1);return await e.readBuffer(f),f}async function n(){let a=await t(),c=await t();c[0]^=128>>c.length-1;let l=Math.min(6,c.length),f=new DataView(a.buffer),u=new DataView(c.buffer,c.length-l,l);return{id:BS(f),len:BS(u)}}async function o(a){for(;a>0;){let c=await n();if(c.id===17026)return(await e.readToken(new zn(c.len))).replaceAll(/\00.*$/g,"");await e.ignore(c.len),--a}}let i=await n();switch(await o(i.len)){case"webm":return{ext:"webm",mime:"video/webm"};case"matroska":return{ext:"mkv",mime:"video/matroska"};default:return}}if(this.checkString("SQLi"))return{ext:"sqlite",mime:"application/x-sqlite3"};if(this.check([78,69,83,26]))return{ext:"nes",mime:"application/x-nintendo-nes-rom"};if(this.checkString("Cr24"))return{ext:"crx",mime:"application/x-google-chrome-extension"};if(this.checkString("MSCF")||this.checkString("ISc("))return{ext:"cab",mime:"application/vnd.ms-cab-compressed"};if(this.check([237,171,238,219]))return{ext:"rpm",mime:"application/x-rpm"};if(this.check([197,208,211,198]))return{ext:"eps",mime:"application/eps"};if(this.check([40,181,47,253]))return{ext:"zst",mime:"application/zstd"};if(this.check([127,69,76,70]))return{ext:"elf",mime:"application/x-elf"};if(this.check([33,66,68,78]))return{ext:"pst",mime:"application/vnd.ms-outlook"};if(this.checkString("PAR1")||this.checkString("PARE"))return{ext:"parquet",mime:"application/vnd.apache.parquet"};if(this.checkString("ttcf"))return{ext:"ttc",mime:"font/collection"};if(this.check([207,250,237,254]))return{ext:"macho",mime:"application/x-mach-binary"};if(this.check([4,34,77,24]))return{ext:"lz4",mime:"application/x-lz4"};if(this.checkString("regf"))return{ext:"dat",mime:"application/x-ft-windows-registry-hive"};if(this.check([79,84,84,79,0]))return{ext:"otf",mime:"font/otf"};if(this.checkString("#!AMR"))return{ext:"amr",mime:"audio/amr"};if(this.checkString("{\\rtf"))return{ext:"rtf",mime:"application/rtf"};if(this.check([70,76,86,1]))return{ext:"flv",mime:"video/x-flv"};if(this.checkString("IMPM"))return{ext:"it",mime:"audio/x-it"};if(this.checkString("-lh0-",{offset:2})||this.checkString("-lh1-",{offset:2})||this.checkString("-lh2-",{offset:2})||this.checkString("-lh3-",{offset:2})||this.checkString("-lh4-",{offset:2})||this.checkString("-lh5-",{offset:2})||this.checkString("-lh6-",{offset:2})||this.checkString("-lh7-",{offset:2})||this.checkString("-lzs-",{offset:2})||this.checkString("-lz4-",{offset:2})||this.checkString("-lz5-",{offset:2})||this.checkString("-lhd-",{offset:2}))return{ext:"lzh",mime:"application/x-lzh-compressed"};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:"mpg",mime:"video/MP1S"};if(this.check([68],{offset:4,mask:[196]}))return{ext:"mpg",mime:"video/MP2P"}}if(this.checkString("ITSF"))return{ext:"chm",mime:"application/vnd.ms-htmlhelp"};if(this.check([202,254,186,190]))return{ext:"class",mime:"application/java-vm"};if(this.checkString(".RMF"))return{ext:"rm",mime:"application/vnd.rn-realmedia"};if(this.checkString("DRACO"))return{ext:"drc",mime:"application/vnd.google.draco"};if(this.check([253,55,122,88,90,0]))return{ext:"xz",mime:"application/x-xz"};if(this.checkString("<?xml "))return{ext:"xml",mime:"application/xml"};if(this.check([55,122,188,175,39,28]))return{ext:"7z",mime:"application/x-7z-compressed"};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:"rar",mime:"application/x-rar-compressed"};if(this.checkString("solid "))return{ext:"stl",mime:"model/stl"};if(this.checkString("AC")){let t=new zn(4,"latin1").get(this.buffer,2);if(t.match("^d*")&&t>=1e3&&t<=1050)return{ext:"dwg",mime:"image/vnd.dwg"}}if(this.checkString("070707"))return{ext:"cpio",mime:"application/x-cpio"};if(this.checkString("BLENDER"))return{ext:"blend",mime:"application/x-blender"};if(this.checkString("!<arch>"))return await e.ignore(8),await e.readToken(new zn(13,"ascii"))==="debian-binary"?{ext:"deb",mime:"application/x-deb"}:{ext:"ar",mime:"application/x-unix-archive"};if(this.checkString("WEBVTT")&&[`
|
|
116
|
+
`));return D(e)}function I8(r){let e=new Uint8Array(512),t=r.name,n="";if(r.typeflag===5&&t[t.length-1]!=="/"&&(t+="/"),D(t).byteLength!==t.length)return null;for(;D(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 D(t).byteLength>100||D(n).byteLength>155||r.linkname!=null&&D(r.linkname).byteLength>100?null:(e.set(D(t),0),e.set(Cc(r.mode&sJ,6),100),e.set(Cc(r.uid,6),108),e.set(Cc(r.gid,6),116),e.set(Cc(r.size,11),124),e.set(Cc(r.mtime.getTime()/1e3|0,11),136),e[156]=nJ+lJ(r.type),r.linkname!=null&&e.set(D(r.linkname),157),e.set(oJ,aJ),e.set(iJ,cJ),r.uname!=null&&e.set(D(r.uname),265),r.gname!=null&&e.set(D(r.gname),297),e.set(Cc(r.devmajor??0,6),329),e.set(Cc(r.devminor??0,6),337),n!=null&&e.set(D(n),345),e.set(Cc(uJ(e),6),148),e)}var{S_IFMT:dJ,S_IFBLK:hJ,S_IFCHR:pJ,S_IFDIR:mJ,S_IFIFO:gJ,S_IFLNK:yJ}=bU.default,wJ=parseInt("755",8),xJ=parseInt("644",8),vU=new Uint8Array(1024);function bJ(r=0){switch(r&dJ){case hJ:return"block-device";case pJ:return"character-device";case mJ:return"directory";case gJ:return"fifo";case yJ:return"symlink";default:return"file"}}function PS(r){return r&=511,r!==0?vU.subarray(0,512-r):new Uint8Array(0)}function kS(r){if(r.pax==null){let e=I8(r);if(e!=null)return e}return vJ(r)}function vJ(r){let e=xU(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 se(I8(t)??new Uint8Array(0),e,PS(e.length),I8({...t,size:r.size,type:r.type})??new Uint8Array(0)).subarray()}function k8(){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??bJ(e.mode),mode:e.mode??(e.type==="directory"?wJ:xJ),uid:e.uid??0,gid:e.gid??0,mtime:e.mtime??new Date};if(typeof t=="string"&&(t=D(t)),t instanceof Uint8Array||Eo(t)){n.size=t.length,yield kS(n),yield Eo(t)?t.subarray():t,yield PS(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=H(await Ge(t)),yield kS(n);continue}if(yield kS(n),n.type!=="file"&&n.type!=="contiguous-file")continue;let o=0;for await(let i of t??[])o+=i.length,yield Eo(i)?i.subarray():i;if(o!==n.size)throw new Error(`size mismatch, wrote ${o} of ${n.size} bytes`);yield PS(n.size)}yield vU}}var EJ=["file","raw","directory"];function SJ(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 EU(r){if(!EJ.includes(r.type))throw new Ru(`${r.type} is not a UnixFS node`);let e={header:SJ(r)};return(r.type==="file"||r.type==="raw")&&(e.body=r.content()),e}async function*SU(r,e,t){let n=await C0(r,e,t);if(n.type==="file"||n.type==="raw"){yield*ln([EU(n)],k8());return}if(n.type==="directory"){yield*ln(nU(r,e,t),o=>Kt(o,i=>EU(i)),k8());return}throw new Ru("Not a UnixFS node")}var P8=class extends Vn{id="tar-plugin";codes=[];canHandle({accept:e}){return e.some(t=>t.contentType.mediaType===fh)}async handle(e){let{terminalElement:t,url:n,resource:o,options:i,blockstore:s,range:a}=e;if(t.cid.code!==pt&&t.cid.code!==rt)return Kn(o,new Ru("Only UnixFS data can be returned in a TAR file"));if(a!=null)return Kn(o,new Error("Range requests are not supported for TAR files"));let c=Lo(SU(`/ipfs/${t.cid}${n.pathname}`,s,i));return _i(o,c,{headers:{"content-type":fh,"content-disposition":`attachment; ${zo(n.searchParams.get("filename")??`${t.cid.toString()}.tar`)}`,"accept-ranges":"none"}})}};function AJ(r,e,t){let n;try{n=new URL(r)}catch{n=e}if(t?.type==="directory"&&!n.pathname.endsWith("/"))return n.pathname+="/",n.toString()}var R8=class extends Vn{id="unixfs-plugin";codes=[pt,rt];canHandle({terminalElement:e,accept:t}){let n=this.codes.includes(e.cid.code),o=t.length===0||t.some(i=>i.contentType.mediaType===Kr||i.contentType.mediaType===I0);return n&&o}async handle(e){let{url:t,resource:n,terminalElement:o,ipfsRoots:i}=e,s=t.searchParams.get("filename")??o.name,a;if(o.type==="directory"){let c=AJ(n,t,o);if(c!=null){if(this.log.trace("directory url normalization spec requires redirect"),e.options?.redirect==="error")throw this.log('could not redirect to %s as redirect option was set to "error"',c),new TypeError("Failed to fetch");if(e.options?.redirect==="manual")return this.log("returning 301 permanent redirect to %s",c),pU(e.resource,c);this.log("following redirect to %s",c),n=c,a=!0}let l=o.cid;if(e.options?.supportDirectoryIndexes!==!1){let u="index.html";try{this.log.trace("found directory at %c/%s, looking for index.html",l,t.pathname);let h=await e.serverTiming.time("exporter-dir","",C0(`/ipfs/${l}/${u}`,e.blockstore,e.options));return h.type==="directory"||h.type==="object"?hh(n,"Unable to stream content"):(s=u,this.log.trace("found directory index at %c/%s with cid %c",l,u,h.cid),await this.streamFile(n,h,s,a,e.range,e.options))}catch(h){if(h.name!=="NotFoundError")throw this.log.error("error loading path %c/%s - %e",l,u,h),h}}let f=await Ge(e.blockstore.get(l,e.options));return _i(n,f,{headers:{"content-type":I0,"content-length":`${f.byteLength}`,"content-disposition":`${t.searchParams.get("download")==="true"?"attachment":"inline"}; ${zo(`${l}.dir`)}`,"x-ipfs-roots":i.map(u=>u.toV1()).join(","),"accept-ranges":"bytes"},redirected:a})}else return o.type==="file"||o.type==="raw"||o.type==="identity"?(this.log("streaming file"),this.streamFile(n,o,s,a,e.range,e.options)):(this.log.error("cannot stream terminal element type %s",o.type),hh(n,"Unable to stream content"))}async streamFile(e,t,n,o,i,s){let a=Kr;return i==null&&(a=await this.detectContentType(t,n,s)),i!=null?v8(e,(c,l)=>t.content({...s??{},offset:c,length:l}),i,t.size,{headers:{"content-type":a,"content-disposition":`inline; ${zo(n)}`,"x-ipfs-roots":t.cid.toString(),"accept-ranges":"bytes"},redirected:o}):_i(e,Lo(t.content(s)),{headers:{"content-type":a,"content-length":`${t.size}`,"content-disposition":`inline; ${zo(n)}`,"x-ipfs-roots":t.cid.toString(),"accept-ranges":"bytes"},redirected:o})}async detectContentType(e,t,n){let o;if(e.type==="raw"||e.type==="identity"?o=e.node:o=await Py(e.content(n)),o==null)throw new Error("stream ended before first block was read");let i;if(this.pluginOptions.contentTypeParser!=null)try{let s=this.pluginOptions.contentTypeParser(o,t);if(yf(s)){let a=await s;a!=null&&(i=a)}else s!=null&&(i=s);this.log.trace("contentTypeParser returned %s for file with name %s",i,t)}catch(s){this.log.error("error parsing content type - %e",s)}return i??Kr}};var D0=class extends Map{#t=0;#e=new Map;#r=new Map;#s;#c;#a;constructor(e={}){if(super(),!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if(typeof e.maxAge=="number"&&e.maxAge===0)throw new TypeError("`maxAge` must be a number greater than 0");this.#s=e.maxSize,this.#c=e.maxAge||Number.POSITIVE_INFINITY,this.#a=e.onEviction}get __oldCache(){return this.#r}#l(e){if(typeof this.#a=="function")for(let[t,n]of e)this.#a(t,n.value)}#n(e,t){return typeof t.expiry=="number"&&t.expiry<=Date.now()?(typeof this.#a=="function"&&this.#a(e,t.value),this.delete(e)):!1}#d(e,t){if(this.#n(e,t)===!1)return t.value}#u(e,t){return t.expiry?this.#d(e,t):t.value}#f(e,t){let n=t.get(e);return this.#u(e,n)}#o(e,t){this.#e.set(e,t),this.#t++,this.#t>=this.#s&&(this.#t=0,this.#l(this.#r),this.#r=this.#e,this.#e=new Map)}#h(e,t){this.#r.delete(e),this.#o(e,t)}*#i(){for(let e of this.#r){let[t,n]=e;this.#e.has(t)||this.#n(t,n)===!1&&(yield e)}for(let e of this.#e){let[t,n]=e;this.#n(t,n)===!1&&(yield e)}}get(e){if(this.#e.has(e)){let t=this.#e.get(e);return this.#u(e,t)}if(this.#r.has(e)){let t=this.#r.get(e);if(this.#n(e,t)===!1)return this.#h(e,t),t.value}}set(e,t,{maxAge:n=this.#c}={}){let o=typeof n=="number"&&n!==Number.POSITIVE_INFINITY?Date.now()+n:void 0;return this.#e.has(e)?this.#e.set(e,{value:t,expiry:o}):this.#o(e,{value:t,expiry:o}),this}has(e){return this.#e.has(e)?!this.#n(e,this.#e.get(e)):this.#r.has(e)?!this.#n(e,this.#r.get(e)):!1}peek(e){if(this.#e.has(e))return this.#f(e,this.#e);if(this.#r.has(e))return this.#f(e,this.#r)}expiresIn(e){let t=this.#e.get(e)??this.#r.get(e);if(t)return t.expiry?t.expiry-Date.now():Number.POSITIVE_INFINITY}delete(e){let t=this.#e.delete(e);return t&&this.#t--,this.#r.delete(e)||t}clear(){this.#e.clear(),this.#r.clear(),this.#t=0}resize(e){if(!(e&&e>0))throw new TypeError("`maxSize` must be a number greater than 0");let t=[...this.#i()],n=t.length-e;n<0?(this.#e=new Map(t),this.#r=new Map,this.#t=t.length):(n>0&&this.#l(t.slice(0,n)),this.#r=new Map(t.slice(n)),this.#e=new Map,this.#t=0),this.#s=e}evict(e=1){let t=Number(e);if(!t||t<=0)return;let n=[...this.#i()],o=Math.trunc(Math.min(t,Math.max(n.length-1,0)));o<=0||(this.#l(n.slice(0,o)),this.#r=new Map(n.slice(o)),this.#e=new Map,this.#t=0)}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let e of this.#e){let[t,n]=e;this.#n(t,n)===!1&&(yield[t,n.value])}for(let e of this.#r){let[t,n]=e;this.#e.has(t)||this.#n(t,n)===!1&&(yield[t,n.value])}}*entriesDescending(){let e=[...this.#e];for(let t=e.length-1;t>=0;--t){let n=e[t],[o,i]=n;this.#n(o,i)===!1&&(yield[o,i.value])}e=[...this.#r];for(let t=e.length-1;t>=0;--t){let n=e[t],[o,i]=n;this.#e.has(o)||this.#n(o,i)===!1&&(yield[o,i.value])}}*entriesAscending(){for(let[e,t]of this.#i())yield[e,t.value]}get size(){if(!this.#t)return this.#r.size;let e=0;for(let t of this.#r.keys())this.#e.has(t)||e++;return Math.min(this.#t+e,this.#s)}get maxSize(){return this.#s}get maxAge(){return this.#c}entries(){return this.entriesAscending()}forEach(e,t=this){for(let[n,o]of this.entriesAscending())e.call(t,o,n,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}};var _J=/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;function AU(r){return _J.test(r)&&r.includes("-")&&!r.includes(".")}function _U(r){return r.replace(/--/g,"%").replace(/-/g,".").replace(/%/g,"-")}function TU(r){if(!r.startsWith("/ipfs/")&&!r.startsWith("/ipns/"))throw new O(`Path ${r} did not start with /ipfs/ or /ipns/`);let e=r.indexOf("#"),t="";e>-1&&(t=r.substring(e),r=r.substring(0,e));let n=r.indexOf("?"),o="";n>-1&&(o=r.substring(n),r=r.substring(0,n));let i=r.substring(1,5),s=r.substring(6);return`https://example.org/${i}/${s}${o}${t}`}function CU(r){if(!r.startsWith("ipfs://")&&!r.startsWith("ipns://"))throw new O(`URL ${r} did not start with ipfs:// or ipns://`);let e=r.substring(0,4),t=r.substring(7);return`https://example.org/${e}/${t}`}var TJ=/^(?<cidOrPeerIdOrDnsLink>[^/?]+)\.(?<protocol>ip[fn]s)\.([^/?]+)$/,CJ=114;function IJ(r){let e=r?.protocol;return!(e!=="ipfs"&&e!=="ipns"||r?.cidOrPeerIdOrDnsLink==null)}function kJ(r,e){let t=e.toLowerCase().indexOf(r);return t===-1?r:e.substring(t,t+r.length)}function PJ(r){if(r instanceof URL)return r;if((r.startsWith("/ipfs/")||r.startsWith("/ipns/"))&&(r=TU(r)),(r.startsWith("ipfs://")||r.startsWith("ipns://"))&&(r=CU(r)),r.startsWith("http://")||r.startsWith("https://"))return new URL(r);throw new O(`Invalid URL: ${r}`)}function RJ(r){let e=PJ(r),t=e.hostname.match(TJ);if(IJ(t?.groups)){let n=t.groups;n.protocol==="ipns"&&AU(n.cidOrPeerIdOrDnsLink)&&(n.cidOrPeerIdOrDnsLink=_U(n.cidOrPeerIdOrDnsLink));let o=kJ(n.cidOrPeerIdOrDnsLink,r),i=new URL(`not-${r}`);return new URL(`${n.protocol}://${o}${i.pathname}${e.search}${e.hash}`)}if(e.pathname.startsWith("/ipfs/")){let o=e.pathname.substring(6).split("/").shift();if(o==null)throw new O(`Path gateway URL ${r} had no CID`);return new URL(`ipfs://${o}${e.pathname.replace(`/ipfs/${o}`,"")}${e.search}${e.hash}`)}if(e.pathname.startsWith("/ipns/")){let o=e.pathname.substring(6).split("/").shift();if(o==null)throw new O(`Path gateway URL ${r} had no name`);return new URL(`ipns://${o}${e.pathname.replace(`/ipns/${o}`,"")}${e.search}${e.hash}`)}throw new TypeError(`Invalid URL: ${r}, please use ipfs://, ipns://, or gateway URLs only`)}function O8(r){let e=RJ(r);if(e.protocol==="ipns:")try{ze(e.hostname)}catch{e.protocol="dnslink:"}if(e.protocol==="ipfs:"){let t=Z.parse(e.hostname);if(t.code===CJ)return new URL(`ipns://${oo(t)}${e.pathname}${e.search}${e.hash}`)}return e}function IU(r){let e=Z.asCID(r);if(e!=null)return`ipfs://${e}`;try{return`ipfs://${Z.parse(r.toString())}`}catch{}let{protocol:t,host:n}=O8(r.toString());return`${t}//${n}`}var ph=class{headers;constructor(){this.headers=[]}getHeader(){return this.headers.join(",")}async time(e,t,n){let o=performance.now();try{return await n}finally{let s=(performance.now()-o).toFixed(1);this.headers.push(`${e};dur=${s};desc="${t}"`)}}};var OJ=29030400,DJ=[81,lr,rt],NJ=[pt,fr,dr,rt];function kU(r,e,t){return{name:e.toString(),path:e.toString(),depth:0,type:r,node:t,cid:e,size:BigInt(t.byteLength),content:async function*(){yield t}}}var D8=class{components;blockstoreSessions;constructor(e,t={}){this.components=e,this.blockstoreSessions=new D0({maxSize:t.sessionCacheSize??100,maxAge:t.sessionTTLms??6e4,onEviction:(n,o)=>{o.close()}})}async resolve(e,t=new ph,n={}){if(e.protocol==="ipfs:")return this.resolveIPFSPath(e,t,n);if(e.protocol==="ipns:")return this.resolveIPNSName(e,t,n);if(e.protocol==="dnslink:")return this.resolveDNSLink(e,t,n);throw new ca(`Invalid resource. Unsupported protocol in URL, must be ipfs:, ipns:, or dnslink: ${e}`)}getBlockstore(e,t={}){if(t.session===!1)return this.components.helia.blockstore;let n=IU(e),o=this.blockstoreSessions.get(n);return o==null&&(o=this.components.helia.blockstore.createSession(e,t),this.blockstoreSessions.set(n,o)),o}async resolveDNSLink(e,t,n){let i=(await t.time("dnsLink.resolve",`Resolve DNSLink ${e.hostname}`,this.components.dnsLink.resolve(e.hostname,n)))?.[0];if(i==null)throw new TypeError(`Invalid resource. Cannot resolve DNSLink from domain: ${e.hostname}`);if(i.namespace==="ipns")return this.resolveIPNSName(e,t,n);if(i.namespace!=="ipfs")throw new TypeError(`Invalid resource. Unexpected DNSLink namespace ${i.namespace} from domain: ${domain}`);i.path!=null&&e.pathname!==""&&e.pathname;let s=new URL(`ipfs://${i.cid}/${e.pathname}`);return{...await this.resolveIPFSPath(s,t,n),url:e,ttl:i.answer.TTL}}async resolveIPNSName(e,t,n){let o=ze(e.hostname),i=await t.time("ipns.resolve",`Resolve IPNS name ${o}`,this.components.ipnsResolver.resolve(o,n));i.path!=null&&e.pathname!==""&&e.pathname;let s=new URL(`ipfs://${i.cid}/${e.pathname}`);return{...await this.resolveIPFSPath(s,t,n),url:e,ttl:Number((i.record.ttl??0n)/BigInt(1e9))}}async resolveIPFSPath(e,t,n){let o=await t.time("ipfs.resolve","",this.walkPath(e,n));return{...o,url:e,ttl:OJ,blockstore:o.blockstore}}async walkPath(e,t={}){let n=Z.parse(e.hostname),o=this.getBlockstore(n,t);if(NJ.includes(n.code)){let s=[],a,c=LJ(e);for await(let l of ES(c,o,{...t,offline:t.onlyIfCached===!0,extended:t.isRawBlockRequest!==!0}))s.push(l.cid),a=l;if(a==null)throw new C8("No terminal element found");return{ipfsRoots:s,terminalElement:a,blockstore:o}}let i;return n.multihash.code===0?i=n.multihash.digest:i=await Ge(o.get(n,t)),DJ.includes(n.code)?{ipfsRoots:[n],terminalElement:kU("object",n,i),blockstore:o}:{ipfsRoots:[n],terminalElement:kU("raw",n,i),blockstore:o}}};function LJ(r){return`/ipfs/${r.hostname}${decodeURI(r.pathname)}`}var OU=gt(PU(),1);var OS={128:"\u20AC",130:"\u201A",131:"\u0192",132:"\u201E",133:"\u2026",134:"\u2020",135:"\u2021",136:"\u02C6",137:"\u2030",138:"\u0160",139:"\u2039",140:"\u0152",142:"\u017D",145:"\u2018",146:"\u2019",147:"\u201C",148:"\u201D",149:"\u2022",150:"\u2013",151:"\u2014",152:"\u02DC",153:"\u2122",154:"\u0161",155:"\u203A",156:"\u0153",158:"\u017E",159:"\u0178"},BJ={};for(let[r,e]of Object.entries(OS))BJ[e]=Number.parseInt(r);function RU(r,e="utf-8"){switch(e.toLowerCase()){case"utf-8":case"utf8":return typeof globalThis.TextDecoder<"u"?new globalThis.TextDecoder("utf-8").decode(r):MJ(r);case"utf-16le":return UJ(r);case"ascii":return FJ(r);case"latin1":case"iso-8859-1":return $J(r);case"windows-1252":return HJ(r);default:throw new RangeError(`Encoding '${e}' not supported`)}}function MJ(r){let e="",t=0;for(;t<r.length;){let n=r[t++];if(n<128)e+=String.fromCharCode(n);else if(n<224){let o=r[t++]&63;e+=String.fromCharCode((n&31)<<6|o)}else if(n<240){let o=r[t++]&63,i=r[t++]&63;e+=String.fromCharCode((n&15)<<12|o<<6|i)}else{let o=r[t++]&63,i=r[t++]&63,s=r[t++]&63,a=(n&7)<<18|o<<12|i<<6|s;a-=65536,e+=String.fromCharCode(55296+(a>>10&1023),56320+(a&1023))}}return e}function UJ(r){let e="";for(let t=0;t<r.length;t+=2)e+=String.fromCharCode(r[t]|r[t+1]<<8);return e}function FJ(r){return String.fromCharCode(...r.map(e=>e&127))}function $J(r){return String.fromCharCode(...r)}function HJ(r){let e="";for(let t of r)t>=128&&t<=159&&OS[t]?e+=OS[t]:e+=String.fromCharCode(t);return e}function qn(r){return new DataView(r.buffer,r.byteOffset)}var DU={len:1,get(r,e){return qn(r).getUint8(e)},put(r,e,t){return qn(r).setUint8(e,t),e+1}},Ut={len:2,get(r,e){return qn(r).getUint16(e,!0)},put(r,e,t){return qn(r).setUint16(e,t,!0),e+2}},mh={len:2,get(r,e){return qn(r).getUint16(e)},put(r,e,t){return qn(r).setUint16(e,t),e+2}};var Yt={len:4,get(r,e){return qn(r).getUint32(e,!0)},put(r,e,t){return qn(r).setUint32(e,t,!0),e+4}},NU={len:4,get(r,e){return qn(r).getUint32(e)},put(r,e,t){return qn(r).setUint32(e,t),e+4}};var LU={len:4,get(r,e){return qn(r).getInt32(e)},put(r,e,t){return qn(r).setInt32(e,t),e+4}};var BU={len:8,get(r,e){return qn(r).getBigUint64(e,!0)},put(r,e,t){return qn(r).setBigUint64(e,t,!0),e+8}};var zn=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){let n=e.subarray(t,t+this.len);return RU(n,this.encoding)}};var VJ="End-Of-Stream",kt=class extends Error{constructor(){super(VJ),this.name="EndOfStreamError"}},Ou=class extends Error{constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var Du=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let n=await this.read(e,t);return this.peekQueue.push(e.subarray(0,n)),n}async read(e,t=!1){if(e.length===0)return 0;let n=this.readFromPeekBuffer(e);if(this.endOfStream||(n+=await this.readRemainderFromStream(e.subarray(n),t)),n===0&&!t)throw new kt;return n}readFromPeekBuffer(e){let t=e.length,n=0;for(;this.peekQueue.length>0&&t>0;){let o=this.peekQueue.pop();if(!o)throw new Error("peekData should be defined");let i=Math.min(o.length,t);e.set(o.subarray(0,i),n),n+=i,t-=i,i<o.length&&this.peekQueue.push(o.subarray(i))}return n}async readRemainderFromStream(e,t){let n=0;for(;n<e.length&&!this.endOfStream;){if(this.interrupted)throw new Ou;let o=await this.readFromStream(e.subarray(n),t);if(o===0)break;n+=o}if(!t&&n<e.length)throw new kt;return n}};var N8=class extends Du{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}};var N0=class extends N8{async readFromStream(e,t){if(e.length===0)return 0;let n=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return n.done&&(this.endOfStream=n.done),n.value?(e.set(n.value),n.value.length):0}};var gh=class extends Du{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let n=Math.min(t.length,e.length);return e.set(t.subarray(0,n)),n<t.length?this.buffer=t.subarray(n):this.buffer=null,n}async readFromStream(e,t){if(e.length===0)return 0;let n=0;for(this.buffer&&(n+=this.writeChunk(e,this.buffer));n<e.length&&!this.endOfStream;){let o=await this.reader.read();if(o.done){this.endOfStream=!0;break}o.value&&(n+=this.writeChunk(e.subarray(n),o.value))}if(!t&&n===0&&this.endOfStream)throw new kt;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function DS(r){try{let e=r.getReader({mode:"byob"});return e instanceof ReadableStreamDefaultReader?new gh(e):new N0(e)}catch(e){if(e instanceof TypeError)return new gh(r.getReader());throw e}}var ua=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener("abort",()=>{this.abort()})}async readToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.readBuffer(n,{position:t})<e.len)throw new kt;return e.get(n,0)}async peekToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.peekBuffer(n,{position:t})<e.len)throw new kt;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new kt;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new kt;return e.get(this.numBuffer,0)}async ignore(e){if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}};var zJ=256e3,L8=class extends ua{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let n=this.normalizeOptions(e,t),o=n.position-this.position;if(o>0)return await this.ignore(o),this.readBuffer(e,t);if(o<0)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");if(n.length===0)return 0;let i=await this.streamReader.read(e.subarray(0,n.length),n.mayBeLess);if(this.position+=i,(!t||!t.mayBeLess)&&i<n.length)throw new kt;return i}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),o=0;if(n.position){let i=n.position-this.position;if(i>0){let s=new Uint8Array(n.length+i);return o=await this.peekBuffer(s,{mayBeLess:n.mayBeLess}),e.set(s.subarray(i)),o-i}if(i<0)throw new Error("Cannot peek from a negative offset in a stream")}if(n.length>0){try{o=await this.streamReader.peek(e.subarray(0,n.length),n.mayBeLess)}catch(i){if(t?.mayBeLess&&i instanceof kt)return 0;throw i}if(!n.mayBeLess&&o<n.length)throw new kt}return o}async ignore(e){let t=Math.min(zJ,e),n=new Uint8Array(t),o=0;for(;o<e;){let i=e-o,s=await this.readBuffer(n,{length:Math.min(t,i)});if(s<0)return s;o+=s}return o}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}};var B8=class extends ua{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),o=Math.min(this.uint8Array.length-n.position,n.length);if(!n.mayBeLess&&o<n.length)throw new kt;return e.set(this.uint8Array.subarray(n.position,n.position+o)),o}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};var M8=class extends ua{constructor(e,t){super(t),this.blob=e,this.fileInfo={...t?.fileInfo??{},size:e.size,mimeType:e.type}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),o=Math.min(this.blob.size-n.position,n.length);if(!n.mayBeLess&&o<n.length)throw new kt;let i=await this.blob.slice(n.position,n.position+o).arrayBuffer();return e.set(new Uint8Array(i)),o}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function MU(r,e){let t=DS(r),n=e??{},o=n.onClose;return n.onClose=async()=>{if(await t.close(),o)return o()},new L8(t,n)}function UU(r,e){return new B8(r,e)}function FU(r,e){return new M8(r,e)}var GU=gt(qU(),1);var Lu={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},NS={get(r){return{signature:Yt.get(r,0),compressedSize:Yt.get(r,8),uncompressedSize:Yt.get(r,12)}},len:16},zU={get(r){let e=Ut.get(r,6);return{signature:Yt.get(r,0),minVersion:Ut.get(r,4),dataDescriptor:!!(e&8),compressedMethod:Ut.get(r,8),compressedSize:Yt.get(r,18),uncompressedSize:Yt.get(r,22),filenameLength:Ut.get(r,26),extraFieldLength:Ut.get(r,28),filename:null}},len:30},jU={get(r){return{signature:Yt.get(r,0),nrOfThisDisk:Ut.get(r,4),nrOfThisDiskWithTheStart:Ut.get(r,6),nrOfEntriesOnThisDisk:Ut.get(r,8),nrOfEntriesOfSize:Ut.get(r,10),sizeOfCd:Yt.get(r,12),offsetOfStartOfCd:Yt.get(r,16),zipFileCommentLength:Ut.get(r,20)}},len:22},WU={get(r){let e=Ut.get(r,8);return{signature:Yt.get(r,0),minVersion:Ut.get(r,6),dataDescriptor:!!(e&8),compressedMethod:Ut.get(r,10),compressedSize:Yt.get(r,20),uncompressedSize:Yt.get(r,24),filenameLength:Ut.get(r,28),extraFieldLength:Ut.get(r,30),fileCommentLength:Ut.get(r,32),relativeOffsetOfLocalHeader:Yt.get(r,42),filename:null}},len:46};function XU(r){let e=new Uint8Array(Yt.len);return Yt.put(e,0,r),e}var as=(0,GU.default)("tokenizer:inflate"),LS=256*1024,iee=XU(Lu.DataDescriptor),$8=XU(Lu.EndOfCentralDirectory),L0=class r{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(LS)}async isZip(){return await this.peekSignature()===Lu.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(Yt)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16*1024,e.fileInfo.size),n=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(n,{position:e.fileInfo.size-t});for(let o=n.length-4;o>=0;o--)if(n[o]===$8[0]&&n[o+1]===$8[1]&&n[o+2]===$8[2]&&n[o+3]===$8[3])return e.fileInfo.size-t+o;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){as("Cannot reading central-directory without random-read support");return}as("Reading central-directory...");let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){as("Central-directory 32-bit signature found");let n=await this.tokenizer.readToken(jU,t),o=[];this.tokenizer.setPosition(n.offsetOfStartOfCd);for(let i=0;i<n.nrOfEntriesOfSize;++i){let s=await this.tokenizer.readToken(WU);if(s.signature!==Lu.CentralFileHeader)throw new Error("Expected Central-File-Header signature");s.filename=await this.tokenizer.readToken(new zn(s.filenameLength,"utf-8")),await this.tokenizer.ignore(s.extraFieldLength),await this.tokenizer.ignore(s.fileCommentLength),o.push(s),as(`Add central-directory file-entry: n=${i+1}/${o.length}: filename=${o[i].filename}`)}return this.tokenizer.setPosition(e),o}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let n=!1;do{let o=await this.readLocalFileHeader();if(!o)break;let i=e(o);n=!!i.stop;let s;if(await this.tokenizer.ignore(o.extraFieldLength),o.dataDescriptor&&o.compressedSize===0){let a=[],c=LS;as("Compressed-file-size unknown, scanning for next data-descriptor-signature....");let l=-1;for(;l<0&&c===LS;){c=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),l=see(this.syncBuffer.subarray(0,c),iee);let f=l>=0?l:c;if(i.handler){let u=new Uint8Array(f);await this.tokenizer.readBuffer(u),a.push(u)}else await this.tokenizer.ignore(f)}as(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),i.handler&&await this.inflate(o,aee(a),i.handler)}else i.handler?(as(`Reading compressed-file-data: ${o.compressedSize} bytes`),s=new Uint8Array(o.compressedSize),await this.tokenizer.readBuffer(s),await this.inflate(o,s,i.handler)):(as(`Ignoring compressed-file-data: ${o.compressedSize} bytes`),await this.tokenizer.ignore(o.compressedSize));if(as(`Reading data-descriptor at pos=${this.tokenizer.position}`),o.dataDescriptor&&(await this.tokenizer.readToken(NS)).signature!==134695760)throw new Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-NS.len}`)}while(!n)}async iterateOverCentralDirectory(e,t){for(let n of e){let o=t(n);if(o.handler){this.tokenizer.setPosition(n.relativeOffsetOfLocalHeader);let i=await this.readLocalFileHeader();if(i){await this.tokenizer.ignore(i.extraFieldLength);let s=new Uint8Array(n.compressedSize);await this.tokenizer.readBuffer(s),await this.inflate(i,s,o.handler)}}if(o.stop)break}}async inflate(e,t,n){if(e.compressedMethod===0)return n(t);if(e.compressedMethod!==8)throw new Error(`Unsupported ZIP compression method: ${e.compressedMethod}`);as(`Decompress filename=${e.filename}, compressed-size=${t.length}`);let o=await r.decompressDeflateRaw(t);return n(o)}static async decompressDeflateRaw(e){let t=new ReadableStream({start(i){i.enqueue(e),i.close()}}),n=new DecompressionStream("deflate-raw"),o=t.pipeThrough(n);try{let s=await new Response(o).arrayBuffer();return new Uint8Array(s)}catch(i){let s=i instanceof Error?`Failed to deflate ZIP entry: ${i.message}`:"Unknown decompression error in ZIP entry";throw new TypeError(s)}}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(Yt);if(e===Lu.LocalFileHeader){let t=await this.tokenizer.readToken(zU);return t.filename=await this.tokenizer.readToken(new zn(t.filenameLength,"utf-8")),t}if(e===Lu.CentralFileHeader)return!1;throw e===3759263696?new Error("Encrypted ZIP"):new Error("Unexpected signature")}};function see(r,e){let t=r.length,n=e.length;if(n>t)return-1;for(let o=0;o<=t-n;o++){let i=!0;for(let s=0;s<n;s++)if(r[o+s]!==e[s]){i=!1;break}if(i)return o}return-1}function aee(r){let e=r.reduce((o,i)=>o+i.length,0),t=new Uint8Array(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var B0=class{constructor(e){this.tokenizer=e}inflate(){let e=this.tokenizer;return new ReadableStream({async pull(t){let n=new Uint8Array(1024),o=await e.readBuffer(n,{mayBeLess:!0});if(o===0){t.close();return}t.enqueue(n.subarray(0,o))}}).pipeThrough(new DecompressionStream("gzip"))}};var Qnt={utf8:new globalThis.TextDecoder("utf8")};var Znt=new globalThis.TextEncoder;var Jnt=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function BS(r){let{byteLength:e}=r;if(e===6)return r.getUint16(0)*2**32+r.getUint32(2);if(e===5)return r.getUint8(0)*2**32+r.getUint32(1);if(e===4)return r.getUint32(0);if(e===3)return r.getUint8(0)*2**16+r.getUint16(1);if(e===2)return r.getUint16(0);if(e===1)return r.getUint8(0)}function YU(r,e){if(e==="utf-16le"){let t=[];for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);t.push(o&255,o>>8&255)}return t}if(e==="utf-16be"){let t=[];for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);t.push(o>>8&255,o&255)}return t}return[...r].map(t=>t.charCodeAt(0))}function QU(r,e=0){let t=Number.parseInt(new zn(6).get(r,148).replace(/\0.*$/,"").trim(),8);if(Number.isNaN(t))return!1;let n=256;for(let o=e;o<e+148;o++)n+=r[o];for(let o=e+156;o<e+512;o++)n+=r[o];return t===n}var ZU={get:(r,e)=>r[e+3]&127|r[e+2]<<7|r[e+1]<<14|r[e]<<21,len:4};var JU=["jpg","png","apng","gif","webp","flif","xcf","cr2","cr3","orf","arw","dng","nef","rw2","raf","tif","bmp","icns","jxr","psd","indd","zip","tar","rar","gz","bz2","7z","dmg","mp4","mid","mkv","webm","mov","avi","mpg","mp2","mp3","m4a","oga","ogg","ogv","opus","flac","wav","spx","amr","pdf","epub","elf","macho","exe","swf","rtf","wasm","woff","woff2","eot","ttf","otf","ttc","ico","flv","ps","xz","sqlite","nes","crx","xpi","cab","deb","ar","rpm","Z","lz","cfb","mxf","mts","blend","bpg","docx","pptx","xlsx","3gp","3g2","j2c","jp2","jpm","jpx","mj2","aif","qcp","odt","ods","odp","xml","mobi","heic","cur","ktx","ape","wv","dcm","ics","glb","pcap","dsf","lnk","alias","voc","ac3","m4v","m4p","m4b","f4v","f4p","f4b","f4a","mie","asf","ogm","ogx","mpc","arrow","shp","aac","mp1","it","s3m","xm","skp","avif","eps","lzh","pgp","asar","stl","chm","3mf","zst","jxl","vcf","jls","pst","dwg","parquet","class","arj","cpio","ace","avro","icc","fbx","vsdx","vtt","apk","drc","lz4","potx","xltx","dotx","xltm","ott","ots","otp","odg","otg","xlsm","docm","dotm","potm","pptm","jar","rm","ppsm","ppsx","tar.gz","reg","dat"],eF=["image/jpeg","image/png","image/gif","image/webp","image/flif","image/x-xcf","image/x-canon-cr2","image/x-canon-cr3","image/tiff","image/bmp","image/vnd.ms-photo","image/vnd.adobe.photoshop","application/x-indesign","application/epub+zip","application/x-xpinstall","application/vnd.ms-powerpoint.slideshow.macroenabled.12","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.spreadsheet","application/vnd.oasis.opendocument.presentation","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.openxmlformats-officedocument.presentationml.slideshow","application/zip","application/x-tar","application/x-rar-compressed","application/gzip","application/x-bzip2","application/x-7z-compressed","application/x-apple-diskimage","application/vnd.apache.arrow.file","video/mp4","audio/midi","video/matroska","video/webm","video/quicktime","video/vnd.avi","audio/wav","audio/qcelp","audio/x-ms-asf","video/x-ms-asf","application/vnd.ms-asf","video/mpeg","video/3gpp","audio/mpeg","audio/mp4","video/ogg","audio/ogg","audio/ogg; codecs=opus","application/ogg","audio/flac","audio/ape","audio/wavpack","audio/amr","application/pdf","application/x-elf","application/x-mach-binary","application/x-msdownload","application/x-shockwave-flash","application/rtf","application/wasm","font/woff","font/woff2","application/vnd.ms-fontobject","font/ttf","font/otf","font/collection","image/x-icon","video/x-flv","application/postscript","application/eps","application/x-xz","application/x-sqlite3","application/x-nintendo-nes-rom","application/x-google-chrome-extension","application/vnd.ms-cab-compressed","application/x-deb","application/x-unix-archive","application/x-rpm","application/x-compress","application/x-lzip","application/x-cfb","application/x-mie","application/mxf","video/mp2t","application/x-blender","image/bpg","image/j2c","image/jp2","image/jpx","image/jpm","image/mj2","audio/aiff","application/xml","application/x-mobipocket-ebook","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/icns","image/ktx","application/dicom","audio/x-musepack","text/calendar","text/vcard","text/vtt","model/gltf-binary","application/vnd.tcpdump.pcap","audio/x-dsf","application/x.ms.shortcut","application/x.apple.alias","audio/x-voc","audio/vnd.dolby.dd-raw","audio/x-m4a","image/apng","image/x-olympus-orf","image/x-sony-arw","image/x-adobe-dng","image/x-nikon-nef","image/x-panasonic-rw2","image/x-fujifilm-raf","video/x-m4v","video/3gpp2","application/x-esri-shape","audio/aac","audio/x-it","audio/x-s3m","audio/x-xm","video/MP1S","video/MP2P","application/vnd.sketchup.skp","image/avif","application/x-lzh-compressed","application/pgp-encrypted","application/x-asar","model/stl","application/vnd.ms-htmlhelp","model/3mf","image/jxl","application/zstd","image/jls","application/vnd.ms-outlook","image/vnd.dwg","application/vnd.apache.parquet","application/java-vm","application/x-arj","application/x-cpio","application/x-ace-compressed","application/avro","application/vnd.iccprofile","application/x.autodesk.fbx","application/vnd.visio","application/vnd.android.package-archive","application/vnd.google.draco","application/x-lz4","application/vnd.openxmlformats-officedocument.presentationml.template","application/vnd.openxmlformats-officedocument.spreadsheetml.template","application/vnd.openxmlformats-officedocument.wordprocessingml.template","application/vnd.ms-excel.template.macroenabled.12","application/vnd.oasis.opendocument.text-template","application/vnd.oasis.opendocument.spreadsheet-template","application/vnd.oasis.opendocument.presentation-template","application/vnd.oasis.opendocument.graphics","application/vnd.oasis.opendocument.graphics-template","application/vnd.ms-excel.sheet.macroenabled.12","application/vnd.ms-word.document.macroenabled.12","application/vnd.ms-word.template.macroenabled.12","application/vnd.ms-powerpoint.template.macroenabled.12","application/vnd.ms-powerpoint.presentation.macroenabled.12","application/java-archive","application/vnd.rn-realmedia","application/x-ms-regedit","application/x-ft-windows-registry-hive"];var MS=4100;async function tF(r,e){return new FS(e).fromBuffer(r)}function US(r){switch(r=r.toLowerCase(),r){case"application/epub+zip":return{ext:"epub",mime:r};case"application/vnd.oasis.opendocument.text":return{ext:"odt",mime:r};case"application/vnd.oasis.opendocument.text-template":return{ext:"ott",mime:r};case"application/vnd.oasis.opendocument.spreadsheet":return{ext:"ods",mime:r};case"application/vnd.oasis.opendocument.spreadsheet-template":return{ext:"ots",mime:r};case"application/vnd.oasis.opendocument.presentation":return{ext:"odp",mime:r};case"application/vnd.oasis.opendocument.presentation-template":return{ext:"otp",mime:r};case"application/vnd.oasis.opendocument.graphics":return{ext:"odg",mime:r};case"application/vnd.oasis.opendocument.graphics-template":return{ext:"otg",mime:r};case"application/vnd.openxmlformats-officedocument.presentationml.slideshow":return{ext:"ppsx",mime:r};case"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":return{ext:"xlsx",mime:r};case"application/vnd.ms-excel.sheet.macroenabled":return{ext:"xlsm",mime:"application/vnd.ms-excel.sheet.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.spreadsheetml.template":return{ext:"xltx",mime:r};case"application/vnd.ms-excel.template.macroenabled":return{ext:"xltm",mime:"application/vnd.ms-excel.template.macroenabled.12"};case"application/vnd.ms-powerpoint.slideshow.macroenabled":return{ext:"ppsm",mime:"application/vnd.ms-powerpoint.slideshow.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.document":return{ext:"docx",mime:r};case"application/vnd.ms-word.document.macroenabled":return{ext:"docm",mime:"application/vnd.ms-word.document.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.template":return{ext:"dotx",mime:r};case"application/vnd.ms-word.template.macroenabledtemplate":return{ext:"dotm",mime:"application/vnd.ms-word.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.template":return{ext:"potx",mime:r};case"application/vnd.ms-powerpoint.template.macroenabled":return{ext:"potm",mime:"application/vnd.ms-powerpoint.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.presentation":return{ext:"pptx",mime:r};case"application/vnd.ms-powerpoint.presentation.macroenabled":return{ext:"pptm",mime:"application/vnd.ms-powerpoint.presentation.macroenabled.12"};case"application/vnd.ms-visio.drawing":return{ext:"vsdx",mime:"application/vnd.visio"};case"application/vnd.ms-package.3dmanufacturing-3dmodel+xml":return{ext:"3mf",mime:"model/3mf"};default:}}function cs(r,e,t){t={offset:0,...t};for(let[n,o]of e.entries())if(t.mask){if(o!==(t.mask[n]&r[n+t.offset]))return!1}else if(o!==r[n+t.offset])return!1;return!0}var FS=class{constructor(e){this.options={mpegOffsetTolerance:0,...e},this.detectors=[...e?.customDetectors??[],{id:"core",detect:this.detectConfident},{id:"core.imprecise",detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:e?.signal}}async fromTokenizer(e){let t=e.position;for(let n of this.detectors){let o=await n.detect(e);if(o)return o;if(t!==e.position)return}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t?.length>1)return this.fromTokenizer(UU(t,this.tokenizerOptions))}async fromBlob(e){let t=FU(e,this.tokenizerOptions);try{return await this.fromTokenizer(t)}finally{await t.close()}}async fromStream(e){let t=MU(e,this.tokenizerOptions);try{return await this.fromTokenizer(t)}finally{await t.close()}}async toDetectionStream(e,t){let{sampleSize:n=MS}=t,o,i,s=e.getReader({mode:"byob"});try{let{value:l,done:f}=await s.read(new Uint8Array(n));if(i=l,!f&&l)try{o=await this.fromBuffer(l.subarray(0,n))}catch(u){if(!(u instanceof kt))throw u;o=void 0}i=l}finally{s.releaseLock()}let a=new TransformStream({async start(l){l.enqueue(i)},transform(l,f){f.enqueue(l)}}),c=e.pipeThrough(a);return c.fileType=o,c}check(e,t){return cs(this.buffer,e,t)}checkString(e,t){return this.check(YU(e,t?.encoding),t)}detectConfident=async e=>{if(this.buffer=new Uint8Array(MS),e.fileInfo.size===void 0&&(e.fileInfo.size=Number.MAX_SAFE_INTEGER),this.tokenizer=e,await e.peekBuffer(this.buffer,{length:32,mayBeLess:!0}),this.check([66,77]))return{ext:"bmp",mime:"image/bmp"};if(this.check([11,119]))return{ext:"ac3",mime:"audio/vnd.dolby.dd-raw"};if(this.check([120,1]))return{ext:"dmg",mime:"application/x-apple-diskimage"};if(this.check([77,90]))return{ext:"exe",mime:"application/x-msdownload"};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString("PS-Adobe-",{offset:2})&&this.checkString(" EPSF-",{offset:14})?{ext:"eps",mime:"application/eps"}:{ext:"ps",mime:"application/postscript"};if(this.check([31,160])||this.check([31,157]))return{ext:"Z",mime:"application/x-compress"};if(this.check([199,113]))return{ext:"cpio",mime:"application/x-cpio"};if(this.check([96,234]))return{ext:"arj",mime:"application/x-arj"};if(this.check([239,187,191]))return this.tokenizer.ignore(3),this.detectConfident(e);if(this.check([71,73,70]))return{ext:"gif",mime:"image/gif"};if(this.check([73,73,188]))return{ext:"jxr",mime:"image/vnd.ms-photo"};if(this.check([31,139,8])){let n=new B0(e).inflate(),o=!0;try{let i;try{i=await this.fromStream(n)}catch{o=!1}if(i&&i.ext==="tar")return{ext:"tar.gz",mime:"application/gzip"}}finally{o&&await n.cancel()}return{ext:"gz",mime:"application/gzip"}}if(this.check([66,90,104]))return{ext:"bz2",mime:"application/x-bzip2"};if(this.checkString("ID3")){await e.ignore(6);let t=await e.readToken(ZU);return e.position+t>e.fileInfo.size?{ext:"mp3",mime:"audio/mpeg"}:(await e.ignore(t),this.fromTokenizer(e))}if(this.checkString("MP+"))return{ext:"mpc",mime:"audio/x-musepack"};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:"swf",mime:"application/x-shockwave-flash"};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:"jls",mime:"image/jls"}:{ext:"jpg",mime:"image/jpeg"};if(this.check([79,98,106,1]))return{ext:"avro",mime:"application/avro"};if(this.checkString("FLIF"))return{ext:"flif",mime:"image/flif"};if(this.checkString("8BPS"))return{ext:"psd",mime:"image/vnd.adobe.photoshop"};if(this.checkString("MPCK"))return{ext:"mpc",mime:"audio/x-musepack"};if(this.checkString("FORM"))return{ext:"aif",mime:"audio/aiff"};if(this.checkString("icns",{offset:0}))return{ext:"icns",mime:"image/icns"};if(this.check([80,75,3,4])){let t;return await new L0(e).unzip(n=>{switch(n.filename){case"META-INF/mozilla.rsa":return t={ext:"xpi",mime:"application/x-xpinstall"},{stop:!0};case"META-INF/MANIFEST.MF":return t={ext:"jar",mime:"application/java-archive"},{stop:!0};case"mimetype":return{async handler(o){let i=new TextDecoder("utf-8").decode(o).trim();t=US(i)},stop:!0};case"[Content_Types].xml":return{async handler(o){let i=new TextDecoder("utf-8").decode(o),s=i.indexOf('.main+xml"');if(s===-1){let a="application/vnd.ms-package.3dmanufacturing-3dmodel+xml";i.includes(`ContentType="${a}"`)&&(t=US(a))}else{i=i.slice(0,Math.max(0,s));let a=i.lastIndexOf('"'),c=i.slice(Math.max(0,a+1));t=US(c)}},stop:!0};default:return/classes\d*\.dex/.test(n.filename)?(t={ext:"apk",mime:"application/vnd.android.package-archive"},{stop:!0}):{}}}).catch(n=>{if(!(n instanceof kt))throw n}),t??{ext:"zip",mime:"application/zip"}}if(this.checkString("OggS")){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),cs(t,[79,112,117,115,72,101,97,100])?{ext:"opus",mime:"audio/ogg; codecs=opus"}:cs(t,[128,116,104,101,111,114,97])?{ext:"ogv",mime:"video/ogg"}:cs(t,[1,118,105,100,101,111,0])?{ext:"ogm",mime:"video/ogg"}:cs(t,[127,70,76,65,67])?{ext:"oga",mime:"audio/ogg"}:cs(t,[83,112,101,101,120,32,32])?{ext:"spx",mime:"audio/ogg"}:cs(t,[1,118,111,114,98,105,115])?{ext:"ogg",mime:"audio/ogg"}:{ext:"ogx",mime:"application/ogg"}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:"zip",mime:"application/zip"};if(this.checkString("MThd"))return{ext:"mid",mime:"audio/midi"};if(this.checkString("wOFF")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff",mime:"font/woff"};if(this.checkString("wOF2")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff2",mime:"font/woff2"};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:"pcap",mime:"application/vnd.tcpdump.pcap"};if(this.checkString("DSD "))return{ext:"dsf",mime:"audio/x-dsf"};if(this.checkString("LZIP"))return{ext:"lz",mime:"application/x-lzip"};if(this.checkString("fLaC"))return{ext:"flac",mime:"audio/flac"};if(this.check([66,80,71,251]))return{ext:"bpg",mime:"image/bpg"};if(this.checkString("wvpk"))return{ext:"wv",mime:"audio/wavpack"};if(this.checkString("%PDF"))return{ext:"pdf",mime:"application/pdf"};if(this.check([0,97,115,109]))return{ext:"wasm",mime:"application/wasm"};if(this.check([73,73])){let t=await this.readTiffHeader(!1);if(t)return t}if(this.check([77,77])){let t=await this.readTiffHeader(!0);if(t)return t}if(this.checkString("MAC "))return{ext:"ape",mime:"audio/ape"};if(this.check([26,69,223,163])){async function t(){let a=await e.peekNumber(DU),c=128,l=0;for(;(a&c)===0&&c!==0;)++l,c>>=1;let f=new Uint8Array(l+1);return await e.readBuffer(f),f}async function n(){let a=await t(),c=await t();c[0]^=128>>c.length-1;let l=Math.min(6,c.length),f=new DataView(a.buffer),u=new DataView(c.buffer,c.length-l,l);return{id:BS(f),len:BS(u)}}async function o(a){for(;a>0;){let c=await n();if(c.id===17026)return(await e.readToken(new zn(c.len))).replaceAll(/\00.*$/g,"");await e.ignore(c.len),--a}}let i=await n();switch(await o(i.len)){case"webm":return{ext:"webm",mime:"video/webm"};case"matroska":return{ext:"mkv",mime:"video/matroska"};default:return}}if(this.checkString("SQLi"))return{ext:"sqlite",mime:"application/x-sqlite3"};if(this.check([78,69,83,26]))return{ext:"nes",mime:"application/x-nintendo-nes-rom"};if(this.checkString("Cr24"))return{ext:"crx",mime:"application/x-google-chrome-extension"};if(this.checkString("MSCF")||this.checkString("ISc("))return{ext:"cab",mime:"application/vnd.ms-cab-compressed"};if(this.check([237,171,238,219]))return{ext:"rpm",mime:"application/x-rpm"};if(this.check([197,208,211,198]))return{ext:"eps",mime:"application/eps"};if(this.check([40,181,47,253]))return{ext:"zst",mime:"application/zstd"};if(this.check([127,69,76,70]))return{ext:"elf",mime:"application/x-elf"};if(this.check([33,66,68,78]))return{ext:"pst",mime:"application/vnd.ms-outlook"};if(this.checkString("PAR1")||this.checkString("PARE"))return{ext:"parquet",mime:"application/vnd.apache.parquet"};if(this.checkString("ttcf"))return{ext:"ttc",mime:"font/collection"};if(this.check([207,250,237,254]))return{ext:"macho",mime:"application/x-mach-binary"};if(this.check([4,34,77,24]))return{ext:"lz4",mime:"application/x-lz4"};if(this.checkString("regf"))return{ext:"dat",mime:"application/x-ft-windows-registry-hive"};if(this.check([79,84,84,79,0]))return{ext:"otf",mime:"font/otf"};if(this.checkString("#!AMR"))return{ext:"amr",mime:"audio/amr"};if(this.checkString("{\\rtf"))return{ext:"rtf",mime:"application/rtf"};if(this.check([70,76,86,1]))return{ext:"flv",mime:"video/x-flv"};if(this.checkString("IMPM"))return{ext:"it",mime:"audio/x-it"};if(this.checkString("-lh0-",{offset:2})||this.checkString("-lh1-",{offset:2})||this.checkString("-lh2-",{offset:2})||this.checkString("-lh3-",{offset:2})||this.checkString("-lh4-",{offset:2})||this.checkString("-lh5-",{offset:2})||this.checkString("-lh6-",{offset:2})||this.checkString("-lh7-",{offset:2})||this.checkString("-lzs-",{offset:2})||this.checkString("-lz4-",{offset:2})||this.checkString("-lz5-",{offset:2})||this.checkString("-lhd-",{offset:2}))return{ext:"lzh",mime:"application/x-lzh-compressed"};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:"mpg",mime:"video/MP1S"};if(this.check([68],{offset:4,mask:[196]}))return{ext:"mpg",mime:"video/MP2P"}}if(this.checkString("ITSF"))return{ext:"chm",mime:"application/vnd.ms-htmlhelp"};if(this.check([202,254,186,190]))return{ext:"class",mime:"application/java-vm"};if(this.checkString(".RMF"))return{ext:"rm",mime:"application/vnd.rn-realmedia"};if(this.checkString("DRACO"))return{ext:"drc",mime:"application/vnd.google.draco"};if(this.check([253,55,122,88,90,0]))return{ext:"xz",mime:"application/x-xz"};if(this.checkString("<?xml "))return{ext:"xml",mime:"application/xml"};if(this.check([55,122,188,175,39,28]))return{ext:"7z",mime:"application/x-7z-compressed"};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:"rar",mime:"application/x-rar-compressed"};if(this.checkString("solid "))return{ext:"stl",mime:"model/stl"};if(this.checkString("AC")){let t=new zn(4,"latin1").get(this.buffer,2);if(t.match("^d*")&&t>=1e3&&t<=1050)return{ext:"dwg",mime:"image/vnd.dwg"}}if(this.checkString("070707"))return{ext:"cpio",mime:"application/x-cpio"};if(this.checkString("BLENDER"))return{ext:"blend",mime:"application/x-blender"};if(this.checkString("!<arch>"))return await e.ignore(8),await e.readToken(new zn(13,"ascii"))==="debian-binary"?{ext:"deb",mime:"application/x-deb"}:{ext:"ar",mime:"application/x-unix-archive"};if(this.checkString("WEBVTT")&&[`
|
|
117
117
|
`,"\r"," "," ","\0"].some(t=>this.checkString(t,{offset:6})))return{ext:"vtt",mime:"text/vtt"};if(this.check([137,80,78,71,13,10,26,10])){await e.ignore(8);async function t(){return{length:await e.readToken(LU),type:await e.readToken(new zn(4,"latin1"))}}do{let n=await t();if(n.length<0)return;switch(n.type){case"IDAT":return{ext:"png",mime:"image/png"};case"acTL":return{ext:"apng",mime:"image/apng"};default:await e.ignore(n.length+4)}}while(e.position+8<e.fileInfo.size);return{ext:"png",mime:"image/png"}}if(this.check([65,82,82,79,87,49,0,0]))return{ext:"arrow",mime:"application/vnd.apache.arrow.file"};if(this.check([103,108,84,70,2,0,0,0]))return{ext:"glb",mime:"model/gltf-binary"};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:"mov",mime:"video/quicktime"};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:"orf",mime:"image/x-olympus-orf"};if(this.checkString("gimp xcf "))return{ext:"xcf",mime:"image/x-xcf"};if(this.checkString("ftyp",{offset:4})&&(this.buffer[8]&96)!==0){let t=new zn(4,"latin1").get(this.buffer,8).replace("\0"," ").trim();switch(t){case"avif":case"avis":return{ext:"avif",mime:"image/avif"};case"mif1":return{ext:"heic",mime:"image/heif"};case"msf1":return{ext:"heic",mime:"image/heif-sequence"};case"heic":case"heix":return{ext:"heic",mime:"image/heic"};case"hevc":case"hevx":return{ext:"heic",mime:"image/heic-sequence"};case"qt":return{ext:"mov",mime:"video/quicktime"};case"M4V":case"M4VH":case"M4VP":return{ext:"m4v",mime:"video/x-m4v"};case"M4P":return{ext:"m4p",mime:"video/mp4"};case"M4B":return{ext:"m4b",mime:"audio/mp4"};case"M4A":return{ext:"m4a",mime:"audio/x-m4a"};case"F4V":return{ext:"f4v",mime:"video/mp4"};case"F4P":return{ext:"f4p",mime:"video/mp4"};case"F4A":return{ext:"f4a",mime:"audio/mp4"};case"F4B":return{ext:"f4b",mime:"audio/mp4"};case"crx":return{ext:"cr3",mime:"image/x-canon-cr3"};default:return t.startsWith("3g")?t.startsWith("3g2")?{ext:"3g2",mime:"video/3gpp2"}:{ext:"3gp",mime:"video/3gpp"}:{ext:"mp4",mime:"video/mp4"}}}if(this.checkString(`REGEDIT4\r
|
|
118
118
|
`))return{ext:"reg",mime:"application/x-ms-regedit"};if(this.check([82,73,70,70])){if(this.checkString("WEBP",{offset:8}))return{ext:"webp",mime:"image/webp"};if(this.check([65,86,73],{offset:8}))return{ext:"avi",mime:"video/vnd.avi"};if(this.check([87,65,86,69],{offset:8}))return{ext:"wav",mime:"audio/wav"};if(this.check([81,76,67,77],{offset:8}))return{ext:"qcp",mime:"audio/qcelp"}}if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:"rw2",mime:"image/x-panasonic-rw2"};if(this.check([48,38,178,117,142,102,207,17,166,217])){async function t(){let n=new Uint8Array(16);return await e.readBuffer(n),{id:n,size:Number(await e.readToken(BU))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){let n=await t(),o=n.size-24;if(cs(n.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let i=new Uint8Array(16);if(o-=await e.readBuffer(i),cs(i,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"audio/x-ms-asf"};if(cs(i,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"video/x-ms-asf"};break}await e.ignore(o)}return{ext:"asf",mime:"application/vnd.ms-asf"}}if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:"ktx",mime:"image/ktx"};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:"mie",mime:"application/x-mie"};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:"shp",mime:"application/x-esri-shape"};if(this.check([255,79,255,81]))return{ext:"j2c",mime:"image/j2c"};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10]))switch(await e.ignore(20),await e.readToken(new zn(4,"ascii"))){case"jp2 ":return{ext:"jp2",mime:"image/jp2"};case"jpx ":return{ext:"jpx",mime:"image/jpx"};case"jpm ":return{ext:"jpm",mime:"image/jpm"};case"mjp2":return{ext:"mj2",mime:"image/mj2"};default:return}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:"jxl",mime:"image/jxl"};if(this.check([254,255]))return this.checkString("<?xml ",{offset:2,encoding:"utf-16be"})?{ext:"xml",mime:"application/xml"}:void 0;if(this.check([208,207,17,224,161,177,26,225]))return{ext:"cfb",mime:"application/x-cfb"};if(await e.peekBuffer(this.buffer,{length:Math.min(256,e.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:"icc",mime:"application/vnd.iccprofile"};if(this.checkString("**ACE",{offset:7})&&this.checkString("**",{offset:12}))return{ext:"ace",mime:"application/x-ace-compressed"};if(this.checkString("BEGIN:")){if(this.checkString("VCARD",{offset:6}))return{ext:"vcf",mime:"text/vcard"};if(this.checkString("VCALENDAR",{offset:6}))return{ext:"ics",mime:"text/calendar"}}if(this.checkString("FUJIFILMCCD-RAW"))return{ext:"raf",mime:"image/x-fujifilm-raf"};if(this.checkString("Extended Module:"))return{ext:"xm",mime:"audio/x-xm"};if(this.checkString("Creative Voice File"))return{ext:"voc",mime:"audio/x-voc"};if(this.check([4,0,0,0])&&this.buffer.length>=16){let t=new DataView(this.buffer.buffer).getUint32(12,!0);if(t>12&&this.buffer.length>=t+16)try{let n=new TextDecoder().decode(this.buffer.subarray(16,t+16));if(JSON.parse(n).files)return{ext:"asar",mime:"application/x-asar"}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:"mxf",mime:"application/mxf"};if(this.checkString("SCRM",{offset:44}))return{ext:"s3m",mime:"audio/x-s3m"};if(this.check([71])&&this.check([71],{offset:188}))return{ext:"mts",mime:"video/mp2t"};if(this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:"mts",mime:"video/mp2t"};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:"mobi",mime:"application/x-mobipocket-ebook"};if(this.check([68,73,67,77],{offset:128}))return{ext:"dcm",mime:"application/dicom"};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:"lnk",mime:"application/x.ms.shortcut"};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:"alias",mime:"application/x.apple.alias"};if(this.checkString("Kaydara FBX Binary \0"))return{ext:"fbx",mime:"application/x.autodesk.fbx"};if(this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8})))return{ext:"eot",mime:"application/vnd.ms-fontobject"};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:"indd",mime:"application/x-indesign"};if(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),this.checkString("ustar",{offset:257})&&(this.checkString("\0",{offset:262})||this.checkString(" ",{offset:262}))||this.check([0,0,0,0,0,0],{offset:257})&&QU(this.buffer))return{ext:"tar",mime:"application/x-tar"};if(this.check([255,254])){let t="utf-16le";return this.checkString("<?xml ",{offset:2,encoding:t})?{ext:"xml",mime:"application/xml"}:this.check([255,14],{offset:2})&&this.checkString("SketchUp Model",{offset:4,encoding:t})?{ext:"skp",mime:"application/vnd.sketchup.skp"}:this.checkString(`Windows Registry Editor Version 5.00\r
|
|
119
|
-
`,{offset:2,encoding:t})?{ext:"reg",mime:"application/x-ms-regedit"}:void 0}if(this.checkString("-----BEGIN PGP MESSAGE-----"))return{ext:"pgp",mime:"application/pgp-encrypted"}};detectImprecise=async e=>{if(this.buffer=new Uint8Array(MS),await e.peekBuffer(this.buffer,{length:Math.min(8,e.fileInfo.size),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:"mpg",mime:"video/mpeg"};if(this.check([0,1,0,0,0]))return{ext:"ttf",mime:"font/ttf"};if(this.check([0,0,1,0]))return{ext:"ico",mime:"image/x-icon"};if(this.check([0,0,2,0]))return{ext:"cur",mime:"image/x-icon"};if(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,e.fileInfo.size),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let t=0;t<=this.options.mpegOffsetTolerance;++t){let n=this.scanMpeg(t);if(n)return n}};async readTiffTag(e){let t=await this.tokenizer.readToken(e?mh:Ut);switch(this.tokenizer.ignore(10),t){case 50341:return{ext:"arw",mime:"image/x-sony-arw"};case 50706:return{ext:"dng",mime:"image/x-adobe-dng"};default:}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?mh:Ut);for(let n=0;n<t;++n){let o=await this.readTiffTag(e);if(o)return o}}async readTiffHeader(e){let t=(e?mh:Ut).get(this.buffer,2),n=(e?NU:Yt).get(this.buffer,4);if(t===42){if(n>=6){if(this.checkString("CR",{offset:8}))return{ext:"cr2",mime:"image/x-canon-cr2"};if(n>=8){let i=(e?mh:Ut).get(this.buffer,8),s=(e?mh:Ut).get(this.buffer,10);if(i===28&&s===254||i===31&&s===11)return{ext:"nef",mime:"image/x-nikon-nef"}}}return await this.tokenizer.ignore(n),await this.readTiffIFD(e)??{ext:"tif",mime:"image/tiff"}}if(t===43)return{ext:"tif",mime:"image/tiff"}}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]})?{ext:"aac",mime:"audio/aac"}:{ext:"aac",mime:"audio/aac"};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:"mp3",mime:"audio/mpeg"};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:"mp2",mime:"audio/mpeg"};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:"mp1",mime:"audio/mpeg"}}}},cot=new Set(JU),lot=new Set(eF);var rF="application/octet-stream";function cee(r){return/^(<\?xml[^>]+>)?[^<^\w]+<svg/ig.test(r)}async function lee(r){try{return JSON.parse(r),!0}catch{return!1}}function uee(r){let e=new TextDecoder("utf-8",{fatal:!0});try{return e.decode(r)}catch{return null}}async function fee(r){return/^\s*<(?:!doctype\s+html|html|head|body)\b/i.test(r)}async function nF(r,e){let t=(await tF(r))?.mime;if(t!=null)return t==="application/xml"&&e?.toLowerCase().endsWith(".svg")?"image/svg+xml":t;if(e==null||e.includes(".")===!1){let n=uee(r);return n!=null?cee(n)?"image/svg+xml":await lee(n)?"application/json":await fee(n)?"text/html; charset=utf-8":"text/plain; charset=utf-8":rF}switch(e.split(".").pop()){case"css":return"text/css";case"html":return"text/html; charset=utf-8";case"js":return"application/javascript";case"json":return"application/json";case"txt":return"text/plain";case"woff2":return"font/woff2";case"svg":return"image/svg+xml";case"csv":return"text/csv";case"doc":return"application/msword";case"xls":return"application/vnd.ms-excel";case"ppt":return"application/vnd.ms-powerpoint";case"msi":return"application/x-msdownload";default:return rF}}function dee(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r?.errors)}function H8(r){let e;return dee(r)&&(e=r.errors.map(t=>H8(t))),{name:r.name,message:r.message,stack:r.stack,errors:e}}function oF(r,e){if(e.name==="AbortError")throw e;return e.code==="ECONNREFUSED"||e.code==="ECANCELLED"||e.name==="DNSQueryFailedError"?hh(r.toString(),e):["NotUnixFSError"].includes(e.name)?ss(r.toString(),[b8,dh]):e.code==="ETIMEOUT"||e.name==="TimeoutError"?hU(r.toString(),e):["ERR_NO_PROP","ERR_NO_TERMINAL_ELEMENT","ERR_NOT_FOUND"].includes(e.code)?CS(r.toString()):["DoesNotExistError"].includes(e.name)?CS(r.toString()):["BlockNotFoundWhileOfflineError"].includes(e.name)?mU(r.toString()):["RecordNotFoundError"].includes("err.name")?hh(r.toString(),e):O0(r.toString(),e)}function iF({cid:r,contentType:e,rangeStart:t,rangeEnd:n,contentPrefix:o}){let i=e.immutable?"":"W/",s=e.etag;return(t!=null||n!=null)&&(s+=`.${t??"0"}-${n??"N"}`),`${i}"${o??""}${r.toString()}${s}"`}function $S(r){if(r==null||r==="")return;let e=Number(r);if(isNaN(e))throw new Hn(`Invalid range specification: could not parse "${e}" as number`);return e}function hee(r){if(r==null||r==="")return[];if(!r.startsWith("bytes="))throw new Hn("Invalid range request");let t=r.substring(6).split(",").map(o=>o.trim()),n=[];for(let o of t){let i=o.match(/^(?<start>\d+)?-(?<end>\d+)?$/);if(i?.groups==null)throw new Hn(`Invalid range specification: ${o}`);if(o.startsWith("-"))n.push({end:$S(o)});else{let{start:s,end:a}=i.groups;n.push({start:$S(s),end:$S(a)})}}return n}function sF(r,e){let t=e.get("range");if(t!=null)try{let n=hee(t);return n.length===0?void 0:{multipartBoundary:`multipart_byteranges_${Math.floor(Math.random()*1e9)}`,ranges:n}}catch(n){return n.name==="InvalidRangeError"?E8(r):Kn(r,n)}}function pee(r){if(r!=null)return{...r,signal:r?.signal==null?void 0:r?.signal}}function mee(r){let e=r.get("accept")?.split(",")??[];return e.length!==1?!1:e[0].split(";")[0]===ku}function gee(r){let e=r.get("accept")?.split(",")??[];return e.length!==1?!1:e[0].split(";")[0]===En}var K8=class{helia;ipnsResolver;dnsLink;log;contentTypeParser;withServerTiming;plugins=[];urlResolver;constructor(e,t={}){this.helia=e,this.log=e.logger.forComponent("helia:verified-fetch"),this.ipnsResolver=t.ipnsResolver??cM(e),this.dnsLink=t.dnsLink??rM(e),this.contentTypeParser=t.contentTypeParser??nF,this.withServerTiming=t?.withServerTiming??!1,this.urlResolver=new D8({ipnsResolver:this.ipnsResolver,dnsLink:this.dnsLink,helia:this.helia},t);let n={...t,logger:e.logger.forComponent("verified-fetch"),helia:e,contentTypeParser:this.contentTypeParser,ipnsResolver:this.ipnsResolver},o=[new R8(n),new A8(n),new S8(n),new P8(n),new _8(n)],i=t.plugins?.map(s=>s(n))??[];if(i.length>0){let s=new Map(o.map(c=>[c.id,c])),a=new Map(i.map(c=>[c.id,c]));this.plugins=o.map(c=>a.get(c.id)??c),this.plugins.unshift(...i.filter(c=>!s.has(c.id)))}else this.plugins=o}async fetch(e,t){if(this.log("fetch %s %s",t?.method??"GET",e),t?.method==="OPTIONS")return this.handleFinalResponse(new Response(null,{status:200}));let n=pee(t),o=new Headers(n?.headers),i=new ph;n?.onProgress?.(new Y("verified-fetch:request:start",{resource:e}));let s=sF(e.toString(),o);if(s instanceof Response)return this.handleFinalResponse(s);let a;try{a=O8(typeof e=="string"?e:`ipfs://${e}`)}catch(h){return this.handleFinalResponse(Kn(e.toString(),h))}let c;if(mee(o)){if(a.protocol!=="ipns:")return ss(a,[]);let h=this.plugins.find(d=>d.id==="ipns-record-plugin");return h==null?ss(a,[]):this.handleFinalResponse(await h.handle({range:s,url:a,resource:e.toString(),options:n}))}else try{c=await this.urlResolver.resolve(a,i,{...n,isRawBlockRequest:gee(o),onlyIfCached:o.get("cache-control")==="only-if-cached"})}catch(h){return n?.signal?.throwIfAborted(),this.log.error("error parsing resource %s - %e",e,h),this.handleFinalResponse(oF(e,h))}n?.onProgress?.(new Y("verified-fetch:request:resolve",{cid:c.terminalElement.cid,path:c.url.pathname}));let l=this.getAcceptHeader(c.url,o.get("accept"),c.terminalElement.cid);if(l instanceof Response)return this.log("allowed media types for requested CID did not contain anything the client can understand"),this.handleFinalResponse(l);let f={...c,resource:e.toString(),accept:l,range:s,options:n,onProgress:n?.onProgress,serverTiming:i,headers:o};this.log.trace('finding handler for cid code "0x%s" and response content types %s',c.terminalElement.cid.code.toString(16),l.map(h=>h.contentType.mediaType).join(", "));let u=await this.runPluginPipeline(f);return n?.onProgress?.(new Y("verified-fetch:request:end",{cid:c.terminalElement.cid,path:c.url.pathname})),u==null&&this.log.error("no plugin could handle request for %s",e),this.handleFinalResponse(u,!!n?.withServerTiming||!!this.withServerTiming,f)}getAcceptHeader(e,t,n){if(t==null||t===""){try{let a=e.searchParams.get("dag-scope"),c=e.searchParams.get("entity-bytes"),l=e.searchParams.get("car-dups"),f=e.searchParams.get("car-order"),u=e.searchParams.get("car-version");if(a!=null||c!=null||l!=null||c!=null||f!=null){let h={};return l!=null&&(h.dups=l),f!=null&&(h.order=f),u!=null&&(h.version=u),[{contentType:P0,options:h}]}}catch{}t="*/*"}let o=[],i=t.split(",").map(a=>{let c=a.trim().split(";"),l={q:"1"};for(let f=1;f<c.length;f++){let[u,h]=c[f].split("=").map(d=>d.trim());l[u]=h}return{mediaType:`${c[0]}`.trim(),options:l}}).sort((a,c)=>a.options.q===c.options.q?0:a.options.q>c.options.q?-1:1),s=aU(e.protocol,n);for(let a of i){let[c,l]=a.mediaType.split("/");for(let f of s){let[u,h]=f.mediaType.split("/");a.mediaType.includes(f.mediaType)&&o.push({contentType:f,options:a.options}),a.mediaType==="*/*"&&o.push({contentType:f,options:a.options}),a.mediaType.startsWith("*/")&&h===l&&o.push({contentType:f,options:a.options}),a.mediaType.endsWith("/*")&&u===c&&o.push({contentType:f,options:a.options})}}return o.length===0?(this.log("requested %o",i.map(({mediaType:a})=>a)),this.log("supported %o",s.map(({mediaType:a})=>a)),ss(e,s)):o}handleFinalResponse(e,t,n){let o=sU(e.headers.get("content-type"))??dh;if(t===!0&&n?.serverTiming!=null){let i=n?.serverTiming.getHeader();i!==""&&e.headers.set("server-timing",i)}if(n?.terminalElement.cid!=null&&e.headers.get("etag")==null&&e.headers.set("etag",iF({cid:n.terminalElement.cid,contentType:o})),n?.url?.protocol!=null&&n.ttl!=null&&fU({response:e,ttl:n.ttl,protocol:n.url.protocol}),n?.terminalElement.cid!=null){let i=decodeURI(n?.url.pathname),s=H(D(i),"ascii");e.headers.set("x-ipfs-path",`/${n.url.protocol==="ipfs:"?"ipfs":"ipns"}/${n?.url.hostname}${s}`)}return e.headers.set("access-control-allow-origin","*"),e.headers.set("access-control-allow-methods","GET, HEAD, OPTIONS"),e.headers.set("access-control-allow-headers","Range, X-Requested-With"),e.headers.set("access-control-expose-headers","Content-Range, Content-Length, X-Ipfs-Path, X-Ipfs-Roots, X-Stream-Output"),n?.options?.method==="HEAD"?new Response(null,{status:200,headers:e.headers}):(e.status>399&&e.headers.delete("content-disposition"),e)}async runPluginPipeline(e){let t,n=new Set;this.log.trace("checking which plugins can handle %c%s with accept %s",e.terminalElement.cid,e.url.pathname,e.accept.map(a=>a.contentType.mediaType).join(", "));let o=this.plugins.filter(a=>!n.has(a.id)).filter(a=>a.canHandle(e));if(o.length===0)return this.log.trace("no plugins found that can handle request; exiting pipeline"),TS(e.resource);this.log.trace("plugins ready to handle request: %s",o.map(a=>a.id).join(", "));let i=!1,s=!1;for(let a of o){try{this.log("invoking plugin: %s",a.id),n.add(a.id);let c=await a.handle(e);if(this.log("plugin response %s %o",a.id,c),c!=null){t=c,s=!0;break}}catch(c){if(e.options?.signal?.aborted)throw new Tr(e.options?.signal?.reason);return this.log.error("error in plugin %s - %e",a.id,c),O0(e.resource,JSON.stringify({error:H8(c)}),{headers:{"content-type":"application/json"}})}if(t!=null){this.log.trace("plugin %s produced final response",a.id);break}if(s&&t!=null)break;if(!i){this.log.trace("no context changes and no final response; exiting pipeline.");break}}return t??TS(e.resource,JSON.stringify({error:H8(new Error("No verified fetch plugin could handle the request"))}),{headers:{"content-type":"application/json"}})}async start(){await this.helia.start()}async stop(){await this.helia.stop()}};var M0,V8=async function(e,t){return M0==null&&(M0=await HS()),M0(e,t)};V8.start=async function(){await M0?.start()};V8.stop=async function(){await M0?.stop()};async function HS(r,e){let t;if(!yee(r)){let i=wee(r?.dnsResolvers),s=JB();s.dns=i;let a=r?.routers??["https://delegated-ipfs.dev"];for(let f=0;f<a.length;f++)s.services[`delegatedRouting${f}`]=xk({url:a[f]});r?.libp2pConfig!=null&&Object.assign(s,r.libp2pConfig),t=await _3(s);let c=[Fp()],l=[Gp(t)];(r?.gateways==null||r.gateways.length>0)&&(c.push(Vp({allowInsecure:r?.allowInsecure,allowLocal:r?.allowLocal})),l.push(Wp({gateways:r?.gateways??["https://trustless-gateway.link"]}))),r=await ZB({libp2p:t,blockBrokers:c,dns:i,routers:l,hashers:r?.hashers}),r.logger.forComponent("helia:verified-fetch").trace("created verified-fetch with libp2p config: %j",s)}let n=new K8(r,e);async function o(i,s){return n.fetch(i,s)}return o.start=n.start.bind(n),o.stop=n.stop.bind(n),o}function yee(r){return r?.blockstore!=null&&r?.datastore!=null&&r?.gc!=null&&r?.stop!=null&&r?.start!=null}function wee(r){if(r!=null)return Array.isArray(r)?dl({resolvers:{".":r}}):dl({resolvers:r})}return vF(xee);})();
|
|
119
|
+
`,{offset:2,encoding:t})?{ext:"reg",mime:"application/x-ms-regedit"}:void 0}if(this.checkString("-----BEGIN PGP MESSAGE-----"))return{ext:"pgp",mime:"application/pgp-encrypted"}};detectImprecise=async e=>{if(this.buffer=new Uint8Array(MS),await e.peekBuffer(this.buffer,{length:Math.min(8,e.fileInfo.size),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:"mpg",mime:"video/mpeg"};if(this.check([0,1,0,0,0]))return{ext:"ttf",mime:"font/ttf"};if(this.check([0,0,1,0]))return{ext:"ico",mime:"image/x-icon"};if(this.check([0,0,2,0]))return{ext:"cur",mime:"image/x-icon"};if(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,e.fileInfo.size),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let t=0;t<=this.options.mpegOffsetTolerance;++t){let n=this.scanMpeg(t);if(n)return n}};async readTiffTag(e){let t=await this.tokenizer.readToken(e?mh:Ut);switch(this.tokenizer.ignore(10),t){case 50341:return{ext:"arw",mime:"image/x-sony-arw"};case 50706:return{ext:"dng",mime:"image/x-adobe-dng"};default:}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?mh:Ut);for(let n=0;n<t;++n){let o=await this.readTiffTag(e);if(o)return o}}async readTiffHeader(e){let t=(e?mh:Ut).get(this.buffer,2),n=(e?NU:Yt).get(this.buffer,4);if(t===42){if(n>=6){if(this.checkString("CR",{offset:8}))return{ext:"cr2",mime:"image/x-canon-cr2"};if(n>=8){let i=(e?mh:Ut).get(this.buffer,8),s=(e?mh:Ut).get(this.buffer,10);if(i===28&&s===254||i===31&&s===11)return{ext:"nef",mime:"image/x-nikon-nef"}}}return await this.tokenizer.ignore(n),await this.readTiffIFD(e)??{ext:"tif",mime:"image/tiff"}}if(t===43)return{ext:"tif",mime:"image/tiff"}}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]})?{ext:"aac",mime:"audio/aac"}:{ext:"aac",mime:"audio/aac"};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:"mp3",mime:"audio/mpeg"};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:"mp2",mime:"audio/mpeg"};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:"mp1",mime:"audio/mpeg"}}}},cot=new Set(JU),lot=new Set(eF);var rF="application/octet-stream";function cee(r){return/^(<\?xml[^>]+>)?[^<^\w]+<svg/ig.test(r)}async function lee(r){try{return JSON.parse(r),!0}catch{return!1}}function uee(r){let e=new TextDecoder("utf-8",{fatal:!0});try{return e.decode(r)}catch{return null}}async function fee(r){return/^\s*<(?:!doctype\s+html|html|head|body)\b/i.test(r)}async function nF(r,e){let t=(await tF(r))?.mime;if(t!=null)return t==="application/xml"&&e?.toLowerCase().endsWith(".svg")?"image/svg+xml":t;if(e==null||e.includes(".")===!1){let n=uee(r);return n!=null?cee(n)?"image/svg+xml":await lee(n)?"application/json":await fee(n)?"text/html; charset=utf-8":"text/plain; charset=utf-8":rF}switch(e.split(".").pop()){case"css":return"text/css";case"html":return"text/html; charset=utf-8";case"js":return"application/javascript";case"json":return"application/json";case"txt":return"text/plain";case"woff2":return"font/woff2";case"svg":return"image/svg+xml";case"csv":return"text/csv";case"doc":return"application/msword";case"xls":return"application/vnd.ms-excel";case"ppt":return"application/vnd.ms-powerpoint";case"msi":return"application/x-msdownload";default:return rF}}function dee(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r?.errors)}function H8(r){let e;return dee(r)&&(e=r.errors.map(t=>H8(t))),{name:r.name,message:r.message,stack:r.stack,errors:e}}function oF(r,e){if(e.name==="AbortError")throw e;return e.code==="ECONNREFUSED"||e.code==="ECANCELLED"||e.name==="DNSQueryFailedError"?hh(r.toString(),e):["NotUnixFSError"].includes(e.name)?ss(r.toString(),[b8,dh]):e.code==="ETIMEOUT"||e.name==="TimeoutError"?hU(r.toString(),e):["ERR_NO_PROP","ERR_NO_TERMINAL_ELEMENT","ERR_NOT_FOUND"].includes(e.code)?CS(r.toString()):["DoesNotExistError"].includes(e.name)?CS(r.toString()):["BlockNotFoundWhileOfflineError"].includes(e.name)?mU(r.toString()):["RecordNotFoundError"].includes("err.name")?hh(r.toString(),e):O0(r.toString(),e)}function iF({cid:r,contentType:e,ranges:t,contentPrefix:n}){let o=e.immutable?"":"W/",i=e.etag;if(t?.length!=null&&t?.length>0){let s=t.filter(a=>a.start!=null||a.end!=null);s.length>0&&(i+="."+s.map(a=>`${a.start??0}-${a.end??"N"}`).join(","))}return`${o}"${n??""}${r.toString()}${i}"`}function $S(r){if(r==null||r==="")return;let e=Number(r);if(isNaN(e))throw new Hn(`Invalid range specification: could not parse "${e}" as number`);return e}function hee(r){if(r==null||r==="")return[];if(!r.startsWith("bytes="))throw new Hn("Invalid range request");let t=r.substring(6).split(",").map(o=>o.trim()),n=[];for(let o of t){let i=o.match(/^(?<start>\d+)?-(?<end>\d+)?$/);if(i?.groups==null)throw new Hn(`Invalid range specification: ${o}`);if(o.startsWith("-"))n.push({end:$S(o)});else{let{start:s,end:a}=i.groups;n.push({start:$S(s),end:$S(a)})}}return n}function sF(r,e){let t=e.get("range");if(t!=null)try{let n=hee(t);return n.length===0?void 0:{multipartBoundary:`multipart_byteranges_${Math.floor(Math.random()*1e9)}`,ranges:n}}catch(n){return n.name==="InvalidRangeError"?E8(r):Kn(r,n)}}function pee(r){if(r!=null)return{...r,signal:r?.signal==null?void 0:r?.signal}}function mee(r){let e=r.get("accept")?.split(",")??[];return e.length!==1?!1:e[0].split(";")[0]===ku}function gee(r){let e=r.get("accept")?.split(",")??[];return e.length!==1?!1:e[0].split(";")[0]===En}var K8=class{helia;ipnsResolver;dnsLink;log;contentTypeParser;withServerTiming;plugins=[];urlResolver;constructor(e,t={}){this.helia=e,this.log=e.logger.forComponent("helia:verified-fetch"),this.ipnsResolver=t.ipnsResolver??cM(e),this.dnsLink=t.dnsLink??rM(e),this.contentTypeParser=t.contentTypeParser??nF,this.withServerTiming=t?.withServerTiming??!1,this.urlResolver=new D8({ipnsResolver:this.ipnsResolver,dnsLink:this.dnsLink,helia:this.helia},t);let n={...t,logger:e.logger.forComponent("verified-fetch"),helia:e,contentTypeParser:this.contentTypeParser,ipnsResolver:this.ipnsResolver},o=[new R8(n),new A8(n),new S8(n),new P8(n),new _8(n)],i=t.plugins?.map(s=>s(n))??[];if(i.length>0){let s=new Map(o.map(c=>[c.id,c])),a=new Map(i.map(c=>[c.id,c]));this.plugins=o.map(c=>a.get(c.id)??c),this.plugins.unshift(...i.filter(c=>!s.has(c.id)))}else this.plugins=o}async fetch(e,t){if(this.log("fetch %s %s",t?.method??"GET",e),t?.method==="OPTIONS")return this.handleFinalResponse(new Response(null,{status:200}));let n=pee(t),o=new Headers(n?.headers),i=new ph;n?.onProgress?.(new Y("verified-fetch:request:start",{resource:e}));let s=sF(e.toString(),o);if(s instanceof Response)return this.handleFinalResponse(s);let a;try{a=O8(typeof e=="string"?e:`ipfs://${e}`)}catch(h){return this.handleFinalResponse(Kn(e.toString(),h))}let c;if(mee(o)){if(a.protocol!=="ipns:")return ss(a,[]);let h=this.plugins.find(d=>d.id==="ipns-record-plugin");return h==null?ss(a,[]):this.handleFinalResponse(await h.handle({range:s,url:a,resource:e.toString(),options:n}))}else try{c=await this.urlResolver.resolve(a,i,{...n,isRawBlockRequest:gee(o),onlyIfCached:o.get("cache-control")==="only-if-cached"})}catch(h){return n?.signal?.throwIfAborted(),this.log.error("error parsing resource %s - %e",e,h),this.handleFinalResponse(oF(e,h))}n?.onProgress?.(new Y("verified-fetch:request:resolve",{cid:c.terminalElement.cid,path:c.url.pathname}));let l=this.getAcceptHeader(c.url,o.get("accept"),c.terminalElement.cid);if(l instanceof Response)return this.log("allowed media types for requested CID did not contain anything the client can understand"),this.handleFinalResponse(l);let f={...c,resource:e.toString(),accept:l,range:s,options:n,onProgress:n?.onProgress,serverTiming:i,headers:o};this.log.trace('finding handler for cid code "0x%s" and response content types %s',c.terminalElement.cid.code.toString(16),l.map(h=>h.contentType.mediaType).join(", "));let u=await this.runPluginPipeline(f);return n?.onProgress?.(new Y("verified-fetch:request:end",{cid:c.terminalElement.cid,path:c.url.pathname})),u==null&&this.log.error("no plugin could handle request for %s",e),this.handleFinalResponse(u,!!n?.withServerTiming||!!this.withServerTiming,f)}getAcceptHeader(e,t,n){if(t==null||t===""){try{let a=e.searchParams.get("dag-scope"),c=e.searchParams.get("entity-bytes"),l=e.searchParams.get("car-dups"),f=e.searchParams.get("car-order"),u=e.searchParams.get("car-version");if(a!=null||c!=null||l!=null||c!=null||f!=null){let h={};return l!=null&&(h.dups=l),f!=null&&(h.order=f),u!=null&&(h.version=u),[{contentType:P0,options:h}]}}catch{}t="*/*"}let o=[],i=t.split(",").map(a=>{let c=a.trim().split(";"),l={q:"1"};for(let f=1;f<c.length;f++){let[u,h]=c[f].split("=").map(d=>d.trim());l[u]=h}return{mediaType:`${c[0]}`.trim(),options:l}}).sort((a,c)=>a.options.q===c.options.q?0:a.options.q>c.options.q?-1:1),s=aU(e.protocol,n);for(let a of i){let[c,l]=a.mediaType.split("/");for(let f of s){let[u,h]=f.mediaType.split("/");a.mediaType.includes(f.mediaType)&&o.push({contentType:f,options:a.options}),a.mediaType==="*/*"&&o.push({contentType:f,options:a.options}),a.mediaType.startsWith("*/")&&h===l&&o.push({contentType:f,options:a.options}),a.mediaType.endsWith("/*")&&u===c&&o.push({contentType:f,options:a.options})}}return o.length===0?(this.log("requested %o",i.map(({mediaType:a})=>a)),this.log("supported %o",s.map(({mediaType:a})=>a)),ss(e,s)):o}handleFinalResponse(e,t,n){let o=sU(e.headers.get("content-type"))??dh;if(t===!0&&n?.serverTiming!=null){let i=n?.serverTiming.getHeader();i!==""&&e.headers.set("server-timing",i)}if(n?.terminalElement.cid!=null&&e.headers.get("etag")==null&&e.headers.set("etag",iF({cid:n.terminalElement.cid,contentType:o,ranges:n?.range?.ranges})),n?.url?.protocol!=null&&n.ttl!=null&&fU({response:e,ttl:n.ttl,protocol:n.url.protocol}),n?.terminalElement.cid!=null){let i=decodeURI(n?.url.pathname),s=H(D(i),"ascii");e.headers.set("x-ipfs-path",`/${n.url.protocol==="ipfs:"?"ipfs":"ipns"}/${n?.url.hostname}${s}`)}return e.headers.set("access-control-allow-origin","*"),e.headers.set("access-control-allow-methods","GET, HEAD, OPTIONS"),e.headers.set("access-control-allow-headers","Range, X-Requested-With"),e.headers.set("access-control-expose-headers","Content-Range, Content-Length, X-Ipfs-Path, X-Ipfs-Roots, X-Stream-Output"),n?.options?.method==="HEAD"?new Response(null,{status:200,headers:e.headers}):(e.status>399&&e.headers.delete("content-disposition"),e)}async runPluginPipeline(e){let t,n=new Set;this.log.trace("checking which plugins can handle %c%s with accept %s",e.terminalElement.cid,e.url.pathname,e.accept.map(a=>a.contentType.mediaType).join(", "));let o=this.plugins.filter(a=>!n.has(a.id)).filter(a=>a.canHandle(e));if(o.length===0)return this.log.trace("no plugins found that can handle request; exiting pipeline"),TS(e.resource);this.log.trace("plugins ready to handle request: %s",o.map(a=>a.id).join(", "));let i=!1,s=!1;for(let a of o){try{this.log("invoking plugin: %s",a.id),n.add(a.id);let c=await a.handle(e);if(this.log("plugin response %s %o",a.id,c),c!=null){t=c,s=!0;break}}catch(c){if(e.options?.signal?.aborted)throw new Tr(e.options?.signal?.reason);return this.log.error("error in plugin %s - %e",a.id,c),O0(e.resource,JSON.stringify({error:H8(c)}),{headers:{"content-type":"application/json"}})}if(t!=null){this.log.trace("plugin %s produced final response",a.id);break}if(s&&t!=null)break;if(!i){this.log.trace("no context changes and no final response; exiting pipeline.");break}}return t??TS(e.resource,JSON.stringify({error:H8(new Error("No verified fetch plugin could handle the request"))}),{headers:{"content-type":"application/json"}})}async start(){await this.helia.start()}async stop(){await this.helia.stop()}};var M0,V8=async function(e,t){return M0==null&&(M0=await HS()),M0(e,t)};V8.start=async function(){await M0?.start()};V8.stop=async function(){await M0?.stop()};async function HS(r,e){let t;if(!yee(r)){let i=wee(r?.dnsResolvers),s=JB();s.dns=i;let a=r?.routers??["https://delegated-ipfs.dev"];for(let f=0;f<a.length;f++)s.services[`delegatedRouting${f}`]=xk({url:a[f]});r?.libp2pConfig!=null&&Object.assign(s,r.libp2pConfig),t=await _3(s);let c=[Fp()],l=[Gp(t)];(r?.gateways==null||r.gateways.length>0)&&(c.push(Vp({allowInsecure:r?.allowInsecure,allowLocal:r?.allowLocal})),l.push(Wp({gateways:r?.gateways??["https://trustless-gateway.link"]}))),r=await ZB({libp2p:t,blockBrokers:c,dns:i,routers:l,hashers:r?.hashers}),r.logger.forComponent("helia:verified-fetch").trace("created verified-fetch with libp2p config: %j",s)}let n=new K8(r,e);async function o(i,s){return n.fetch(i,s)}return o.start=n.start.bind(n),o.stop=n.stop.bind(n),o}function yee(r){return r?.blockstore!=null&&r?.datastore!=null&&r?.gc!=null&&r?.stop!=null&&r?.start!=null}function wee(r){if(r!=null)return Array.isArray(r)?dl({resolvers:{".":r}}):dl({resolvers:r})}return vF(xee);})();
|
|
120
120
|
/*! Bundled license information:
|
|
121
121
|
|
|
122
122
|
pvtsutils/build/index.js:
|