@helia/verified-fetch 5.0.1 → 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 +1 -1
- package/dist/index.min.js.map +3 -3
- 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/utils/get-e-tag.ts +13 -10
- package/src/verified-fetch.ts +2 -1
package/dist/index.min.js
CHANGED
|
@@ -116,7 +116,7 @@ a=ice-pwd:`+e+t)}catch{}return r}var tS=D("libp2p-webrtc-noise:");function $B(r,
|
|
|
116
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:
|