diff --git a/node_modules/pmtiles/.DS_Store b/node_modules/pmtiles/.DS_Store
new file mode 100644
index 0000000..e69de29
diff --git a/node_modules/pmtiles/dist/cjs/index.cjs b/node_modules/pmtiles/dist/cjs/index.cjs
index 5301d69..4b734c3 100644
--- a/node_modules/pmtiles/dist/cjs/index.cjs
+++ b/node_modules/pmtiles/dist/cjs/index.cjs
@@ -1,2 +1,2 @@
-"use strict";Object.defineProperty(exports, "__esModule", {value: true});var z=Object.defineProperty;var b=Math.pow;var l=(i,e)=>z(i,"name",{value:e,configurable:!0});var m=(i,e,t)=>new Promise((r,n)=>{var s=u=>{try{a(t.next(u))}catch(c){n(c)}},o=u=>{try{a(t.throw(u))}catch(c){n(c)}},a=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,o);a((t=t.apply(i,e)).next())});var _fflate = require('fflate');var re=l((i,e)=>{let t=!1,r="",n=L.GridLayer.extend({createTile:l((s,o)=>{let a=document.createElement("img"),u=new AbortController,c=u.signal;return a.cancel=()=>{u.abort()},t||(i.getHeader().then(d=>{d.tileType===1?console.error("Error: archive contains MVT vector tiles, but leafletRasterLayer is for displaying raster tiles. See https://github.com/protomaps/PMTiles/tree/main/js for details."):d.tileType===2?r="image/png":d.tileType===3?r="image/jpeg":d.tileType===4?r="image/webp":d.tileType===5&&(r="image/avif")}),t=!0),i.getZxy(s.z,s.x,s.y,c).then(d=>{if(d){let h=new Blob([d.data],{type:r}),p=window.URL.createObjectURL(h);a.src=p,a.cancel=void 0,o(void 0,a)}}).catch(d=>{if(d.name!=="AbortError")throw d}),a},"createTile"),_removeTile:l(function(s){let o=this._tiles[s];o&&(o.el.cancel&&o.el.cancel(),o.el.width=0,o.el.height=0,o.el.deleted=!0,L.DomUtil.remove(o.el),delete this._tiles[s],this.fire("tileunload",{tile:o.el,coords:this._keyToTileCoords(s)}))},"_removeTile")});return new n(e)},"leafletRasterLayer"),j=l(i=>(e,t)=>{if(t instanceof AbortController)return i(e,t);let r=new AbortController;return i(e,r).then(n=>t(void 0,n.data,n.cacheControl||"",n.expires||""),n=>t(n)).catch(n=>t(n)),{cancel:l(()=>r.abort(),"cancel")}},"v3compat"),T=class T{constructor(e){this.tilev4=l((e,t)=>m(this,null,function*(){if(e.type==="json"){let p=e.url.substr(10),y=this.tiles.get(p);if(y||(y=new x(p),this.tiles.set(p,y)),this.metadata)return{data:yield y.getTileJson(e.url)};let f=yield y.getHeader();return(f.minLon>=f.maxLon||f.minLat>=f.maxLat)&&console.error(`Bounds of PMTiles archive ${f.minLon},${f.minLat},${f.maxLon},${f.maxLat} are not valid.`),{data:{tiles:[`${e.url}/{z}/{x}/{y}`],minzoom:f.minZoom,maxzoom:f.maxZoom,bounds:[f.minLon,f.minLat,f.maxLon,f.maxLat]}}}let r=new RegExp(/pmtiles:\/\/(.+)\/(\d+)\/(\d+)\/(\d+)/),n=e.url.match(r);if(!n)throw new Error("Invalid PMTiles protocol URL");let s=n[1],o=this.tiles.get(s);o||(o=new x(s),this.tiles.set(s,o));let a=n[2],u=n[3],c=n[4],d=yield o.getHeader(),h=yield o==null?void 0:o.getZxy(+a,+u,+c,t.signal);if(h)return{data:new Uint8Array(h.data),cacheControl:h.cacheControl,expires:h.expires};if(d.tileType===1){if(this.errorOnMissingTile)throw new Error("Tile not found.");return{data:new Uint8Array}}return{data:null}}),"tilev4");this.tile=j(this.tilev4);this.tiles=new Map,this.metadata=(e==null?void 0:e.metadata)||!1,this.errorOnMissingTile=(e==null?void 0:e.errorOnMissingTile)||!1}add(e){this.tiles.set(e.source.getKey(),e)}get(e){return this.tiles.get(e)}};l(T,"Protocol");var S=T;function w(i,e){return(e>>>0)*4294967296+(i>>>0)}l(w,"toNum");function F(i,e){let t=e.buf,r=t[e.pos++],n=(r&112)>>4;if(r<128||(r=t[e.pos++],n|=(r&127)<<3,r<128)||(r=t[e.pos++],n|=(r&127)<<10,r<128)||(r=t[e.pos++],n|=(r&127)<<17,r<128)||(r=t[e.pos++],n|=(r&127)<<24,r<128)||(r=t[e.pos++],n|=(r&1)<<31,r<128))return w(i,n);throw new Error("Expected varint not more than 10 bytes")}l(F,"readVarintRemainder");function v(i){let e=i.buf,t=e[i.pos++],r=t&127;return t<128||(t=e[i.pos++],r|=(t&127)<<7,t<128)||(t=e[i.pos++],r|=(t&127)<<14,t<128)||(t=e[i.pos++],r|=(t&127)<<21,t<128)?r:(t=e[i.pos],r|=(t&15)<<28,F(r,i))}l(v,"readVarint");function k(i,e,t,r){if(r===0){t===1&&(e[0]=i-1-e[0],e[1]=i-1-e[1]);let n=e[0];e[0]=e[1],e[1]=n}}l(k,"rotate");function N(i,e){let t=b(2,i),r=e,n=e,s=e,o=[0,0],a=1;for(;a<t;)r=1&s/2,n=1&(s^r),k(a,o,r,n),o[0]+=a*r,o[1]+=a*n,s=s/4,a*=2;return[i,o[0],o[1]]}l(N,"idOnLevel");var q=[0,1,5,21,85,341,1365,5461,21845,87381,349525,1398101,5592405,22369621,89478485,357913941,1431655765,5726623061,22906492245,91625968981,366503875925,1466015503701,5864062014805,23456248059221,93824992236885,375299968947541,0x5555555555555];function G(i,e,t){if(i>26)throw new Error("Tile zoom level exceeds max safe number limit (26)");if(e>b(2,i)-1||t>b(2,i)-1)throw new Error("tile x/y outside zoom level bounds");let r=q[i],n=b(2,i),s=0,o=0,a=0,u=[e,t],c=n/2;for(;c>0;)s=(u[0]&c)>0?1:0,o=(u[1]&c)>0?1:0,a+=c*c*(3*s^o),k(c,u,s,o),c=c/2;return r+a}l(G,"zxyToTileId");function ie(i){let e=0,t=0;for(let r=0;r<27;r++){let n=(1<<r)*(1<<r);if(e+n>i)return N(r,i-e);e+=n}throw new Error("Tile zoom level exceeds max safe number limit (26)")}l(ie,"tileIdToZxy");var J=(s=>(s[s.Unknown=0]="Unknown",s[s.None=1]="None",s[s.Gzip=2]="Gzip",s[s.Brotli=3]="Brotli",s[s.Zstd=4]="Zstd",s))(J||{});function D(i,e){return m(this,null,function*(){if(e===1||e===0)return i;if(e===2){if(typeof globalThis.DecompressionStream=="undefined")return _fflate.decompressSync.call(void 0, new Uint8Array(i));let t=new Response(i).body;if(!t)throw new Error("Failed to read response stream");let r=t.pipeThrough(new globalThis.DecompressionStream("gzip"));return new Response(r).arrayBuffer()}throw new Error("Compression method not supported")})}l(D,"defaultDecompress");var O=(o=>(o[o.Unknown=0]="Unknown",o[o.Mvt=1]="Mvt",o[o.Png=2]="Png",o[o.Jpeg=3]="Jpeg",o[o.Webp=4]="Webp",o[o.Avif=5]="Avif",o))(O||{});function _(i){return i===1?".mvt":i===2?".png":i===3?".jpg":i===4?".webp":i===5?".avif":""}l(_,"tileTypeExt");var Y=127;function Q(i,e){let t=0,r=i.length-1;for(;t<=r;){let n=r+t>>1,s=e-i[n].tileId;if(s>0)t=n+1;else if(s<0)r=n-1;else return i[n]}return r>=0&&(i[r].runLength===0||e-i[r].tileId<i[r].runLength)?i[r]:null}l(Q,"findTile");var A=class A{constructor(e){this.file=e}getKey(){return this.file.name}getBytes(e,t){return m(this,null,function*(){return{data:yield this.file.slice(e,e+t).arrayBuffer()}})}};l(A,"FileSource");var V=A,U=class U{constructor(e,t=new Headers){this.url=e,this.customHeaders=t,this.mustReload=!1;let r="";"navigator"in globalThis&&(r=globalThis.navigator.userAgent||"");let n=r.indexOf("Windows")>-1,s=/Chrome|Chromium|Edg|OPR|Brave/.test(r);this.chromeWindowsNoCache=!1,n&&s&&(this.chromeWindowsNoCache=!0)}getKey(){return this.url}setHeaders(e){this.customHeaders=e}getBytes(e,t,r,n){return m(this,null,function*(){let s,o;r?o=r:(s=new AbortController,o=s.signal);let a=new Headers(this.customHeaders);a.set("range",`bytes=${e}-${e+t-1}`);let u;this.mustReload?u="reload":this.chromeWindowsNoCache&&(u="no-store");let c=yield fetch(this.url,{signal:o,cache:u,headers:a});if(e===0&&c.status===416){let y=c.headers.get("Content-Range");if(!y||!y.startsWith("bytes */"))throw new Error("Missing content-length on 416 response");let f=+y.substr(8);c=yield fetch(this.url,{signal:o,cache:"reload",headers:{range:`bytes=0-${f-1}`}})}let d=c.headers.get("Etag");if(d!=null&&d.startsWith("W/")&&(d=null),c.status===416||n&&d&&d!==n)throw this.mustReload=!0,new E(`Server returned non-matching ETag ${n} after one retry. Check browser extensions and servers for issues that may affect correct ETag headers.`);if(c.status>=300)throw new Error(`Bad response code: ${c.status}`);let h=c.headers.get("Content-Length");if(c.status===200&&(!h||+h>t))throw s&&s.abort(),new Error("Server returned no content-length header or content-length exceeding request. Check that your storage backend supports HTTP Byte Serving.");return{data:yield c.arrayBuffer(),etag:d||void 0,cacheControl:c.headers.get("Cache-Control")||void 0,expires:c.headers.get("Expires")||void 0}})}};l(U,"FetchSource");var C=U;function g(i,e){let t=i.getUint32(e+4,!0),r=i.getUint32(e+0,!0);return t*b(2,32)+r}l(g,"getUint64");function X(i,e){let t=new DataView(i),r=t.getUint8(7);if(r>3)throw new Error(`Archive is spec version ${r} but this library supports up to spec version 3`);return{specVersion:r,rootDirectoryOffset:g(t,8),rootDirectoryLength:g(t,16),jsonMetadataOffset:g(t,24),jsonMetadataLength:g(t,32),leafDirectoryOffset:g(t,40),leafDirectoryLength:g(t,48),tileDataOffset:g(t,56),tileDataLength:g(t,64),numAddressedTiles:g(t,72),numTileEntries:g(t,80),numTileContents:g(t,88),clustered:t.getUint8(96)===1,internalCompression:t.getUint8(97),tileCompression:t.getUint8(98),tileType:t.getUint8(99),minZoom:t.getUint8(100),maxZoom:t.getUint8(101),minLon:t.getInt32(102,!0)/1e7,minLat:t.getInt32(106,!0)/1e7,maxLon:t.getInt32(110,!0)/1e7,maxLat:t.getInt32(114,!0)/1e7,centerZoom:t.getUint8(118),centerLon:t.getInt32(119,!0)/1e7,centerLat:t.getInt32(123,!0)/1e7,etag:e}}l(X,"bytesToHeader");function Z(i){let e={buf:new Uint8Array(i),pos:0},t=v(e),r=[],n=0;for(let s=0;s<t;s++){let o=v(e);r.push({tileId:n+o,offset:0,length:0,runLength:1}),n+=o}for(let s=0;s<t;s++)r[s].runLength=v(e);for(let s=0;s<t;s++)r[s].length=v(e);for(let s=0;s<t;s++){let o=v(e);o===0&&s>0?r[s].offset=r[s-1].offset+r[s-1].length:r[s].offset=o-1}return r}l(Z,"deserializeIndex");var R=class R extends Error{};l(R,"EtagMismatch");var E=R;function K(i,e){return m(this,null,function*(){let t=yield i.getBytes(0,16384);if(new DataView(t.data).getUint16(0,!0)!==19792)throw new Error("Wrong magic number for PMTiles archive");let n=t.data.slice(0,Y),s=X(n,t.etag),o=t.data.slice(s.rootDirectoryOffset,s.rootDirectoryOffset+s.rootDirectoryLength),a=`${i.getKey()}|${s.etag||""}|${s.rootDirectoryOffset}|${s.rootDirectoryLength}`,u=Z(yield e(o,s.internalCompression));return[s,[a,u.length,u]]})}l(K,"getHeaderAndRoot");function I(i,e,t,r,n){return m(this,null,function*(){let s=yield i.getBytes(t,r,void 0,n.etag),o=yield e(s.data,n.internalCompression),a=Z(o);if(a.length===0)throw new Error("Empty directory is invalid");return a})}l(I,"getDirectory");var H=class H{constructor(e=100,t=!0,r=D){this.cache=new Map,this.maxCacheEntries=e,this.counter=1,this.decompress=r}getHeader(e){return m(this,null,function*(){let t=e.getKey(),r=this.cache.get(t);if(r)return r.lastUsed=this.counter++,r.data;let n=yield K(e,this.decompress);return n[1]&&this.cache.set(n[1][0],{lastUsed:this.counter++,data:n[1][2]}),this.cache.set(t,{lastUsed:this.counter++,data:n[0]}),this.prune(),n[0]})}getDirectory(e,t,r,n){return m(this,null,function*(){let s=`${e.getKey()}|${n.etag||""}|${t}|${r}`,o=this.cache.get(s);if(o)return o.lastUsed=this.counter++,o.data;let a=yield I(e,this.decompress,t,r,n);return this.cache.set(s,{lastUsed:this.counter++,data:a}),this.prune(),a})}prune(){if(this.cache.size>this.maxCacheEntries){let e=1/0,t;this.cache.forEach((r,n)=>{r.lastUsed<e&&(e=r.lastUsed,t=n)}),t&&this.cache.delete(t)}}invalidate(e){return m(this,null,function*(){this.cache.delete(e.getKey())})}};l(H,"ResolvedValueCache");var $=H,M=class M{constructor(e=100,t=!0,r=D){this.cache=new Map,this.invalidations=new Map,this.maxCacheEntries=e,this.counter=1,this.decompress=r}getHeader(e){return m(this,null,function*(){let t=e.getKey(),r=this.cache.get(t);if(r)return r.lastUsed=this.counter++,yield r.data;let n=new Promise((s,o)=>{K(e,this.decompress).then(a=>{a[1]&&this.cache.set(a[1][0],{lastUsed:this.counter++,data:Promise.resolve(a[1][2])}),s(a[0]),this.prune()}).catch(a=>{o(a)})});return this.cache.set(t,{lastUsed:this.counter++,data:n}),n})}getDirectory(e,t,r,n){return m(this,null,function*(){let s=`${e.getKey()}|${n.etag||""}|${t}|${r}`,o=this.cache.get(s);if(o)return o.lastUsed=this.counter++,yield o.data;let a=new Promise((u,c)=>{I(e,this.decompress,t,r,n).then(d=>{u(d),this.prune()}).catch(d=>{c(d)})});return this.cache.set(s,{lastUsed:this.counter++,data:a}),a})}prune(){if(this.cache.size>=this.maxCacheEntries){let e=1/0,t;this.cache.forEach((r,n)=>{r.lastUsed<e&&(e=r.lastUsed,t=n)}),t&&this.cache.delete(t)}}invalidate(e){return m(this,null,function*(){let t=e.getKey();if(this.invalidations.get(t))return yield this.invalidations.get(t);this.cache.delete(e.getKey());let r=new Promise((n,s)=>{this.getHeader(e).then(o=>{n(),this.invalidations.delete(t)}).catch(o=>{s(o)})});this.invalidations.set(t,r)})}};l(M,"SharedPromiseCache");var P=M,B=class B{constructor(e,t,r){typeof e=="string"?this.source=new C(e):this.source=e,r?this.decompress=r:this.decompress=D,t?this.cache=t:this.cache=new P}getHeader(){return m(this,null,function*(){return yield this.cache.getHeader(this.source)})}getZxyAttempt(e,t,r,n){return m(this,null,function*(){let s=G(e,t,r),o=yield this.cache.getHeader(this.source);if(e<o.minZoom||e>o.maxZoom)return;let a=o.rootDirectoryOffset,u=o.rootDirectoryLength;for(let c=0;c<=3;c++){let d=yield this.cache.getDirectory(this.source,a,u,o),h=Q(d,s);if(h){if(h.runLength>0){let p=yield this.source.getBytes(o.tileDataOffset+h.offset,h.length,n,o.etag);return{data:yield this.decompress(p.data,o.tileCompression),cacheControl:p.cacheControl,expires:p.expires}}a=o.leafDirectoryOffset+h.offset,u=h.length}else return}throw new Error("Maximum directory depth exceeded")})}getZxy(e,t,r,n){return m(this,null,function*(){try{return yield this.getZxyAttempt(e,t,r,n)}catch(s){if(s instanceof E)return this.cache.invalidate(this.source),yield this.getZxyAttempt(e,t,r,n);throw s}})}getMetadataAttempt(){return m(this,null,function*(){let e=yield this.cache.getHeader(this.source),t=yield this.source.getBytes(e.jsonMetadataOffset,e.jsonMetadataLength,void 0,e.etag),r=yield this.decompress(t.data,e.internalCompression),n=new TextDecoder("utf-8");return JSON.parse(n.decode(r))})}getMetadata(){return m(this,null,function*(){try{return yield this.getMetadataAttempt()}catch(e){if(e instanceof E)return this.cache.invalidate(this.source),yield this.getMetadataAttempt();throw e}})}getTileJson(e){return m(this,null,function*(){let t=yield this.getHeader(),r=yield this.getMetadata(),n=_(t.tileType);return{tilejson:"3.0.0",scheme:"xyz",tiles:[`${e}/{z}/{x}/{y}${n}`],vector_layers:r.vector_layers,attribution:r.attribution,description:r.description,name:r.name,version:r.version,bounds:[t.minLon,t.minLat,t.maxLon,t.maxLat],center:[t.centerLon,t.centerLat,t.centerZoom],minzoom:t.minZoom,maxzoom:t.maxZoom}})}};l(B,"PMTiles");var x=B;exports.Compression = J; exports.EtagMismatch = E; exports.FetchSource = C; exports.FileSource = V; exports.PMTiles = x; exports.Protocol = S; exports.ResolvedValueCache = $; exports.SharedPromiseCache = P; exports.TileType = O; exports.bytesToHeader = X; exports.findTile = Q; exports.getUint64 = g; exports.leafletRasterLayer = re; exports.readVarint = v; exports.tileIdToZxy = ie; exports.tileTypeExt = _; exports.zxyToTileId = G;
+"use strict";Object.defineProperty(exports, "__esModule", {value: true});var W=Object.defineProperty;var O=Math.pow;var u=(a,e)=>W(a,"name",{value:e,configurable:!0});var m=(a,e,t)=>new Promise((r,n)=>{var s=c=>{try{i(t.next(c))}catch(l){n(l)}},o=c=>{try{i(t.throw(c))}catch(l){n(l)}},i=c=>c.done?r(c.value):Promise.resolve(c.value).then(s,o);i((t=t.apply(a,e)).next())});var _fflate = require('fflate');var ne=u((a,e)=>{let t=!1,r="",n=L.GridLayer.extend({createTile:u((s,o)=>{let i=document.createElement("img"),c=new AbortController,l=c.signal;return i.cancel=()=>{c.abort()},t||(a.getHeader().then(d=>{d.tileType===1?console.error("Error: archive contains MVT vector tiles, but leafletRasterLayer is for displaying raster tiles. See https://github.com/protomaps/PMTiles/tree/main/js for details."):d.tileType===2?r="image/png":d.tileType===3?r="image/jpeg":d.tileType===4?r="image/webp":d.tileType===5&&(r="image/avif")}),t=!0),a.getZxy(s.z,s.x,s.y,l).then(d=>{if(d){let h=new Blob([d.data],{type:r}),y=window.URL.createObjectURL(h);i.src=y,i.cancel=void 0,o(void 0,i)}}).catch(d=>{if(d.name!=="AbortError")throw d}),i},"createTile"),_removeTile:u(function(s){let o=this._tiles[s];o&&(o.el.cancel&&o.el.cancel(),o.el.width=0,o.el.height=0,o.el.deleted=!0,L.DomUtil.remove(o.el),delete this._tiles[s],this.fire("tileunload",{tile:o.el,coords:this._keyToTileCoords(s)}))},"_removeTile")});return new n(e)},"leafletRasterLayer"),E=u((a,e)=>{let t=Object.keys(a),r=Object.keys(e);if(t.length!==r.length)return!1;for(var n of t){let s=a[n],o=e[n],i=S(s)&&S(o);if(i&&!E(s,o)||!i&&s!==o)return!1}return!0},"isDeepEqual"),S=u(a=>a!=null&&typeof a=="object","isObject"),q=u(a=>(e,t)=>{if(t instanceof AbortController)return a(e,t);let r=new AbortController;return a(e,r).then(n=>t(void 0,n.data,n.cacheControl||"",n.expires||""),n=>t(n)).catch(n=>t(n)),{cancel:u(()=>r.abort(),"cancel")}},"v3compat"),T=class T{constructor(e){this.tilev4=u((e,t)=>m(this,null,function*(){if(e.type==="json"){let y=e.url.substr(10),p=this.tiles.get(y);if((!p||!E(p.source.customHeaders,e.headers))&&(p=new w(y,e.headers),this.tiles.set(y,p)),this.metadata)return{data:yield p.getTileJson(e.url)};let f=yield p.getHeader();return(f.minLon>=f.maxLon||f.minLat>=f.maxLat)&&console.error(`Bounds of PMTiles archive ${f.minLon},${f.minLat},${f.maxLon},${f.maxLat} are not valid.`),{data:{tiles:[`${e.url}/{z}/{x}/{y}`],minzoom:f.minZoom,maxzoom:f.maxZoom,bounds:[f.minLon,f.minLat,f.maxLon,f.maxLat]}}}let r=new RegExp(/pmtiles:\/\/(.+)\/(\d+)\/(\d+)\/(\d+)/),n=e.url.match(r);if(!n)throw new Error("Invalid PMTiles protocol URL");let s=n[1],o=this.tiles.get(s);(!o||!E(o.source.customHeaders,e.headers))&&(o=new w(s,e.headers),this.tiles.set(s,o));let i=n[2],c=n[3],l=n[4],d=yield o.getHeader(),h=yield o==null?void 0:o.getZxy(+i,+c,+l,t.signal);if(h)return{data:new Uint8Array(h.data),cacheControl:h.cacheControl,expires:h.expires};if(d.tileType===1){if(this.errorOnMissingTile)throw new Error("Tile not found.");return{data:new Uint8Array}}return{data:null}}),"tilev4");this.tile=q(this.tilev4);this.tiles=new Map,this.metadata=(e==null?void 0:e.metadata)||!1,this.errorOnMissingTile=(e==null?void 0:e.errorOnMissingTile)||!1}add(e){this.tiles.set(e.source.getKey(),e)}get(e){return this.tiles.get(e)}};u(T,"Protocol");var V=T;function b(a,e){return(e>>>0)*4294967296+(a>>>0)}u(b,"toNum");function N(a,e){let t=e.buf,r=t[e.pos++],n=(r&112)>>4;if(r<128||(r=t[e.pos++],n|=(r&127)<<3,r<128)||(r=t[e.pos++],n|=(r&127)<<10,r<128)||(r=t[e.pos++],n|=(r&127)<<17,r<128)||(r=t[e.pos++],n|=(r&127)<<24,r<128)||(r=t[e.pos++],n|=(r&1)<<31,r<128))return b(a,n);throw new Error("Expected varint not more than 10 bytes")}u(N,"readVarintRemainder");function x(a){let e=a.buf,t=e[a.pos++],r=t&127;return t<128||(t=e[a.pos++],r|=(t&127)<<7,t<128)||(t=e[a.pos++],r|=(t&127)<<14,t<128)||(t=e[a.pos++],r|=(t&127)<<21,t<128)?r:(t=e[a.pos],r|=(t&15)<<28,N(r,a))}u(x,"readVarint");function K(a,e,t,r,n){return n===0?r!==0?[a-1-t,a-1-e]:[t,e]:[e,t]}u(K,"rotate");function G(a,e,t){if(a>26)throw new Error("Tile zoom level exceeds max safe number limit (26)");if(e>=1<<a||t>=1<<a)throw new Error("tile x/y outside zoom level bounds");let r=((1<<a)*(1<<a)-1)/3,n=a-1,[s,o]=[e,t];for(let i=1<<n;i>0;i>>=1){let c=s&i,l=o&i;r+=(3*c^l)*(1<<n),[s,o]=K(i,s,o,c,l),n--}return r}u(G,"zxyToTileId");function J(a){let e=3*a+1;return e<4294967296?31-Math.clz32(e):63-Math.clz32(e/4294967296)}u(J,"tileIdToZ");function ie(a){let e=J(a)>>1;if(e>26)throw new Error("Tile zoom level exceeds max safe number limit (26)");let t=((1<<e)*(1<<e)-1)/3,r=a-t,n=0,s=0,o=1<<e;for(let i=1;i<o;i<<=1){let c=i&r/2,l=i&(r^c);[n,s]=K(i,n,s,c,l),r=r/2,n+=c,s+=l}return[e,n,s]}u(ie,"tileIdToZxy");var _=(s=>(s[s.Unknown=0]="Unknown",s[s.None=1]="None",s[s.Gzip=2]="Gzip",s[s.Brotli=3]="Brotli",s[s.Zstd=4]="Zstd",s))(_||{});function D(a,e){return m(this,null,function*(){if(e===1||e===0)return a;if(e===2){if(typeof globalThis.DecompressionStream=="undefined")return _fflate.decompressSync.call(void 0, new Uint8Array(a));let t=new Response(a).body;if(!t)throw new Error("Failed to read response stream");let r=t.pipeThrough(new globalThis.DecompressionStream("gzip"));return new Response(r).arrayBuffer()}throw new Error("Compression method not supported")})}u(D,"defaultDecompress");var $=(o=>(o[o.Unknown=0]="Unknown",o[o.Mvt=1]="Mvt",o[o.Png=2]="Png",o[o.Jpeg=3]="Jpeg",o[o.Webp=4]="Webp",o[o.Avif=5]="Avif",o))($||{});function Y(a){return a===1?".mvt":a===2?".png":a===3?".jpg":a===4?".webp":a===5?".avif":""}u(Y,"tileTypeExt");var Q=127;function X(a,e){let t=0,r=a.length-1;for(;t<=r;){let n=r+t>>1,s=e-a[n].tileId;if(s>0)t=n+1;else if(s<0)r=n-1;else return a[n]}return r>=0&&(a[r].runLength===0||e-a[r].tileId<a[r].runLength)?a[r]:null}u(X,"findTile");var A=class A{constructor(e){this.file=e}getKey(){return this.file.name}getBytes(e,t){return m(this,null,function*(){return{data:yield this.file.slice(e,e+t).arrayBuffer()}})}};u(A,"FileSource");var k=A,U=class U{constructor(e,t=new Headers){this.url=e,this.customHeaders=t,this.mustReload=!1;let r="";"navigator"in globalThis&&(r=globalThis.navigator.userAgent||"");let n=r.indexOf("Windows")>-1,s=/Chrome|Chromium|Edg|OPR|Brave/.test(r);this.chromeWindowsNoCache=!1,n&&s&&(this.chromeWindowsNoCache=!0)}getKey(){return this.url}setHeaders(e){this.customHeaders=e}getBytes(e,t,r,n){return m(this,null,function*(){let s,o;r?o=r:(s=new AbortController,o=s.signal);let i=new Headers(this.customHeaders);i.set("range",`bytes=${e}-${e+t-1}`);let c;this.mustReload?c="reload":this.chromeWindowsNoCache&&(c="no-store");let l=yield fetch(this.url,{signal:o,cache:c,headers:i});if(e===0&&l.status===416){let p=l.headers.get("Content-Range");if(!p||!p.startsWith("bytes */"))throw new Error("Missing content-length on 416 response");let f=+p.substr(8);l=yield fetch(this.url,{signal:o,cache:"reload",headers:{range:`bytes=0-${f-1}`}})}let d=l.headers.get("Etag");if(d!=null&&d.startsWith("W/")&&(d=null),l.status===416||n&&d&&d!==n)throw this.mustReload=!0,new v(`Server returned non-matching ETag ${n} after one retry. Check browser extensions and servers for issues that may affect correct ETag headers.`);if(l.status>=300)throw new Error(`Bad response code: ${l.status}`);let h=l.headers.get("Content-Length");if(l.status===200&&(!h||+h>t))throw s&&s.abort(),new Error("Server returned no content-length header or content-length exceeding request. Check that your storage backend supports HTTP Byte Serving.");return{data:yield l.arrayBuffer(),etag:d||void 0,cacheControl:l.headers.get("Cache-Control")||void 0,expires:l.headers.get("Expires")||void 0}})}};u(U,"FetchSource");var C=U;function g(a,e){let t=a.getUint32(e+4,!0),r=a.getUint32(e+0,!0);return t*O(2,32)+r}u(g,"getUint64");function ee(a,e){let t=new DataView(a),r=t.getUint8(7);if(r>3)throw new Error(`Archive is spec version ${r} but this library supports up to spec version 3`);return{specVersion:r,rootDirectoryOffset:g(t,8),rootDirectoryLength:g(t,16),jsonMetadataOffset:g(t,24),jsonMetadataLength:g(t,32),leafDirectoryOffset:g(t,40),leafDirectoryLength:g(t,48),tileDataOffset:g(t,56),tileDataLength:g(t,64),numAddressedTiles:g(t,72),numTileEntries:g(t,80),numTileContents:g(t,88),clustered:t.getUint8(96)===1,internalCompression:t.getUint8(97),tileCompression:t.getUint8(98),tileType:t.getUint8(99),minZoom:t.getUint8(100),maxZoom:t.getUint8(101),minLon:t.getInt32(102,!0)/1e7,minLat:t.getInt32(106,!0)/1e7,maxLon:t.getInt32(110,!0)/1e7,maxLat:t.getInt32(114,!0)/1e7,centerZoom:t.getUint8(118),centerLon:t.getInt32(119,!0)/1e7,centerLat:t.getInt32(123,!0)/1e7,etag:e}}u(ee,"bytesToHeader");function I(a){let e={buf:new Uint8Array(a),pos:0},t=x(e),r=[],n=0;for(let s=0;s<t;s++){let o=x(e);r.push({tileId:n+o,offset:0,length:0,runLength:1}),n+=o}for(let s=0;s<t;s++)r[s].runLength=x(e);for(let s=0;s<t;s++)r[s].length=x(e);for(let s=0;s<t;s++){let o=x(e);o===0&&s>0?r[s].offset=r[s-1].offset+r[s-1].length:r[s].offset=o-1}return r}u(I,"deserializeIndex");var R=class R extends Error{};u(R,"EtagMismatch");var v=R;function j(a,e){return m(this,null,function*(){let t=yield a.getBytes(0,16384);if(new DataView(t.data).getUint16(0,!0)!==19792)throw new Error("Wrong magic number for PMTiles archive");let n=t.data.slice(0,Q),s=ee(n,t.etag),o=t.data.slice(s.rootDirectoryOffset,s.rootDirectoryOffset+s.rootDirectoryLength),i=`${a.getKey()}|${s.etag||""}|${s.rootDirectoryOffset}|${s.rootDirectoryLength}`,c=I(yield e(o,s.internalCompression));return[s,[i,c.length,c]]})}u(j,"getHeaderAndRoot");function z(a,e,t,r,n){return m(this,null,function*(){let s=yield a.getBytes(t,r,void 0,n.etag),o=yield e(s.data,n.internalCompression),i=I(o);if(i.length===0)throw new Error("Empty directory is invalid");return i})}u(z,"getDirectory");var H=class H{constructor(e=100,t=!0,r=D){this.cache=new Map,this.maxCacheEntries=e,this.counter=1,this.decompress=r}getHeader(e){return m(this,null,function*(){let t=e.getKey(),r=this.cache.get(t);if(r)return r.lastUsed=this.counter++,r.data;let n=yield j(e,this.decompress);return n[1]&&this.cache.set(n[1][0],{lastUsed:this.counter++,data:n[1][2]}),this.cache.set(t,{lastUsed:this.counter++,data:n[0]}),this.prune(),n[0]})}getDirectory(e,t,r,n){return m(this,null,function*(){let s=`${e.getKey()}|${n.etag||""}|${t}|${r}`,o=this.cache.get(s);if(o)return o.lastUsed=this.counter++,o.data;let i=yield z(e,this.decompress,t,r,n);return this.cache.set(s,{lastUsed:this.counter++,data:i}),this.prune(),i})}prune(){if(this.cache.size>this.maxCacheEntries){let e=1/0,t;this.cache.forEach((r,n)=>{r.lastUsed<e&&(e=r.lastUsed,t=n)}),t&&this.cache.delete(t)}}invalidate(e){return m(this,null,function*(){this.cache.delete(e.getKey())})}};u(H,"ResolvedValueCache");var Z=H,M=class M{constructor(e=100,t=!0,r=D){this.cache=new Map,this.invalidations=new Map,this.maxCacheEntries=e,this.counter=1,this.decompress=r}getHeader(e){return m(this,null,function*(){let t=e.getKey(),r=this.cache.get(t);if(r)return r.lastUsed=this.counter++,yield r.data;let n=new Promise((s,o)=>{j(e,this.decompress).then(i=>{i[1]&&this.cache.set(i[1][0],{lastUsed:this.counter++,data:Promise.resolve(i[1][2])}),s(i[0]),this.prune()}).catch(i=>{o(i)})});return this.cache.set(t,{lastUsed:this.counter++,data:n}),n})}getDirectory(e,t,r,n){return m(this,null,function*(){let s=`${e.getKey()}|${n.etag||""}|${t}|${r}`,o=this.cache.get(s);if(o)return o.lastUsed=this.counter++,yield o.data;let i=new Promise((c,l)=>{z(e,this.decompress,t,r,n).then(d=>{c(d),this.prune()}).catch(d=>{l(d)})});return this.cache.set(s,{lastUsed:this.counter++,data:i}),i})}prune(){if(this.cache.size>=this.maxCacheEntries){let e=1/0,t;this.cache.forEach((r,n)=>{r.lastUsed<e&&(e=r.lastUsed,t=n)}),t&&this.cache.delete(t)}}invalidate(e){return m(this,null,function*(){let t=e.getKey();if(this.invalidations.get(t))return yield this.invalidations.get(t);this.cache.delete(e.getKey());let r=new Promise((n,s)=>{this.getHeader(e).then(o=>{n(),this.invalidations.delete(t)}).catch(o=>{s(o)})});this.invalidations.set(t,r)})}};u(M,"SharedPromiseCache");var P=M,B=class B{constructor(e,t,r,n){typeof e=="string"?this.source=new C(e,t):this.source=e,n?this.decompress=n:this.decompress=D,r?this.cache=r:this.cache=new P}getHeader(){return m(this,null,function*(){return yield this.cache.getHeader(this.source)})}getZxyAttempt(e,t,r,n){return m(this,null,function*(){let s=G(e,t,r),o=yield this.cache.getHeader(this.source);if(e<o.minZoom||e>o.maxZoom)return;let i=o.rootDirectoryOffset,c=o.rootDirectoryLength;for(let l=0;l<=3;l++){let d=yield this.cache.getDirectory(this.source,i,c,o),h=X(d,s);if(h){if(h.runLength>0){let y=yield this.source.getBytes(o.tileDataOffset+h.offset,h.length,n,o.etag);return{data:yield this.decompress(y.data,o.tileCompression),cacheControl:y.cacheControl,expires:y.expires}}i=o.leafDirectoryOffset+h.offset,c=h.length}else return}throw new Error("Maximum directory depth exceeded")})}getZxy(e,t,r,n){return m(this,null,function*(){try{return yield this.getZxyAttempt(e,t,r,n)}catch(s){if(s instanceof v)return this.cache.invalidate(this.source),yield this.getZxyAttempt(e,t,r,n);throw s}})}getMetadataAttempt(){return m(this,null,function*(){let e=yield this.cache.getHeader(this.source),t=yield this.source.getBytes(e.jsonMetadataOffset,e.jsonMetadataLength,void 0,e.etag),r=yield this.decompress(t.data,e.internalCompression),n=new TextDecoder("utf-8");return JSON.parse(n.decode(r))})}getMetadata(){return m(this,null,function*(){try{return yield this.getMetadataAttempt()}catch(e){if(e instanceof v)return this.cache.invalidate(this.source),yield this.getMetadataAttempt();throw e}})}getTileJson(e){return m(this,null,function*(){let t=yield this.getHeader(),r=yield this.getMetadata(),n=Y(t.tileType);return{tilejson:"3.0.0",scheme:"xyz",tiles:[`${e}/{z}/{x}/{y}${n}`],vector_layers:r.vector_layers,attribution:r.attribution,description:r.description,name:r.name,version:r.version,bounds:[t.minLon,t.minLat,t.maxLon,t.maxLat],center:[t.centerLon,t.centerLat,t.centerZoom],minzoom:t.minZoom,maxzoom:t.maxZoom}})}};u(B,"PMTiles");var w=B;exports.Compression = _; exports.EtagMismatch = v; exports.FetchSource = C; exports.FileSource = k; exports.PMTiles = w; exports.Protocol = V; exports.ResolvedValueCache = Z; exports.SharedPromiseCache = P; exports.TileType = $; exports.bytesToHeader = ee; exports.findTile = X; exports.getUint64 = g; exports.leafletRasterLayer = ne; exports.readVarint = x; exports.tileIdToZxy = ie; exports.tileTypeExt = Y; exports.zxyToTileId = G;
 //# sourceMappingURL=index.cjs.map
\ No newline at end of file
diff --git a/node_modules/pmtiles/dist/cjs/index.cjs.map b/node_modules/pmtiles/dist/cjs/index.cjs.map
index feef2eb..694cabe 100644
--- a/node_modules/pmtiles/dist/cjs/index.cjs.map
+++ b/node_modules/pmtiles/dist/cjs/index.cjs.map
@@ -1 +1 @@
-{"version":3,"sources":["/Users/bdon/workspace/protomaps/PMTiles/js/dist/cjs/index.cjs","../../src/index.ts","../../src/adapters.ts"],"names":["leafletRasterLayer","__name","source","options","loaded","mimeType","cls","coord","done","el","controller","signal","header","arr","blob","imageUrl","e","key","tile","v3compat","v4","requestParameters","arg2","abortController","result","err","_Protocol","params","__async","pmtilesUrl","instance","PMTiles","h"],"mappings":"AAAA,6EAAI,CAAC,CAAC,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,I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AU,CAAA,CAEnC,MAAA,CAAIE,CAAAA,CAAE,MAAA,EAAUA,CAAAA,CAAE,MAAA,EAAUA,CAAAA,CAAE,MAAA,EAAUA,CAAAA,CAAE,MAAA,CAAA,EACxC,OAAA,CAAQ,KAAA,CACN,CAAA,0BAAA,EAA6BA,CAAAA,CAAE,MAAM,CAAA,CAAA,EAAIA,CAAAA,CAAE,MAAM,CAAA,CAAA,EAAIA,CAAAA,CAAE,MAAM,CAAA,CAAA,EAAIA,CAAAA,CAAE,MAAM,CAAA,eAAA,CAC3E,CAAA,CAGK,CACL,IAAA,CAAM,CACJ,KAAA,CAAO,CAAC,CAAA,EAAA","file":"/Users/bdon/workspace/protomaps/PMTiles/js/dist/cjs/index.cjs","sourcesContent":[null,"import { decompressSync } from \"fflate\";\nexport * from \"./adapters\";\n\n/** @hidden */\nexport interface BufferPosition {\n  buf: Uint8Array;\n  pos: number;\n}\n\nfunction toNum(low: number, high: number): number {\n  return (high >>> 0) * 0x100000000 + (low >>> 0);\n}\n\nfunction readVarintRemainder(l: number, p: BufferPosition): number {\n  const buf = p.buf;\n  let b = buf[p.pos++];\n  let h = (b & 0x70) >> 4;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x7f) << 3;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x7f) << 10;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x7f) << 17;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x7f) << 24;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x01) << 31;\n  if (b < 0x80) return toNum(l, h);\n  throw new Error(\"Expected varint not more than 10 bytes\");\n}\n\n/** @hidden */\nexport function readVarint(p: BufferPosition): number {\n  const buf = p.buf;\n  let b = buf[p.pos++];\n  let val = b & 0x7f;\n  if (b < 0x80) return val;\n  b = buf[p.pos++];\n  val |= (b & 0x7f) << 7;\n  if (b < 0x80) return val;\n  b = buf[p.pos++];\n  val |= (b & 0x7f) << 14;\n  if (b < 0x80) return val;\n  b = buf[p.pos++];\n  val |= (b & 0x7f) << 21;\n  if (b < 0x80) return val;\n  b = buf[p.pos];\n  val |= (b & 0x0f) << 28;\n\n  return readVarintRemainder(val, p);\n}\n\nfunction rotate(n: number, xy: number[], rx: number, ry: number): void {\n  if (ry === 0) {\n    if (rx === 1) {\n      xy[0] = n - 1 - xy[0];\n      xy[1] = n - 1 - xy[1];\n    }\n    const t = xy[0];\n    xy[0] = xy[1];\n    xy[1] = t;\n  }\n}\n\nfunction idOnLevel(z: number, pos: number): [number, number, number] {\n  const n = 2 ** z;\n  let rx = pos;\n  let ry = pos;\n  let t = pos;\n  const xy = [0, 0];\n  let s = 1;\n  while (s < n) {\n    rx = 1 & (t / 2);\n    ry = 1 & (t ^ rx);\n    rotate(s, xy, rx, ry);\n    xy[0] += s * rx;\n    xy[1] += s * ry;\n    t = t / 4;\n    s *= 2;\n  }\n  return [z, xy[0], xy[1]];\n}\n\nconst tzValues: number[] = [\n  0, 1, 5, 21, 85, 341, 1365, 5461, 21845, 87381, 349525, 1398101, 5592405,\n  22369621, 89478485, 357913941, 1431655765, 5726623061, 22906492245,\n  91625968981, 366503875925, 1466015503701, 5864062014805, 23456248059221,\n  93824992236885, 375299968947541, 1501199875790165,\n];\n\n/**\n * Convert Z,X,Y to a Hilbert TileID.\n */\nexport function zxyToTileId(z: number, x: number, y: number): number {\n  if (z > 26) {\n    throw new Error(\"Tile zoom level exceeds max safe number limit (26)\");\n  }\n  if (x > 2 ** z - 1 || y > 2 ** z - 1) {\n    throw new Error(\"tile x/y outside zoom level bounds\");\n  }\n\n  const acc = tzValues[z];\n  const n = 2 ** z;\n  let rx = 0;\n  let ry = 0;\n  let d = 0;\n  const xy = [x, y];\n  let s = n / 2;\n  while (s > 0) {\n    rx = (xy[0] & s) > 0 ? 1 : 0;\n    ry = (xy[1] & s) > 0 ? 1 : 0;\n    d += s * s * ((3 * rx) ^ ry);\n    rotate(s, xy, rx, ry);\n    s = s / 2;\n  }\n  return acc + d;\n}\n\n/**\n * Convert a Hilbert TileID to Z,X,Y.\n */\nexport function tileIdToZxy(i: number): [number, number, number] {\n  let acc = 0;\n  const z = 0;\n\n  for (let z = 0; z < 27; z++) {\n    const numTiles = (0x1 << z) * (0x1 << z);\n    if (acc + numTiles > i) {\n      return idOnLevel(z, i - acc);\n    }\n    acc += numTiles;\n  }\n\n  throw new Error(\"Tile zoom level exceeds max safe number limit (26)\");\n}\n\n/**\n * PMTiles v3 directory entry.\n */\nexport interface Entry {\n  tileId: number;\n  offset: number;\n  length: number;\n  runLength: number;\n}\n\ninterface MetadataLike {\n  attribution?: string;\n  name?: string;\n  version?: string;\n  // biome-ignore lint: TileJSON spec\n  vector_layers?: string;\n  description?: string;\n}\n\n/**\n * Enum representing a compression algorithm used.\n * 0 = unknown compression, for if you must use a different or unspecified algorithm.\n * 1 = no compression.\n */\nexport enum Compression {\n  Unknown = 0,\n  None = 1,\n  Gzip = 2,\n  Brotli = 3,\n  Zstd = 4,\n}\n\n/**\n * Provide a decompression implementation that acts on `buf` and returns decompressed data.\n *\n * Should use the native DecompressionStream on browsers, zlib on node.\n * Should throw if the compression algorithm is not supported.\n */\nexport type DecompressFunc = (\n  buf: ArrayBuffer,\n  compression: Compression\n) => Promise<ArrayBuffer>;\n\nasync function defaultDecompress(\n  buf: ArrayBuffer,\n  compression: Compression\n): Promise<ArrayBuffer> {\n  if (compression === Compression.None || compression === Compression.Unknown) {\n    return buf;\n  }\n  if (compression === Compression.Gzip) {\n    // biome-ignore lint: needed to detect DecompressionStream in browser+node+cloudflare workers\n    if (typeof (globalThis as any).DecompressionStream === \"undefined\") {\n      return decompressSync(new Uint8Array(buf));\n    }\n    const stream = new Response(buf).body;\n    if (!stream) {\n      throw new Error(\"Failed to read response stream\");\n    }\n    const result: ReadableStream<Uint8Array> = stream.pipeThrough(\n      // biome-ignore lint: needed to detect DecompressionStream in browser+node+cloudflare workers\n      new (globalThis as any).DecompressionStream(\"gzip\")\n    );\n    return new Response(result).arrayBuffer();\n  }\n  throw new Error(\"Compression method not supported\");\n}\n\n/**\n * Describe the type of tiles stored in the archive.\n * 0 is unknown/other, 1 is \"MVT\" vector tiles.\n */\nexport enum TileType {\n  Unknown = 0,\n  Mvt = 1,\n  Png = 2,\n  Jpeg = 3,\n  Webp = 4,\n  Avif = 5,\n}\n\nexport function tileTypeExt(t: TileType): string {\n  if (t === TileType.Mvt) return \".mvt\";\n  if (t === TileType.Png) return \".png\";\n  if (t === TileType.Jpeg) return \".jpg\";\n  if (t === TileType.Webp) return \".webp\";\n  if (t === TileType.Avif) return \".avif\";\n  return \"\";\n}\n\nconst HEADER_SIZE_BYTES = 127;\n\n/**\n * PMTiles v3 header storing basic archive-level information.\n */\nexport interface Header {\n  specVersion: number;\n  rootDirectoryOffset: number;\n  rootDirectoryLength: number;\n  jsonMetadataOffset: number;\n  jsonMetadataLength: number;\n  leafDirectoryOffset: number;\n  leafDirectoryLength?: number;\n  tileDataOffset: number;\n  tileDataLength?: number;\n  numAddressedTiles: number;\n  numTileEntries: number;\n  numTileContents: number;\n  clustered: boolean;\n  internalCompression: Compression;\n  tileCompression: Compression;\n  tileType: TileType;\n  minZoom: number;\n  maxZoom: number;\n  minLon: number;\n  minLat: number;\n  maxLon: number;\n  maxLat: number;\n  centerZoom: number;\n  centerLon: number;\n  centerLat: number;\n  etag?: string;\n}\n\n/**\n * Low-level function for looking up a TileID or leaf directory inside a directory.\n */\nexport function findTile(entries: Entry[], tileId: number): Entry | null {\n  let m = 0;\n  let n = entries.length - 1;\n  while (m <= n) {\n    const k = (n + m) >> 1;\n    const cmp = tileId - entries[k].tileId;\n    if (cmp > 0) {\n      m = k + 1;\n    } else if (cmp < 0) {\n      n = k - 1;\n    } else {\n      return entries[k];\n    }\n  }\n\n  // at this point, m > n\n  if (n >= 0) {\n    if (entries[n].runLength === 0) {\n      return entries[n];\n    }\n    if (tileId - entries[n].tileId < entries[n].runLength) {\n      return entries[n];\n    }\n  }\n  return null;\n}\n\nexport interface RangeResponse {\n  data: ArrayBuffer;\n  etag?: string;\n  expires?: string;\n  cacheControl?: string;\n}\n\n/**\n * Interface for retrieving an archive from remote or local storage.\n */\nexport interface Source {\n  getBytes: (\n    offset: number,\n    length: number,\n    signal?: AbortSignal,\n    etag?: string\n  ) => Promise<RangeResponse>;\n\n  /**\n   * Return a unique string key for the archive e.g. a URL.\n   */\n  getKey: () => string;\n}\n\n/**\n * Use the Browser's File API, which is different from the NodeJS file API.\n * see https://developer.mozilla.org/en-US/docs/Web/API/File_API\n */\nexport class FileSource implements Source {\n  file: File;\n\n  constructor(file: File) {\n    this.file = file;\n  }\n\n  getKey() {\n    return this.file.name;\n  }\n\n  async getBytes(offset: number, length: number): Promise<RangeResponse> {\n    const blob = this.file.slice(offset, offset + length);\n    const a = await blob.arrayBuffer();\n    return { data: a };\n  }\n}\n\n/**\n * Uses the browser Fetch API to make tile requests via HTTP.\n *\n * This method does not send conditional request headers If-Match because of CORS.\n * Instead, it detects ETag mismatches via the response ETag or the 416 response code.\n *\n * This also works around browser and storage-specific edge cases.\n */\nexport class FetchSource implements Source {\n  url: string;\n\n  /**\n   * A [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) object, specfying custom [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) set for all requests to the remote archive.\n   *\n   * This should be used instead of maplibre's [transformRequest](https://maplibre.org/maplibre-gl-js/docs/API/classes/Map/#example) for PMTiles archives.\n   */\n  customHeaders: Headers;\n  /** @hidden */\n  mustReload: boolean;\n  /** @hidden */\n  chromeWindowsNoCache: boolean;\n\n  constructor(url: string, customHeaders: Headers = new Headers()) {\n    this.url = url;\n    this.customHeaders = customHeaders;\n    this.mustReload = false;\n    let userAgent = \"\";\n    if (\"navigator\" in globalThis) {\n      //biome-ignore lint: cf workers\n      userAgent = (globalThis as any).navigator.userAgent || \"\";\n    }\n    const isWindows = userAgent.indexOf(\"Windows\") > -1;\n    const isChromiumBased = /Chrome|Chromium|Edg|OPR|Brave/.test(userAgent);\n    this.chromeWindowsNoCache = false;\n    if (isWindows && isChromiumBased) {\n      this.chromeWindowsNoCache = true;\n    }\n  }\n\n  getKey() {\n    return this.url;\n  }\n\n  /**\n   * Mutate the custom [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) set for all requests to the remote archive.\n   */\n  setHeaders(customHeaders: Headers) {\n    this.customHeaders = customHeaders;\n  }\n\n  async getBytes(\n    offset: number,\n    length: number,\n    passedSignal?: AbortSignal,\n    etag?: string\n  ): Promise<RangeResponse> {\n    let controller: AbortController | undefined;\n    let signal: AbortSignal | undefined;\n    if (passedSignal) {\n      signal = passedSignal;\n    } else {\n      controller = new AbortController();\n      signal = controller.signal;\n    }\n\n    const requestHeaders = new Headers(this.customHeaders);\n    requestHeaders.set(\"range\", `bytes=${offset}-${offset + length - 1}`);\n\n    // we don't send if match because:\n    // * it disables browser caching completely (Chromium)\n    // * it requires a preflight request for every tile request\n    // * it requires CORS configuration becasue If-Match is not a CORs-safelisted header\n    // CORs configuration should expose ETag.\n    // if any etag mismatch is detected, we need to ignore the browser cache\n    let cache: string | undefined;\n    if (this.mustReload) {\n      cache = \"reload\";\n    } else if (this.chromeWindowsNoCache) {\n      cache = \"no-store\";\n    }\n\n    let resp = await fetch(this.url, {\n      signal: signal,\n      cache: cache,\n      headers: requestHeaders,\n      //biome-ignore lint: \"cache\" is incompatible between cloudflare workers and browser\n    } as any);\n\n    // handle edge case where the archive is < 16384 kb total.\n    if (offset === 0 && resp.status === 416) {\n      const contentRange = resp.headers.get(\"Content-Range\");\n      if (!contentRange || !contentRange.startsWith(\"bytes */\")) {\n        throw new Error(\"Missing content-length on 416 response\");\n      }\n      const actualLength = +contentRange.substr(8);\n      resp = await fetch(this.url, {\n        signal: signal,\n        cache: \"reload\",\n        headers: { range: `bytes=0-${actualLength - 1}` },\n        //biome-ignore lint: \"cache\" is incompatible between cloudflare workers and browser\n      } as any);\n    }\n\n    // if it's a weak etag, it's not useful for us, so ignore it.\n    let newEtag = resp.headers.get(\"Etag\");\n    if (newEtag?.startsWith(\"W/\")) {\n      newEtag = null;\n    }\n\n    // some storage systems are misbehaved (Cloudflare R2)\n    if (resp.status === 416 || (etag && newEtag && newEtag !== etag)) {\n      this.mustReload = true;\n      throw new EtagMismatch(\n        `Server returned non-matching ETag ${etag} after one retry. Check browser extensions and servers for issues that may affect correct ETag headers.`\n      );\n    }\n\n    if (resp.status >= 300) {\n      throw new Error(`Bad response code: ${resp.status}`);\n    }\n\n    // some well-behaved backends, e.g. DigitalOcean CDN, respond with 200 instead of 206\n    // but we also need to detect no support for Byte Serving which is returning the whole file\n    const contentLength = resp.headers.get(\"Content-Length\");\n    if (resp.status === 200 && (!contentLength || +contentLength > length)) {\n      if (controller) controller.abort();\n      throw new Error(\n        \"Server returned no content-length header or content-length exceeding request. Check that your storage backend supports HTTP Byte Serving.\"\n      );\n    }\n\n    const a = await resp.arrayBuffer();\n    return {\n      data: a,\n      etag: newEtag || undefined,\n      cacheControl: resp.headers.get(\"Cache-Control\") || undefined,\n      expires: resp.headers.get(\"Expires\") || undefined,\n    };\n  }\n}\n\n/** @hidden */\nexport function getUint64(v: DataView, offset: number): number {\n  const wh = v.getUint32(offset + 4, true);\n  const wl = v.getUint32(offset + 0, true);\n  return wh * 2 ** 32 + wl;\n}\n\n/**\n * Parse raw header bytes into a Header object.\n */\nexport function bytesToHeader(bytes: ArrayBuffer, etag?: string): Header {\n  const v = new DataView(bytes);\n  const specVersion = v.getUint8(7);\n  if (specVersion > 3) {\n    throw new Error(\n      `Archive is spec version ${specVersion} but this library supports up to spec version 3`\n    );\n  }\n\n  return {\n    specVersion: specVersion,\n    rootDirectoryOffset: getUint64(v, 8),\n    rootDirectoryLength: getUint64(v, 16),\n    jsonMetadataOffset: getUint64(v, 24),\n    jsonMetadataLength: getUint64(v, 32),\n    leafDirectoryOffset: getUint64(v, 40),\n    leafDirectoryLength: getUint64(v, 48),\n    tileDataOffset: getUint64(v, 56),\n    tileDataLength: getUint64(v, 64),\n    numAddressedTiles: getUint64(v, 72),\n    numTileEntries: getUint64(v, 80),\n    numTileContents: getUint64(v, 88),\n    clustered: v.getUint8(96) === 1,\n    internalCompression: v.getUint8(97),\n    tileCompression: v.getUint8(98),\n    tileType: v.getUint8(99),\n    minZoom: v.getUint8(100),\n    maxZoom: v.getUint8(101),\n    minLon: v.getInt32(102, true) / 10000000,\n    minLat: v.getInt32(106, true) / 10000000,\n    maxLon: v.getInt32(110, true) / 10000000,\n    maxLat: v.getInt32(114, true) / 10000000,\n    centerZoom: v.getUint8(118),\n    centerLon: v.getInt32(119, true) / 10000000,\n    centerLat: v.getInt32(123, true) / 10000000,\n    etag: etag,\n  };\n}\n\nfunction deserializeIndex(buffer: ArrayBuffer): Entry[] {\n  const p = { buf: new Uint8Array(buffer), pos: 0 };\n  const numEntries = readVarint(p);\n\n  const entries: Entry[] = [];\n\n  let lastId = 0;\n  for (let i = 0; i < numEntries; i++) {\n    const v = readVarint(p);\n    entries.push({ tileId: lastId + v, offset: 0, length: 0, runLength: 1 });\n    lastId += v;\n  }\n\n  for (let i = 0; i < numEntries; i++) {\n    entries[i].runLength = readVarint(p);\n  }\n\n  for (let i = 0; i < numEntries; i++) {\n    entries[i].length = readVarint(p);\n  }\n\n  for (let i = 0; i < numEntries; i++) {\n    const v = readVarint(p);\n    if (v === 0 && i > 0) {\n      entries[i].offset = entries[i - 1].offset + entries[i - 1].length;\n    } else {\n      entries[i].offset = v - 1;\n    }\n  }\n\n  return entries;\n}\n\nfunction detectVersion(a: ArrayBuffer): number {\n  const v = new DataView(a);\n  if (v.getUint16(2, true) === 2) {\n    console.error(\n      \"PMTiles spec version 2 is not supported; please see github.com/protomaps/PMTiles for tools to upgrade\"\n    );\n    return 2;\n  }\n  if (v.getUint16(2, true) === 1) {\n    console.error(\n      \"PMTiles spec version 1 is not supported; please see github.com/protomaps/PMTiles for tools to upgrade\"\n    );\n    return 1;\n  }\n  return 3;\n}\n\n/**\n * Error thrown when a response for PMTiles over HTTP does not match previous, cached parts of the archive.\n * The default PMTiles implementation will catch this error once internally and retry a request.\n */\nexport class EtagMismatch extends Error {}\n\n/**\n * Interface for caches of parts (headers, directories) of a PMTiles archive.\n */\nexport interface Cache {\n  getHeader: (source: Source) => Promise<Header>;\n  getDirectory: (\n    source: Source,\n    offset: number,\n    length: number,\n    header: Header\n  ) => Promise<Entry[]>;\n  invalidate: (source: Source) => Promise<void>;\n}\n\nasync function getHeaderAndRoot(\n  source: Source,\n  decompress: DecompressFunc\n): Promise<[Header, [string, number, Entry[] | ArrayBuffer]?]> {\n  const resp = await source.getBytes(0, 16384);\n\n  const v = new DataView(resp.data);\n  if (v.getUint16(0, true) !== 0x4d50) {\n    throw new Error(\"Wrong magic number for PMTiles archive\");\n  }\n\n  const headerData = resp.data.slice(0, HEADER_SIZE_BYTES);\n\n  const header = bytesToHeader(headerData, resp.etag);\n\n  // optimistically set the root directory\n  // TODO check root bounds\n  const rootDirData = resp.data.slice(\n    header.rootDirectoryOffset,\n    header.rootDirectoryOffset + header.rootDirectoryLength\n  );\n  const dirKey = `${source.getKey()}|${header.etag || \"\"}|${\n    header.rootDirectoryOffset\n  }|${header.rootDirectoryLength}`;\n\n  const rootDir = deserializeIndex(\n    await decompress(rootDirData, header.internalCompression)\n  );\n  return [header, [dirKey, rootDir.length, rootDir]];\n}\n\nasync function getDirectory(\n  source: Source,\n  decompress: DecompressFunc,\n  offset: number,\n  length: number,\n  header: Header\n): Promise<Entry[]> {\n  const resp = await source.getBytes(offset, length, undefined, header.etag);\n  const data = await decompress(resp.data, header.internalCompression);\n  const directory = deserializeIndex(data);\n  if (directory.length === 0) {\n    throw new Error(\"Empty directory is invalid\");\n  }\n\n  return directory;\n}\n\ninterface ResolvedValue {\n  lastUsed: number;\n  data: Header | Entry[] | ArrayBuffer;\n}\n\n/**\n * A cache for parts of a PMTiles archive where promises are never shared between requests.\n *\n * Runtimes such as Cloudflare Workers cannot share promises between different requests.\n *\n * Only caches headers and directories, not individual tile contents.\n */\nexport class ResolvedValueCache {\n  cache: Map<string, ResolvedValue>;\n  maxCacheEntries: number;\n  counter: number;\n  decompress: DecompressFunc;\n\n  constructor(\n    maxCacheEntries = 100,\n    prefetch = true, // deprecated\n    decompress: DecompressFunc = defaultDecompress\n  ) {\n    this.cache = new Map<string, ResolvedValue>();\n    this.maxCacheEntries = maxCacheEntries;\n    this.counter = 1;\n    this.decompress = decompress;\n  }\n\n  async getHeader(source: Source): Promise<Header> {\n    const cacheKey = source.getKey();\n    const cacheValue = this.cache.get(cacheKey);\n    if (cacheValue) {\n      cacheValue.lastUsed = this.counter++;\n      const data = cacheValue.data;\n      return data as Header;\n    }\n\n    const res = await getHeaderAndRoot(source, this.decompress);\n    if (res[1]) {\n      this.cache.set(res[1][0], {\n        lastUsed: this.counter++,\n        data: res[1][2],\n      });\n    }\n\n    this.cache.set(cacheKey, {\n      lastUsed: this.counter++,\n      data: res[0],\n    });\n    this.prune();\n    return res[0];\n  }\n\n  async getDirectory(\n    source: Source,\n    offset: number,\n    length: number,\n    header: Header\n  ): Promise<Entry[]> {\n    const cacheKey = `${source.getKey()}|${\n      header.etag || \"\"\n    }|${offset}|${length}`;\n    const cacheValue = this.cache.get(cacheKey);\n    if (cacheValue) {\n      cacheValue.lastUsed = this.counter++;\n      const data = cacheValue.data;\n      return data as Entry[];\n    }\n\n    const directory = await getDirectory(\n      source,\n      this.decompress,\n      offset,\n      length,\n      header\n    );\n    this.cache.set(cacheKey, {\n      lastUsed: this.counter++,\n      data: directory,\n    });\n    this.prune();\n    return directory;\n  }\n\n  prune() {\n    if (this.cache.size > this.maxCacheEntries) {\n      let minUsed = Infinity;\n      let minKey = undefined;\n      this.cache.forEach((cacheValue: ResolvedValue, key: string) => {\n        if (cacheValue.lastUsed < minUsed) {\n          minUsed = cacheValue.lastUsed;\n          minKey = key;\n        }\n      });\n      if (minKey) {\n        this.cache.delete(minKey);\n      }\n    }\n  }\n\n  async invalidate(source: Source) {\n    this.cache.delete(source.getKey());\n  }\n}\n\ninterface SharedPromiseCacheValue {\n  lastUsed: number;\n  data: Promise<Header | Entry[] | ArrayBuffer>;\n}\n\n/**\n * A cache for parts of a PMTiles archive where promises can be shared between requests.\n *\n * Only caches headers and directories, not individual tile contents.\n */\nexport class SharedPromiseCache {\n  cache: Map<string, SharedPromiseCacheValue>;\n  invalidations: Map<string, Promise<void>>;\n  maxCacheEntries: number;\n  counter: number;\n  decompress: DecompressFunc;\n\n  constructor(\n    maxCacheEntries = 100,\n    prefetch = true, // deprecated\n    decompress: DecompressFunc = defaultDecompress\n  ) {\n    this.cache = new Map<string, SharedPromiseCacheValue>();\n    this.invalidations = new Map<string, Promise<void>>();\n    this.maxCacheEntries = maxCacheEntries;\n    this.counter = 1;\n    this.decompress = decompress;\n  }\n\n  async getHeader(source: Source): Promise<Header> {\n    const cacheKey = source.getKey();\n    const cacheValue = this.cache.get(cacheKey);\n    if (cacheValue) {\n      cacheValue.lastUsed = this.counter++;\n      const data = await cacheValue.data;\n      return data as Header;\n    }\n\n    const p = new Promise<Header>((resolve, reject) => {\n      getHeaderAndRoot(source, this.decompress)\n        .then((res) => {\n          if (res[1]) {\n            this.cache.set(res[1][0], {\n              lastUsed: this.counter++,\n              data: Promise.resolve(res[1][2]),\n            });\n          }\n          resolve(res[0]);\n          this.prune();\n        })\n        .catch((e) => {\n          reject(e);\n        });\n    });\n    this.cache.set(cacheKey, { lastUsed: this.counter++, data: p });\n    return p;\n  }\n\n  async getDirectory(\n    source: Source,\n    offset: number,\n    length: number,\n    header: Header\n  ): Promise<Entry[]> {\n    const cacheKey = `${source.getKey()}|${\n      header.etag || \"\"\n    }|${offset}|${length}`;\n    const cacheValue = this.cache.get(cacheKey);\n    if (cacheValue) {\n      cacheValue.lastUsed = this.counter++;\n      const data = await cacheValue.data;\n      return data as Entry[];\n    }\n\n    const p = new Promise<Entry[]>((resolve, reject) => {\n      getDirectory(source, this.decompress, offset, length, header)\n        .then((directory) => {\n          resolve(directory);\n          this.prune();\n        })\n        .catch((e) => {\n          reject(e);\n        });\n    });\n    this.cache.set(cacheKey, { lastUsed: this.counter++, data: p });\n    return p;\n  }\n\n  prune() {\n    if (this.cache.size >= this.maxCacheEntries) {\n      let minUsed = Infinity;\n      let minKey = undefined;\n      this.cache.forEach((cacheValue: SharedPromiseCacheValue, key: string) => {\n        if (cacheValue.lastUsed < minUsed) {\n          minUsed = cacheValue.lastUsed;\n          minKey = key;\n        }\n      });\n      if (minKey) {\n        this.cache.delete(minKey);\n      }\n    }\n  }\n\n  async invalidate(source: Source) {\n    const key = source.getKey();\n    if (this.invalidations.get(key)) {\n      return await this.invalidations.get(key);\n    }\n    this.cache.delete(source.getKey());\n    const p = new Promise<void>((resolve, reject) => {\n      this.getHeader(source)\n        .then((h) => {\n          resolve();\n          this.invalidations.delete(key);\n        })\n        .catch((e) => {\n          reject(e);\n        });\n    });\n    this.invalidations.set(key, p);\n  }\n}\n\n/**\n * Main class encapsulating PMTiles decoding logic.\n *\n * if `source` is a string, creates a FetchSource using that string as the URL to a remote PMTiles.\n * if no `cache` is passed, use a SharedPromiseCache.\n * if no `decompress` is passed, default to the browser DecompressionStream API with a fallback to `fflate`.\n */\n// biome-ignore lint: that's just how its capitalized\nexport class PMTiles {\n  source: Source;\n  cache: Cache;\n  decompress: DecompressFunc;\n\n  constructor(\n    source: Source | string,\n    cache?: Cache,\n    decompress?: DecompressFunc\n  ) {\n    if (typeof source === \"string\") {\n      this.source = new FetchSource(source);\n    } else {\n      this.source = source;\n    }\n    if (decompress) {\n      this.decompress = decompress;\n    } else {\n      this.decompress = defaultDecompress;\n    }\n    if (cache) {\n      this.cache = cache;\n    } else {\n      this.cache = new SharedPromiseCache();\n    }\n  }\n\n  /**\n   * Return the header of the archive,\n   * including information such as tile type, min/max zoom, bounds, and summary statistics.\n   */\n  async getHeader() {\n    return await this.cache.getHeader(this.source);\n  }\n\n  /** @hidden */\n  async getZxyAttempt(\n    z: number,\n    x: number,\n    y: number,\n    signal?: AbortSignal\n  ): Promise<RangeResponse | undefined> {\n    const tileId = zxyToTileId(z, x, y);\n    const header = await this.cache.getHeader(this.source);\n\n    if (z < header.minZoom || z > header.maxZoom) {\n      return undefined;\n    }\n\n    let dO = header.rootDirectoryOffset;\n    let dL = header.rootDirectoryLength;\n    for (let depth = 0; depth <= 3; depth++) {\n      const directory = await this.cache.getDirectory(\n        this.source,\n        dO,\n        dL,\n        header\n      );\n      const entry = findTile(directory, tileId);\n      if (entry) {\n        if (entry.runLength > 0) {\n          const resp = await this.source.getBytes(\n            header.tileDataOffset + entry.offset,\n            entry.length,\n            signal,\n            header.etag\n          );\n          return {\n            data: await this.decompress(resp.data, header.tileCompression),\n            cacheControl: resp.cacheControl,\n            expires: resp.expires,\n          };\n        }\n        dO = header.leafDirectoryOffset + entry.offset;\n        dL = entry.length;\n      } else {\n        // TODO: We should in fact return a valid RangeResponse\n        // with empty data, but filled in cache control / expires headers\n        return undefined;\n      }\n    }\n    throw new Error(\"Maximum directory depth exceeded\");\n  }\n\n  /**\n   * Primary method to get a single tile's bytes from an archive.\n   *\n   * Returns undefined if the tile does not exist in the archive.\n   */\n  async getZxy(\n    z: number,\n    x: number,\n    y: number,\n    signal?: AbortSignal\n  ): Promise<RangeResponse | undefined> {\n    try {\n      return await this.getZxyAttempt(z, x, y, signal);\n    } catch (e) {\n      if (e instanceof EtagMismatch) {\n        this.cache.invalidate(this.source);\n        return await this.getZxyAttempt(z, x, y, signal);\n      }\n      throw e;\n    }\n  }\n\n  /** @hidden */\n  async getMetadataAttempt(): Promise<unknown> {\n    const header = await this.cache.getHeader(this.source);\n\n    const resp = await this.source.getBytes(\n      header.jsonMetadataOffset,\n      header.jsonMetadataLength,\n      undefined,\n      header.etag\n    );\n    const decompressed = await this.decompress(\n      resp.data,\n      header.internalCompression\n    );\n    const dec = new TextDecoder(\"utf-8\");\n    return JSON.parse(dec.decode(decompressed));\n  }\n\n  /**\n   * Return the arbitrary JSON metadata of the archive.\n   */\n  async getMetadata(): Promise<unknown> {\n    try {\n      return await this.getMetadataAttempt();\n    } catch (e) {\n      if (e instanceof EtagMismatch) {\n        this.cache.invalidate(this.source);\n        return await this.getMetadataAttempt();\n      }\n      throw e;\n    }\n  }\n\n  /**\n   * Construct a [TileJSON](https://github.com/mapbox/tilejson-spec) object.\n   *\n   * baseTilesUrl is the desired tiles URL, excluding the suffix `/{z}/{x}/{y}.{ext}`.\n   * For example, if the desired URL is `http://example.com/tileset/{z}/{x}/{y}.mvt`,\n   * the baseTilesUrl should be `https://example.com/tileset`.\n   */\n  async getTileJson(baseTilesUrl: string): Promise<unknown> {\n    const header = await this.getHeader();\n    const metadata = (await this.getMetadata()) as MetadataLike;\n    const ext = tileTypeExt(header.tileType);\n\n    return {\n      tilejson: \"3.0.0\",\n      scheme: \"xyz\",\n      tiles: [`${baseTilesUrl}/{z}/{x}/{y}${ext}`],\n      // biome-ignore lint: TileJSON spec\n      vector_layers: metadata.vector_layers,\n      attribution: metadata.attribution,\n      description: metadata.description,\n      name: metadata.name,\n      version: metadata.version,\n      bounds: [header.minLon, header.minLat, header.maxLon, header.maxLat],\n      center: [header.centerLon, header.centerLat, header.centerZoom],\n      minzoom: header.minZoom,\n      maxzoom: header.maxZoom,\n    };\n  }\n}\n","// biome-ignore lint: needed for Leaflet + IIFE to work\ndeclare const L: any;\n// biome-ignore lint: needed for window.URL to disambiguate from cloudflare workers\ndeclare const window: any;\ndeclare const document: DocumentLike;\n\nimport type { Coords } from \"leaflet\";\nimport { PMTiles, TileType } from \"./index\";\n\ninterface DocumentLike {\n  // biome-ignore lint: we don't want to bring in the entire document type\n  createElement: (s: string) => any;\n}\n\n// biome-ignore lint: we don't want to bring in the entire document type\ntype DoneCallback = (error?: Error, tile?: any) => void;\n\n/**\n * Add a raster PMTiles as a layer to a Leaflet map.\n *\n * For vector tiles see https://github.com/protomaps/protomaps-leaflet\n */\nexport const leafletRasterLayer = (source: PMTiles, options: unknown) => {\n  let loaded = false;\n  let mimeType = \"\";\n  const cls = L.GridLayer.extend({\n    createTile: (coord: Coords, done: DoneCallback) => {\n      const el = document.createElement(\"img\");\n      const controller = new AbortController();\n      const signal = controller.signal;\n      el.cancel = () => {\n        controller.abort();\n      };\n      if (!loaded) {\n        source.getHeader().then((header) => {\n          if (header.tileType === TileType.Mvt) {\n            console.error(\n              \"Error: archive contains MVT vector tiles, but leafletRasterLayer is for displaying raster tiles. See https://github.com/protomaps/PMTiles/tree/main/js for details.\"\n            );\n          } else if (header.tileType === 2) {\n            mimeType = \"image/png\";\n          } else if (header.tileType === 3) {\n            mimeType = \"image/jpeg\";\n          } else if (header.tileType === 4) {\n            mimeType = \"image/webp\";\n          } else if (header.tileType === 5) {\n            mimeType = \"image/avif\";\n          }\n        });\n        loaded = true;\n      }\n      source\n        .getZxy(coord.z, coord.x, coord.y, signal)\n        .then((arr) => {\n          if (arr) {\n            const blob = new Blob([arr.data], { type: mimeType });\n            const imageUrl = window.URL.createObjectURL(blob);\n            el.src = imageUrl;\n            el.cancel = undefined;\n            done(undefined, el);\n          }\n        })\n        .catch((e) => {\n          if (e.name !== \"AbortError\") {\n            throw e;\n          }\n        });\n      return el;\n    },\n\n    _removeTile: function (key: string) {\n      const tile = this._tiles[key];\n      if (!tile) {\n        return;\n      }\n\n      if (tile.el.cancel) tile.el.cancel();\n\n      tile.el.width = 0;\n      tile.el.height = 0;\n      tile.el.deleted = true;\n      L.DomUtil.remove(tile.el);\n      delete this._tiles[key];\n      this.fire(\"tileunload\", {\n        tile: tile.el,\n        coords: this._keyToTileCoords(key),\n      });\n    },\n  });\n  return new cls(options);\n};\n\ntype GetResourceResponse<T> = ExpiryData & {\n  data: T;\n};\ntype AddProtocolAction = (\n  requestParameters: RequestParameters,\n  abortController: AbortController\n) => Promise<GetResourceResponse<unknown>>;\n\ntype ExpiryData = {\n  cacheControl?: string | null;\n  expires?: string | null; // MapLibre can be a Date object\n};\n\n// copied from MapLibre /util/ajax.ts\ntype RequestParameters = {\n  url: string;\n  headers?: unknown;\n  method?: \"GET\" | \"POST\" | \"PUT\";\n  body?: string;\n  type?: \"string\" | \"json\" | \"arrayBuffer\" | \"image\";\n  credentials?: \"same-origin\" | \"include\";\n  collectResourceTiming?: boolean;\n};\n\n// for legacy maplibre-3 interop\ntype ResponseCallbackV3 = (\n  error?: Error | undefined,\n  data?: unknown | undefined,\n  cacheControl?: string | undefined,\n  expires?: string | undefined\n) => void;\n\ntype V3OrV4Protocol = <\n  T extends AbortController | ResponseCallbackV3,\n  R = T extends AbortController\n    ? Promise<GetResourceResponse<unknown>>\n    : { cancel: () => void },\n>(\n  requestParameters: RequestParameters,\n  arg2: T\n) => R;\n\nconst v3compat =\n  (v4: AddProtocolAction): V3OrV4Protocol =>\n  (requestParameters, arg2) => {\n    if (arg2 instanceof AbortController) {\n      // biome-ignore lint: overloading return type not handled by compiler\n      return v4(requestParameters, arg2) as any;\n    }\n    const abortController = new AbortController();\n    v4(requestParameters, abortController)\n      .then(\n        (result) => {\n          return arg2(\n            undefined,\n            result.data,\n            result.cacheControl || \"\",\n            result.expires || \"\"\n          );\n        },\n        (err) => {\n          return arg2(err);\n        }\n      )\n      .catch((e) => {\n        return arg2(e);\n      });\n    return { cancel: () => abortController.abort() };\n  };\n\n/**\n * MapLibre GL JS protocol. Must be added once globally.\n */\nexport class Protocol {\n  /** @hidden */\n  tiles: Map<string, PMTiles>;\n  metadata: boolean;\n  errorOnMissingTile: boolean;\n\n  /**\n   * Initialize the MapLibre PMTiles protocol.\n   *\n   * * metadata: also load the metadata section of the PMTiles. required for some \"inspect\" functionality\n   * and to automatically populate the map attribution. Requires an extra HTTP request.\n   * * errorOnMissingTile: When a vector MVT tile is missing from the archive, raise an error instead of\n   * returning the empty array. Not recommended. This is only to reproduce the behavior of ZXY tile APIs\n   * which some applications depend on when overzooming.\n   */\n  constructor(options?: { metadata?: boolean; errorOnMissingTile?: boolean }) {\n    this.tiles = new Map<string, PMTiles>();\n    this.metadata = options?.metadata || false;\n    this.errorOnMissingTile = options?.errorOnMissingTile || false;\n  }\n\n  /**\n   * Add a {@link PMTiles} instance to the global protocol instance.\n   *\n   * For remote fetch sources, references in MapLibre styles like pmtiles://http://...\n   * will resolve to the same instance if the URLs match.\n   */\n  add(p: PMTiles) {\n    this.tiles.set(p.source.getKey(), p);\n  }\n\n  /**\n   * Fetch a {@link PMTiles} instance by URL, for remote PMTiles instances.\n   */\n  get(url: string) {\n    return this.tiles.get(url);\n  }\n\n  /** @hidden */\n  tilev4 = async (\n    params: RequestParameters,\n    abortController: AbortController\n  ) => {\n    if (params.type === \"json\") {\n      const pmtilesUrl = params.url.substr(10);\n      let instance = this.tiles.get(pmtilesUrl);\n      if (!instance) {\n        instance = new PMTiles(pmtilesUrl);\n        this.tiles.set(pmtilesUrl, instance);\n      }\n\n      if (this.metadata) {\n        return {\n          data: await instance.getTileJson(params.url),\n        };\n      }\n\n      const h = await instance.getHeader();\n\n      if (h.minLon >= h.maxLon || h.minLat >= h.maxLat) {\n        console.error(\n          `Bounds of PMTiles archive ${h.minLon},${h.minLat},${h.maxLon},${h.maxLat} are not valid.`\n        );\n      }\n\n      return {\n        data: {\n          tiles: [`${params.url}/{z}/{x}/{y}`],\n          minzoom: h.minZoom,\n          maxzoom: h.maxZoom,\n          bounds: [h.minLon, h.minLat, h.maxLon, h.maxLat],\n        },\n      };\n    }\n    const re = new RegExp(/pmtiles:\\/\\/(.+)\\/(\\d+)\\/(\\d+)\\/(\\d+)/);\n    const result = params.url.match(re);\n    if (!result) {\n      throw new Error(\"Invalid PMTiles protocol URL\");\n    }\n    const pmtilesUrl = result[1];\n\n    let instance = this.tiles.get(pmtilesUrl);\n    if (!instance) {\n      instance = new PMTiles(pmtilesUrl);\n      this.tiles.set(pmtilesUrl, instance);\n    }\n    const z = result[2];\n    const x = result[3];\n    const y = result[4];\n\n    const header = await instance.getHeader();\n    const resp = await instance?.getZxy(+z, +x, +y, abortController.signal);\n    if (resp) {\n      return {\n        data: new Uint8Array(resp.data),\n        cacheControl: resp.cacheControl,\n        expires: resp.expires,\n      };\n    }\n    if (header.tileType === TileType.Mvt) {\n      if (this.errorOnMissingTile) {\n        throw new Error(\"Tile not found.\");\n      }\n      return { data: new Uint8Array() };\n    }\n    return { data: null };\n  };\n\n  tile = v3compat(this.tilev4);\n}\n"]}
\ No newline at end of file
+{"version":3,"sources":["/home/quentin/Documents/PMTiles/js/dist/cjs/index.cjs","../../src/index.ts","../../src/adapters.ts"],"names":["leafletRasterLayer","__name","source","options","loaded","mimeType","cls","coord","done","el","controller","signal","header","arr","blob","imageUrl","e","key","tile","isDeepEqual","object1","object2","objKeys1","objKeys2","value1","value2","isObjects","isObject","object","v3compat","v4","requestParameters","arg2","abortController","result","err","_Protocol","params","__async","pmtilesUrl","instance","PMTiles","h"],"mappings":"AAAA,6EAAI,CAAC,CAAC,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,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AAA,CAAA,EAAA,CAClFG,CAAAA,CAAW,IAAIC,CAAAA,CAAQF,CAAAA,CAAYF,CAAAA,CAAO,OAAkB,CAAA,CAC5D,IAAA,CAAK,KAAA,CAAM,GAAA,CAAIE,CAAAA,CAAYC,CAAQ,CAAA,CAAA,CAGjC,IAAA,CAAK,QAAA,CACP,MAAO,CACL,IAAA,CAAM,MAAMA,CAAAA,CAAS,WAAA,CAAYH,CAAAA,CAAO,GAAG,CAC7C,CAAA,CAGF,IAAMK,CAAAA,CAAI,MAAMF,CAAAA,CAAS,SAAA,CAAU,CAAA,CAEnC,MAAA,CAAIE,CAAAA,CAAE,MAAA,EAAUA,CAAAA,CAAE,MAAA,EAAUA,CAAAA,CAAE,MAAA,EAAUA,CAAAA,CAAE,MAAA,CAAA,EACxC,OAAA,CAAQ,KAAA,CACN,CAAA,0BAAA,EAA6BA,CAAAA,CAAE,MAAM,CAAA,CAAA,EAAIA,CAAAA,CAAE,MAAM,CAAA,CAAA,EAAIA,CAAAA,CAAE,MAAM,CAAA,CAAA,EAAIA,CAAAA,CAAE,MAAM,CAAA,eAAA,CAC3E,CAAA,CAGK,CACL,IAAA,CAAM,CACJ,KAAA,CAAO,CAAC,CAAA,EAAA","file":"/home/quentin/Documents/PMTiles/js/dist/cjs/index.cjs","sourcesContent":[null,"import { decompressSync } from \"fflate\";\nexport * from \"./adapters\";\n\n/** @hidden */\nexport interface BufferPosition {\n  buf: Uint8Array;\n  pos: number;\n}\n\nfunction toNum(low: number, high: number): number {\n  return (high >>> 0) * 0x100000000 + (low >>> 0);\n}\n\nfunction readVarintRemainder(l: number, p: BufferPosition): number {\n  const buf = p.buf;\n  let b = buf[p.pos++];\n  let h = (b & 0x70) >> 4;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x7f) << 3;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x7f) << 10;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x7f) << 17;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x7f) << 24;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x01) << 31;\n  if (b < 0x80) return toNum(l, h);\n  throw new Error(\"Expected varint not more than 10 bytes\");\n}\n\n/** @hidden */\nexport function readVarint(p: BufferPosition): number {\n  const buf = p.buf;\n  let b = buf[p.pos++];\n  let val = b & 0x7f;\n  if (b < 0x80) return val;\n  b = buf[p.pos++];\n  val |= (b & 0x7f) << 7;\n  if (b < 0x80) return val;\n  b = buf[p.pos++];\n  val |= (b & 0x7f) << 14;\n  if (b < 0x80) return val;\n  b = buf[p.pos++];\n  val |= (b & 0x7f) << 21;\n  if (b < 0x80) return val;\n  b = buf[p.pos];\n  val |= (b & 0x0f) << 28;\n\n  return readVarintRemainder(val, p);\n}\n\nfunction rotate(\n  n: number,\n  x: number,\n  y: number,\n  rx: number,\n  ry: number\n): [number, number] {\n  if (ry === 0) {\n    if (rx !== 0) {\n      return [n - 1 - y, n - 1 - x];\n    }\n    return [y, x];\n  }\n  return [x, y];\n}\n\n/**\n * Convert Z,X,Y to a Hilbert TileID.\n */\nexport function zxyToTileId(z: number, x: number, y: number): number {\n  if (z > 26) {\n    throw new Error(\"Tile zoom level exceeds max safe number limit (26)\");\n  }\n  if (x >= 1 << z || y >= 1 << z) {\n    throw new Error(\"tile x/y outside zoom level bounds\");\n  }\n  let acc = ((1 << z) * (1 << z) - 1) / 3;\n  let a = z - 1;\n  let [tx, ty] = [x, y];\n  for (let s = 1 << a; s > 0; s >>= 1) {\n    const rx = tx & s;\n    const ry = ty & s;\n    acc += ((3 * rx) ^ ry) * (1 << a);\n    [tx, ty] = rotate(s, tx, ty, rx, ry);\n    a--;\n  }\n  return acc;\n}\n\nfunction tileIdToZ(i: number): number {\n  const c = 3 * i + 1;\n  if (c < 0x100000000) {\n    return 31 - Math.clz32(c);\n  }\n  return 63 - Math.clz32(c / 0x100000000);\n}\n\n/**\n * Convert a Hilbert TileID to Z,X,Y.\n */\nexport function tileIdToZxy(i: number): [number, number, number] {\n  const z = tileIdToZ(i) >> 1;\n  if (z > 26)\n    throw new Error(\"Tile zoom level exceeds max safe number limit (26)\");\n  const acc = ((1 << z) * (1 << z) - 1) / 3;\n\n  let t = i - acc;\n  let x = 0;\n  let y = 0;\n  const n = 1 << z;\n  for (let s = 1; s < n; s <<= 1) {\n    const rx = s & (t / 2);\n    const ry = s & (t ^ rx);\n    [x, y] = rotate(s, x, y, rx, ry);\n    t = t / 2;\n    x += rx;\n    y += ry;\n  }\n  return [z, x, y];\n}\n\n/**\n * PMTiles v3 directory entry.\n */\nexport interface Entry {\n  tileId: number;\n  offset: number;\n  length: number;\n  runLength: number;\n}\n\ninterface MetadataLike {\n  attribution?: string;\n  name?: string;\n  version?: string;\n  // biome-ignore lint: TileJSON spec\n  vector_layers?: string;\n  description?: string;\n}\n\n/**\n * Enum representing a compression algorithm used.\n * 0 = unknown compression, for if you must use a different or unspecified algorithm.\n * 1 = no compression.\n */\nexport enum Compression {\n  Unknown = 0,\n  None = 1,\n  Gzip = 2,\n  Brotli = 3,\n  Zstd = 4,\n}\n\n/**\n * Provide a decompression implementation that acts on `buf` and returns decompressed data.\n *\n * Should use the native DecompressionStream on browsers, zlib on node.\n * Should throw if the compression algorithm is not supported.\n */\nexport type DecompressFunc = (\n  buf: ArrayBuffer,\n  compression: Compression\n) => Promise<ArrayBuffer>;\n\nasync function defaultDecompress(\n  buf: ArrayBuffer,\n  compression: Compression\n): Promise<ArrayBuffer> {\n  if (compression === Compression.None || compression === Compression.Unknown) {\n    return buf;\n  }\n  if (compression === Compression.Gzip) {\n    // biome-ignore lint: needed to detect DecompressionStream in browser+node+cloudflare workers\n    if (typeof (globalThis as any).DecompressionStream === \"undefined\") {\n      return decompressSync(new Uint8Array(buf));\n    }\n    const stream = new Response(buf).body;\n    if (!stream) {\n      throw new Error(\"Failed to read response stream\");\n    }\n    const result: ReadableStream<Uint8Array> = stream.pipeThrough(\n      // biome-ignore lint: needed to detect DecompressionStream in browser+node+cloudflare workers\n      new (globalThis as any).DecompressionStream(\"gzip\")\n    );\n    return new Response(result).arrayBuffer();\n  }\n  throw new Error(\"Compression method not supported\");\n}\n\n/**\n * Describe the type of tiles stored in the archive.\n * 0 is unknown/other, 1 is \"MVT\" vector tiles.\n */\nexport enum TileType {\n  Unknown = 0,\n  Mvt = 1,\n  Png = 2,\n  Jpeg = 3,\n  Webp = 4,\n  Avif = 5,\n}\n\nexport function tileTypeExt(t: TileType): string {\n  if (t === TileType.Mvt) return \".mvt\";\n  if (t === TileType.Png) return \".png\";\n  if (t === TileType.Jpeg) return \".jpg\";\n  if (t === TileType.Webp) return \".webp\";\n  if (t === TileType.Avif) return \".avif\";\n  return \"\";\n}\n\nconst HEADER_SIZE_BYTES = 127;\n\n/**\n * PMTiles v3 header storing basic archive-level information.\n */\nexport interface Header {\n  specVersion: number;\n  rootDirectoryOffset: number;\n  rootDirectoryLength: number;\n  jsonMetadataOffset: number;\n  jsonMetadataLength: number;\n  leafDirectoryOffset: number;\n  leafDirectoryLength?: number;\n  tileDataOffset: number;\n  tileDataLength?: number;\n  numAddressedTiles: number;\n  numTileEntries: number;\n  numTileContents: number;\n  clustered: boolean;\n  internalCompression: Compression;\n  tileCompression: Compression;\n  tileType: TileType;\n  minZoom: number;\n  maxZoom: number;\n  minLon: number;\n  minLat: number;\n  maxLon: number;\n  maxLat: number;\n  centerZoom: number;\n  centerLon: number;\n  centerLat: number;\n  etag?: string;\n}\n\n/**\n * Low-level function for looking up a TileID or leaf directory inside a directory.\n */\nexport function findTile(entries: Entry[], tileId: number): Entry | null {\n  let m = 0;\n  let n = entries.length - 1;\n  while (m <= n) {\n    const k = (n + m) >> 1;\n    const cmp = tileId - entries[k].tileId;\n    if (cmp > 0) {\n      m = k + 1;\n    } else if (cmp < 0) {\n      n = k - 1;\n    } else {\n      return entries[k];\n    }\n  }\n\n  // at this point, m > n\n  if (n >= 0) {\n    if (entries[n].runLength === 0) {\n      return entries[n];\n    }\n    if (tileId - entries[n].tileId < entries[n].runLength) {\n      return entries[n];\n    }\n  }\n  return null;\n}\n\nexport interface RangeResponse {\n  data: ArrayBuffer;\n  etag?: string;\n  expires?: string;\n  cacheControl?: string;\n}\n\n/**\n * Interface for retrieving an archive from remote or local storage.\n */\nexport interface Source {\n  getBytes: (\n    offset: number,\n    length: number,\n    signal?: AbortSignal,\n    etag?: string\n  ) => Promise<RangeResponse>;\n\n  /**\n   * Return a unique string key for the archive e.g. a URL.\n   */\n  getKey: () => string;\n}\n\n/**\n * Use the Browser's File API, which is different from the NodeJS file API.\n * see https://developer.mozilla.org/en-US/docs/Web/API/File_API\n */\nexport class FileSource implements Source {\n  file: File;\n\n  constructor(file: File) {\n    this.file = file;\n  }\n\n  getKey() {\n    return this.file.name;\n  }\n\n  async getBytes(offset: number, length: number): Promise<RangeResponse> {\n    const blob = this.file.slice(offset, offset + length);\n    const a = await blob.arrayBuffer();\n    return { data: a };\n  }\n}\n\n/**\n * Uses the browser Fetch API to make tile requests via HTTP.\n *\n * This method does not send conditional request headers If-Match because of CORS.\n * Instead, it detects ETag mismatches via the response ETag or the 416 response code.\n *\n * This also works around browser and storage-specific edge cases.\n */\nexport class FetchSource implements Source {\n  url: string;\n\n  /**\n   * A [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) object, specfying custom [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) set for all requests to the remote archive.\n   *\n   * This should be used instead of maplibre's [transformRequest](https://maplibre.org/maplibre-gl-js/docs/API/classes/Map/#example) for PMTiles archives.\n   */\n  customHeaders: Headers;\n  /** @hidden */\n  mustReload: boolean;\n  /** @hidden */\n  chromeWindowsNoCache: boolean;\n\n  constructor(url: string, customHeaders: Headers = new Headers()) {\n    this.url = url;\n    this.customHeaders = customHeaders;\n    this.mustReload = false;\n    let userAgent = \"\";\n    if (\"navigator\" in globalThis) {\n      //biome-ignore lint: cf workers\n      userAgent = (globalThis as any).navigator.userAgent || \"\";\n    }\n    const isWindows = userAgent.indexOf(\"Windows\") > -1;\n    const isChromiumBased = /Chrome|Chromium|Edg|OPR|Brave/.test(userAgent);\n    this.chromeWindowsNoCache = false;\n    if (isWindows && isChromiumBased) {\n      this.chromeWindowsNoCache = true;\n    }\n  }\n\n  getKey() {\n    return this.url;\n  }\n\n  /**\n   * Mutate the custom [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) set for all requests to the remote archive.\n   */\n  setHeaders(customHeaders: Headers) {\n    this.customHeaders = customHeaders;\n  }\n\n  async getBytes(\n    offset: number,\n    length: number,\n    passedSignal?: AbortSignal,\n    etag?: string\n  ): Promise<RangeResponse> {\n    let controller: AbortController | undefined;\n    let signal: AbortSignal | undefined;\n    if (passedSignal) {\n      signal = passedSignal;\n    } else {\n      controller = new AbortController();\n      signal = controller.signal;\n    }\n\n    const requestHeaders = new Headers(this.customHeaders);\n    requestHeaders.set(\"range\", `bytes=${offset}-${offset + length - 1}`);\n\n    // we don't send if match because:\n    // * it disables browser caching completely (Chromium)\n    // * it requires a preflight request for every tile request\n    // * it requires CORS configuration becasue If-Match is not a CORs-safelisted header\n    // CORs configuration should expose ETag.\n    // if any etag mismatch is detected, we need to ignore the browser cache\n    let cache: string | undefined;\n    if (this.mustReload) {\n      cache = \"reload\";\n    } else if (this.chromeWindowsNoCache) {\n      cache = \"no-store\";\n    }\n\n    let resp = await fetch(this.url, {\n      signal: signal,\n      cache: cache,\n      headers: requestHeaders,\n      //biome-ignore lint: \"cache\" is incompatible between cloudflare workers and browser\n    } as any);\n\n    // handle edge case where the archive is < 16384 kb total.\n    if (offset === 0 && resp.status === 416) {\n      const contentRange = resp.headers.get(\"Content-Range\");\n      if (!contentRange || !contentRange.startsWith(\"bytes */\")) {\n        throw new Error(\"Missing content-length on 416 response\");\n      }\n      const actualLength = +contentRange.substr(8);\n      resp = await fetch(this.url, {\n        signal: signal,\n        cache: \"reload\",\n        headers: { range: `bytes=0-${actualLength - 1}` },\n        //biome-ignore lint: \"cache\" is incompatible between cloudflare workers and browser\n      } as any);\n    }\n\n    // if it's a weak etag, it's not useful for us, so ignore it.\n    let newEtag = resp.headers.get(\"Etag\");\n    if (newEtag?.startsWith(\"W/\")) {\n      newEtag = null;\n    }\n\n    // some storage systems are misbehaved (Cloudflare R2)\n    if (resp.status === 416 || (etag && newEtag && newEtag !== etag)) {\n      this.mustReload = true;\n      throw new EtagMismatch(\n        `Server returned non-matching ETag ${etag} after one retry. Check browser extensions and servers for issues that may affect correct ETag headers.`\n      );\n    }\n\n    if (resp.status >= 300) {\n      throw new Error(`Bad response code: ${resp.status}`);\n    }\n\n    // some well-behaved backends, e.g. DigitalOcean CDN, respond with 200 instead of 206\n    // but we also need to detect no support for Byte Serving which is returning the whole file\n    const contentLength = resp.headers.get(\"Content-Length\");\n    if (resp.status === 200 && (!contentLength || +contentLength > length)) {\n      if (controller) controller.abort();\n      throw new Error(\n        \"Server returned no content-length header or content-length exceeding request. Check that your storage backend supports HTTP Byte Serving.\"\n      );\n    }\n\n    const a = await resp.arrayBuffer();\n    return {\n      data: a,\n      etag: newEtag || undefined,\n      cacheControl: resp.headers.get(\"Cache-Control\") || undefined,\n      expires: resp.headers.get(\"Expires\") || undefined,\n    };\n  }\n}\n\n/** @hidden */\nexport function getUint64(v: DataView, offset: number): number {\n  const wh = v.getUint32(offset + 4, true);\n  const wl = v.getUint32(offset + 0, true);\n  return wh * 2 ** 32 + wl;\n}\n\n/**\n * Parse raw header bytes into a Header object.\n */\nexport function bytesToHeader(bytes: ArrayBuffer, etag?: string): Header {\n  const v = new DataView(bytes);\n  const specVersion = v.getUint8(7);\n  if (specVersion > 3) {\n    throw new Error(\n      `Archive is spec version ${specVersion} but this library supports up to spec version 3`\n    );\n  }\n\n  return {\n    specVersion: specVersion,\n    rootDirectoryOffset: getUint64(v, 8),\n    rootDirectoryLength: getUint64(v, 16),\n    jsonMetadataOffset: getUint64(v, 24),\n    jsonMetadataLength: getUint64(v, 32),\n    leafDirectoryOffset: getUint64(v, 40),\n    leafDirectoryLength: getUint64(v, 48),\n    tileDataOffset: getUint64(v, 56),\n    tileDataLength: getUint64(v, 64),\n    numAddressedTiles: getUint64(v, 72),\n    numTileEntries: getUint64(v, 80),\n    numTileContents: getUint64(v, 88),\n    clustered: v.getUint8(96) === 1,\n    internalCompression: v.getUint8(97),\n    tileCompression: v.getUint8(98),\n    tileType: v.getUint8(99),\n    minZoom: v.getUint8(100),\n    maxZoom: v.getUint8(101),\n    minLon: v.getInt32(102, true) / 10000000,\n    minLat: v.getInt32(106, true) / 10000000,\n    maxLon: v.getInt32(110, true) / 10000000,\n    maxLat: v.getInt32(114, true) / 10000000,\n    centerZoom: v.getUint8(118),\n    centerLon: v.getInt32(119, true) / 10000000,\n    centerLat: v.getInt32(123, true) / 10000000,\n    etag: etag,\n  };\n}\n\nfunction deserializeIndex(buffer: ArrayBuffer): Entry[] {\n  const p = { buf: new Uint8Array(buffer), pos: 0 };\n  const numEntries = readVarint(p);\n\n  const entries: Entry[] = [];\n\n  let lastId = 0;\n  for (let i = 0; i < numEntries; i++) {\n    const v = readVarint(p);\n    entries.push({ tileId: lastId + v, offset: 0, length: 0, runLength: 1 });\n    lastId += v;\n  }\n\n  for (let i = 0; i < numEntries; i++) {\n    entries[i].runLength = readVarint(p);\n  }\n\n  for (let i = 0; i < numEntries; i++) {\n    entries[i].length = readVarint(p);\n  }\n\n  for (let i = 0; i < numEntries; i++) {\n    const v = readVarint(p);\n    if (v === 0 && i > 0) {\n      entries[i].offset = entries[i - 1].offset + entries[i - 1].length;\n    } else {\n      entries[i].offset = v - 1;\n    }\n  }\n\n  return entries;\n}\n\nfunction detectVersion(a: ArrayBuffer): number {\n  const v = new DataView(a);\n  if (v.getUint16(2, true) === 2) {\n    console.error(\n      \"PMTiles spec version 2 is not supported; please see github.com/protomaps/PMTiles for tools to upgrade\"\n    );\n    return 2;\n  }\n  if (v.getUint16(2, true) === 1) {\n    console.error(\n      \"PMTiles spec version 1 is not supported; please see github.com/protomaps/PMTiles for tools to upgrade\"\n    );\n    return 1;\n  }\n  return 3;\n}\n\n/**\n * Error thrown when a response for PMTiles over HTTP does not match previous, cached parts of the archive.\n * The default PMTiles implementation will catch this error once internally and retry a request.\n */\nexport class EtagMismatch extends Error {}\n\n/**\n * Interface for caches of parts (headers, directories) of a PMTiles archive.\n */\nexport interface Cache {\n  getHeader: (source: Source) => Promise<Header>;\n  getDirectory: (\n    source: Source,\n    offset: number,\n    length: number,\n    header: Header\n  ) => Promise<Entry[]>;\n  invalidate: (source: Source) => Promise<void>;\n}\n\nasync function getHeaderAndRoot(\n  source: Source,\n  decompress: DecompressFunc\n): Promise<[Header, [string, number, Entry[] | ArrayBuffer]?]> {\n  const resp = await source.getBytes(0, 16384);\n\n  const v = new DataView(resp.data);\n  if (v.getUint16(0, true) !== 0x4d50) {\n    throw new Error(\"Wrong magic number for PMTiles archive\");\n  }\n\n  const headerData = resp.data.slice(0, HEADER_SIZE_BYTES);\n\n  const header = bytesToHeader(headerData, resp.etag);\n\n  // optimistically set the root directory\n  // TODO check root bounds\n  const rootDirData = resp.data.slice(\n    header.rootDirectoryOffset,\n    header.rootDirectoryOffset + header.rootDirectoryLength\n  );\n  const dirKey = `${source.getKey()}|${header.etag || \"\"}|${\n    header.rootDirectoryOffset\n  }|${header.rootDirectoryLength}`;\n\n  const rootDir = deserializeIndex(\n    await decompress(rootDirData, header.internalCompression)\n  );\n  return [header, [dirKey, rootDir.length, rootDir]];\n}\n\nasync function getDirectory(\n  source: Source,\n  decompress: DecompressFunc,\n  offset: number,\n  length: number,\n  header: Header\n): Promise<Entry[]> {\n  const resp = await source.getBytes(offset, length, undefined, header.etag);\n  const data = await decompress(resp.data, header.internalCompression);\n  const directory = deserializeIndex(data);\n  if (directory.length === 0) {\n    throw new Error(\"Empty directory is invalid\");\n  }\n\n  return directory;\n}\n\ninterface ResolvedValue {\n  lastUsed: number;\n  data: Header | Entry[] | ArrayBuffer;\n}\n\n/**\n * A cache for parts of a PMTiles archive where promises are never shared between requests.\n *\n * Runtimes such as Cloudflare Workers cannot share promises between different requests.\n *\n * Only caches headers and directories, not individual tile contents.\n */\nexport class ResolvedValueCache {\n  cache: Map<string, ResolvedValue>;\n  maxCacheEntries: number;\n  counter: number;\n  decompress: DecompressFunc;\n\n  constructor(\n    maxCacheEntries = 100,\n    prefetch = true, // deprecated\n    decompress: DecompressFunc = defaultDecompress\n  ) {\n    this.cache = new Map<string, ResolvedValue>();\n    this.maxCacheEntries = maxCacheEntries;\n    this.counter = 1;\n    this.decompress = decompress;\n  }\n\n  async getHeader(source: Source): Promise<Header> {\n    const cacheKey = source.getKey();\n    const cacheValue = this.cache.get(cacheKey);\n    if (cacheValue) {\n      cacheValue.lastUsed = this.counter++;\n      const data = cacheValue.data;\n      return data as Header;\n    }\n\n    const res = await getHeaderAndRoot(source, this.decompress);\n    if (res[1]) {\n      this.cache.set(res[1][0], {\n        lastUsed: this.counter++,\n        data: res[1][2],\n      });\n    }\n\n    this.cache.set(cacheKey, {\n      lastUsed: this.counter++,\n      data: res[0],\n    });\n    this.prune();\n    return res[0];\n  }\n\n  async getDirectory(\n    source: Source,\n    offset: number,\n    length: number,\n    header: Header\n  ): Promise<Entry[]> {\n    const cacheKey = `${source.getKey()}|${\n      header.etag || \"\"\n    }|${offset}|${length}`;\n    const cacheValue = this.cache.get(cacheKey);\n    if (cacheValue) {\n      cacheValue.lastUsed = this.counter++;\n      const data = cacheValue.data;\n      return data as Entry[];\n    }\n\n    const directory = await getDirectory(\n      source,\n      this.decompress,\n      offset,\n      length,\n      header\n    );\n    this.cache.set(cacheKey, {\n      lastUsed: this.counter++,\n      data: directory,\n    });\n    this.prune();\n    return directory;\n  }\n\n  prune() {\n    if (this.cache.size > this.maxCacheEntries) {\n      let minUsed = Infinity;\n      let minKey = undefined;\n      this.cache.forEach((cacheValue: ResolvedValue, key: string) => {\n        if (cacheValue.lastUsed < minUsed) {\n          minUsed = cacheValue.lastUsed;\n          minKey = key;\n        }\n      });\n      if (minKey) {\n        this.cache.delete(minKey);\n      }\n    }\n  }\n\n  async invalidate(source: Source) {\n    this.cache.delete(source.getKey());\n  }\n}\n\ninterface SharedPromiseCacheValue {\n  lastUsed: number;\n  data: Promise<Header | Entry[] | ArrayBuffer>;\n}\n\n/**\n * A cache for parts of a PMTiles archive where promises can be shared between requests.\n *\n * Only caches headers and directories, not individual tile contents.\n */\nexport class SharedPromiseCache {\n  cache: Map<string, SharedPromiseCacheValue>;\n  invalidations: Map<string, Promise<void>>;\n  maxCacheEntries: number;\n  counter: number;\n  decompress: DecompressFunc;\n\n  constructor(\n    maxCacheEntries = 100,\n    prefetch = true, // deprecated\n    decompress: DecompressFunc = defaultDecompress\n  ) {\n    this.cache = new Map<string, SharedPromiseCacheValue>();\n    this.invalidations = new Map<string, Promise<void>>();\n    this.maxCacheEntries = maxCacheEntries;\n    this.counter = 1;\n    this.decompress = decompress;\n  }\n\n  async getHeader(source: Source): Promise<Header> {\n    const cacheKey = source.getKey();\n    const cacheValue = this.cache.get(cacheKey);\n    if (cacheValue) {\n      cacheValue.lastUsed = this.counter++;\n      const data = await cacheValue.data;\n      return data as Header;\n    }\n\n    const p = new Promise<Header>((resolve, reject) => {\n      getHeaderAndRoot(source, this.decompress)\n        .then((res) => {\n          if (res[1]) {\n            this.cache.set(res[1][0], {\n              lastUsed: this.counter++,\n              data: Promise.resolve(res[1][2]),\n            });\n          }\n          resolve(res[0]);\n          this.prune();\n        })\n        .catch((e) => {\n          reject(e);\n        });\n    });\n    this.cache.set(cacheKey, { lastUsed: this.counter++, data: p });\n    return p;\n  }\n\n  async getDirectory(\n    source: Source,\n    offset: number,\n    length: number,\n    header: Header\n  ): Promise<Entry[]> {\n    const cacheKey = `${source.getKey()}|${\n      header.etag || \"\"\n    }|${offset}|${length}`;\n    const cacheValue = this.cache.get(cacheKey);\n    if (cacheValue) {\n      cacheValue.lastUsed = this.counter++;\n      const data = await cacheValue.data;\n      return data as Entry[];\n    }\n\n    const p = new Promise<Entry[]>((resolve, reject) => {\n      getDirectory(source, this.decompress, offset, length, header)\n        .then((directory) => {\n          resolve(directory);\n          this.prune();\n        })\n        .catch((e) => {\n          reject(e);\n        });\n    });\n    this.cache.set(cacheKey, { lastUsed: this.counter++, data: p });\n    return p;\n  }\n\n  prune() {\n    if (this.cache.size >= this.maxCacheEntries) {\n      let minUsed = Infinity;\n      let minKey = undefined;\n      this.cache.forEach((cacheValue: SharedPromiseCacheValue, key: string) => {\n        if (cacheValue.lastUsed < minUsed) {\n          minUsed = cacheValue.lastUsed;\n          minKey = key;\n        }\n      });\n      if (minKey) {\n        this.cache.delete(minKey);\n      }\n    }\n  }\n\n  async invalidate(source: Source) {\n    const key = source.getKey();\n    if (this.invalidations.get(key)) {\n      return await this.invalidations.get(key);\n    }\n    this.cache.delete(source.getKey());\n    const p = new Promise<void>((resolve, reject) => {\n      this.getHeader(source)\n        .then((h) => {\n          resolve();\n          this.invalidations.delete(key);\n        })\n        .catch((e) => {\n          reject(e);\n        });\n    });\n    this.invalidations.set(key, p);\n  }\n}\n\n/**\n * Main class encapsulating PMTiles decoding logic.\n *\n * if `source` is a string, creates a FetchSource using that string as the URL to a remote PMTiles.\n * if no `cache` is passed, use a SharedPromiseCache.\n * if no `decompress` is passed, default to the browser DecompressionStream API with a fallback to `fflate`.\n */\n// biome-ignore lint: that's just how its capitalized\nexport class PMTiles {\n  source: Source;\n  cache: Cache;\n  decompress: DecompressFunc;\n\n  constructor(\n    source: Source | string,\n    customHeaders: Headers,\n    cache?: Cache,\n    decompress?: DecompressFunc\n  ) {\n    if (typeof source === \"string\") {\n      this.source = new FetchSource(source, customHeaders);\n    } else {\n      this.source = source;\n    }\n    if (decompress) {\n      this.decompress = decompress;\n    } else {\n      this.decompress = defaultDecompress;\n    }\n    if (cache) {\n      this.cache = cache;\n    } else {\n      this.cache = new SharedPromiseCache();\n    }\n  }\n\n  /**\n   * Return the header of the archive,\n   * including information such as tile type, min/max zoom, bounds, and summary statistics.\n   */\n  async getHeader() {\n    return await this.cache.getHeader(this.source);\n  }\n\n  /** @hidden */\n  async getZxyAttempt(\n    z: number,\n    x: number,\n    y: number,\n    signal?: AbortSignal\n  ): Promise<RangeResponse | undefined> {\n    const tileId = zxyToTileId(z, x, y);\n    const header = await this.cache.getHeader(this.source);\n\n    if (z < header.minZoom || z > header.maxZoom) {\n      return undefined;\n    }\n\n    let dO = header.rootDirectoryOffset;\n    let dL = header.rootDirectoryLength;\n    for (let depth = 0; depth <= 3; depth++) {\n      const directory = await this.cache.getDirectory(\n        this.source,\n        dO,\n        dL,\n        header\n      );\n      const entry = findTile(directory, tileId);\n      if (entry) {\n        if (entry.runLength > 0) {\n          const resp = await this.source.getBytes(\n            header.tileDataOffset + entry.offset,\n            entry.length,\n            signal,\n            header.etag\n          );\n          return {\n            data: await this.decompress(resp.data, header.tileCompression),\n            cacheControl: resp.cacheControl,\n            expires: resp.expires,\n          };\n        }\n        dO = header.leafDirectoryOffset + entry.offset;\n        dL = entry.length;\n      } else {\n        // TODO: We should in fact return a valid RangeResponse\n        // with empty data, but filled in cache control / expires headers\n        return undefined;\n      }\n    }\n    throw new Error(\"Maximum directory depth exceeded\");\n  }\n\n  /**\n   * Primary method to get a single tile's bytes from an archive.\n   *\n   * Returns undefined if the tile does not exist in the archive.\n   */\n  async getZxy(\n    z: number,\n    x: number,\n    y: number,\n    signal?: AbortSignal\n  ): Promise<RangeResponse | undefined> {\n    try {\n      return await this.getZxyAttempt(z, x, y, signal);\n    } catch (e) {\n      if (e instanceof EtagMismatch) {\n        this.cache.invalidate(this.source);\n        return await this.getZxyAttempt(z, x, y, signal);\n      }\n      throw e;\n    }\n  }\n\n  /** @hidden */\n  async getMetadataAttempt(): Promise<unknown> {\n    const header = await this.cache.getHeader(this.source);\n\n    const resp = await this.source.getBytes(\n      header.jsonMetadataOffset,\n      header.jsonMetadataLength,\n      undefined,\n      header.etag\n    );\n    const decompressed = await this.decompress(\n      resp.data,\n      header.internalCompression\n    );\n    const dec = new TextDecoder(\"utf-8\");\n    return JSON.parse(dec.decode(decompressed));\n  }\n\n  /**\n   * Return the arbitrary JSON metadata of the archive.\n   */\n  async getMetadata(): Promise<unknown> {\n    try {\n      return await this.getMetadataAttempt();\n    } catch (e) {\n      if (e instanceof EtagMismatch) {\n        this.cache.invalidate(this.source);\n        return await this.getMetadataAttempt();\n      }\n      throw e;\n    }\n  }\n\n  /**\n   * Construct a [TileJSON](https://github.com/mapbox/tilejson-spec) object.\n   *\n   * baseTilesUrl is the desired tiles URL, excluding the suffix `/{z}/{x}/{y}.{ext}`.\n   * For example, if the desired URL is `http://example.com/tileset/{z}/{x}/{y}.mvt`,\n   * the baseTilesUrl should be `https://example.com/tileset`.\n   */\n  async getTileJson(baseTilesUrl: string): Promise<unknown> {\n    const header = await this.getHeader();\n    const metadata = (await this.getMetadata()) as MetadataLike;\n    const ext = tileTypeExt(header.tileType);\n\n    return {\n      tilejson: \"3.0.0\",\n      scheme: \"xyz\",\n      tiles: [`${baseTilesUrl}/{z}/{x}/{y}${ext}`],\n      // biome-ignore lint: TileJSON spec\n      vector_layers: metadata.vector_layers,\n      attribution: metadata.attribution,\n      description: metadata.description,\n      name: metadata.name,\n      version: metadata.version,\n      bounds: [header.minLon, header.minLat, header.maxLon, header.maxLat],\n      center: [header.centerLon, header.centerLat, header.centerZoom],\n      minzoom: header.minZoom,\n      maxzoom: header.maxZoom,\n    };\n  }\n}\n","// biome-ignore lint: needed for Leaflet + IIFE to work\ndeclare const L: any;\n// biome-ignore lint: needed for window.URL to disambiguate from cloudflare workers\ndeclare const window: any;\ndeclare const document: DocumentLike;\n\nimport type { Coords } from \"leaflet\";\nimport { PMTiles, TileType } from \"./index\";\n\ninterface DocumentLike {\n  // biome-ignore lint: we don't want to bring in the entire document type\n  createElement: (s: string) => any;\n}\n\n// biome-ignore lint: we don't want to bring in the entire document type\ntype DoneCallback = (error?: Error, tile?: any) => void;\n\n/**\n * Add a raster PMTiles as a layer to a Leaflet map.\n *\n * For vector tiles see https://github.com/protomaps/protomaps-leaflet\n */\nexport const leafletRasterLayer = (source: PMTiles, options: unknown) => {\n  let loaded = false;\n  let mimeType = \"\";\n  const cls = L.GridLayer.extend({\n    createTile: (coord: Coords, done: DoneCallback) => {\n      const el = document.createElement(\"img\");\n      const controller = new AbortController();\n      const signal = controller.signal;\n      el.cancel = () => {\n        controller.abort();\n      };\n      if (!loaded) {\n        source.getHeader().then((header) => {\n          if (header.tileType === TileType.Mvt) {\n            console.error(\n              \"Error: archive contains MVT vector tiles, but leafletRasterLayer is for displaying raster tiles. See https://github.com/protomaps/PMTiles/tree/main/js for details.\"\n            );\n          } else if (header.tileType === 2) {\n            mimeType = \"image/png\";\n          } else if (header.tileType === 3) {\n            mimeType = \"image/jpeg\";\n          } else if (header.tileType === 4) {\n            mimeType = \"image/webp\";\n          } else if (header.tileType === 5) {\n            mimeType = \"image/avif\";\n          }\n        });\n        loaded = true;\n      }\n      source\n        .getZxy(coord.z, coord.x, coord.y, signal)\n        .then((arr) => {\n          if (arr) {\n            const blob = new Blob([arr.data], { type: mimeType });\n            const imageUrl = window.URL.createObjectURL(blob);\n            el.src = imageUrl;\n            el.cancel = undefined;\n            done(undefined, el);\n          }\n        })\n        .catch((e) => {\n          if (e.name !== \"AbortError\") {\n            throw e;\n          }\n        });\n      return el;\n    },\n\n    _removeTile: function (key: string) {\n      const tile = this._tiles[key];\n      if (!tile) {\n        return;\n      }\n\n      if (tile.el.cancel) tile.el.cancel();\n\n      tile.el.width = 0;\n      tile.el.height = 0;\n      tile.el.deleted = true;\n      L.DomUtil.remove(tile.el);\n      delete this._tiles[key];\n      this.fire(\"tileunload\", {\n        tile: tile.el,\n        coords: this._keyToTileCoords(key),\n      });\n    },\n  });\n  return new cls(options);\n};\n\nconst isDeepEqual = (object1: any, object2: any) => {\n  const objKeys1 = Object.keys(object1);\n  const objKeys2 = Object.keys(object2);\n  if (objKeys1.length !== objKeys2.length)\n    return false;\n  for (var key of objKeys1) {\n    const value1 = object1[key];\n    const value2 = object2[key];\n    const isObjects = isObject(value1) && isObject(value2);\n    if (isObjects && !isDeepEqual(value1, value2) || !isObjects && value1 !== value2) {\n      return false;\n    }\n  }\n  return true;\n};\n\nconst isObject = (object: any) => {\n  return object != null && typeof object === \"object\";\n};\n\ntype GetResourceResponse<T> = ExpiryData & {\n  data: T;\n};\ntype AddProtocolAction = (\n  requestParameters: RequestParameters,\n  abortController: AbortController\n) => Promise<GetResourceResponse<unknown>>;\n\ntype ExpiryData = {\n  cacheControl?: string | null;\n  expires?: string | null; // MapLibre can be a Date object\n};\n\n// copied from MapLibre /util/ajax.ts\ntype RequestParameters = {\n  url: string;\n  headers?: unknown;\n  method?: \"GET\" | \"POST\" | \"PUT\";\n  body?: string;\n  type?: \"string\" | \"json\" | \"arrayBuffer\" | \"image\";\n  credentials?: \"same-origin\" | \"include\";\n  collectResourceTiming?: boolean;\n};\n\n// for legacy maplibre-3 interop\ntype ResponseCallbackV3 = (\n  error?: Error | undefined,\n  data?: unknown | undefined,\n  cacheControl?: string | undefined,\n  expires?: string | undefined\n) => void;\n\ntype V3OrV4Protocol = <\n  T extends AbortController | ResponseCallbackV3,\n  R = T extends AbortController\n    ? Promise<GetResourceResponse<unknown>>\n    : { cancel: () => void },\n>(\n  requestParameters: RequestParameters,\n  arg2: T\n) => R;\n\nconst v3compat =\n  (v4: AddProtocolAction): V3OrV4Protocol =>\n  (requestParameters, arg2) => {\n    if (arg2 instanceof AbortController) {\n      // biome-ignore lint: overloading return type not handled by compiler\n      return v4(requestParameters, arg2) as any;\n    }\n    const abortController = new AbortController();\n    v4(requestParameters, abortController)\n      .then(\n        (result) => {\n          return arg2(\n            undefined,\n            result.data,\n            result.cacheControl || \"\",\n            result.expires || \"\"\n          );\n        },\n        (err) => {\n          return arg2(err);\n        }\n      )\n      .catch((e) => {\n        return arg2(e);\n      });\n    return { cancel: () => abortController.abort() };\n  };\n\n/**\n * MapLibre GL JS protocol. Must be added once globally.\n */\nexport class Protocol {\n  /** @hidden */\n  tiles: Map<string, PMTiles>;\n  metadata: boolean;\n  errorOnMissingTile: boolean;\n\n  /**\n   * Initialize the MapLibre PMTiles protocol.\n   *\n   * * metadata: also load the metadata section of the PMTiles. required for some \"inspect\" functionality\n   * and to automatically populate the map attribution. Requires an extra HTTP request.\n   * * errorOnMissingTile: When a vector MVT tile is missing from the archive, raise an error instead of\n   * returning the empty array. Not recommended. This is only to reproduce the behavior of ZXY tile APIs\n   * which some applications depend on when overzooming.\n   */\n  constructor(options?: { metadata?: boolean; errorOnMissingTile?: boolean }) {\n    this.tiles = new Map<string, PMTiles>();\n    this.metadata = options?.metadata || false;\n    this.errorOnMissingTile = options?.errorOnMissingTile || false;\n  }\n\n  /**\n   * Add a {@link PMTiles} instance to the global protocol instance.\n   *\n   * For remote fetch sources, references in MapLibre styles like pmtiles://http://...\n   * will resolve to the same instance if the URLs match.\n   */\n  add(p: PMTiles) {\n    this.tiles.set(p.source.getKey(), p);\n  }\n\n  /**\n   * Fetch a {@link PMTiles} instance by URL, for remote PMTiles instances.\n   */\n  get(url: string) {\n    return this.tiles.get(url);\n  }\n\n  /** @hidden */\n  tilev4 = async (\n    params: RequestParameters,\n    abortController: AbortController\n  ) => {\n    if (params.type === \"json\") {\n      const pmtilesUrl = params.url.substr(10);\n      let instance = this.tiles.get(pmtilesUrl);\n      if (!instance || !isDeepEqual((instance.source as any).customHeaders, params.headers)) {\n        instance = new PMTiles(pmtilesUrl, params.headers as Headers);\n        this.tiles.set(pmtilesUrl, instance);\n      }\n\n      if (this.metadata) {\n        return {\n          data: await instance.getTileJson(params.url),\n        };\n      }\n\n      const h = await instance.getHeader();\n\n      if (h.minLon >= h.maxLon || h.minLat >= h.maxLat) {\n        console.error(\n          `Bounds of PMTiles archive ${h.minLon},${h.minLat},${h.maxLon},${h.maxLat} are not valid.`\n        );\n      }\n\n      return {\n        data: {\n          tiles: [`${params.url}/{z}/{x}/{y}`],\n          minzoom: h.minZoom,\n          maxzoom: h.maxZoom,\n          bounds: [h.minLon, h.minLat, h.maxLon, h.maxLat],\n        },\n      };\n    }\n    const re = new RegExp(/pmtiles:\\/\\/(.+)\\/(\\d+)\\/(\\d+)\\/(\\d+)/);\n    const result = params.url.match(re);\n    if (!result) {\n      throw new Error(\"Invalid PMTiles protocol URL\");\n    }\n    const pmtilesUrl = result[1];\n\n    let instance = this.tiles.get(pmtilesUrl);\n    if (!instance || !isDeepEqual((instance.source as any).customHeaders, params.headers)) {\n      instance = new PMTiles(pmtilesUrl, params.headers as Headers);\n      this.tiles.set(pmtilesUrl, instance);\n    }\n    const z = result[2];\n    const x = result[3];\n    const y = result[4];\n\n    const header = await instance.getHeader();\n    const resp = await instance?.getZxy(+z, +x, +y, abortController.signal);\n    if (resp) {\n      return {\n        data: new Uint8Array(resp.data),\n        cacheControl: resp.cacheControl,\n        expires: resp.expires,\n      };\n    }\n    if (header.tileType === TileType.Mvt) {\n      if (this.errorOnMissingTile) {\n        throw new Error(\"Tile not found.\");\n      }\n      return { data: new Uint8Array() };\n    }\n    return { data: null };\n  };\n\n  tile = v3compat(this.tilev4);\n}\n"]}
\ No newline at end of file
diff --git a/node_modules/pmtiles/dist/cjs/index.d.cts b/node_modules/pmtiles/dist/cjs/index.d.cts
index 788c842..709c6c2 100644
--- a/node_modules/pmtiles/dist/cjs/index.d.cts
+++ b/node_modules/pmtiles/dist/cjs/index.d.cts
@@ -290,7 +290,7 @@ declare class PMTiles {
     source: Source;
     cache: Cache;
     decompress: DecompressFunc;
-    constructor(source: Source | string, cache?: Cache, decompress?: DecompressFunc);
+    constructor(source: Source | string, customHeaders: Headers, cache?: Cache, decompress?: DecompressFunc);
     /**
      * Return the header of the archive,
      * including information such as tile type, min/max zoom, bounds, and summary statistics.
diff --git a/node_modules/pmtiles/dist/esm/index.d.ts b/node_modules/pmtiles/dist/esm/index.d.ts
index 788c842..709c6c2 100644
--- a/node_modules/pmtiles/dist/esm/index.d.ts
+++ b/node_modules/pmtiles/dist/esm/index.d.ts
@@ -290,7 +290,7 @@ declare class PMTiles {
     source: Source;
     cache: Cache;
     decompress: DecompressFunc;
-    constructor(source: Source | string, cache?: Cache, decompress?: DecompressFunc);
+    constructor(source: Source | string, customHeaders: Headers, cache?: Cache, decompress?: DecompressFunc);
     /**
      * Return the header of the archive,
      * including information such as tile type, min/max zoom, bounds, and summary statistics.
diff --git a/node_modules/pmtiles/dist/esm/index.js b/node_modules/pmtiles/dist/esm/index.js
index e3a3bf0..14b534d 100644
--- a/node_modules/pmtiles/dist/esm/index.js
+++ b/node_modules/pmtiles/dist/esm/index.js
@@ -1,2 +1,2 @@
-var z=Object.defineProperty;var b=Math.pow;var l=(i,e)=>z(i,"name",{value:e,configurable:!0});var m=(i,e,t)=>new Promise((r,n)=>{var s=u=>{try{a(t.next(u))}catch(c){n(c)}},o=u=>{try{a(t.throw(u))}catch(c){n(c)}},a=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,o);a((t=t.apply(i,e)).next())});import{decompressSync as W}from"fflate";var re=l((i,e)=>{let t=!1,r="",n=L.GridLayer.extend({createTile:l((s,o)=>{let a=document.createElement("img"),u=new AbortController,c=u.signal;return a.cancel=()=>{u.abort()},t||(i.getHeader().then(d=>{d.tileType===1?console.error("Error: archive contains MVT vector tiles, but leafletRasterLayer is for displaying raster tiles. See https://github.com/protomaps/PMTiles/tree/main/js for details."):d.tileType===2?r="image/png":d.tileType===3?r="image/jpeg":d.tileType===4?r="image/webp":d.tileType===5&&(r="image/avif")}),t=!0),i.getZxy(s.z,s.x,s.y,c).then(d=>{if(d){let h=new Blob([d.data],{type:r}),p=window.URL.createObjectURL(h);a.src=p,a.cancel=void 0,o(void 0,a)}}).catch(d=>{if(d.name!=="AbortError")throw d}),a},"createTile"),_removeTile:l(function(s){let o=this._tiles[s];o&&(o.el.cancel&&o.el.cancel(),o.el.width=0,o.el.height=0,o.el.deleted=!0,L.DomUtil.remove(o.el),delete this._tiles[s],this.fire("tileunload",{tile:o.el,coords:this._keyToTileCoords(s)}))},"_removeTile")});return new n(e)},"leafletRasterLayer"),j=l(i=>(e,t)=>{if(t instanceof AbortController)return i(e,t);let r=new AbortController;return i(e,r).then(n=>t(void 0,n.data,n.cacheControl||"",n.expires||""),n=>t(n)).catch(n=>t(n)),{cancel:l(()=>r.abort(),"cancel")}},"v3compat"),T=class T{constructor(e){this.tilev4=l((e,t)=>m(this,null,function*(){if(e.type==="json"){let p=e.url.substr(10),y=this.tiles.get(p);if(y||(y=new x(p),this.tiles.set(p,y)),this.metadata)return{data:yield y.getTileJson(e.url)};let f=yield y.getHeader();return(f.minLon>=f.maxLon||f.minLat>=f.maxLat)&&console.error(`Bounds of PMTiles archive ${f.minLon},${f.minLat},${f.maxLon},${f.maxLat} are not valid.`),{data:{tiles:[`${e.url}/{z}/{x}/{y}`],minzoom:f.minZoom,maxzoom:f.maxZoom,bounds:[f.minLon,f.minLat,f.maxLon,f.maxLat]}}}let r=new RegExp(/pmtiles:\/\/(.+)\/(\d+)\/(\d+)\/(\d+)/),n=e.url.match(r);if(!n)throw new Error("Invalid PMTiles protocol URL");let s=n[1],o=this.tiles.get(s);o||(o=new x(s),this.tiles.set(s,o));let a=n[2],u=n[3],c=n[4],d=yield o.getHeader(),h=yield o==null?void 0:o.getZxy(+a,+u,+c,t.signal);if(h)return{data:new Uint8Array(h.data),cacheControl:h.cacheControl,expires:h.expires};if(d.tileType===1){if(this.errorOnMissingTile)throw new Error("Tile not found.");return{data:new Uint8Array}}return{data:null}}),"tilev4");this.tile=j(this.tilev4);this.tiles=new Map,this.metadata=(e==null?void 0:e.metadata)||!1,this.errorOnMissingTile=(e==null?void 0:e.errorOnMissingTile)||!1}add(e){this.tiles.set(e.source.getKey(),e)}get(e){return this.tiles.get(e)}};l(T,"Protocol");var S=T;function w(i,e){return(e>>>0)*4294967296+(i>>>0)}l(w,"toNum");function F(i,e){let t=e.buf,r=t[e.pos++],n=(r&112)>>4;if(r<128||(r=t[e.pos++],n|=(r&127)<<3,r<128)||(r=t[e.pos++],n|=(r&127)<<10,r<128)||(r=t[e.pos++],n|=(r&127)<<17,r<128)||(r=t[e.pos++],n|=(r&127)<<24,r<128)||(r=t[e.pos++],n|=(r&1)<<31,r<128))return w(i,n);throw new Error("Expected varint not more than 10 bytes")}l(F,"readVarintRemainder");function v(i){let e=i.buf,t=e[i.pos++],r=t&127;return t<128||(t=e[i.pos++],r|=(t&127)<<7,t<128)||(t=e[i.pos++],r|=(t&127)<<14,t<128)||(t=e[i.pos++],r|=(t&127)<<21,t<128)?r:(t=e[i.pos],r|=(t&15)<<28,F(r,i))}l(v,"readVarint");function k(i,e,t,r){if(r===0){t===1&&(e[0]=i-1-e[0],e[1]=i-1-e[1]);let n=e[0];e[0]=e[1],e[1]=n}}l(k,"rotate");function N(i,e){let t=b(2,i),r=e,n=e,s=e,o=[0,0],a=1;for(;a<t;)r=1&s/2,n=1&(s^r),k(a,o,r,n),o[0]+=a*r,o[1]+=a*n,s=s/4,a*=2;return[i,o[0],o[1]]}l(N,"idOnLevel");var q=[0,1,5,21,85,341,1365,5461,21845,87381,349525,1398101,5592405,22369621,89478485,357913941,1431655765,5726623061,22906492245,91625968981,366503875925,1466015503701,5864062014805,23456248059221,93824992236885,375299968947541,0x5555555555555];function G(i,e,t){if(i>26)throw new Error("Tile zoom level exceeds max safe number limit (26)");if(e>b(2,i)-1||t>b(2,i)-1)throw new Error("tile x/y outside zoom level bounds");let r=q[i],n=b(2,i),s=0,o=0,a=0,u=[e,t],c=n/2;for(;c>0;)s=(u[0]&c)>0?1:0,o=(u[1]&c)>0?1:0,a+=c*c*(3*s^o),k(c,u,s,o),c=c/2;return r+a}l(G,"zxyToTileId");function ie(i){let e=0,t=0;for(let r=0;r<27;r++){let n=(1<<r)*(1<<r);if(e+n>i)return N(r,i-e);e+=n}throw new Error("Tile zoom level exceeds max safe number limit (26)")}l(ie,"tileIdToZxy");var J=(s=>(s[s.Unknown=0]="Unknown",s[s.None=1]="None",s[s.Gzip=2]="Gzip",s[s.Brotli=3]="Brotli",s[s.Zstd=4]="Zstd",s))(J||{});function D(i,e){return m(this,null,function*(){if(e===1||e===0)return i;if(e===2){if(typeof globalThis.DecompressionStream=="undefined")return W(new Uint8Array(i));let t=new Response(i).body;if(!t)throw new Error("Failed to read response stream");let r=t.pipeThrough(new globalThis.DecompressionStream("gzip"));return new Response(r).arrayBuffer()}throw new Error("Compression method not supported")})}l(D,"defaultDecompress");var O=(o=>(o[o.Unknown=0]="Unknown",o[o.Mvt=1]="Mvt",o[o.Png=2]="Png",o[o.Jpeg=3]="Jpeg",o[o.Webp=4]="Webp",o[o.Avif=5]="Avif",o))(O||{});function _(i){return i===1?".mvt":i===2?".png":i===3?".jpg":i===4?".webp":i===5?".avif":""}l(_,"tileTypeExt");var Y=127;function Q(i,e){let t=0,r=i.length-1;for(;t<=r;){let n=r+t>>1,s=e-i[n].tileId;if(s>0)t=n+1;else if(s<0)r=n-1;else return i[n]}return r>=0&&(i[r].runLength===0||e-i[r].tileId<i[r].runLength)?i[r]:null}l(Q,"findTile");var A=class A{constructor(e){this.file=e}getKey(){return this.file.name}getBytes(e,t){return m(this,null,function*(){return{data:yield this.file.slice(e,e+t).arrayBuffer()}})}};l(A,"FileSource");var V=A,U=class U{constructor(e,t=new Headers){this.url=e,this.customHeaders=t,this.mustReload=!1;let r="";"navigator"in globalThis&&(r=globalThis.navigator.userAgent||"");let n=r.indexOf("Windows")>-1,s=/Chrome|Chromium|Edg|OPR|Brave/.test(r);this.chromeWindowsNoCache=!1,n&&s&&(this.chromeWindowsNoCache=!0)}getKey(){return this.url}setHeaders(e){this.customHeaders=e}getBytes(e,t,r,n){return m(this,null,function*(){let s,o;r?o=r:(s=new AbortController,o=s.signal);let a=new Headers(this.customHeaders);a.set("range",`bytes=${e}-${e+t-1}`);let u;this.mustReload?u="reload":this.chromeWindowsNoCache&&(u="no-store");let c=yield fetch(this.url,{signal:o,cache:u,headers:a});if(e===0&&c.status===416){let y=c.headers.get("Content-Range");if(!y||!y.startsWith("bytes */"))throw new Error("Missing content-length on 416 response");let f=+y.substr(8);c=yield fetch(this.url,{signal:o,cache:"reload",headers:{range:`bytes=0-${f-1}`}})}let d=c.headers.get("Etag");if(d!=null&&d.startsWith("W/")&&(d=null),c.status===416||n&&d&&d!==n)throw this.mustReload=!0,new E(`Server returned non-matching ETag ${n} after one retry. Check browser extensions and servers for issues that may affect correct ETag headers.`);if(c.status>=300)throw new Error(`Bad response code: ${c.status}`);let h=c.headers.get("Content-Length");if(c.status===200&&(!h||+h>t))throw s&&s.abort(),new Error("Server returned no content-length header or content-length exceeding request. Check that your storage backend supports HTTP Byte Serving.");return{data:yield c.arrayBuffer(),etag:d||void 0,cacheControl:c.headers.get("Cache-Control")||void 0,expires:c.headers.get("Expires")||void 0}})}};l(U,"FetchSource");var C=U;function g(i,e){let t=i.getUint32(e+4,!0),r=i.getUint32(e+0,!0);return t*b(2,32)+r}l(g,"getUint64");function X(i,e){let t=new DataView(i),r=t.getUint8(7);if(r>3)throw new Error(`Archive is spec version ${r} but this library supports up to spec version 3`);return{specVersion:r,rootDirectoryOffset:g(t,8),rootDirectoryLength:g(t,16),jsonMetadataOffset:g(t,24),jsonMetadataLength:g(t,32),leafDirectoryOffset:g(t,40),leafDirectoryLength:g(t,48),tileDataOffset:g(t,56),tileDataLength:g(t,64),numAddressedTiles:g(t,72),numTileEntries:g(t,80),numTileContents:g(t,88),clustered:t.getUint8(96)===1,internalCompression:t.getUint8(97),tileCompression:t.getUint8(98),tileType:t.getUint8(99),minZoom:t.getUint8(100),maxZoom:t.getUint8(101),minLon:t.getInt32(102,!0)/1e7,minLat:t.getInt32(106,!0)/1e7,maxLon:t.getInt32(110,!0)/1e7,maxLat:t.getInt32(114,!0)/1e7,centerZoom:t.getUint8(118),centerLon:t.getInt32(119,!0)/1e7,centerLat:t.getInt32(123,!0)/1e7,etag:e}}l(X,"bytesToHeader");function Z(i){let e={buf:new Uint8Array(i),pos:0},t=v(e),r=[],n=0;for(let s=0;s<t;s++){let o=v(e);r.push({tileId:n+o,offset:0,length:0,runLength:1}),n+=o}for(let s=0;s<t;s++)r[s].runLength=v(e);for(let s=0;s<t;s++)r[s].length=v(e);for(let s=0;s<t;s++){let o=v(e);o===0&&s>0?r[s].offset=r[s-1].offset+r[s-1].length:r[s].offset=o-1}return r}l(Z,"deserializeIndex");var R=class R extends Error{};l(R,"EtagMismatch");var E=R;function K(i,e){return m(this,null,function*(){let t=yield i.getBytes(0,16384);if(new DataView(t.data).getUint16(0,!0)!==19792)throw new Error("Wrong magic number for PMTiles archive");let n=t.data.slice(0,Y),s=X(n,t.etag),o=t.data.slice(s.rootDirectoryOffset,s.rootDirectoryOffset+s.rootDirectoryLength),a=`${i.getKey()}|${s.etag||""}|${s.rootDirectoryOffset}|${s.rootDirectoryLength}`,u=Z(yield e(o,s.internalCompression));return[s,[a,u.length,u]]})}l(K,"getHeaderAndRoot");function I(i,e,t,r,n){return m(this,null,function*(){let s=yield i.getBytes(t,r,void 0,n.etag),o=yield e(s.data,n.internalCompression),a=Z(o);if(a.length===0)throw new Error("Empty directory is invalid");return a})}l(I,"getDirectory");var H=class H{constructor(e=100,t=!0,r=D){this.cache=new Map,this.maxCacheEntries=e,this.counter=1,this.decompress=r}getHeader(e){return m(this,null,function*(){let t=e.getKey(),r=this.cache.get(t);if(r)return r.lastUsed=this.counter++,r.data;let n=yield K(e,this.decompress);return n[1]&&this.cache.set(n[1][0],{lastUsed:this.counter++,data:n[1][2]}),this.cache.set(t,{lastUsed:this.counter++,data:n[0]}),this.prune(),n[0]})}getDirectory(e,t,r,n){return m(this,null,function*(){let s=`${e.getKey()}|${n.etag||""}|${t}|${r}`,o=this.cache.get(s);if(o)return o.lastUsed=this.counter++,o.data;let a=yield I(e,this.decompress,t,r,n);return this.cache.set(s,{lastUsed:this.counter++,data:a}),this.prune(),a})}prune(){if(this.cache.size>this.maxCacheEntries){let e=1/0,t;this.cache.forEach((r,n)=>{r.lastUsed<e&&(e=r.lastUsed,t=n)}),t&&this.cache.delete(t)}}invalidate(e){return m(this,null,function*(){this.cache.delete(e.getKey())})}};l(H,"ResolvedValueCache");var $=H,M=class M{constructor(e=100,t=!0,r=D){this.cache=new Map,this.invalidations=new Map,this.maxCacheEntries=e,this.counter=1,this.decompress=r}getHeader(e){return m(this,null,function*(){let t=e.getKey(),r=this.cache.get(t);if(r)return r.lastUsed=this.counter++,yield r.data;let n=new Promise((s,o)=>{K(e,this.decompress).then(a=>{a[1]&&this.cache.set(a[1][0],{lastUsed:this.counter++,data:Promise.resolve(a[1][2])}),s(a[0]),this.prune()}).catch(a=>{o(a)})});return this.cache.set(t,{lastUsed:this.counter++,data:n}),n})}getDirectory(e,t,r,n){return m(this,null,function*(){let s=`${e.getKey()}|${n.etag||""}|${t}|${r}`,o=this.cache.get(s);if(o)return o.lastUsed=this.counter++,yield o.data;let a=new Promise((u,c)=>{I(e,this.decompress,t,r,n).then(d=>{u(d),this.prune()}).catch(d=>{c(d)})});return this.cache.set(s,{lastUsed:this.counter++,data:a}),a})}prune(){if(this.cache.size>=this.maxCacheEntries){let e=1/0,t;this.cache.forEach((r,n)=>{r.lastUsed<e&&(e=r.lastUsed,t=n)}),t&&this.cache.delete(t)}}invalidate(e){return m(this,null,function*(){let t=e.getKey();if(this.invalidations.get(t))return yield this.invalidations.get(t);this.cache.delete(e.getKey());let r=new Promise((n,s)=>{this.getHeader(e).then(o=>{n(),this.invalidations.delete(t)}).catch(o=>{s(o)})});this.invalidations.set(t,r)})}};l(M,"SharedPromiseCache");var P=M,B=class B{constructor(e,t,r){typeof e=="string"?this.source=new C(e):this.source=e,r?this.decompress=r:this.decompress=D,t?this.cache=t:this.cache=new P}getHeader(){return m(this,null,function*(){return yield this.cache.getHeader(this.source)})}getZxyAttempt(e,t,r,n){return m(this,null,function*(){let s=G(e,t,r),o=yield this.cache.getHeader(this.source);if(e<o.minZoom||e>o.maxZoom)return;let a=o.rootDirectoryOffset,u=o.rootDirectoryLength;for(let c=0;c<=3;c++){let d=yield this.cache.getDirectory(this.source,a,u,o),h=Q(d,s);if(h){if(h.runLength>0){let p=yield this.source.getBytes(o.tileDataOffset+h.offset,h.length,n,o.etag);return{data:yield this.decompress(p.data,o.tileCompression),cacheControl:p.cacheControl,expires:p.expires}}a=o.leafDirectoryOffset+h.offset,u=h.length}else return}throw new Error("Maximum directory depth exceeded")})}getZxy(e,t,r,n){return m(this,null,function*(){try{return yield this.getZxyAttempt(e,t,r,n)}catch(s){if(s instanceof E)return this.cache.invalidate(this.source),yield this.getZxyAttempt(e,t,r,n);throw s}})}getMetadataAttempt(){return m(this,null,function*(){let e=yield this.cache.getHeader(this.source),t=yield this.source.getBytes(e.jsonMetadataOffset,e.jsonMetadataLength,void 0,e.etag),r=yield this.decompress(t.data,e.internalCompression),n=new TextDecoder("utf-8");return JSON.parse(n.decode(r))})}getMetadata(){return m(this,null,function*(){try{return yield this.getMetadataAttempt()}catch(e){if(e instanceof E)return this.cache.invalidate(this.source),yield this.getMetadataAttempt();throw e}})}getTileJson(e){return m(this,null,function*(){let t=yield this.getHeader(),r=yield this.getMetadata(),n=_(t.tileType);return{tilejson:"3.0.0",scheme:"xyz",tiles:[`${e}/{z}/{x}/{y}${n}`],vector_layers:r.vector_layers,attribution:r.attribution,description:r.description,name:r.name,version:r.version,bounds:[t.minLon,t.minLat,t.maxLon,t.maxLat],center:[t.centerLon,t.centerLat,t.centerZoom],minzoom:t.minZoom,maxzoom:t.maxZoom}})}};l(B,"PMTiles");var x=B;export{J as Compression,E as EtagMismatch,C as FetchSource,V as FileSource,x as PMTiles,S as Protocol,$ as ResolvedValueCache,P as SharedPromiseCache,O as TileType,X as bytesToHeader,Q as findTile,g as getUint64,re as leafletRasterLayer,v as readVarint,ie as tileIdToZxy,_ as tileTypeExt,G as zxyToTileId};
+var W=Object.defineProperty;var O=Math.pow;var u=(a,e)=>W(a,"name",{value:e,configurable:!0});var m=(a,e,t)=>new Promise((r,n)=>{var s=c=>{try{i(t.next(c))}catch(l){n(l)}},o=c=>{try{i(t.throw(c))}catch(l){n(l)}},i=c=>c.done?r(c.value):Promise.resolve(c.value).then(s,o);i((t=t.apply(a,e)).next())});import{decompressSync as F}from"fflate";var ne=u((a,e)=>{let t=!1,r="",n=L.GridLayer.extend({createTile:u((s,o)=>{let i=document.createElement("img"),c=new AbortController,l=c.signal;return i.cancel=()=>{c.abort()},t||(a.getHeader().then(d=>{d.tileType===1?console.error("Error: archive contains MVT vector tiles, but leafletRasterLayer is for displaying raster tiles. See https://github.com/protomaps/PMTiles/tree/main/js for details."):d.tileType===2?r="image/png":d.tileType===3?r="image/jpeg":d.tileType===4?r="image/webp":d.tileType===5&&(r="image/avif")}),t=!0),a.getZxy(s.z,s.x,s.y,l).then(d=>{if(d){let h=new Blob([d.data],{type:r}),y=window.URL.createObjectURL(h);i.src=y,i.cancel=void 0,o(void 0,i)}}).catch(d=>{if(d.name!=="AbortError")throw d}),i},"createTile"),_removeTile:u(function(s){let o=this._tiles[s];o&&(o.el.cancel&&o.el.cancel(),o.el.width=0,o.el.height=0,o.el.deleted=!0,L.DomUtil.remove(o.el),delete this._tiles[s],this.fire("tileunload",{tile:o.el,coords:this._keyToTileCoords(s)}))},"_removeTile")});return new n(e)},"leafletRasterLayer"),E=u((a,e)=>{let t=Object.keys(a),r=Object.keys(e);if(t.length!==r.length)return!1;for(var n of t){let s=a[n],o=e[n],i=S(s)&&S(o);if(i&&!E(s,o)||!i&&s!==o)return!1}return!0},"isDeepEqual"),S=u(a=>a!=null&&typeof a=="object","isObject"),q=u(a=>(e,t)=>{if(t instanceof AbortController)return a(e,t);let r=new AbortController;return a(e,r).then(n=>t(void 0,n.data,n.cacheControl||"",n.expires||""),n=>t(n)).catch(n=>t(n)),{cancel:u(()=>r.abort(),"cancel")}},"v3compat"),T=class T{constructor(e){this.tilev4=u((e,t)=>m(this,null,function*(){if(e.type==="json"){let y=e.url.substr(10),p=this.tiles.get(y);if((!p||!E(p.source.customHeaders,e.headers))&&(p=new w(y,e.headers),this.tiles.set(y,p)),this.metadata)return{data:yield p.getTileJson(e.url)};let f=yield p.getHeader();return(f.minLon>=f.maxLon||f.minLat>=f.maxLat)&&console.error(`Bounds of PMTiles archive ${f.minLon},${f.minLat},${f.maxLon},${f.maxLat} are not valid.`),{data:{tiles:[`${e.url}/{z}/{x}/{y}`],minzoom:f.minZoom,maxzoom:f.maxZoom,bounds:[f.minLon,f.minLat,f.maxLon,f.maxLat]}}}let r=new RegExp(/pmtiles:\/\/(.+)\/(\d+)\/(\d+)\/(\d+)/),n=e.url.match(r);if(!n)throw new Error("Invalid PMTiles protocol URL");let s=n[1],o=this.tiles.get(s);(!o||!E(o.source.customHeaders,e.headers))&&(o=new w(s,e.headers),this.tiles.set(s,o));let i=n[2],c=n[3],l=n[4],d=yield o.getHeader(),h=yield o==null?void 0:o.getZxy(+i,+c,+l,t.signal);if(h)return{data:new Uint8Array(h.data),cacheControl:h.cacheControl,expires:h.expires};if(d.tileType===1){if(this.errorOnMissingTile)throw new Error("Tile not found.");return{data:new Uint8Array}}return{data:null}}),"tilev4");this.tile=q(this.tilev4);this.tiles=new Map,this.metadata=(e==null?void 0:e.metadata)||!1,this.errorOnMissingTile=(e==null?void 0:e.errorOnMissingTile)||!1}add(e){this.tiles.set(e.source.getKey(),e)}get(e){return this.tiles.get(e)}};u(T,"Protocol");var V=T;function b(a,e){return(e>>>0)*4294967296+(a>>>0)}u(b,"toNum");function N(a,e){let t=e.buf,r=t[e.pos++],n=(r&112)>>4;if(r<128||(r=t[e.pos++],n|=(r&127)<<3,r<128)||(r=t[e.pos++],n|=(r&127)<<10,r<128)||(r=t[e.pos++],n|=(r&127)<<17,r<128)||(r=t[e.pos++],n|=(r&127)<<24,r<128)||(r=t[e.pos++],n|=(r&1)<<31,r<128))return b(a,n);throw new Error("Expected varint not more than 10 bytes")}u(N,"readVarintRemainder");function x(a){let e=a.buf,t=e[a.pos++],r=t&127;return t<128||(t=e[a.pos++],r|=(t&127)<<7,t<128)||(t=e[a.pos++],r|=(t&127)<<14,t<128)||(t=e[a.pos++],r|=(t&127)<<21,t<128)?r:(t=e[a.pos],r|=(t&15)<<28,N(r,a))}u(x,"readVarint");function K(a,e,t,r,n){return n===0?r!==0?[a-1-t,a-1-e]:[t,e]:[e,t]}u(K,"rotate");function G(a,e,t){if(a>26)throw new Error("Tile zoom level exceeds max safe number limit (26)");if(e>=1<<a||t>=1<<a)throw new Error("tile x/y outside zoom level bounds");let r=((1<<a)*(1<<a)-1)/3,n=a-1,[s,o]=[e,t];for(let i=1<<n;i>0;i>>=1){let c=s&i,l=o&i;r+=(3*c^l)*(1<<n),[s,o]=K(i,s,o,c,l),n--}return r}u(G,"zxyToTileId");function J(a){let e=3*a+1;return e<4294967296?31-Math.clz32(e):63-Math.clz32(e/4294967296)}u(J,"tileIdToZ");function ie(a){let e=J(a)>>1;if(e>26)throw new Error("Tile zoom level exceeds max safe number limit (26)");let t=((1<<e)*(1<<e)-1)/3,r=a-t,n=0,s=0,o=1<<e;for(let i=1;i<o;i<<=1){let c=i&r/2,l=i&(r^c);[n,s]=K(i,n,s,c,l),r=r/2,n+=c,s+=l}return[e,n,s]}u(ie,"tileIdToZxy");var _=(s=>(s[s.Unknown=0]="Unknown",s[s.None=1]="None",s[s.Gzip=2]="Gzip",s[s.Brotli=3]="Brotli",s[s.Zstd=4]="Zstd",s))(_||{});function D(a,e){return m(this,null,function*(){if(e===1||e===0)return a;if(e===2){if(typeof globalThis.DecompressionStream=="undefined")return F(new Uint8Array(a));let t=new Response(a).body;if(!t)throw new Error("Failed to read response stream");let r=t.pipeThrough(new globalThis.DecompressionStream("gzip"));return new Response(r).arrayBuffer()}throw new Error("Compression method not supported")})}u(D,"defaultDecompress");var $=(o=>(o[o.Unknown=0]="Unknown",o[o.Mvt=1]="Mvt",o[o.Png=2]="Png",o[o.Jpeg=3]="Jpeg",o[o.Webp=4]="Webp",o[o.Avif=5]="Avif",o))($||{});function Y(a){return a===1?".mvt":a===2?".png":a===3?".jpg":a===4?".webp":a===5?".avif":""}u(Y,"tileTypeExt");var Q=127;function X(a,e){let t=0,r=a.length-1;for(;t<=r;){let n=r+t>>1,s=e-a[n].tileId;if(s>0)t=n+1;else if(s<0)r=n-1;else return a[n]}return r>=0&&(a[r].runLength===0||e-a[r].tileId<a[r].runLength)?a[r]:null}u(X,"findTile");var A=class A{constructor(e){this.file=e}getKey(){return this.file.name}getBytes(e,t){return m(this,null,function*(){return{data:yield this.file.slice(e,e+t).arrayBuffer()}})}};u(A,"FileSource");var k=A,U=class U{constructor(e,t=new Headers){this.url=e,this.customHeaders=t,this.mustReload=!1;let r="";"navigator"in globalThis&&(r=globalThis.navigator.userAgent||"");let n=r.indexOf("Windows")>-1,s=/Chrome|Chromium|Edg|OPR|Brave/.test(r);this.chromeWindowsNoCache=!1,n&&s&&(this.chromeWindowsNoCache=!0)}getKey(){return this.url}setHeaders(e){this.customHeaders=e}getBytes(e,t,r,n){return m(this,null,function*(){let s,o;r?o=r:(s=new AbortController,o=s.signal);let i=new Headers(this.customHeaders);i.set("range",`bytes=${e}-${e+t-1}`);let c;this.mustReload?c="reload":this.chromeWindowsNoCache&&(c="no-store");let l=yield fetch(this.url,{signal:o,cache:c,headers:i});if(e===0&&l.status===416){let p=l.headers.get("Content-Range");if(!p||!p.startsWith("bytes */"))throw new Error("Missing content-length on 416 response");let f=+p.substr(8);l=yield fetch(this.url,{signal:o,cache:"reload",headers:{range:`bytes=0-${f-1}`}})}let d=l.headers.get("Etag");if(d!=null&&d.startsWith("W/")&&(d=null),l.status===416||n&&d&&d!==n)throw this.mustReload=!0,new v(`Server returned non-matching ETag ${n} after one retry. Check browser extensions and servers for issues that may affect correct ETag headers.`);if(l.status>=300)throw new Error(`Bad response code: ${l.status}`);let h=l.headers.get("Content-Length");if(l.status===200&&(!h||+h>t))throw s&&s.abort(),new Error("Server returned no content-length header or content-length exceeding request. Check that your storage backend supports HTTP Byte Serving.");return{data:yield l.arrayBuffer(),etag:d||void 0,cacheControl:l.headers.get("Cache-Control")||void 0,expires:l.headers.get("Expires")||void 0}})}};u(U,"FetchSource");var C=U;function g(a,e){let t=a.getUint32(e+4,!0),r=a.getUint32(e+0,!0);return t*O(2,32)+r}u(g,"getUint64");function ee(a,e){let t=new DataView(a),r=t.getUint8(7);if(r>3)throw new Error(`Archive is spec version ${r} but this library supports up to spec version 3`);return{specVersion:r,rootDirectoryOffset:g(t,8),rootDirectoryLength:g(t,16),jsonMetadataOffset:g(t,24),jsonMetadataLength:g(t,32),leafDirectoryOffset:g(t,40),leafDirectoryLength:g(t,48),tileDataOffset:g(t,56),tileDataLength:g(t,64),numAddressedTiles:g(t,72),numTileEntries:g(t,80),numTileContents:g(t,88),clustered:t.getUint8(96)===1,internalCompression:t.getUint8(97),tileCompression:t.getUint8(98),tileType:t.getUint8(99),minZoom:t.getUint8(100),maxZoom:t.getUint8(101),minLon:t.getInt32(102,!0)/1e7,minLat:t.getInt32(106,!0)/1e7,maxLon:t.getInt32(110,!0)/1e7,maxLat:t.getInt32(114,!0)/1e7,centerZoom:t.getUint8(118),centerLon:t.getInt32(119,!0)/1e7,centerLat:t.getInt32(123,!0)/1e7,etag:e}}u(ee,"bytesToHeader");function I(a){let e={buf:new Uint8Array(a),pos:0},t=x(e),r=[],n=0;for(let s=0;s<t;s++){let o=x(e);r.push({tileId:n+o,offset:0,length:0,runLength:1}),n+=o}for(let s=0;s<t;s++)r[s].runLength=x(e);for(let s=0;s<t;s++)r[s].length=x(e);for(let s=0;s<t;s++){let o=x(e);o===0&&s>0?r[s].offset=r[s-1].offset+r[s-1].length:r[s].offset=o-1}return r}u(I,"deserializeIndex");var R=class R extends Error{};u(R,"EtagMismatch");var v=R;function j(a,e){return m(this,null,function*(){let t=yield a.getBytes(0,16384);if(new DataView(t.data).getUint16(0,!0)!==19792)throw new Error("Wrong magic number for PMTiles archive");let n=t.data.slice(0,Q),s=ee(n,t.etag),o=t.data.slice(s.rootDirectoryOffset,s.rootDirectoryOffset+s.rootDirectoryLength),i=`${a.getKey()}|${s.etag||""}|${s.rootDirectoryOffset}|${s.rootDirectoryLength}`,c=I(yield e(o,s.internalCompression));return[s,[i,c.length,c]]})}u(j,"getHeaderAndRoot");function z(a,e,t,r,n){return m(this,null,function*(){let s=yield a.getBytes(t,r,void 0,n.etag),o=yield e(s.data,n.internalCompression),i=I(o);if(i.length===0)throw new Error("Empty directory is invalid");return i})}u(z,"getDirectory");var H=class H{constructor(e=100,t=!0,r=D){this.cache=new Map,this.maxCacheEntries=e,this.counter=1,this.decompress=r}getHeader(e){return m(this,null,function*(){let t=e.getKey(),r=this.cache.get(t);if(r)return r.lastUsed=this.counter++,r.data;let n=yield j(e,this.decompress);return n[1]&&this.cache.set(n[1][0],{lastUsed:this.counter++,data:n[1][2]}),this.cache.set(t,{lastUsed:this.counter++,data:n[0]}),this.prune(),n[0]})}getDirectory(e,t,r,n){return m(this,null,function*(){let s=`${e.getKey()}|${n.etag||""}|${t}|${r}`,o=this.cache.get(s);if(o)return o.lastUsed=this.counter++,o.data;let i=yield z(e,this.decompress,t,r,n);return this.cache.set(s,{lastUsed:this.counter++,data:i}),this.prune(),i})}prune(){if(this.cache.size>this.maxCacheEntries){let e=1/0,t;this.cache.forEach((r,n)=>{r.lastUsed<e&&(e=r.lastUsed,t=n)}),t&&this.cache.delete(t)}}invalidate(e){return m(this,null,function*(){this.cache.delete(e.getKey())})}};u(H,"ResolvedValueCache");var Z=H,M=class M{constructor(e=100,t=!0,r=D){this.cache=new Map,this.invalidations=new Map,this.maxCacheEntries=e,this.counter=1,this.decompress=r}getHeader(e){return m(this,null,function*(){let t=e.getKey(),r=this.cache.get(t);if(r)return r.lastUsed=this.counter++,yield r.data;let n=new Promise((s,o)=>{j(e,this.decompress).then(i=>{i[1]&&this.cache.set(i[1][0],{lastUsed:this.counter++,data:Promise.resolve(i[1][2])}),s(i[0]),this.prune()}).catch(i=>{o(i)})});return this.cache.set(t,{lastUsed:this.counter++,data:n}),n})}getDirectory(e,t,r,n){return m(this,null,function*(){let s=`${e.getKey()}|${n.etag||""}|${t}|${r}`,o=this.cache.get(s);if(o)return o.lastUsed=this.counter++,yield o.data;let i=new Promise((c,l)=>{z(e,this.decompress,t,r,n).then(d=>{c(d),this.prune()}).catch(d=>{l(d)})});return this.cache.set(s,{lastUsed:this.counter++,data:i}),i})}prune(){if(this.cache.size>=this.maxCacheEntries){let e=1/0,t;this.cache.forEach((r,n)=>{r.lastUsed<e&&(e=r.lastUsed,t=n)}),t&&this.cache.delete(t)}}invalidate(e){return m(this,null,function*(){let t=e.getKey();if(this.invalidations.get(t))return yield this.invalidations.get(t);this.cache.delete(e.getKey());let r=new Promise((n,s)=>{this.getHeader(e).then(o=>{n(),this.invalidations.delete(t)}).catch(o=>{s(o)})});this.invalidations.set(t,r)})}};u(M,"SharedPromiseCache");var P=M,B=class B{constructor(e,t,r,n){typeof e=="string"?this.source=new C(e,t):this.source=e,n?this.decompress=n:this.decompress=D,r?this.cache=r:this.cache=new P}getHeader(){return m(this,null,function*(){return yield this.cache.getHeader(this.source)})}getZxyAttempt(e,t,r,n){return m(this,null,function*(){let s=G(e,t,r),o=yield this.cache.getHeader(this.source);if(e<o.minZoom||e>o.maxZoom)return;let i=o.rootDirectoryOffset,c=o.rootDirectoryLength;for(let l=0;l<=3;l++){let d=yield this.cache.getDirectory(this.source,i,c,o),h=X(d,s);if(h){if(h.runLength>0){let y=yield this.source.getBytes(o.tileDataOffset+h.offset,h.length,n,o.etag);return{data:yield this.decompress(y.data,o.tileCompression),cacheControl:y.cacheControl,expires:y.expires}}i=o.leafDirectoryOffset+h.offset,c=h.length}else return}throw new Error("Maximum directory depth exceeded")})}getZxy(e,t,r,n){return m(this,null,function*(){try{return yield this.getZxyAttempt(e,t,r,n)}catch(s){if(s instanceof v)return this.cache.invalidate(this.source),yield this.getZxyAttempt(e,t,r,n);throw s}})}getMetadataAttempt(){return m(this,null,function*(){let e=yield this.cache.getHeader(this.source),t=yield this.source.getBytes(e.jsonMetadataOffset,e.jsonMetadataLength,void 0,e.etag),r=yield this.decompress(t.data,e.internalCompression),n=new TextDecoder("utf-8");return JSON.parse(n.decode(r))})}getMetadata(){return m(this,null,function*(){try{return yield this.getMetadataAttempt()}catch(e){if(e instanceof v)return this.cache.invalidate(this.source),yield this.getMetadataAttempt();throw e}})}getTileJson(e){return m(this,null,function*(){let t=yield this.getHeader(),r=yield this.getMetadata(),n=Y(t.tileType);return{tilejson:"3.0.0",scheme:"xyz",tiles:[`${e}/{z}/{x}/{y}${n}`],vector_layers:r.vector_layers,attribution:r.attribution,description:r.description,name:r.name,version:r.version,bounds:[t.minLon,t.minLat,t.maxLon,t.maxLat],center:[t.centerLon,t.centerLat,t.centerZoom],minzoom:t.minZoom,maxzoom:t.maxZoom}})}};u(B,"PMTiles");var w=B;export{_ as Compression,v as EtagMismatch,C as FetchSource,k as FileSource,w as PMTiles,V as Protocol,Z as ResolvedValueCache,P as SharedPromiseCache,$ as TileType,ee as bytesToHeader,X as findTile,g as getUint64,ne as leafletRasterLayer,x as readVarint,ie as tileIdToZxy,Y as tileTypeExt,G as zxyToTileId};
 //# sourceMappingURL=index.js.map
\ No newline at end of file
diff --git a/node_modules/pmtiles/dist/esm/index.js.map b/node_modules/pmtiles/dist/esm/index.js.map
index 589af80..d26cbff 100644
--- a/node_modules/pmtiles/dist/esm/index.js.map
+++ b/node_modules/pmtiles/dist/esm/index.js.map
@@ -1 +1 @@
-{"version":3,"sources":["../../src/index.ts","../../src/adapters.ts"],"sourcesContent":["import { decompressSync } from \"fflate\";\nexport * from \"./adapters\";\n\n/** @hidden */\nexport interface BufferPosition {\n  buf: Uint8Array;\n  pos: number;\n}\n\nfunction toNum(low: number, high: number): number {\n  return (high >>> 0) * 0x100000000 + (low >>> 0);\n}\n\nfunction readVarintRemainder(l: number, p: BufferPosition): number {\n  const buf = p.buf;\n  let b = buf[p.pos++];\n  let h = (b & 0x70) >> 4;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x7f) << 3;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x7f) << 10;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x7f) << 17;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x7f) << 24;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x01) << 31;\n  if (b < 0x80) return toNum(l, h);\n  throw new Error(\"Expected varint not more than 10 bytes\");\n}\n\n/** @hidden */\nexport function readVarint(p: BufferPosition): number {\n  const buf = p.buf;\n  let b = buf[p.pos++];\n  let val = b & 0x7f;\n  if (b < 0x80) return val;\n  b = buf[p.pos++];\n  val |= (b & 0x7f) << 7;\n  if (b < 0x80) return val;\n  b = buf[p.pos++];\n  val |= (b & 0x7f) << 14;\n  if (b < 0x80) return val;\n  b = buf[p.pos++];\n  val |= (b & 0x7f) << 21;\n  if (b < 0x80) return val;\n  b = buf[p.pos];\n  val |= (b & 0x0f) << 28;\n\n  return readVarintRemainder(val, p);\n}\n\nfunction rotate(n: number, xy: number[], rx: number, ry: number): void {\n  if (ry === 0) {\n    if (rx === 1) {\n      xy[0] = n - 1 - xy[0];\n      xy[1] = n - 1 - xy[1];\n    }\n    const t = xy[0];\n    xy[0] = xy[1];\n    xy[1] = t;\n  }\n}\n\nfunction idOnLevel(z: number, pos: number): [number, number, number] {\n  const n = 2 ** z;\n  let rx = pos;\n  let ry = pos;\n  let t = pos;\n  const xy = [0, 0];\n  let s = 1;\n  while (s < n) {\n    rx = 1 & (t / 2);\n    ry = 1 & (t ^ rx);\n    rotate(s, xy, rx, ry);\n    xy[0] += s * rx;\n    xy[1] += s * ry;\n    t = t / 4;\n    s *= 2;\n  }\n  return [z, xy[0], xy[1]];\n}\n\nconst tzValues: number[] = [\n  0, 1, 5, 21, 85, 341, 1365, 5461, 21845, 87381, 349525, 1398101, 5592405,\n  22369621, 89478485, 357913941, 1431655765, 5726623061, 22906492245,\n  91625968981, 366503875925, 1466015503701, 5864062014805, 23456248059221,\n  93824992236885, 375299968947541, 1501199875790165,\n];\n\n/**\n * Convert Z,X,Y to a Hilbert TileID.\n */\nexport function zxyToTileId(z: number, x: number, y: number): number {\n  if (z > 26) {\n    throw new Error(\"Tile zoom level exceeds max safe number limit (26)\");\n  }\n  if (x > 2 ** z - 1 || y > 2 ** z - 1) {\n    throw new Error(\"tile x/y outside zoom level bounds\");\n  }\n\n  const acc = tzValues[z];\n  const n = 2 ** z;\n  let rx = 0;\n  let ry = 0;\n  let d = 0;\n  const xy = [x, y];\n  let s = n / 2;\n  while (s > 0) {\n    rx = (xy[0] & s) > 0 ? 1 : 0;\n    ry = (xy[1] & s) > 0 ? 1 : 0;\n    d += s * s * ((3 * rx) ^ ry);\n    rotate(s, xy, rx, ry);\n    s = s / 2;\n  }\n  return acc + d;\n}\n\n/**\n * Convert a Hilbert TileID to Z,X,Y.\n */\nexport function tileIdToZxy(i: number): [number, number, number] {\n  let acc = 0;\n  const z = 0;\n\n  for (let z = 0; z < 27; z++) {\n    const numTiles = (0x1 << z) * (0x1 << z);\n    if (acc + numTiles > i) {\n      return idOnLevel(z, i - acc);\n    }\n    acc += numTiles;\n  }\n\n  throw new Error(\"Tile zoom level exceeds max safe number limit (26)\");\n}\n\n/**\n * PMTiles v3 directory entry.\n */\nexport interface Entry {\n  tileId: number;\n  offset: number;\n  length: number;\n  runLength: number;\n}\n\ninterface MetadataLike {\n  attribution?: string;\n  name?: string;\n  version?: string;\n  // biome-ignore lint: TileJSON spec\n  vector_layers?: string;\n  description?: string;\n}\n\n/**\n * Enum representing a compression algorithm used.\n * 0 = unknown compression, for if you must use a different or unspecified algorithm.\n * 1 = no compression.\n */\nexport enum Compression {\n  Unknown = 0,\n  None = 1,\n  Gzip = 2,\n  Brotli = 3,\n  Zstd = 4,\n}\n\n/**\n * Provide a decompression implementation that acts on `buf` and returns decompressed data.\n *\n * Should use the native DecompressionStream on browsers, zlib on node.\n * Should throw if the compression algorithm is not supported.\n */\nexport type DecompressFunc = (\n  buf: ArrayBuffer,\n  compression: Compression\n) => Promise<ArrayBuffer>;\n\nasync function defaultDecompress(\n  buf: ArrayBuffer,\n  compression: Compression\n): Promise<ArrayBuffer> {\n  if (compression === Compression.None || compression === Compression.Unknown) {\n    return buf;\n  }\n  if (compression === Compression.Gzip) {\n    // biome-ignore lint: needed to detect DecompressionStream in browser+node+cloudflare workers\n    if (typeof (globalThis as any).DecompressionStream === \"undefined\") {\n      return decompressSync(new Uint8Array(buf));\n    }\n    const stream = new Response(buf).body;\n    if (!stream) {\n      throw new Error(\"Failed to read response stream\");\n    }\n    const result: ReadableStream<Uint8Array> = stream.pipeThrough(\n      // biome-ignore lint: needed to detect DecompressionStream in browser+node+cloudflare workers\n      new (globalThis as any).DecompressionStream(\"gzip\")\n    );\n    return new Response(result).arrayBuffer();\n  }\n  throw new Error(\"Compression method not supported\");\n}\n\n/**\n * Describe the type of tiles stored in the archive.\n * 0 is unknown/other, 1 is \"MVT\" vector tiles.\n */\nexport enum TileType {\n  Unknown = 0,\n  Mvt = 1,\n  Png = 2,\n  Jpeg = 3,\n  Webp = 4,\n  Avif = 5,\n}\n\nexport function tileTypeExt(t: TileType): string {\n  if (t === TileType.Mvt) return \".mvt\";\n  if (t === TileType.Png) return \".png\";\n  if (t === TileType.Jpeg) return \".jpg\";\n  if (t === TileType.Webp) return \".webp\";\n  if (t === TileType.Avif) return \".avif\";\n  return \"\";\n}\n\nconst HEADER_SIZE_BYTES = 127;\n\n/**\n * PMTiles v3 header storing basic archive-level information.\n */\nexport interface Header {\n  specVersion: number;\n  rootDirectoryOffset: number;\n  rootDirectoryLength: number;\n  jsonMetadataOffset: number;\n  jsonMetadataLength: number;\n  leafDirectoryOffset: number;\n  leafDirectoryLength?: number;\n  tileDataOffset: number;\n  tileDataLength?: number;\n  numAddressedTiles: number;\n  numTileEntries: number;\n  numTileContents: number;\n  clustered: boolean;\n  internalCompression: Compression;\n  tileCompression: Compression;\n  tileType: TileType;\n  minZoom: number;\n  maxZoom: number;\n  minLon: number;\n  minLat: number;\n  maxLon: number;\n  maxLat: number;\n  centerZoom: number;\n  centerLon: number;\n  centerLat: number;\n  etag?: string;\n}\n\n/**\n * Low-level function for looking up a TileID or leaf directory inside a directory.\n */\nexport function findTile(entries: Entry[], tileId: number): Entry | null {\n  let m = 0;\n  let n = entries.length - 1;\n  while (m <= n) {\n    const k = (n + m) >> 1;\n    const cmp = tileId - entries[k].tileId;\n    if (cmp > 0) {\n      m = k + 1;\n    } else if (cmp < 0) {\n      n = k - 1;\n    } else {\n      return entries[k];\n    }\n  }\n\n  // at this point, m > n\n  if (n >= 0) {\n    if (entries[n].runLength === 0) {\n      return entries[n];\n    }\n    if (tileId - entries[n].tileId < entries[n].runLength) {\n      return entries[n];\n    }\n  }\n  return null;\n}\n\nexport interface RangeResponse {\n  data: ArrayBuffer;\n  etag?: string;\n  expires?: string;\n  cacheControl?: string;\n}\n\n/**\n * Interface for retrieving an archive from remote or local storage.\n */\nexport interface Source {\n  getBytes: (\n    offset: number,\n    length: number,\n    signal?: AbortSignal,\n    etag?: string\n  ) => Promise<RangeResponse>;\n\n  /**\n   * Return a unique string key for the archive e.g. a URL.\n   */\n  getKey: () => string;\n}\n\n/**\n * Use the Browser's File API, which is different from the NodeJS file API.\n * see https://developer.mozilla.org/en-US/docs/Web/API/File_API\n */\nexport class FileSource implements Source {\n  file: File;\n\n  constructor(file: File) {\n    this.file = file;\n  }\n\n  getKey() {\n    return this.file.name;\n  }\n\n  async getBytes(offset: number, length: number): Promise<RangeResponse> {\n    const blob = this.file.slice(offset, offset + length);\n    const a = await blob.arrayBuffer();\n    return { data: a };\n  }\n}\n\n/**\n * Uses the browser Fetch API to make tile requests via HTTP.\n *\n * This method does not send conditional request headers If-Match because of CORS.\n * Instead, it detects ETag mismatches via the response ETag or the 416 response code.\n *\n * This also works around browser and storage-specific edge cases.\n */\nexport class FetchSource implements Source {\n  url: string;\n\n  /**\n   * A [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) object, specfying custom [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) set for all requests to the remote archive.\n   *\n   * This should be used instead of maplibre's [transformRequest](https://maplibre.org/maplibre-gl-js/docs/API/classes/Map/#example) for PMTiles archives.\n   */\n  customHeaders: Headers;\n  /** @hidden */\n  mustReload: boolean;\n  /** @hidden */\n  chromeWindowsNoCache: boolean;\n\n  constructor(url: string, customHeaders: Headers = new Headers()) {\n    this.url = url;\n    this.customHeaders = customHeaders;\n    this.mustReload = false;\n    let userAgent = \"\";\n    if (\"navigator\" in globalThis) {\n      //biome-ignore lint: cf workers\n      userAgent = (globalThis as any).navigator.userAgent || \"\";\n    }\n    const isWindows = userAgent.indexOf(\"Windows\") > -1;\n    const isChromiumBased = /Chrome|Chromium|Edg|OPR|Brave/.test(userAgent);\n    this.chromeWindowsNoCache = false;\n    if (isWindows && isChromiumBased) {\n      this.chromeWindowsNoCache = true;\n    }\n  }\n\n  getKey() {\n    return this.url;\n  }\n\n  /**\n   * Mutate the custom [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) set for all requests to the remote archive.\n   */\n  setHeaders(customHeaders: Headers) {\n    this.customHeaders = customHeaders;\n  }\n\n  async getBytes(\n    offset: number,\n    length: number,\n    passedSignal?: AbortSignal,\n    etag?: string\n  ): Promise<RangeResponse> {\n    let controller: AbortController | undefined;\n    let signal: AbortSignal | undefined;\n    if (passedSignal) {\n      signal = passedSignal;\n    } else {\n      controller = new AbortController();\n      signal = controller.signal;\n    }\n\n    const requestHeaders = new Headers(this.customHeaders);\n    requestHeaders.set(\"range\", `bytes=${offset}-${offset + length - 1}`);\n\n    // we don't send if match because:\n    // * it disables browser caching completely (Chromium)\n    // * it requires a preflight request for every tile request\n    // * it requires CORS configuration becasue If-Match is not a CORs-safelisted header\n    // CORs configuration should expose ETag.\n    // if any etag mismatch is detected, we need to ignore the browser cache\n    let cache: string | undefined;\n    if (this.mustReload) {\n      cache = \"reload\";\n    } else if (this.chromeWindowsNoCache) {\n      cache = \"no-store\";\n    }\n\n    let resp = await fetch(this.url, {\n      signal: signal,\n      cache: cache,\n      headers: requestHeaders,\n      //biome-ignore lint: \"cache\" is incompatible between cloudflare workers and browser\n    } as any);\n\n    // handle edge case where the archive is < 16384 kb total.\n    if (offset === 0 && resp.status === 416) {\n      const contentRange = resp.headers.get(\"Content-Range\");\n      if (!contentRange || !contentRange.startsWith(\"bytes */\")) {\n        throw new Error(\"Missing content-length on 416 response\");\n      }\n      const actualLength = +contentRange.substr(8);\n      resp = await fetch(this.url, {\n        signal: signal,\n        cache: \"reload\",\n        headers: { range: `bytes=0-${actualLength - 1}` },\n        //biome-ignore lint: \"cache\" is incompatible between cloudflare workers and browser\n      } as any);\n    }\n\n    // if it's a weak etag, it's not useful for us, so ignore it.\n    let newEtag = resp.headers.get(\"Etag\");\n    if (newEtag?.startsWith(\"W/\")) {\n      newEtag = null;\n    }\n\n    // some storage systems are misbehaved (Cloudflare R2)\n    if (resp.status === 416 || (etag && newEtag && newEtag !== etag)) {\n      this.mustReload = true;\n      throw new EtagMismatch(\n        `Server returned non-matching ETag ${etag} after one retry. Check browser extensions and servers for issues that may affect correct ETag headers.`\n      );\n    }\n\n    if (resp.status >= 300) {\n      throw new Error(`Bad response code: ${resp.status}`);\n    }\n\n    // some well-behaved backends, e.g. DigitalOcean CDN, respond with 200 instead of 206\n    // but we also need to detect no support for Byte Serving which is returning the whole file\n    const contentLength = resp.headers.get(\"Content-Length\");\n    if (resp.status === 200 && (!contentLength || +contentLength > length)) {\n      if (controller) controller.abort();\n      throw new Error(\n        \"Server returned no content-length header or content-length exceeding request. Check that your storage backend supports HTTP Byte Serving.\"\n      );\n    }\n\n    const a = await resp.arrayBuffer();\n    return {\n      data: a,\n      etag: newEtag || undefined,\n      cacheControl: resp.headers.get(\"Cache-Control\") || undefined,\n      expires: resp.headers.get(\"Expires\") || undefined,\n    };\n  }\n}\n\n/** @hidden */\nexport function getUint64(v: DataView, offset: number): number {\n  const wh = v.getUint32(offset + 4, true);\n  const wl = v.getUint32(offset + 0, true);\n  return wh * 2 ** 32 + wl;\n}\n\n/**\n * Parse raw header bytes into a Header object.\n */\nexport function bytesToHeader(bytes: ArrayBuffer, etag?: string): Header {\n  const v = new DataView(bytes);\n  const specVersion = v.getUint8(7);\n  if (specVersion > 3) {\n    throw new Error(\n      `Archive is spec version ${specVersion} but this library supports up to spec version 3`\n    );\n  }\n\n  return {\n    specVersion: specVersion,\n    rootDirectoryOffset: getUint64(v, 8),\n    rootDirectoryLength: getUint64(v, 16),\n    jsonMetadataOffset: getUint64(v, 24),\n    jsonMetadataLength: getUint64(v, 32),\n    leafDirectoryOffset: getUint64(v, 40),\n    leafDirectoryLength: getUint64(v, 48),\n    tileDataOffset: getUint64(v, 56),\n    tileDataLength: getUint64(v, 64),\n    numAddressedTiles: getUint64(v, 72),\n    numTileEntries: getUint64(v, 80),\n    numTileContents: getUint64(v, 88),\n    clustered: v.getUint8(96) === 1,\n    internalCompression: v.getUint8(97),\n    tileCompression: v.getUint8(98),\n    tileType: v.getUint8(99),\n    minZoom: v.getUint8(100),\n    maxZoom: v.getUint8(101),\n    minLon: v.getInt32(102, true) / 10000000,\n    minLat: v.getInt32(106, true) / 10000000,\n    maxLon: v.getInt32(110, true) / 10000000,\n    maxLat: v.getInt32(114, true) / 10000000,\n    centerZoom: v.getUint8(118),\n    centerLon: v.getInt32(119, true) / 10000000,\n    centerLat: v.getInt32(123, true) / 10000000,\n    etag: etag,\n  };\n}\n\nfunction deserializeIndex(buffer: ArrayBuffer): Entry[] {\n  const p = { buf: new Uint8Array(buffer), pos: 0 };\n  const numEntries = readVarint(p);\n\n  const entries: Entry[] = [];\n\n  let lastId = 0;\n  for (let i = 0; i < numEntries; i++) {\n    const v = readVarint(p);\n    entries.push({ tileId: lastId + v, offset: 0, length: 0, runLength: 1 });\n    lastId += v;\n  }\n\n  for (let i = 0; i < numEntries; i++) {\n    entries[i].runLength = readVarint(p);\n  }\n\n  for (let i = 0; i < numEntries; i++) {\n    entries[i].length = readVarint(p);\n  }\n\n  for (let i = 0; i < numEntries; i++) {\n    const v = readVarint(p);\n    if (v === 0 && i > 0) {\n      entries[i].offset = entries[i - 1].offset + entries[i - 1].length;\n    } else {\n      entries[i].offset = v - 1;\n    }\n  }\n\n  return entries;\n}\n\nfunction detectVersion(a: ArrayBuffer): number {\n  const v = new DataView(a);\n  if (v.getUint16(2, true) === 2) {\n    console.error(\n      \"PMTiles spec version 2 is not supported; please see github.com/protomaps/PMTiles for tools to upgrade\"\n    );\n    return 2;\n  }\n  if (v.getUint16(2, true) === 1) {\n    console.error(\n      \"PMTiles spec version 1 is not supported; please see github.com/protomaps/PMTiles for tools to upgrade\"\n    );\n    return 1;\n  }\n  return 3;\n}\n\n/**\n * Error thrown when a response for PMTiles over HTTP does not match previous, cached parts of the archive.\n * The default PMTiles implementation will catch this error once internally and retry a request.\n */\nexport class EtagMismatch extends Error {}\n\n/**\n * Interface for caches of parts (headers, directories) of a PMTiles archive.\n */\nexport interface Cache {\n  getHeader: (source: Source) => Promise<Header>;\n  getDirectory: (\n    source: Source,\n    offset: number,\n    length: number,\n    header: Header\n  ) => Promise<Entry[]>;\n  invalidate: (source: Source) => Promise<void>;\n}\n\nasync function getHeaderAndRoot(\n  source: Source,\n  decompress: DecompressFunc\n): Promise<[Header, [string, number, Entry[] | ArrayBuffer]?]> {\n  const resp = await source.getBytes(0, 16384);\n\n  const v = new DataView(resp.data);\n  if (v.getUint16(0, true) !== 0x4d50) {\n    throw new Error(\"Wrong magic number for PMTiles archive\");\n  }\n\n  const headerData = resp.data.slice(0, HEADER_SIZE_BYTES);\n\n  const header = bytesToHeader(headerData, resp.etag);\n\n  // optimistically set the root directory\n  // TODO check root bounds\n  const rootDirData = resp.data.slice(\n    header.rootDirectoryOffset,\n    header.rootDirectoryOffset + header.rootDirectoryLength\n  );\n  const dirKey = `${source.getKey()}|${header.etag || \"\"}|${\n    header.rootDirectoryOffset\n  }|${header.rootDirectoryLength}`;\n\n  const rootDir = deserializeIndex(\n    await decompress(rootDirData, header.internalCompression)\n  );\n  return [header, [dirKey, rootDir.length, rootDir]];\n}\n\nasync function getDirectory(\n  source: Source,\n  decompress: DecompressFunc,\n  offset: number,\n  length: number,\n  header: Header\n): Promise<Entry[]> {\n  const resp = await source.getBytes(offset, length, undefined, header.etag);\n  const data = await decompress(resp.data, header.internalCompression);\n  const directory = deserializeIndex(data);\n  if (directory.length === 0) {\n    throw new Error(\"Empty directory is invalid\");\n  }\n\n  return directory;\n}\n\ninterface ResolvedValue {\n  lastUsed: number;\n  data: Header | Entry[] | ArrayBuffer;\n}\n\n/**\n * A cache for parts of a PMTiles archive where promises are never shared between requests.\n *\n * Runtimes such as Cloudflare Workers cannot share promises between different requests.\n *\n * Only caches headers and directories, not individual tile contents.\n */\nexport class ResolvedValueCache {\n  cache: Map<string, ResolvedValue>;\n  maxCacheEntries: number;\n  counter: number;\n  decompress: DecompressFunc;\n\n  constructor(\n    maxCacheEntries = 100,\n    prefetch = true, // deprecated\n    decompress: DecompressFunc = defaultDecompress\n  ) {\n    this.cache = new Map<string, ResolvedValue>();\n    this.maxCacheEntries = maxCacheEntries;\n    this.counter = 1;\n    this.decompress = decompress;\n  }\n\n  async getHeader(source: Source): Promise<Header> {\n    const cacheKey = source.getKey();\n    const cacheValue = this.cache.get(cacheKey);\n    if (cacheValue) {\n      cacheValue.lastUsed = this.counter++;\n      const data = cacheValue.data;\n      return data as Header;\n    }\n\n    const res = await getHeaderAndRoot(source, this.decompress);\n    if (res[1]) {\n      this.cache.set(res[1][0], {\n        lastUsed: this.counter++,\n        data: res[1][2],\n      });\n    }\n\n    this.cache.set(cacheKey, {\n      lastUsed: this.counter++,\n      data: res[0],\n    });\n    this.prune();\n    return res[0];\n  }\n\n  async getDirectory(\n    source: Source,\n    offset: number,\n    length: number,\n    header: Header\n  ): Promise<Entry[]> {\n    const cacheKey = `${source.getKey()}|${\n      header.etag || \"\"\n    }|${offset}|${length}`;\n    const cacheValue = this.cache.get(cacheKey);\n    if (cacheValue) {\n      cacheValue.lastUsed = this.counter++;\n      const data = cacheValue.data;\n      return data as Entry[];\n    }\n\n    const directory = await getDirectory(\n      source,\n      this.decompress,\n      offset,\n      length,\n      header\n    );\n    this.cache.set(cacheKey, {\n      lastUsed: this.counter++,\n      data: directory,\n    });\n    this.prune();\n    return directory;\n  }\n\n  prune() {\n    if (this.cache.size > this.maxCacheEntries) {\n      let minUsed = Infinity;\n      let minKey = undefined;\n      this.cache.forEach((cacheValue: ResolvedValue, key: string) => {\n        if (cacheValue.lastUsed < minUsed) {\n          minUsed = cacheValue.lastUsed;\n          minKey = key;\n        }\n      });\n      if (minKey) {\n        this.cache.delete(minKey);\n      }\n    }\n  }\n\n  async invalidate(source: Source) {\n    this.cache.delete(source.getKey());\n  }\n}\n\ninterface SharedPromiseCacheValue {\n  lastUsed: number;\n  data: Promise<Header | Entry[] | ArrayBuffer>;\n}\n\n/**\n * A cache for parts of a PMTiles archive where promises can be shared between requests.\n *\n * Only caches headers and directories, not individual tile contents.\n */\nexport class SharedPromiseCache {\n  cache: Map<string, SharedPromiseCacheValue>;\n  invalidations: Map<string, Promise<void>>;\n  maxCacheEntries: number;\n  counter: number;\n  decompress: DecompressFunc;\n\n  constructor(\n    maxCacheEntries = 100,\n    prefetch = true, // deprecated\n    decompress: DecompressFunc = defaultDecompress\n  ) {\n    this.cache = new Map<string, SharedPromiseCacheValue>();\n    this.invalidations = new Map<string, Promise<void>>();\n    this.maxCacheEntries = maxCacheEntries;\n    this.counter = 1;\n    this.decompress = decompress;\n  }\n\n  async getHeader(source: Source): Promise<Header> {\n    const cacheKey = source.getKey();\n    const cacheValue = this.cache.get(cacheKey);\n    if (cacheValue) {\n      cacheValue.lastUsed = this.counter++;\n      const data = await cacheValue.data;\n      return data as Header;\n    }\n\n    const p = new Promise<Header>((resolve, reject) => {\n      getHeaderAndRoot(source, this.decompress)\n        .then((res) => {\n          if (res[1]) {\n            this.cache.set(res[1][0], {\n              lastUsed: this.counter++,\n              data: Promise.resolve(res[1][2]),\n            });\n          }\n          resolve(res[0]);\n          this.prune();\n        })\n        .catch((e) => {\n          reject(e);\n        });\n    });\n    this.cache.set(cacheKey, { lastUsed: this.counter++, data: p });\n    return p;\n  }\n\n  async getDirectory(\n    source: Source,\n    offset: number,\n    length: number,\n    header: Header\n  ): Promise<Entry[]> {\n    const cacheKey = `${source.getKey()}|${\n      header.etag || \"\"\n    }|${offset}|${length}`;\n    const cacheValue = this.cache.get(cacheKey);\n    if (cacheValue) {\n      cacheValue.lastUsed = this.counter++;\n      const data = await cacheValue.data;\n      return data as Entry[];\n    }\n\n    const p = new Promise<Entry[]>((resolve, reject) => {\n      getDirectory(source, this.decompress, offset, length, header)\n        .then((directory) => {\n          resolve(directory);\n          this.prune();\n        })\n        .catch((e) => {\n          reject(e);\n        });\n    });\n    this.cache.set(cacheKey, { lastUsed: this.counter++, data: p });\n    return p;\n  }\n\n  prune() {\n    if (this.cache.size >= this.maxCacheEntries) {\n      let minUsed = Infinity;\n      let minKey = undefined;\n      this.cache.forEach((cacheValue: SharedPromiseCacheValue, key: string) => {\n        if (cacheValue.lastUsed < minUsed) {\n          minUsed = cacheValue.lastUsed;\n          minKey = key;\n        }\n      });\n      if (minKey) {\n        this.cache.delete(minKey);\n      }\n    }\n  }\n\n  async invalidate(source: Source) {\n    const key = source.getKey();\n    if (this.invalidations.get(key)) {\n      return await this.invalidations.get(key);\n    }\n    this.cache.delete(source.getKey());\n    const p = new Promise<void>((resolve, reject) => {\n      this.getHeader(source)\n        .then((h) => {\n          resolve();\n          this.invalidations.delete(key);\n        })\n        .catch((e) => {\n          reject(e);\n        });\n    });\n    this.invalidations.set(key, p);\n  }\n}\n\n/**\n * Main class encapsulating PMTiles decoding logic.\n *\n * if `source` is a string, creates a FetchSource using that string as the URL to a remote PMTiles.\n * if no `cache` is passed, use a SharedPromiseCache.\n * if no `decompress` is passed, default to the browser DecompressionStream API with a fallback to `fflate`.\n */\n// biome-ignore lint: that's just how its capitalized\nexport class PMTiles {\n  source: Source;\n  cache: Cache;\n  decompress: DecompressFunc;\n\n  constructor(\n    source: Source | string,\n    cache?: Cache,\n    decompress?: DecompressFunc\n  ) {\n    if (typeof source === \"string\") {\n      this.source = new FetchSource(source);\n    } else {\n      this.source = source;\n    }\n    if (decompress) {\n      this.decompress = decompress;\n    } else {\n      this.decompress = defaultDecompress;\n    }\n    if (cache) {\n      this.cache = cache;\n    } else {\n      this.cache = new SharedPromiseCache();\n    }\n  }\n\n  /**\n   * Return the header of the archive,\n   * including information such as tile type, min/max zoom, bounds, and summary statistics.\n   */\n  async getHeader() {\n    return await this.cache.getHeader(this.source);\n  }\n\n  /** @hidden */\n  async getZxyAttempt(\n    z: number,\n    x: number,\n    y: number,\n    signal?: AbortSignal\n  ): Promise<RangeResponse | undefined> {\n    const tileId = zxyToTileId(z, x, y);\n    const header = await this.cache.getHeader(this.source);\n\n    if (z < header.minZoom || z > header.maxZoom) {\n      return undefined;\n    }\n\n    let dO = header.rootDirectoryOffset;\n    let dL = header.rootDirectoryLength;\n    for (let depth = 0; depth <= 3; depth++) {\n      const directory = await this.cache.getDirectory(\n        this.source,\n        dO,\n        dL,\n        header\n      );\n      const entry = findTile(directory, tileId);\n      if (entry) {\n        if (entry.runLength > 0) {\n          const resp = await this.source.getBytes(\n            header.tileDataOffset + entry.offset,\n            entry.length,\n            signal,\n            header.etag\n          );\n          return {\n            data: await this.decompress(resp.data, header.tileCompression),\n            cacheControl: resp.cacheControl,\n            expires: resp.expires,\n          };\n        }\n        dO = header.leafDirectoryOffset + entry.offset;\n        dL = entry.length;\n      } else {\n        // TODO: We should in fact return a valid RangeResponse\n        // with empty data, but filled in cache control / expires headers\n        return undefined;\n      }\n    }\n    throw new Error(\"Maximum directory depth exceeded\");\n  }\n\n  /**\n   * Primary method to get a single tile's bytes from an archive.\n   *\n   * Returns undefined if the tile does not exist in the archive.\n   */\n  async getZxy(\n    z: number,\n    x: number,\n    y: number,\n    signal?: AbortSignal\n  ): Promise<RangeResponse | undefined> {\n    try {\n      return await this.getZxyAttempt(z, x, y, signal);\n    } catch (e) {\n      if (e instanceof EtagMismatch) {\n        this.cache.invalidate(this.source);\n        return await this.getZxyAttempt(z, x, y, signal);\n      }\n      throw e;\n    }\n  }\n\n  /** @hidden */\n  async getMetadataAttempt(): Promise<unknown> {\n    const header = await this.cache.getHeader(this.source);\n\n    const resp = await this.source.getBytes(\n      header.jsonMetadataOffset,\n      header.jsonMetadataLength,\n      undefined,\n      header.etag\n    );\n    const decompressed = await this.decompress(\n      resp.data,\n      header.internalCompression\n    );\n    const dec = new TextDecoder(\"utf-8\");\n    return JSON.parse(dec.decode(decompressed));\n  }\n\n  /**\n   * Return the arbitrary JSON metadata of the archive.\n   */\n  async getMetadata(): Promise<unknown> {\n    try {\n      return await this.getMetadataAttempt();\n    } catch (e) {\n      if (e instanceof EtagMismatch) {\n        this.cache.invalidate(this.source);\n        return await this.getMetadataAttempt();\n      }\n      throw e;\n    }\n  }\n\n  /**\n   * Construct a [TileJSON](https://github.com/mapbox/tilejson-spec) object.\n   *\n   * baseTilesUrl is the desired tiles URL, excluding the suffix `/{z}/{x}/{y}.{ext}`.\n   * For example, if the desired URL is `http://example.com/tileset/{z}/{x}/{y}.mvt`,\n   * the baseTilesUrl should be `https://example.com/tileset`.\n   */\n  async getTileJson(baseTilesUrl: string): Promise<unknown> {\n    const header = await this.getHeader();\n    const metadata = (await this.getMetadata()) as MetadataLike;\n    const ext = tileTypeExt(header.tileType);\n\n    return {\n      tilejson: \"3.0.0\",\n      scheme: \"xyz\",\n      tiles: [`${baseTilesUrl}/{z}/{x}/{y}${ext}`],\n      // biome-ignore lint: TileJSON spec\n      vector_layers: metadata.vector_layers,\n      attribution: metadata.attribution,\n      description: metadata.description,\n      name: metadata.name,\n      version: metadata.version,\n      bounds: [header.minLon, header.minLat, header.maxLon, header.maxLat],\n      center: [header.centerLon, header.centerLat, header.centerZoom],\n      minzoom: header.minZoom,\n      maxzoom: header.maxZoom,\n    };\n  }\n}\n","// biome-ignore lint: needed for Leaflet + IIFE to work\ndeclare const L: any;\n// biome-ignore lint: needed for window.URL to disambiguate from cloudflare workers\ndeclare const window: any;\ndeclare const document: DocumentLike;\n\nimport type { Coords } from \"leaflet\";\nimport { PMTiles, TileType } from \"./index\";\n\ninterface DocumentLike {\n  // biome-ignore lint: we don't want to bring in the entire document type\n  createElement: (s: string) => any;\n}\n\n// biome-ignore lint: we don't want to bring in the entire document type\ntype DoneCallback = (error?: Error, tile?: any) => void;\n\n/**\n * Add a raster PMTiles as a layer to a Leaflet map.\n *\n * For vector tiles see https://github.com/protomaps/protomaps-leaflet\n */\nexport const leafletRasterLayer = (source: PMTiles, options: unknown) => {\n  let loaded = false;\n  let mimeType = \"\";\n  const cls = L.GridLayer.extend({\n    createTile: (coord: Coords, done: DoneCallback) => {\n      const el = document.createElement(\"img\");\n      const controller = new AbortController();\n      const signal = controller.signal;\n      el.cancel = () => {\n        controller.abort();\n      };\n      if (!loaded) {\n        source.getHeader().then((header) => {\n          if (header.tileType === TileType.Mvt) {\n            console.error(\n              \"Error: archive contains MVT vector tiles, but leafletRasterLayer is for displaying raster tiles. See https://github.com/protomaps/PMTiles/tree/main/js for details.\"\n            );\n          } else if (header.tileType === 2) {\n            mimeType = \"image/png\";\n          } else if (header.tileType === 3) {\n            mimeType = \"image/jpeg\";\n          } else if (header.tileType === 4) {\n            mimeType = \"image/webp\";\n          } else if (header.tileType === 5) {\n            mimeType = \"image/avif\";\n          }\n        });\n        loaded = true;\n      }\n      source\n        .getZxy(coord.z, coord.x, coord.y, signal)\n        .then((arr) => {\n          if (arr) {\n            const blob = new Blob([arr.data], { type: mimeType });\n            const imageUrl = window.URL.createObjectURL(blob);\n            el.src = imageUrl;\n            el.cancel = undefined;\n            done(undefined, el);\n          }\n        })\n        .catch((e) => {\n          if (e.name !== \"AbortError\") {\n            throw e;\n          }\n        });\n      return el;\n    },\n\n    _removeTile: function (key: string) {\n      const tile = this._tiles[key];\n      if (!tile) {\n        return;\n      }\n\n      if (tile.el.cancel) tile.el.cancel();\n\n      tile.el.width = 0;\n      tile.el.height = 0;\n      tile.el.deleted = true;\n      L.DomUtil.remove(tile.el);\n      delete this._tiles[key];\n      this.fire(\"tileunload\", {\n        tile: tile.el,\n        coords: this._keyToTileCoords(key),\n      });\n    },\n  });\n  return new cls(options);\n};\n\ntype GetResourceResponse<T> = ExpiryData & {\n  data: T;\n};\ntype AddProtocolAction = (\n  requestParameters: RequestParameters,\n  abortController: AbortController\n) => Promise<GetResourceResponse<unknown>>;\n\ntype ExpiryData = {\n  cacheControl?: string | null;\n  expires?: string | null; // MapLibre can be a Date object\n};\n\n// copied from MapLibre /util/ajax.ts\ntype RequestParameters = {\n  url: string;\n  headers?: unknown;\n  method?: \"GET\" | \"POST\" | \"PUT\";\n  body?: string;\n  type?: \"string\" | \"json\" | \"arrayBuffer\" | \"image\";\n  credentials?: \"same-origin\" | \"include\";\n  collectResourceTiming?: boolean;\n};\n\n// for legacy maplibre-3 interop\ntype ResponseCallbackV3 = (\n  error?: Error | undefined,\n  data?: unknown | undefined,\n  cacheControl?: string | undefined,\n  expires?: string | undefined\n) => void;\n\ntype V3OrV4Protocol = <\n  T extends AbortController | ResponseCallbackV3,\n  R = T extends AbortController\n    ? Promise<GetResourceResponse<unknown>>\n    : { cancel: () => void },\n>(\n  requestParameters: RequestParameters,\n  arg2: T\n) => R;\n\nconst v3compat =\n  (v4: AddProtocolAction): V3OrV4Protocol =>\n  (requestParameters, arg2) => {\n    if (arg2 instanceof AbortController) {\n      // biome-ignore lint: overloading return type not handled by compiler\n      return v4(requestParameters, arg2) as any;\n    }\n    const abortController = new AbortController();\n    v4(requestParameters, abortController)\n      .then(\n        (result) => {\n          return arg2(\n            undefined,\n            result.data,\n            result.cacheControl || \"\",\n            result.expires || \"\"\n          );\n        },\n        (err) => {\n          return arg2(err);\n        }\n      )\n      .catch((e) => {\n        return arg2(e);\n      });\n    return { cancel: () => abortController.abort() };\n  };\n\n/**\n * MapLibre GL JS protocol. Must be added once globally.\n */\nexport class Protocol {\n  /** @hidden */\n  tiles: Map<string, PMTiles>;\n  metadata: boolean;\n  errorOnMissingTile: boolean;\n\n  /**\n   * Initialize the MapLibre PMTiles protocol.\n   *\n   * * metadata: also load the metadata section of the PMTiles. required for some \"inspect\" functionality\n   * and to automatically populate the map attribution. Requires an extra HTTP request.\n   * * errorOnMissingTile: When a vector MVT tile is missing from the archive, raise an error instead of\n   * returning the empty array. Not recommended. This is only to reproduce the behavior of ZXY tile APIs\n   * which some applications depend on when overzooming.\n   */\n  constructor(options?: { metadata?: boolean; errorOnMissingTile?: boolean }) {\n    this.tiles = new Map<string, PMTiles>();\n    this.metadata = options?.metadata || false;\n    this.errorOnMissingTile = options?.errorOnMissingTile || false;\n  }\n\n  /**\n   * Add a {@link PMTiles} instance to the global protocol instance.\n   *\n   * For remote fetch sources, references in MapLibre styles like pmtiles://http://...\n   * will resolve to the same instance if the URLs match.\n   */\n  add(p: PMTiles) {\n    this.tiles.set(p.source.getKey(), p);\n  }\n\n  /**\n   * Fetch a {@link PMTiles} instance by URL, for remote PMTiles instances.\n   */\n  get(url: string) {\n    return this.tiles.get(url);\n  }\n\n  /** @hidden */\n  tilev4 = async (\n    params: RequestParameters,\n    abortController: AbortController\n  ) => {\n    if (params.type === \"json\") {\n      const pmtilesUrl = params.url.substr(10);\n      let instance = this.tiles.get(pmtilesUrl);\n      if (!instance) {\n        instance = new PMTiles(pmtilesUrl);\n        this.tiles.set(pmtilesUrl, instance);\n      }\n\n      if (this.metadata) {\n        return {\n          data: await instance.getTileJson(params.url),\n        };\n      }\n\n      const h = await instance.getHeader();\n\n      if (h.minLon >= h.maxLon || h.minLat >= h.maxLat) {\n        console.error(\n          `Bounds of PMTiles archive ${h.minLon},${h.minLat},${h.maxLon},${h.maxLat} are not valid.`\n        );\n      }\n\n      return {\n        data: {\n          tiles: [`${params.url}/{z}/{x}/{y}`],\n          minzoom: h.minZoom,\n          maxzoom: h.maxZoom,\n          bounds: [h.minLon, h.minLat, h.maxLon, h.maxLat],\n        },\n      };\n    }\n    const re = new RegExp(/pmtiles:\\/\\/(.+)\\/(\\d+)\\/(\\d+)\\/(\\d+)/);\n    const result = params.url.match(re);\n    if (!result) {\n      throw new Error(\"Invalid PMTiles protocol URL\");\n    }\n    const pmtilesUrl = result[1];\n\n    let instance = this.tiles.get(pmtilesUrl);\n    if (!instance) {\n      instance = new PMTiles(pmtilesUrl);\n      this.tiles.set(pmtilesUrl, instance);\n    }\n    const z = result[2];\n    const x = result[3];\n    const y = result[4];\n\n    const header = await instance.getHeader();\n    const resp = await instance?.getZxy(+z, +x, +y, abortController.signal);\n    if (resp) {\n      return {\n        data: new Uint8Array(resp.data),\n        cacheControl: resp.cacheControl,\n        expires: resp.expires,\n      };\n    }\n    if (header.tileType === TileType.Mvt) {\n      if (this.errorOnMissingTile) {\n        throw new Error(\"Tile not found.\");\n      }\n      return { data: new Uint8Array() };\n    }\n    return { data: null };\n  };\n\n  tile = v3compat(this.tilev4);\n}\n"],"mappings":"2SAAA,OAAS,kBAAAA,MAAsB,SCsBxB,IAAMC,GAAqBC,EAAA,CAACC,EAAiBC,IAAqB,CACvE,IAAIC,EAAS,GACTC,EAAW,GACTC,EAAM,EAAE,UAAU,OAAO,CAC7B,WAAYL,EAAA,CAACM,EAAeC,IAAuB,CACjD,IAAMC,EAAK,SAAS,cAAc,KAAK,EACjCC,EAAa,IAAI,gBACjBC,EAASD,EAAW,OAC1B,OAAAD,EAAG,OAAS,IAAM,CAChBC,EAAW,MAAM,CACnB,EACKN,IACHF,EAAO,UAAU,EAAE,KAAMU,GAAW,CAC9BA,EAAO,WAAa,EACtB,QAAQ,MACN,qKACF,EACSA,EAAO,WAAa,EAC7BP,EAAW,YACFO,EAAO,WAAa,EAC7BP,EAAW,aACFO,EAAO,WAAa,EAC7BP,EAAW,aACFO,EAAO,WAAa,IAC7BP,EAAW,aAEf,CAAC,EACDD,EAAS,IAEXF,EACG,OAAOK,EAAM,EAA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EAEvC,MAAM,CACR,CACF,GASM,YAAYqD,EAAwC,QAAAjD,EAAA,sBACxD,IAAMI,EAAS,MAAM,KAAK,UAAU,EAC9B8C,EAAY,MAAM,KAAK,YAAY,EACnCC,EAAMC,EAAYhD,EAAO,QAAQ,EAEvC,MAAO,CACL,SAAU,QACV,OAAQ,MACR,MAAO,CAAC,GAAG6C,CAAY,eAAeE,CAAG,EAAE,EAE3C,cAAeD,EAAS,cACxB,YAAaA,EAAS,YACtB,YAAaA,EAAS,YACtB,KAAMA,EAAS,KACf,QAASA,EAAS,QAClB,OAAQ,CAAC9C,EAAO,OAAQA,EAAO,OAAQA,EAAO,OAAQA,EAAO,MAAM,EACnE,OAAQ,CAACA,EAAO,UAAWA,EAAO,UAAWA,EAAO,UAAU,EAC9D,QAASA,EAAO,QAChB,QAASA,EAAO,OAClB,CACF,GACF,EAvKqBT,EAAAsC,EAAA,WAAd,IAAMoB,EAANpB","names":["decompressSync","leafletRasterLayer","__name","source","options","loaded","mimeType","cls","coord","done","el","controller","signal","header","arr","blob","imageUrl","e","key","tile","v3compat","v4","requestParameters","arg2","abortController","result","err","_Protocol","params","__async","pmtilesUrl","instance","PMTiles","h","re","z","x","y","resp","p","url","Protocol","toNum","low","high","__name","readVarintRemainder","l","p","buf","b","h","readVarint","val","rotate","n","xy","rx","ry","t","idOnLevel","z","pos","__pow","s","tzValues","zxyToTileId","x","y","acc","d","tileIdToZxy","numTiles","Compression","defaultDecompress","compression","__async","decompressSync","stream","result","TileType","tileTypeExt","HEADER_SIZE_BYTES","findTile","entries","tileId","m","k","cmp","_FileSource","file","offset","length","FileSource","_FetchSource","url","customHeaders","userAgent","isWindows","isChromiumBased","passedSignal","etag","controller","signal","requestHeaders","cache","resp","contentRange","actualLength","newEtag","EtagMismatch","contentLength","FetchSource","getUint64","v","wh","wl","bytesToHeader","bytes","specVersion","deserializeIndex","buffer","numEntries","lastId","i","_EtagMismatch","__name","EtagMismatch","getHeaderAndRoot","source","decompress","__async","resp","headerData","HEADER_SIZE_BYTES","header","bytesToHeader","rootDirData","dirKey","rootDir","deserializeIndex","getDirectory","offset","length","data","directory","_ResolvedValueCache","maxCacheEntries","prefetch","defaultDecompress","cacheKey","cacheValue","res","minUsed","minKey","key","ResolvedValueCache","_SharedPromiseCache","p","resolve","reject","e","h","SharedPromiseCache","_PMTiles","cache","FetchSource","z","x","y","signal","tileId","zxyToTileId","dO","dL","depth","entry","findTile","decompressed","dec","baseTilesUrl","metadata","ext","tileTypeExt","PMTiles"]}
\ No newline at end of file
+{"version":3,"sources":["../../src/index.ts","../../src/adapters.ts"],"sourcesContent":["import { decompressSync } from \"fflate\";\nexport * from \"./adapters\";\n\n/** @hidden */\nexport interface BufferPosition {\n  buf: Uint8Array;\n  pos: number;\n}\n\nfunction toNum(low: number, high: number): number {\n  return (high >>> 0) * 0x100000000 + (low >>> 0);\n}\n\nfunction readVarintRemainder(l: number, p: BufferPosition): number {\n  const buf = p.buf;\n  let b = buf[p.pos++];\n  let h = (b & 0x70) >> 4;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x7f) << 3;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x7f) << 10;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x7f) << 17;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x7f) << 24;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x01) << 31;\n  if (b < 0x80) return toNum(l, h);\n  throw new Error(\"Expected varint not more than 10 bytes\");\n}\n\n/** @hidden */\nexport function readVarint(p: BufferPosition): number {\n  const buf = p.buf;\n  let b = buf[p.pos++];\n  let val = b & 0x7f;\n  if (b < 0x80) return val;\n  b = buf[p.pos++];\n  val |= (b & 0x7f) << 7;\n  if (b < 0x80) return val;\n  b = buf[p.pos++];\n  val |= (b & 0x7f) << 14;\n  if (b < 0x80) return val;\n  b = buf[p.pos++];\n  val |= (b & 0x7f) << 21;\n  if (b < 0x80) return val;\n  b = buf[p.pos];\n  val |= (b & 0x0f) << 28;\n\n  return readVarintRemainder(val, p);\n}\n\nfunction rotate(\n  n: number,\n  x: number,\n  y: number,\n  rx: number,\n  ry: number\n): [number, number] {\n  if (ry === 0) {\n    if (rx !== 0) {\n      return [n - 1 - y, n - 1 - x];\n    }\n    return [y, x];\n  }\n  return [x, y];\n}\n\n/**\n * Convert Z,X,Y to a Hilbert TileID.\n */\nexport function zxyToTileId(z: number, x: number, y: number): number {\n  if (z > 26) {\n    throw new Error(\"Tile zoom level exceeds max safe number limit (26)\");\n  }\n  if (x >= 1 << z || y >= 1 << z) {\n    throw new Error(\"tile x/y outside zoom level bounds\");\n  }\n  let acc = ((1 << z) * (1 << z) - 1) / 3;\n  let a = z - 1;\n  let [tx, ty] = [x, y];\n  for (let s = 1 << a; s > 0; s >>= 1) {\n    const rx = tx & s;\n    const ry = ty & s;\n    acc += ((3 * rx) ^ ry) * (1 << a);\n    [tx, ty] = rotate(s, tx, ty, rx, ry);\n    a--;\n  }\n  return acc;\n}\n\nfunction tileIdToZ(i: number): number {\n  const c = 3 * i + 1;\n  if (c < 0x100000000) {\n    return 31 - Math.clz32(c);\n  }\n  return 63 - Math.clz32(c / 0x100000000);\n}\n\n/**\n * Convert a Hilbert TileID to Z,X,Y.\n */\nexport function tileIdToZxy(i: number): [number, number, number] {\n  const z = tileIdToZ(i) >> 1;\n  if (z > 26)\n    throw new Error(\"Tile zoom level exceeds max safe number limit (26)\");\n  const acc = ((1 << z) * (1 << z) - 1) / 3;\n\n  let t = i - acc;\n  let x = 0;\n  let y = 0;\n  const n = 1 << z;\n  for (let s = 1; s < n; s <<= 1) {\n    const rx = s & (t / 2);\n    const ry = s & (t ^ rx);\n    [x, y] = rotate(s, x, y, rx, ry);\n    t = t / 2;\n    x += rx;\n    y += ry;\n  }\n  return [z, x, y];\n}\n\n/**\n * PMTiles v3 directory entry.\n */\nexport interface Entry {\n  tileId: number;\n  offset: number;\n  length: number;\n  runLength: number;\n}\n\ninterface MetadataLike {\n  attribution?: string;\n  name?: string;\n  version?: string;\n  // biome-ignore lint: TileJSON spec\n  vector_layers?: string;\n  description?: string;\n}\n\n/**\n * Enum representing a compression algorithm used.\n * 0 = unknown compression, for if you must use a different or unspecified algorithm.\n * 1 = no compression.\n */\nexport enum Compression {\n  Unknown = 0,\n  None = 1,\n  Gzip = 2,\n  Brotli = 3,\n  Zstd = 4,\n}\n\n/**\n * Provide a decompression implementation that acts on `buf` and returns decompressed data.\n *\n * Should use the native DecompressionStream on browsers, zlib on node.\n * Should throw if the compression algorithm is not supported.\n */\nexport type DecompressFunc = (\n  buf: ArrayBuffer,\n  compression: Compression\n) => Promise<ArrayBuffer>;\n\nasync function defaultDecompress(\n  buf: ArrayBuffer,\n  compression: Compression\n): Promise<ArrayBuffer> {\n  if (compression === Compression.None || compression === Compression.Unknown) {\n    return buf;\n  }\n  if (compression === Compression.Gzip) {\n    // biome-ignore lint: needed to detect DecompressionStream in browser+node+cloudflare workers\n    if (typeof (globalThis as any).DecompressionStream === \"undefined\") {\n      return decompressSync(new Uint8Array(buf));\n    }\n    const stream = new Response(buf).body;\n    if (!stream) {\n      throw new Error(\"Failed to read response stream\");\n    }\n    const result: ReadableStream<Uint8Array> = stream.pipeThrough(\n      // biome-ignore lint: needed to detect DecompressionStream in browser+node+cloudflare workers\n      new (globalThis as any).DecompressionStream(\"gzip\")\n    );\n    return new Response(result).arrayBuffer();\n  }\n  throw new Error(\"Compression method not supported\");\n}\n\n/**\n * Describe the type of tiles stored in the archive.\n * 0 is unknown/other, 1 is \"MVT\" vector tiles.\n */\nexport enum TileType {\n  Unknown = 0,\n  Mvt = 1,\n  Png = 2,\n  Jpeg = 3,\n  Webp = 4,\n  Avif = 5,\n}\n\nexport function tileTypeExt(t: TileType): string {\n  if (t === TileType.Mvt) return \".mvt\";\n  if (t === TileType.Png) return \".png\";\n  if (t === TileType.Jpeg) return \".jpg\";\n  if (t === TileType.Webp) return \".webp\";\n  if (t === TileType.Avif) return \".avif\";\n  return \"\";\n}\n\nconst HEADER_SIZE_BYTES = 127;\n\n/**\n * PMTiles v3 header storing basic archive-level information.\n */\nexport interface Header {\n  specVersion: number;\n  rootDirectoryOffset: number;\n  rootDirectoryLength: number;\n  jsonMetadataOffset: number;\n  jsonMetadataLength: number;\n  leafDirectoryOffset: number;\n  leafDirectoryLength?: number;\n  tileDataOffset: number;\n  tileDataLength?: number;\n  numAddressedTiles: number;\n  numTileEntries: number;\n  numTileContents: number;\n  clustered: boolean;\n  internalCompression: Compression;\n  tileCompression: Compression;\n  tileType: TileType;\n  minZoom: number;\n  maxZoom: number;\n  minLon: number;\n  minLat: number;\n  maxLon: number;\n  maxLat: number;\n  centerZoom: number;\n  centerLon: number;\n  centerLat: number;\n  etag?: string;\n}\n\n/**\n * Low-level function for looking up a TileID or leaf directory inside a directory.\n */\nexport function findTile(entries: Entry[], tileId: number): Entry | null {\n  let m = 0;\n  let n = entries.length - 1;\n  while (m <= n) {\n    const k = (n + m) >> 1;\n    const cmp = tileId - entries[k].tileId;\n    if (cmp > 0) {\n      m = k + 1;\n    } else if (cmp < 0) {\n      n = k - 1;\n    } else {\n      return entries[k];\n    }\n  }\n\n  // at this point, m > n\n  if (n >= 0) {\n    if (entries[n].runLength === 0) {\n      return entries[n];\n    }\n    if (tileId - entries[n].tileId < entries[n].runLength) {\n      return entries[n];\n    }\n  }\n  return null;\n}\n\nexport interface RangeResponse {\n  data: ArrayBuffer;\n  etag?: string;\n  expires?: string;\n  cacheControl?: string;\n}\n\n/**\n * Interface for retrieving an archive from remote or local storage.\n */\nexport interface Source {\n  getBytes: (\n    offset: number,\n    length: number,\n    signal?: AbortSignal,\n    etag?: string\n  ) => Promise<RangeResponse>;\n\n  /**\n   * Return a unique string key for the archive e.g. a URL.\n   */\n  getKey: () => string;\n}\n\n/**\n * Use the Browser's File API, which is different from the NodeJS file API.\n * see https://developer.mozilla.org/en-US/docs/Web/API/File_API\n */\nexport class FileSource implements Source {\n  file: File;\n\n  constructor(file: File) {\n    this.file = file;\n  }\n\n  getKey() {\n    return this.file.name;\n  }\n\n  async getBytes(offset: number, length: number): Promise<RangeResponse> {\n    const blob = this.file.slice(offset, offset + length);\n    const a = await blob.arrayBuffer();\n    return { data: a };\n  }\n}\n\n/**\n * Uses the browser Fetch API to make tile requests via HTTP.\n *\n * This method does not send conditional request headers If-Match because of CORS.\n * Instead, it detects ETag mismatches via the response ETag or the 416 response code.\n *\n * This also works around browser and storage-specific edge cases.\n */\nexport class FetchSource implements Source {\n  url: string;\n\n  /**\n   * A [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) object, specfying custom [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) set for all requests to the remote archive.\n   *\n   * This should be used instead of maplibre's [transformRequest](https://maplibre.org/maplibre-gl-js/docs/API/classes/Map/#example) for PMTiles archives.\n   */\n  customHeaders: Headers;\n  /** @hidden */\n  mustReload: boolean;\n  /** @hidden */\n  chromeWindowsNoCache: boolean;\n\n  constructor(url: string, customHeaders: Headers = new Headers()) {\n    this.url = url;\n    this.customHeaders = customHeaders;\n    this.mustReload = false;\n    let userAgent = \"\";\n    if (\"navigator\" in globalThis) {\n      //biome-ignore lint: cf workers\n      userAgent = (globalThis as any).navigator.userAgent || \"\";\n    }\n    const isWindows = userAgent.indexOf(\"Windows\") > -1;\n    const isChromiumBased = /Chrome|Chromium|Edg|OPR|Brave/.test(userAgent);\n    this.chromeWindowsNoCache = false;\n    if (isWindows && isChromiumBased) {\n      this.chromeWindowsNoCache = true;\n    }\n  }\n\n  getKey() {\n    return this.url;\n  }\n\n  /**\n   * Mutate the custom [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) set for all requests to the remote archive.\n   */\n  setHeaders(customHeaders: Headers) {\n    this.customHeaders = customHeaders;\n  }\n\n  async getBytes(\n    offset: number,\n    length: number,\n    passedSignal?: AbortSignal,\n    etag?: string\n  ): Promise<RangeResponse> {\n    let controller: AbortController | undefined;\n    let signal: AbortSignal | undefined;\n    if (passedSignal) {\n      signal = passedSignal;\n    } else {\n      controller = new AbortController();\n      signal = controller.signal;\n    }\n\n    const requestHeaders = new Headers(this.customHeaders);\n    requestHeaders.set(\"range\", `bytes=${offset}-${offset + length - 1}`);\n\n    // we don't send if match because:\n    // * it disables browser caching completely (Chromium)\n    // * it requires a preflight request for every tile request\n    // * it requires CORS configuration becasue If-Match is not a CORs-safelisted header\n    // CORs configuration should expose ETag.\n    // if any etag mismatch is detected, we need to ignore the browser cache\n    let cache: string | undefined;\n    if (this.mustReload) {\n      cache = \"reload\";\n    } else if (this.chromeWindowsNoCache) {\n      cache = \"no-store\";\n    }\n\n    let resp = await fetch(this.url, {\n      signal: signal,\n      cache: cache,\n      headers: requestHeaders,\n      //biome-ignore lint: \"cache\" is incompatible between cloudflare workers and browser\n    } as any);\n\n    // handle edge case where the archive is < 16384 kb total.\n    if (offset === 0 && resp.status === 416) {\n      const contentRange = resp.headers.get(\"Content-Range\");\n      if (!contentRange || !contentRange.startsWith(\"bytes */\")) {\n        throw new Error(\"Missing content-length on 416 response\");\n      }\n      const actualLength = +contentRange.substr(8);\n      resp = await fetch(this.url, {\n        signal: signal,\n        cache: \"reload\",\n        headers: { range: `bytes=0-${actualLength - 1}` },\n        //biome-ignore lint: \"cache\" is incompatible between cloudflare workers and browser\n      } as any);\n    }\n\n    // if it's a weak etag, it's not useful for us, so ignore it.\n    let newEtag = resp.headers.get(\"Etag\");\n    if (newEtag?.startsWith(\"W/\")) {\n      newEtag = null;\n    }\n\n    // some storage systems are misbehaved (Cloudflare R2)\n    if (resp.status === 416 || (etag && newEtag && newEtag !== etag)) {\n      this.mustReload = true;\n      throw new EtagMismatch(\n        `Server returned non-matching ETag ${etag} after one retry. Check browser extensions and servers for issues that may affect correct ETag headers.`\n      );\n    }\n\n    if (resp.status >= 300) {\n      throw new Error(`Bad response code: ${resp.status}`);\n    }\n\n    // some well-behaved backends, e.g. DigitalOcean CDN, respond with 200 instead of 206\n    // but we also need to detect no support for Byte Serving which is returning the whole file\n    const contentLength = resp.headers.get(\"Content-Length\");\n    if (resp.status === 200 && (!contentLength || +contentLength > length)) {\n      if (controller) controller.abort();\n      throw new Error(\n        \"Server returned no content-length header or content-length exceeding request. Check that your storage backend supports HTTP Byte Serving.\"\n      );\n    }\n\n    const a = await resp.arrayBuffer();\n    return {\n      data: a,\n      etag: newEtag || undefined,\n      cacheControl: resp.headers.get(\"Cache-Control\") || undefined,\n      expires: resp.headers.get(\"Expires\") || undefined,\n    };\n  }\n}\n\n/** @hidden */\nexport function getUint64(v: DataView, offset: number): number {\n  const wh = v.getUint32(offset + 4, true);\n  const wl = v.getUint32(offset + 0, true);\n  return wh * 2 ** 32 + wl;\n}\n\n/**\n * Parse raw header bytes into a Header object.\n */\nexport function bytesToHeader(bytes: ArrayBuffer, etag?: string): Header {\n  const v = new DataView(bytes);\n  const specVersion = v.getUint8(7);\n  if (specVersion > 3) {\n    throw new Error(\n      `Archive is spec version ${specVersion} but this library supports up to spec version 3`\n    );\n  }\n\n  return {\n    specVersion: specVersion,\n    rootDirectoryOffset: getUint64(v, 8),\n    rootDirectoryLength: getUint64(v, 16),\n    jsonMetadataOffset: getUint64(v, 24),\n    jsonMetadataLength: getUint64(v, 32),\n    leafDirectoryOffset: getUint64(v, 40),\n    leafDirectoryLength: getUint64(v, 48),\n    tileDataOffset: getUint64(v, 56),\n    tileDataLength: getUint64(v, 64),\n    numAddressedTiles: getUint64(v, 72),\n    numTileEntries: getUint64(v, 80),\n    numTileContents: getUint64(v, 88),\n    clustered: v.getUint8(96) === 1,\n    internalCompression: v.getUint8(97),\n    tileCompression: v.getUint8(98),\n    tileType: v.getUint8(99),\n    minZoom: v.getUint8(100),\n    maxZoom: v.getUint8(101),\n    minLon: v.getInt32(102, true) / 10000000,\n    minLat: v.getInt32(106, true) / 10000000,\n    maxLon: v.getInt32(110, true) / 10000000,\n    maxLat: v.getInt32(114, true) / 10000000,\n    centerZoom: v.getUint8(118),\n    centerLon: v.getInt32(119, true) / 10000000,\n    centerLat: v.getInt32(123, true) / 10000000,\n    etag: etag,\n  };\n}\n\nfunction deserializeIndex(buffer: ArrayBuffer): Entry[] {\n  const p = { buf: new Uint8Array(buffer), pos: 0 };\n  const numEntries = readVarint(p);\n\n  const entries: Entry[] = [];\n\n  let lastId = 0;\n  for (let i = 0; i < numEntries; i++) {\n    const v = readVarint(p);\n    entries.push({ tileId: lastId + v, offset: 0, length: 0, runLength: 1 });\n    lastId += v;\n  }\n\n  for (let i = 0; i < numEntries; i++) {\n    entries[i].runLength = readVarint(p);\n  }\n\n  for (let i = 0; i < numEntries; i++) {\n    entries[i].length = readVarint(p);\n  }\n\n  for (let i = 0; i < numEntries; i++) {\n    const v = readVarint(p);\n    if (v === 0 && i > 0) {\n      entries[i].offset = entries[i - 1].offset + entries[i - 1].length;\n    } else {\n      entries[i].offset = v - 1;\n    }\n  }\n\n  return entries;\n}\n\nfunction detectVersion(a: ArrayBuffer): number {\n  const v = new DataView(a);\n  if (v.getUint16(2, true) === 2) {\n    console.error(\n      \"PMTiles spec version 2 is not supported; please see github.com/protomaps/PMTiles for tools to upgrade\"\n    );\n    return 2;\n  }\n  if (v.getUint16(2, true) === 1) {\n    console.error(\n      \"PMTiles spec version 1 is not supported; please see github.com/protomaps/PMTiles for tools to upgrade\"\n    );\n    return 1;\n  }\n  return 3;\n}\n\n/**\n * Error thrown when a response for PMTiles over HTTP does not match previous, cached parts of the archive.\n * The default PMTiles implementation will catch this error once internally and retry a request.\n */\nexport class EtagMismatch extends Error {}\n\n/**\n * Interface for caches of parts (headers, directories) of a PMTiles archive.\n */\nexport interface Cache {\n  getHeader: (source: Source) => Promise<Header>;\n  getDirectory: (\n    source: Source,\n    offset: number,\n    length: number,\n    header: Header\n  ) => Promise<Entry[]>;\n  invalidate: (source: Source) => Promise<void>;\n}\n\nasync function getHeaderAndRoot(\n  source: Source,\n  decompress: DecompressFunc\n): Promise<[Header, [string, number, Entry[] | ArrayBuffer]?]> {\n  const resp = await source.getBytes(0, 16384);\n\n  const v = new DataView(resp.data);\n  if (v.getUint16(0, true) !== 0x4d50) {\n    throw new Error(\"Wrong magic number for PMTiles archive\");\n  }\n\n  const headerData = resp.data.slice(0, HEADER_SIZE_BYTES);\n\n  const header = bytesToHeader(headerData, resp.etag);\n\n  // optimistically set the root directory\n  // TODO check root bounds\n  const rootDirData = resp.data.slice(\n    header.rootDirectoryOffset,\n    header.rootDirectoryOffset + header.rootDirectoryLength\n  );\n  const dirKey = `${source.getKey()}|${header.etag || \"\"}|${\n    header.rootDirectoryOffset\n  }|${header.rootDirectoryLength}`;\n\n  const rootDir = deserializeIndex(\n    await decompress(rootDirData, header.internalCompression)\n  );\n  return [header, [dirKey, rootDir.length, rootDir]];\n}\n\nasync function getDirectory(\n  source: Source,\n  decompress: DecompressFunc,\n  offset: number,\n  length: number,\n  header: Header\n): Promise<Entry[]> {\n  const resp = await source.getBytes(offset, length, undefined, header.etag);\n  const data = await decompress(resp.data, header.internalCompression);\n  const directory = deserializeIndex(data);\n  if (directory.length === 0) {\n    throw new Error(\"Empty directory is invalid\");\n  }\n\n  return directory;\n}\n\ninterface ResolvedValue {\n  lastUsed: number;\n  data: Header | Entry[] | ArrayBuffer;\n}\n\n/**\n * A cache for parts of a PMTiles archive where promises are never shared between requests.\n *\n * Runtimes such as Cloudflare Workers cannot share promises between different requests.\n *\n * Only caches headers and directories, not individual tile contents.\n */\nexport class ResolvedValueCache {\n  cache: Map<string, ResolvedValue>;\n  maxCacheEntries: number;\n  counter: number;\n  decompress: DecompressFunc;\n\n  constructor(\n    maxCacheEntries = 100,\n    prefetch = true, // deprecated\n    decompress: DecompressFunc = defaultDecompress\n  ) {\n    this.cache = new Map<string, ResolvedValue>();\n    this.maxCacheEntries = maxCacheEntries;\n    this.counter = 1;\n    this.decompress = decompress;\n  }\n\n  async getHeader(source: Source): Promise<Header> {\n    const cacheKey = source.getKey();\n    const cacheValue = this.cache.get(cacheKey);\n    if (cacheValue) {\n      cacheValue.lastUsed = this.counter++;\n      const data = cacheValue.data;\n      return data as Header;\n    }\n\n    const res = await getHeaderAndRoot(source, this.decompress);\n    if (res[1]) {\n      this.cache.set(res[1][0], {\n        lastUsed: this.counter++,\n        data: res[1][2],\n      });\n    }\n\n    this.cache.set(cacheKey, {\n      lastUsed: this.counter++,\n      data: res[0],\n    });\n    this.prune();\n    return res[0];\n  }\n\n  async getDirectory(\n    source: Source,\n    offset: number,\n    length: number,\n    header: Header\n  ): Promise<Entry[]> {\n    const cacheKey = `${source.getKey()}|${\n      header.etag || \"\"\n    }|${offset}|${length}`;\n    const cacheValue = this.cache.get(cacheKey);\n    if (cacheValue) {\n      cacheValue.lastUsed = this.counter++;\n      const data = cacheValue.data;\n      return data as Entry[];\n    }\n\n    const directory = await getDirectory(\n      source,\n      this.decompress,\n      offset,\n      length,\n      header\n    );\n    this.cache.set(cacheKey, {\n      lastUsed: this.counter++,\n      data: directory,\n    });\n    this.prune();\n    return directory;\n  }\n\n  prune() {\n    if (this.cache.size > this.maxCacheEntries) {\n      let minUsed = Infinity;\n      let minKey = undefined;\n      this.cache.forEach((cacheValue: ResolvedValue, key: string) => {\n        if (cacheValue.lastUsed < minUsed) {\n          minUsed = cacheValue.lastUsed;\n          minKey = key;\n        }\n      });\n      if (minKey) {\n        this.cache.delete(minKey);\n      }\n    }\n  }\n\n  async invalidate(source: Source) {\n    this.cache.delete(source.getKey());\n  }\n}\n\ninterface SharedPromiseCacheValue {\n  lastUsed: number;\n  data: Promise<Header | Entry[] | ArrayBuffer>;\n}\n\n/**\n * A cache for parts of a PMTiles archive where promises can be shared between requests.\n *\n * Only caches headers and directories, not individual tile contents.\n */\nexport class SharedPromiseCache {\n  cache: Map<string, SharedPromiseCacheValue>;\n  invalidations: Map<string, Promise<void>>;\n  maxCacheEntries: number;\n  counter: number;\n  decompress: DecompressFunc;\n\n  constructor(\n    maxCacheEntries = 100,\n    prefetch = true, // deprecated\n    decompress: DecompressFunc = defaultDecompress\n  ) {\n    this.cache = new Map<string, SharedPromiseCacheValue>();\n    this.invalidations = new Map<string, Promise<void>>();\n    this.maxCacheEntries = maxCacheEntries;\n    this.counter = 1;\n    this.decompress = decompress;\n  }\n\n  async getHeader(source: Source): Promise<Header> {\n    const cacheKey = source.getKey();\n    const cacheValue = this.cache.get(cacheKey);\n    if (cacheValue) {\n      cacheValue.lastUsed = this.counter++;\n      const data = await cacheValue.data;\n      return data as Header;\n    }\n\n    const p = new Promise<Header>((resolve, reject) => {\n      getHeaderAndRoot(source, this.decompress)\n        .then((res) => {\n          if (res[1]) {\n            this.cache.set(res[1][0], {\n              lastUsed: this.counter++,\n              data: Promise.resolve(res[1][2]),\n            });\n          }\n          resolve(res[0]);\n          this.prune();\n        })\n        .catch((e) => {\n          reject(e);\n        });\n    });\n    this.cache.set(cacheKey, { lastUsed: this.counter++, data: p });\n    return p;\n  }\n\n  async getDirectory(\n    source: Source,\n    offset: number,\n    length: number,\n    header: Header\n  ): Promise<Entry[]> {\n    const cacheKey = `${source.getKey()}|${\n      header.etag || \"\"\n    }|${offset}|${length}`;\n    const cacheValue = this.cache.get(cacheKey);\n    if (cacheValue) {\n      cacheValue.lastUsed = this.counter++;\n      const data = await cacheValue.data;\n      return data as Entry[];\n    }\n\n    const p = new Promise<Entry[]>((resolve, reject) => {\n      getDirectory(source, this.decompress, offset, length, header)\n        .then((directory) => {\n          resolve(directory);\n          this.prune();\n        })\n        .catch((e) => {\n          reject(e);\n        });\n    });\n    this.cache.set(cacheKey, { lastUsed: this.counter++, data: p });\n    return p;\n  }\n\n  prune() {\n    if (this.cache.size >= this.maxCacheEntries) {\n      let minUsed = Infinity;\n      let minKey = undefined;\n      this.cache.forEach((cacheValue: SharedPromiseCacheValue, key: string) => {\n        if (cacheValue.lastUsed < minUsed) {\n          minUsed = cacheValue.lastUsed;\n          minKey = key;\n        }\n      });\n      if (minKey) {\n        this.cache.delete(minKey);\n      }\n    }\n  }\n\n  async invalidate(source: Source) {\n    const key = source.getKey();\n    if (this.invalidations.get(key)) {\n      return await this.invalidations.get(key);\n    }\n    this.cache.delete(source.getKey());\n    const p = new Promise<void>((resolve, reject) => {\n      this.getHeader(source)\n        .then((h) => {\n          resolve();\n          this.invalidations.delete(key);\n        })\n        .catch((e) => {\n          reject(e);\n        });\n    });\n    this.invalidations.set(key, p);\n  }\n}\n\n/**\n * Main class encapsulating PMTiles decoding logic.\n *\n * if `source` is a string, creates a FetchSource using that string as the URL to a remote PMTiles.\n * if no `cache` is passed, use a SharedPromiseCache.\n * if no `decompress` is passed, default to the browser DecompressionStream API with a fallback to `fflate`.\n */\n// biome-ignore lint: that's just how its capitalized\nexport class PMTiles {\n  source: Source;\n  cache: Cache;\n  decompress: DecompressFunc;\n\n  constructor(\n    source: Source | string,\n    customHeaders: Headers,\n    cache?: Cache,\n    decompress?: DecompressFunc\n  ) {\n    if (typeof source === \"string\") {\n      this.source = new FetchSource(source, customHeaders);\n    } else {\n      this.source = source;\n    }\n    if (decompress) {\n      this.decompress = decompress;\n    } else {\n      this.decompress = defaultDecompress;\n    }\n    if (cache) {\n      this.cache = cache;\n    } else {\n      this.cache = new SharedPromiseCache();\n    }\n  }\n\n  /**\n   * Return the header of the archive,\n   * including information such as tile type, min/max zoom, bounds, and summary statistics.\n   */\n  async getHeader() {\n    return await this.cache.getHeader(this.source);\n  }\n\n  /** @hidden */\n  async getZxyAttempt(\n    z: number,\n    x: number,\n    y: number,\n    signal?: AbortSignal\n  ): Promise<RangeResponse | undefined> {\n    const tileId = zxyToTileId(z, x, y);\n    const header = await this.cache.getHeader(this.source);\n\n    if (z < header.minZoom || z > header.maxZoom) {\n      return undefined;\n    }\n\n    let dO = header.rootDirectoryOffset;\n    let dL = header.rootDirectoryLength;\n    for (let depth = 0; depth <= 3; depth++) {\n      const directory = await this.cache.getDirectory(\n        this.source,\n        dO,\n        dL,\n        header\n      );\n      const entry = findTile(directory, tileId);\n      if (entry) {\n        if (entry.runLength > 0) {\n          const resp = await this.source.getBytes(\n            header.tileDataOffset + entry.offset,\n            entry.length,\n            signal,\n            header.etag\n          );\n          return {\n            data: await this.decompress(resp.data, header.tileCompression),\n            cacheControl: resp.cacheControl,\n            expires: resp.expires,\n          };\n        }\n        dO = header.leafDirectoryOffset + entry.offset;\n        dL = entry.length;\n      } else {\n        // TODO: We should in fact return a valid RangeResponse\n        // with empty data, but filled in cache control / expires headers\n        return undefined;\n      }\n    }\n    throw new Error(\"Maximum directory depth exceeded\");\n  }\n\n  /**\n   * Primary method to get a single tile's bytes from an archive.\n   *\n   * Returns undefined if the tile does not exist in the archive.\n   */\n  async getZxy(\n    z: number,\n    x: number,\n    y: number,\n    signal?: AbortSignal\n  ): Promise<RangeResponse | undefined> {\n    try {\n      return await this.getZxyAttempt(z, x, y, signal);\n    } catch (e) {\n      if (e instanceof EtagMismatch) {\n        this.cache.invalidate(this.source);\n        return await this.getZxyAttempt(z, x, y, signal);\n      }\n      throw e;\n    }\n  }\n\n  /** @hidden */\n  async getMetadataAttempt(): Promise<unknown> {\n    const header = await this.cache.getHeader(this.source);\n\n    const resp = await this.source.getBytes(\n      header.jsonMetadataOffset,\n      header.jsonMetadataLength,\n      undefined,\n      header.etag\n    );\n    const decompressed = await this.decompress(\n      resp.data,\n      header.internalCompression\n    );\n    const dec = new TextDecoder(\"utf-8\");\n    return JSON.parse(dec.decode(decompressed));\n  }\n\n  /**\n   * Return the arbitrary JSON metadata of the archive.\n   */\n  async getMetadata(): Promise<unknown> {\n    try {\n      return await this.getMetadataAttempt();\n    } catch (e) {\n      if (e instanceof EtagMismatch) {\n        this.cache.invalidate(this.source);\n        return await this.getMetadataAttempt();\n      }\n      throw e;\n    }\n  }\n\n  /**\n   * Construct a [TileJSON](https://github.com/mapbox/tilejson-spec) object.\n   *\n   * baseTilesUrl is the desired tiles URL, excluding the suffix `/{z}/{x}/{y}.{ext}`.\n   * For example, if the desired URL is `http://example.com/tileset/{z}/{x}/{y}.mvt`,\n   * the baseTilesUrl should be `https://example.com/tileset`.\n   */\n  async getTileJson(baseTilesUrl: string): Promise<unknown> {\n    const header = await this.getHeader();\n    const metadata = (await this.getMetadata()) as MetadataLike;\n    const ext = tileTypeExt(header.tileType);\n\n    return {\n      tilejson: \"3.0.0\",\n      scheme: \"xyz\",\n      tiles: [`${baseTilesUrl}/{z}/{x}/{y}${ext}`],\n      // biome-ignore lint: TileJSON spec\n      vector_layers: metadata.vector_layers,\n      attribution: metadata.attribution,\n      description: metadata.description,\n      name: metadata.name,\n      version: metadata.version,\n      bounds: [header.minLon, header.minLat, header.maxLon, header.maxLat],\n      center: [header.centerLon, header.centerLat, header.centerZoom],\n      minzoom: header.minZoom,\n      maxzoom: header.maxZoom,\n    };\n  }\n}\n","// biome-ignore lint: needed for Leaflet + IIFE to work\ndeclare const L: any;\n// biome-ignore lint: needed for window.URL to disambiguate from cloudflare workers\ndeclare const window: any;\ndeclare const document: DocumentLike;\n\nimport type { Coords } from \"leaflet\";\nimport { PMTiles, TileType } from \"./index\";\n\ninterface DocumentLike {\n  // biome-ignore lint: we don't want to bring in the entire document type\n  createElement: (s: string) => any;\n}\n\n// biome-ignore lint: we don't want to bring in the entire document type\ntype DoneCallback = (error?: Error, tile?: any) => void;\n\n/**\n * Add a raster PMTiles as a layer to a Leaflet map.\n *\n * For vector tiles see https://github.com/protomaps/protomaps-leaflet\n */\nexport const leafletRasterLayer = (source: PMTiles, options: unknown) => {\n  let loaded = false;\n  let mimeType = \"\";\n  const cls = L.GridLayer.extend({\n    createTile: (coord: Coords, done: DoneCallback) => {\n      const el = document.createElement(\"img\");\n      const controller = new AbortController();\n      const signal = controller.signal;\n      el.cancel = () => {\n        controller.abort();\n      };\n      if (!loaded) {\n        source.getHeader().then((header) => {\n          if (header.tileType === TileType.Mvt) {\n            console.error(\n              \"Error: archive contains MVT vector tiles, but leafletRasterLayer is for displaying raster tiles. See https://github.com/protomaps/PMTiles/tree/main/js for details.\"\n            );\n          } else if (header.tileType === 2) {\n            mimeType = \"image/png\";\n          } else if (header.tileType === 3) {\n            mimeType = \"image/jpeg\";\n          } else if (header.tileType === 4) {\n            mimeType = \"image/webp\";\n          } else if (header.tileType === 5) {\n            mimeType = \"image/avif\";\n          }\n        });\n        loaded = true;\n      }\n      source\n        .getZxy(coord.z, coord.x, coord.y, signal)\n        .then((arr) => {\n          if (arr) {\n            const blob = new Blob([arr.data], { type: mimeType });\n            const imageUrl = window.URL.createObjectURL(blob);\n            el.src = imageUrl;\n            el.cancel = undefined;\n            done(undefined, el);\n          }\n        })\n        .catch((e) => {\n          if (e.name !== \"AbortError\") {\n            throw e;\n          }\n        });\n      return el;\n    },\n\n    _removeTile: function (key: string) {\n      const tile = this._tiles[key];\n      if (!tile) {\n        return;\n      }\n\n      if (tile.el.cancel) tile.el.cancel();\n\n      tile.el.width = 0;\n      tile.el.height = 0;\n      tile.el.deleted = true;\n      L.DomUtil.remove(tile.el);\n      delete this._tiles[key];\n      this.fire(\"tileunload\", {\n        tile: tile.el,\n        coords: this._keyToTileCoords(key),\n      });\n    },\n  });\n  return new cls(options);\n};\n\nconst isDeepEqual = (object1: any, object2: any) => {\n  const objKeys1 = Object.keys(object1);\n  const objKeys2 = Object.keys(object2);\n  if (objKeys1.length !== objKeys2.length)\n    return false;\n  for (var key of objKeys1) {\n    const value1 = object1[key];\n    const value2 = object2[key];\n    const isObjects = isObject(value1) && isObject(value2);\n    if (isObjects && !isDeepEqual(value1, value2) || !isObjects && value1 !== value2) {\n      return false;\n    }\n  }\n  return true;\n};\n\nconst isObject = (object: any) => {\n  return object != null && typeof object === \"object\";\n};\n\ntype GetResourceResponse<T> = ExpiryData & {\n  data: T;\n};\ntype AddProtocolAction = (\n  requestParameters: RequestParameters,\n  abortController: AbortController\n) => Promise<GetResourceResponse<unknown>>;\n\ntype ExpiryData = {\n  cacheControl?: string | null;\n  expires?: string | null; // MapLibre can be a Date object\n};\n\n// copied from MapLibre /util/ajax.ts\ntype RequestParameters = {\n  url: string;\n  headers?: unknown;\n  method?: \"GET\" | \"POST\" | \"PUT\";\n  body?: string;\n  type?: \"string\" | \"json\" | \"arrayBuffer\" | \"image\";\n  credentials?: \"same-origin\" | \"include\";\n  collectResourceTiming?: boolean;\n};\n\n// for legacy maplibre-3 interop\ntype ResponseCallbackV3 = (\n  error?: Error | undefined,\n  data?: unknown | undefined,\n  cacheControl?: string | undefined,\n  expires?: string | undefined\n) => void;\n\ntype V3OrV4Protocol = <\n  T extends AbortController | ResponseCallbackV3,\n  R = T extends AbortController\n    ? Promise<GetResourceResponse<unknown>>\n    : { cancel: () => void },\n>(\n  requestParameters: RequestParameters,\n  arg2: T\n) => R;\n\nconst v3compat =\n  (v4: AddProtocolAction): V3OrV4Protocol =>\n  (requestParameters, arg2) => {\n    if (arg2 instanceof AbortController) {\n      // biome-ignore lint: overloading return type not handled by compiler\n      return v4(requestParameters, arg2) as any;\n    }\n    const abortController = new AbortController();\n    v4(requestParameters, abortController)\n      .then(\n        (result) => {\n          return arg2(\n            undefined,\n            result.data,\n            result.cacheControl || \"\",\n            result.expires || \"\"\n          );\n        },\n        (err) => {\n          return arg2(err);\n        }\n      )\n      .catch((e) => {\n        return arg2(e);\n      });\n    return { cancel: () => abortController.abort() };\n  };\n\n/**\n * MapLibre GL JS protocol. Must be added once globally.\n */\nexport class Protocol {\n  /** @hidden */\n  tiles: Map<string, PMTiles>;\n  metadata: boolean;\n  errorOnMissingTile: boolean;\n\n  /**\n   * Initialize the MapLibre PMTiles protocol.\n   *\n   * * metadata: also load the metadata section of the PMTiles. required for some \"inspect\" functionality\n   * and to automatically populate the map attribution. Requires an extra HTTP request.\n   * * errorOnMissingTile: When a vector MVT tile is missing from the archive, raise an error instead of\n   * returning the empty array. Not recommended. This is only to reproduce the behavior of ZXY tile APIs\n   * which some applications depend on when overzooming.\n   */\n  constructor(options?: { metadata?: boolean; errorOnMissingTile?: boolean }) {\n    this.tiles = new Map<string, PMTiles>();\n    this.metadata = options?.metadata || false;\n    this.errorOnMissingTile = options?.errorOnMissingTile || false;\n  }\n\n  /**\n   * Add a {@link PMTiles} instance to the global protocol instance.\n   *\n   * For remote fetch sources, references in MapLibre styles like pmtiles://http://...\n   * will resolve to the same instance if the URLs match.\n   */\n  add(p: PMTiles) {\n    this.tiles.set(p.source.getKey(), p);\n  }\n\n  /**\n   * Fetch a {@link PMTiles} instance by URL, for remote PMTiles instances.\n   */\n  get(url: string) {\n    return this.tiles.get(url);\n  }\n\n  /** @hidden */\n  tilev4 = async (\n    params: RequestParameters,\n    abortController: AbortController\n  ) => {\n    if (params.type === \"json\") {\n      const pmtilesUrl = params.url.substr(10);\n      let instance = this.tiles.get(pmtilesUrl);\n      if (!instance || !isDeepEqual((instance.source as any).customHeaders, params.headers)) {\n        instance = new PMTiles(pmtilesUrl, params.headers as Headers);\n        this.tiles.set(pmtilesUrl, instance);\n      }\n\n      if (this.metadata) {\n        return {\n          data: await instance.getTileJson(params.url),\n        };\n      }\n\n      const h = await instance.getHeader();\n\n      if (h.minLon >= h.maxLon || h.minLat >= h.maxLat) {\n        console.error(\n          `Bounds of PMTiles archive ${h.minLon},${h.minLat},${h.maxLon},${h.maxLat} are not valid.`\n        );\n      }\n\n      return {\n        data: {\n          tiles: [`${params.url}/{z}/{x}/{y}`],\n          minzoom: h.minZoom,\n          maxzoom: h.maxZoom,\n          bounds: [h.minLon, h.minLat, h.maxLon, h.maxLat],\n        },\n      };\n    }\n    const re = new RegExp(/pmtiles:\\/\\/(.+)\\/(\\d+)\\/(\\d+)\\/(\\d+)/);\n    const result = params.url.match(re);\n    if (!result) {\n      throw new Error(\"Invalid PMTiles protocol URL\");\n    }\n    const pmtilesUrl = result[1];\n\n    let instance = this.tiles.get(pmtilesUrl);\n    if (!instance || !isDeepEqual((instance.source as any).customHeaders, params.headers)) {\n      instance = new PMTiles(pmtilesUrl, params.headers as Headers);\n      this.tiles.set(pmtilesUrl, instance);\n    }\n    const z = result[2];\n    const x = result[3];\n    const y = result[4];\n\n    const header = await instance.getHeader();\n    const resp = await instance?.getZxy(+z, +x, +y, abortController.signal);\n    if (resp) {\n      return {\n        data: new Uint8Array(resp.data),\n        cacheControl: resp.cacheControl,\n        expires: resp.expires,\n      };\n    }\n    if (header.tileType === TileType.Mvt) {\n      if (this.errorOnMissingTile) {\n        throw new Error(\"Tile not found.\");\n      }\n      return { data: new Uint8Array() };\n    }\n    return { data: null };\n  };\n\n  tile = v3compat(this.tilev4);\n}\n"],"mappings":"2SAAA,OAAS,kBAAAA,MAAsB,SCsBxB,IAAMC,GAAqBC,EAAA,CAACC,EAAiBC,IAAqB,CACvE,IAAIC,EAAS,GACTC,EAAW,GACTC,EAAM,EAAE,UAAU,OAAO,CAC7B,WAAYL,EAAA,CAACM,EAAeC,IAAuB,CACjD,IAAMC,EAAK,SAAS,cAAc,KAAK,EACjCC,EAAa,IAAI,gBACjBC,EAASD,EAAW,OAC1B,OAAAD,EAAG,OAAS,IAAM,CAChBC,EAAW,MAAM,CACnB,EACKN,IACHF,EAAO,UAAU,EAAE,KAAMU,GAAW,CAC9BA,EAAO,WAAa,EACtB,QAAQ,MACN,qKACF,EACSA,EAAO,WAAa,EAC7BP,EAAW,YACFO,EAAO,WAAa,EAC7BP,EAAW,aACFO,EAAO,WAAa,EAC7BP,EAAW,aACFO,EAAO,WAAa,IAC7BP,EAAW,aAEf,CAAC,EACDD,EAAS,IAEXF,EACG,OAAOK,EAAM,EAAGA,EAAM,EAAGA,EAAM,EAAGI,CAAM,EACxC,KAAME,GAAQ,CACb,GAAIA,EAAK,CACP,IAAMC,EAAO,IAAI,KAAK,CAACD,EAAI,IAAI,EAAG,CAAE,KAAMR,CAAS,CAAC,EAC9CU,EAAW,OAAO,IAAI,gBAAgBD,CAAI,EAChDL,EAAG,IAAMM,EACTN,EAAG,OAAS,OACZD,EAAK,OAAWC,CAAE,CACpB,CACF,CAAC,EACA,MAAOO,GAAM,CACZ,GAAIA,EAAE,OAAS,aACb,MAAMA,CAEV,CAAC,EACIP,CACT,EA1CY,cA4CZ,Y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MAAM,KAAK,YAAY,EACnCC,EAAMC,EAAYjD,EAAO,QAAQ,EAEvC,MAAO,CACL,SAAU,QACV,OAAQ,MACR,MAAO,CAAC,GAAG8C,CAAY,eAAeE,CAAG,EAAE,EAE3C,cAAeD,EAAS,cACxB,YAAaA,EAAS,YACtB,YAAaA,EAAS,YACtB,KAAMA,EAAS,KACf,QAASA,EAAS,QAClB,OAAQ,CAAC/C,EAAO,OAAQA,EAAO,OAAQA,EAAO,OAAQA,EAAO,MAAM,EACnE,OAAQ,CAACA,EAAO,UAAWA,EAAO,UAAWA,EAAO,UAAU,EAC9D,QAASA,EAAO,QAChB,QAASA,EAAO,OAClB,CACF,GACF,EAxKqBT,EAAAsC,EAAA,WAAd,IAAMqB,EAANrB","names":["decompressSync","leafletRasterLayer","__name","source","options","loaded","mimeType","cls","coord","done","el","controller","signal","header","arr","blob","imageUrl","e","key","tile","isDeepEqual","object1","object2","objKeys1","objKeys2","value1","value2","isObjects","isObject","object","v3compat","v4","requestParameters","arg2","abortController","result","err","_Protocol","params","__async","pmtilesUrl","instance","PMTiles","h","re","z","x","y","resp","p","url","Protocol","toNum","low","high","__name","readVarintRemainder","l","p","buf","b","h","readVarint","val","rotate","n","x","y","rx","ry","zxyToTileId","z","acc","a","tx","ty","s","tileIdToZ","i","c","tileIdToZxy","t","Compression","defaultDecompress","compression","__async","decompressSync","stream","result","TileType","tileTypeExt","HEADER_SIZE_BYTES","findTile","entries","tileId","m","k","cmp","_FileSource","file","offset","length","FileSource","_FetchSource","url","customHeaders","userAgent","isWindows","isChromiumBased","passedSignal","etag","controller","signal","requestHeaders","cache","resp","contentRange","actualLength","newEtag","EtagMismatch","contentLength","FetchSource","getUint64","v","wh","wl","__pow","bytesToHeader","bytes","specVersion","deserializeIndex","buffer","numEntries","lastId","_EtagMismatch","__name","EtagMismatch","getHeaderAndRoot","source","decompress","__async","resp","headerData","HEADER_SIZE_BYTES","header","bytesToHeader","rootDirData","dirKey","rootDir","deserializeIndex","getDirectory","offset","length","data","directory","_ResolvedValueCache","maxCacheEntries","prefetch","defaultDecompress","cacheKey","cacheValue","res","minUsed","minKey","key","ResolvedValueCache","_SharedPromiseCache","p","resolve","reject","e","h","SharedPromiseCache","_PMTiles","customHeaders","cache","FetchSource","z","x","y","signal","tileId","zxyToTileId","dO","dL","depth","entry","findTile","decompressed","dec","baseTilesUrl","metadata","ext","tileTypeExt","PMTiles"]}
\ No newline at end of file
diff --git a/node_modules/pmtiles/dist/pmtiles.js b/node_modules/pmtiles/dist/pmtiles.js
index 1a901ee..fd38ba1 100644
--- a/node_modules/pmtiles/dist/pmtiles.js
+++ b/node_modules/pmtiles/dist/pmtiles.js
@@ -1,2 +1,2 @@
-"use strict";var pmtiles=(()=>{var k=Object.defineProperty;var Je=Object.getOwnPropertyDescriptor;var Ye=Object.getOwnPropertyNames;var Qe=Object.prototype.hasOwnProperty;var U=Math.pow;var f=(r,e)=>k(r,"name",{value:e,configurable:!0});var Xe=(r,e)=>{for(var t in e)k(r,t,{get:e[t],enumerable:!0})},_e=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ye(e))!Qe.call(r,i)&&i!==t&&k(r,i,{get:()=>e[i],enumerable:!(n=Je(e,i))||n.enumerable});return r};var et=r=>_e(k({},"__esModule",{value:!0}),r);var m=(r,e,t)=>new Promise((n,i)=>{var a=h=>{try{u(t.next(h))}catch(l){i(l)}},s=h=>{try{u(t.throw(h))}catch(l){i(l)}},u=h=>h.done?n(h.value):Promise.resolve(h.value).then(a,s);u((t=t.apply(r,e)).next())});var Dt={};Xe(Dt,{Compression:()=>Oe,EtagMismatch:()=>B,FetchSource:()=>K,FileSource:()=>oe,PMTiles:()=>P,Protocol:()=>ie,ResolvedValueCache:()=>ue,SharedPromiseCache:()=>G,TileType:()=>se,bytesToHeader:()=>$e,findTile:()=>Fe,getUint64:()=>b,leafletRasterLayer:()=>wt,readVarint:()=>R,tileIdToZxy:()=>Tt,tileTypeExt:()=>Ze,zxyToTileId:()=>Ie});var w=Uint8Array,E=Uint16Array,tt=Int32Array,Me=new w([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Ue=new w([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),rt=new w([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ee=f(function(r,e){for(var t=new E(31),n=0;n<31;++n)t[n]=e+=1<<r[n-1];for(var i=new tt(t[30]),n=1;n<30;++n)for(var a=t[n];a<t[n+1];++a)i[a]=a-t[n]<<5|n;return{b:t,r:i}},"freb"),Le=Ee(Me,2),Pe=Le.b,nt=Le.r;Pe[28]=258,nt[258]=28;var Se=Ee(Ue,0),it=Se.b,Ut=Se.r,re=new E(32768);for(g=0;g<32768;++g)T=(g&43690)>>1|(g&21845)<<1,T=(T&52428)>>2|(T&13107)<<2,T=(T&61680)>>4|(T&3855)<<4,re[g]=((T&65280)>>8|(T&255)<<8)>>1;var T,g,F=f(function(r,e,t){for(var n=r.length,i=0,a=new E(e);i<n;++i)r[i]&&++a[r[i]-1];var s=new E(e);for(i=1;i<e;++i)s[i]=s[i-1]+a[i-1]<<1;var u;if(t){u=new E(1<<e);var h=15-e;for(i=0;i<n;++i)if(r[i])for(var l=i<<4|r[i],c=e-r[i],o=s[r[i]-1]++<<c,v=o|(1<<c)-1;o<=v;++o)u[re[o]>>h]=l}else for(u=new E(n),i=0;i<n;++i)r[i]&&(u[i]=re[s[r[i]-1]++]>>15-r[i]);return u},"hMap"),$=new w(288);for(g=0;g<144;++g)$[g]=8;var g;for(g=144;g<256;++g)$[g]=9;var g;for(g=256;g<280;++g)$[g]=7;var g;for(g=280;g<288;++g)$[g]=8;var g,Re=new w(32);for(g=0;g<32;++g)Re[g]=5;var g;var at=F($,9,1);var st=F(Re,5,1),ee=f(function(r){for(var e=r[0],t=1;t<r.length;++t)r[t]>e&&(e=r[t]);return e},"max"),z=f(function(r,e,t){var n=e/8|0;return(r[n]|r[n+1]<<8)>>(e&7)&t},"bits"),te=f(function(r,e){var t=e/8|0;return(r[t]|r[t+1]<<8|r[t+2]<<16)>>(e&7)},"bits16"),ot=f(function(r){return(r+7)/8|0},"shft"),ut=f(function(r,e,t){return(e==null||e<0)&&(e=0),(t==null||t>r.length)&&(t=r.length),new w(r.subarray(e,t))},"slc");var ft=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],y=f(function(r,e,t){var n=new Error(e||ft[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,y),!t)throw n;return n},"err"),ne=f(function(r,e,t,n){var i=r.length,a=n?n.length:0;if(!i||e.f&&!e.l)return t||new w(0);var s=!t,u=s||e.i!=2,h=e.i;s&&(t=new w(i*3));var l=f(function(Te){var Ce=t.length;if(Te>Ce){var De=new w(Math.max(Ce*2,Te));De.set(t),t=De}},"cbuf"),c=e.f||0,o=e.p||0,v=e.b||0,d=e.l,p=e.d,H=e.m,I=e.n,q=i*8;do{if(!d){c=z(r,o,1);var j=z(r,o+1,3);if(o+=3,j)if(j==1)d=at,p=st,H=9,I=5;else if(j==2){var J=z(r,o,31)+257,me=z(r,o+10,15)+4,de=J+z(r,o+5,31)+1;o+=14;for(var O=new w(de),Y=new w(19),x=0;x<me;++x)Y[rt[x]]=z(r,o+x*3,7);o+=me*3;for(var ye=ee(Y),Ge=(1<<ye)-1,qe=F(Y,ye,1),x=0;x<de;){var we=qe[z(r,o,Ge)];o+=we&15;var A=we>>4;if(A<16)O[x++]=A;else{var D=0,V=0;for(A==16?(V=3+z(r,o,3),o+=2,D=O[x-1]):A==17?(V=3+z(r,o,7),o+=3):A==18&&(V=11+z(r,o,127),o+=7);V--;)O[x++]=D}}var xe=O.subarray(0,J),C=O.subarray(J);H=ee(xe),I=ee(C),d=F(xe,H,1),p=F(C,I,1)}else y(1);else{var A=ot(o)+4,W=r[A-4]|r[A-3]<<8,N=A+W;if(N>i){h&&y(0);break}u&&l(v+W),t.set(r.subarray(A,N),v),e.b=v+=W,e.p=o=N*8,e.f=c;continue}if(o>q){h&&y(0);break}}u&&l(v+131072);for(var je=(1<<H)-1,We=(1<<I)-1,Q=o;;Q=o){var D=d[te(r,o)&je],M=D>>4;if(o+=D&15,o>q){h&&y(0);break}if(D||y(2),M<256)t[v++]=M;else if(M==256){Q=o,d=null;break}else{var be=M-254;if(M>264){var x=M-257,Z=Me[x];be=z(r,o,(1<<Z)-1)+Pe[x],o+=Z}var X=p[te(r,o)&We],_=X>>4;X||y(3),o+=X&15;var C=it[_];if(_>3){var Z=Ue[_];C+=te(r,o)&(1<<Z)-1,o+=Z}if(o>q){h&&y(0);break}u&&l(v+131072);var ze=v+be;if(v<C){var Ae=a-C,Ne=Math.min(C,ze);for(Ae+v<0&&y(3);v<Ne;++v)t[v]=n[Ae+v]}for(;v<ze;++v)t[v]=t[v-C]}}e.l=d,e.p=Q,e.b=v,e.f=c,d&&(c=1,e.m=H,e.d=p,e.n=I)}while(!c);return v!=t.length&&s?ut(t,0,v):t.subarray(0,v)},"inflt");var lt=new w(0);var ht=f(function(r){(r[0]!=31||r[1]!=139||r[2]!=8)&&y(6,"invalid gzip data");var e=r[3],t=10;e&4&&(t+=(r[10]|r[11]<<8)+2);for(var n=(e>>3&1)+(e>>4&1);n>0;n-=!r[t++]);return t+(e&2)},"gzs"),ct=f(function(r){var e=r.length;return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0},"gzl");var vt=f(function(r,e){return((r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31)&&y(6,"invalid zlib data"),(r[1]>>5&1)==+!e&&y(6,"invalid zlib data: "+(r[1]&32?"need":"unexpected")+" dictionary"),(r[1]>>3&4)+2},"zls");function gt(r,e){return ne(r,{i:2},e&&e.out,e&&e.dictionary)}f(gt,"inflateSync");function pt(r,e){var t=ht(r);return t+8>r.length&&y(6,"invalid gzip data"),ne(r.subarray(t,-8),{i:2},e&&e.out||new w(ct(r)),e&&e.dictionary)}f(pt,"gunzipSync");function mt(r,e){return ne(r.subarray(vt(r,e&&e.dictionary),-4),{i:2},e&&e.out,e&&e.dictionary)}f(mt,"unzlibSync");function Be(r,e){return r[0]==31&&r[1]==139&&r[2]==8?pt(r,e):(r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31?gt(r,e):mt(r,e)}f(Be,"decompressSync");var dt=typeof TextDecoder!="undefined"&&new TextDecoder,yt=0;try{dt.decode(lt,{stream:!0}),yt=1}catch(r){}var wt=f((r,e)=>{let t=!1,n="",i=L.GridLayer.extend({createTile:f((a,s)=>{let u=document.createElement("img"),h=new AbortController,l=h.signal;return u.cancel=()=>{h.abort()},t||(r.getHeader().then(c=>{c.tileType===1?console.error("Error: archive contains MVT vector tiles, but leafletRasterLayer is for displaying raster tiles. See https://github.com/protomaps/PMTiles/tree/main/js for details."):c.tileType===2?n="image/png":c.tileType===3?n="image/jpeg":c.tileType===4?n="image/webp":c.tileType===5&&(n="image/avif")}),t=!0),r.getZxy(a.z,a.x,a.y,l).then(c=>{if(c){let o=new Blob([c.data],{type:n}),v=window.URL.createObjectURL(o);u.src=v,u.cancel=void 0,s(void 0,u)}}).catch(c=>{if(c.name!=="AbortError")throw c}),u},"createTile"),_removeTile:f(function(a){let s=this._tiles[a];s&&(s.el.cancel&&s.el.cancel(),s.el.width=0,s.el.height=0,s.el.deleted=!0,L.DomUtil.remove(s.el),delete this._tiles[a],this.fire("tileunload",{tile:s.el,coords:this._keyToTileCoords(a)}))},"_removeTile")});return new i(e)},"leafletRasterLayer"),xt=f(r=>(e,t)=>{if(t instanceof AbortController)return r(e,t);let n=new AbortController;return r(e,n).then(i=>t(void 0,i.data,i.cacheControl||"",i.expires||""),i=>t(i)).catch(i=>t(i)),{cancel:f(()=>n.abort(),"cancel")}},"v3compat"),ae=class ae{constructor(e){this.tilev4=f((e,t)=>m(this,null,function*(){if(e.type==="json"){let v=e.url.substr(10),d=this.tiles.get(v);if(d||(d=new P(v),this.tiles.set(v,d)),this.metadata)return{data:yield d.getTileJson(e.url)};let p=yield d.getHeader();return(p.minLon>=p.maxLon||p.minLat>=p.maxLat)&&console.error(`Bounds of PMTiles archive ${p.minLon},${p.minLat},${p.maxLon},${p.maxLat} are not valid.`),{data:{tiles:[`${e.url}/{z}/{x}/{y}`],minzoom:p.minZoom,maxzoom:p.maxZoom,bounds:[p.minLon,p.minLat,p.maxLon,p.maxLat]}}}let n=new RegExp(/pmtiles:\/\/(.+)\/(\d+)\/(\d+)\/(\d+)/),i=e.url.match(n);if(!i)throw new Error("Invalid PMTiles protocol URL");let a=i[1],s=this.tiles.get(a);s||(s=new P(a),this.tiles.set(a,s));let u=i[2],h=i[3],l=i[4],c=yield s.getHeader(),o=yield s==null?void 0:s.getZxy(+u,+h,+l,t.signal);if(o)return{data:new Uint8Array(o.data),cacheControl:o.cacheControl,expires:o.expires};if(c.tileType===1){if(this.errorOnMissingTile)throw new Error("Tile not found.");return{data:new Uint8Array}}return{data:null}}),"tilev4");this.tile=xt(this.tilev4);this.tiles=new Map,this.metadata=(e==null?void 0:e.metadata)||!1,this.errorOnMissingTile=(e==null?void 0:e.errorOnMissingTile)||!1}add(e){this.tiles.set(e.source.getKey(),e)}get(e){return this.tiles.get(e)}};f(ae,"Protocol");var ie=ae;function S(r,e){return(e>>>0)*4294967296+(r>>>0)}f(S,"toNum");function bt(r,e){let t=e.buf,n=t[e.pos++],i=(n&112)>>4;if(n<128||(n=t[e.pos++],i|=(n&127)<<3,n<128)||(n=t[e.pos++],i|=(n&127)<<10,n<128)||(n=t[e.pos++],i|=(n&127)<<17,n<128)||(n=t[e.pos++],i|=(n&127)<<24,n<128)||(n=t[e.pos++],i|=(n&1)<<31,n<128))return S(r,i);throw new Error("Expected varint not more than 10 bytes")}f(bt,"readVarintRemainder");function R(r){let e=r.buf,t=e[r.pos++],n=t&127;return t<128||(t=e[r.pos++],n|=(t&127)<<7,t<128)||(t=e[r.pos++],n|=(t&127)<<14,t<128)||(t=e[r.pos++],n|=(t&127)<<21,t<128)?n:(t=e[r.pos],n|=(t&15)<<28,bt(n,r))}f(R,"readVarint");function He(r,e,t,n){if(n===0){t===1&&(e[0]=r-1-e[0],e[1]=r-1-e[1]);let i=e[0];e[0]=e[1],e[1]=i}}f(He,"rotate");function zt(r,e){let t=U(2,r),n=e,i=e,a=e,s=[0,0],u=1;for(;u<t;)n=1&a/2,i=1&(a^n),He(u,s,n,i),s[0]+=u*n,s[1]+=u*i,a=a/4,u*=2;return[r,s[0],s[1]]}f(zt,"idOnLevel");var At=[0,1,5,21,85,341,1365,5461,21845,87381,349525,1398101,5592405,22369621,89478485,357913941,1431655765,5726623061,22906492245,91625968981,366503875925,1466015503701,5864062014805,23456248059221,93824992236885,375299968947541,0x5555555555555];function Ie(r,e,t){if(r>26)throw new Error("Tile zoom level exceeds max safe number limit (26)");if(e>U(2,r)-1||t>U(2,r)-1)throw new Error("tile x/y outside zoom level bounds");let n=At[r],i=U(2,r),a=0,s=0,u=0,h=[e,t],l=i/2;for(;l>0;)a=(h[0]&l)>0?1:0,s=(h[1]&l)>0?1:0,u+=l*l*(3*a^s),He(l,h,a,s),l=l/2;return n+u}f(Ie,"zxyToTileId");function Tt(r){let e=0,t=0;for(let n=0;n<27;n++){let i=(1<<n)*(1<<n);if(e+i>r)return zt(n,r-e);e+=i}throw new Error("Tile zoom level exceeds max safe number limit (26)")}f(Tt,"tileIdToZxy");var Oe=(a=>(a[a.Unknown=0]="Unknown",a[a.None=1]="None",a[a.Gzip=2]="Gzip",a[a.Brotli=3]="Brotli",a[a.Zstd=4]="Zstd",a))(Oe||{});function fe(r,e){return m(this,null,function*(){if(e===1||e===0)return r;if(e===2){if(typeof globalThis.DecompressionStream=="undefined")return Be(new Uint8Array(r));let t=new Response(r).body;if(!t)throw new Error("Failed to read response stream");let n=t.pipeThrough(new globalThis.DecompressionStream("gzip"));return new Response(n).arrayBuffer()}throw new Error("Compression method not supported")})}f(fe,"defaultDecompress");var se=(s=>(s[s.Unknown=0]="Unknown",s[s.Mvt=1]="Mvt",s[s.Png=2]="Png",s[s.Jpeg=3]="Jpeg",s[s.Webp=4]="Webp",s[s.Avif=5]="Avif",s))(se||{});function Ze(r){return r===1?".mvt":r===2?".png":r===3?".jpg":r===4?".webp":r===5?".avif":""}f(Ze,"tileTypeExt");var Ct=127;function Fe(r,e){let t=0,n=r.length-1;for(;t<=n;){let i=n+t>>1,a=e-r[i].tileId;if(a>0)t=i+1;else if(a<0)n=i-1;else return r[i]}return n>=0&&(r[n].runLength===0||e-r[n].tileId<r[n].runLength)?r[n]:null}f(Fe,"findTile");var le=class le{constructor(e){this.file=e}getKey(){return this.file.name}getBytes(e,t){return m(this,null,function*(){return{data:yield this.file.slice(e,e+t).arrayBuffer()}})}};f(le,"FileSource");var oe=le,he=class he{constructor(e,t=new Headers){this.url=e,this.customHeaders=t,this.mustReload=!1;let n="";"navigator"in globalThis&&(n=globalThis.navigator.userAgent||"");let i=n.indexOf("Windows")>-1,a=/Chrome|Chromium|Edg|OPR|Brave/.test(n);this.chromeWindowsNoCache=!1,i&&a&&(this.chromeWindowsNoCache=!0)}getKey(){return this.url}setHeaders(e){this.customHeaders=e}getBytes(e,t,n,i){return m(this,null,function*(){let a,s;n?s=n:(a=new AbortController,s=a.signal);let u=new Headers(this.customHeaders);u.set("range",`bytes=${e}-${e+t-1}`);let h;this.mustReload?h="reload":this.chromeWindowsNoCache&&(h="no-store");let l=yield fetch(this.url,{signal:s,cache:h,headers:u});if(e===0&&l.status===416){let d=l.headers.get("Content-Range");if(!d||!d.startsWith("bytes */"))throw new Error("Missing content-length on 416 response");let p=+d.substr(8);l=yield fetch(this.url,{signal:s,cache:"reload",headers:{range:`bytes=0-${p-1}`}})}let c=l.headers.get("Etag");if(c!=null&&c.startsWith("W/")&&(c=null),l.status===416||i&&c&&c!==i)throw this.mustReload=!0,new B(`Server returned non-matching ETag ${i} after one retry. Check browser extensions and servers for issues that may affect correct ETag headers.`);if(l.status>=300)throw new Error(`Bad response code: ${l.status}`);let o=l.headers.get("Content-Length");if(l.status===200&&(!o||+o>t))throw a&&a.abort(),new Error("Server returned no content-length header or content-length exceeding request. Check that your storage backend supports HTTP Byte Serving.");return{data:yield l.arrayBuffer(),etag:c||void 0,cacheControl:l.headers.get("Cache-Control")||void 0,expires:l.headers.get("Expires")||void 0}})}};f(he,"FetchSource");var K=he;function b(r,e){let t=r.getUint32(e+4,!0),n=r.getUint32(e+0,!0);return t*U(2,32)+n}f(b,"getUint64");function $e(r,e){let t=new DataView(r),n=t.getUint8(7);if(n>3)throw new Error(`Archive is spec version ${n} but this library supports up to spec version 3`);return{specVersion:n,rootDirectoryOffset:b(t,8),rootDirectoryLength:b(t,16),jsonMetadataOffset:b(t,24),jsonMetadataLength:b(t,32),leafDirectoryOffset:b(t,40),leafDirectoryLength:b(t,48),tileDataOffset:b(t,56),tileDataLength:b(t,64),numAddressedTiles:b(t,72),numTileEntries:b(t,80),numTileContents:b(t,88),clustered:t.getUint8(96)===1,internalCompression:t.getUint8(97),tileCompression:t.getUint8(98),tileType:t.getUint8(99),minZoom:t.getUint8(100),maxZoom:t.getUint8(101),minLon:t.getInt32(102,!0)/1e7,minLat:t.getInt32(106,!0)/1e7,maxLon:t.getInt32(110,!0)/1e7,maxLat:t.getInt32(114,!0)/1e7,centerZoom:t.getUint8(118),centerLon:t.getInt32(119,!0)/1e7,centerLat:t.getInt32(123,!0)/1e7,etag:e}}f($e,"bytesToHeader");function Ve(r){let e={buf:new Uint8Array(r),pos:0},t=R(e),n=[],i=0;for(let a=0;a<t;a++){let s=R(e);n.push({tileId:i+s,offset:0,length:0,runLength:1}),i+=s}for(let a=0;a<t;a++)n[a].runLength=R(e);for(let a=0;a<t;a++)n[a].length=R(e);for(let a=0;a<t;a++){let s=R(e);s===0&&a>0?n[a].offset=n[a-1].offset+n[a-1].length:n[a].offset=s-1}return n}f(Ve,"deserializeIndex");var ce=class ce extends Error{};f(ce,"EtagMismatch");var B=ce;function ke(r,e){return m(this,null,function*(){let t=yield r.getBytes(0,16384);if(new DataView(t.data).getUint16(0,!0)!==19792)throw new Error("Wrong magic number for PMTiles archive");let i=t.data.slice(0,Ct),a=$e(i,t.etag),s=t.data.slice(a.rootDirectoryOffset,a.rootDirectoryOffset+a.rootDirectoryLength),u=`${r.getKey()}|${a.etag||""}|${a.rootDirectoryOffset}|${a.rootDirectoryLength}`,h=Ve(yield e(s,a.internalCompression));return[a,[u,h.length,h]]})}f(ke,"getHeaderAndRoot");function Ke(r,e,t,n,i){return m(this,null,function*(){let a=yield r.getBytes(t,n,void 0,i.etag),s=yield e(a.data,i.internalCompression),u=Ve(s);if(u.length===0)throw new Error("Empty directory is invalid");return u})}f(Ke,"getDirectory");var ve=class ve{constructor(e=100,t=!0,n=fe){this.cache=new Map,this.maxCacheEntries=e,this.counter=1,this.decompress=n}getHeader(e){return m(this,null,function*(){let t=e.getKey(),n=this.cache.get(t);if(n)return n.lastUsed=this.counter++,n.data;let i=yield ke(e,this.decompress);return i[1]&&this.cache.set(i[1][0],{lastUsed:this.counter++,data:i[1][2]}),this.cache.set(t,{lastUsed:this.counter++,data:i[0]}),this.prune(),i[0]})}getDirectory(e,t,n,i){return m(this,null,function*(){let a=`${e.getKey()}|${i.etag||""}|${t}|${n}`,s=this.cache.get(a);if(s)return s.lastUsed=this.counter++,s.data;let u=yield Ke(e,this.decompress,t,n,i);return this.cache.set(a,{lastUsed:this.counter++,data:u}),this.prune(),u})}prune(){if(this.cache.size>this.maxCacheEntries){let e=1/0,t;this.cache.forEach((n,i)=>{n.lastUsed<e&&(e=n.lastUsed,t=i)}),t&&this.cache.delete(t)}}invalidate(e){return m(this,null,function*(){this.cache.delete(e.getKey())})}};f(ve,"ResolvedValueCache");var ue=ve,ge=class ge{constructor(e=100,t=!0,n=fe){this.cache=new Map,this.invalidations=new Map,this.maxCacheEntries=e,this.counter=1,this.decompress=n}getHeader(e){return m(this,null,function*(){let t=e.getKey(),n=this.cache.get(t);if(n)return n.lastUsed=this.counter++,yield n.data;let i=new Promise((a,s)=>{ke(e,this.decompress).then(u=>{u[1]&&this.cache.set(u[1][0],{lastUsed:this.counter++,data:Promise.resolve(u[1][2])}),a(u[0]),this.prune()}).catch(u=>{s(u)})});return this.cache.set(t,{lastUsed:this.counter++,data:i}),i})}getDirectory(e,t,n,i){return m(this,null,function*(){let a=`${e.getKey()}|${i.etag||""}|${t}|${n}`,s=this.cache.get(a);if(s)return s.lastUsed=this.counter++,yield s.data;let u=new Promise((h,l)=>{Ke(e,this.decompress,t,n,i).then(c=>{h(c),this.prune()}).catch(c=>{l(c)})});return this.cache.set(a,{lastUsed:this.counter++,data:u}),u})}prune(){if(this.cache.size>=this.maxCacheEntries){let e=1/0,t;this.cache.forEach((n,i)=>{n.lastUsed<e&&(e=n.lastUsed,t=i)}),t&&this.cache.delete(t)}}invalidate(e){return m(this,null,function*(){let t=e.getKey();if(this.invalidations.get(t))return yield this.invalidations.get(t);this.cache.delete(e.getKey());let n=new Promise((i,a)=>{this.getHeader(e).then(s=>{i(),this.invalidations.delete(t)}).catch(s=>{a(s)})});this.invalidations.set(t,n)})}};f(ge,"SharedPromiseCache");var G=ge,pe=class pe{constructor(e,t,n){typeof e=="string"?this.source=new K(e):this.source=e,n?this.decompress=n:this.decompress=fe,t?this.cache=t:this.cache=new G}getHeader(){return m(this,null,function*(){return yield this.cache.getHeader(this.source)})}getZxyAttempt(e,t,n,i){return m(this,null,function*(){let a=Ie(e,t,n),s=yield this.cache.getHeader(this.source);if(e<s.minZoom||e>s.maxZoom)return;let u=s.rootDirectoryOffset,h=s.rootDirectoryLength;for(let l=0;l<=3;l++){let c=yield this.cache.getDirectory(this.source,u,h,s),o=Fe(c,a);if(o){if(o.runLength>0){let v=yield this.source.getBytes(s.tileDataOffset+o.offset,o.length,i,s.etag);return{data:yield this.decompress(v.data,s.tileCompression),cacheControl:v.cacheControl,expires:v.expires}}u=s.leafDirectoryOffset+o.offset,h=o.length}else return}throw new Error("Maximum directory depth exceeded")})}getZxy(e,t,n,i){return m(this,null,function*(){try{return yield this.getZxyAttempt(e,t,n,i)}catch(a){if(a instanceof B)return this.cache.invalidate(this.source),yield this.getZxyAttempt(e,t,n,i);throw a}})}getMetadataAttempt(){return m(this,null,function*(){let e=yield this.cache.getHeader(this.source),t=yield this.source.getBytes(e.jsonMetadataOffset,e.jsonMetadataLength,void 0,e.etag),n=yield this.decompress(t.data,e.internalCompression),i=new TextDecoder("utf-8");return JSON.parse(i.decode(n))})}getMetadata(){return m(this,null,function*(){try{return yield this.getMetadataAttempt()}catch(e){if(e instanceof B)return this.cache.invalidate(this.source),yield this.getMetadataAttempt();throw e}})}getTileJson(e){return m(this,null,function*(){let t=yield this.getHeader(),n=yield this.getMetadata(),i=Ze(t.tileType);return{tilejson:"3.0.0",scheme:"xyz",tiles:[`${e}/{z}/{x}/{y}${i}`],vector_layers:n.vector_layers,attribution:n.attribution,description:n.description,name:n.name,version:n.version,bounds:[t.minLon,t.minLat,t.maxLon,t.maxLat],center:[t.centerLon,t.centerLat,t.centerZoom],minzoom:t.minZoom,maxzoom:t.maxZoom}})}};f(pe,"PMTiles");var P=pe;return et(Dt);})();
+"use strict";var pmtiles=(()=>{var k=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var _e=Object.prototype.hasOwnProperty;var Me=Math.pow;var f=(r,e)=>k(r,"name",{value:e,configurable:!0});var et=(r,e)=>{for(var t in e)k(r,t,{get:e[t],enumerable:!0})},tt=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Xe(e))!_e.call(r,i)&&i!==t&&k(r,i,{get:()=>e[i],enumerable:!(n=Qe(e,i))||n.enumerable});return r};var rt=r=>tt(k({},"__esModule",{value:!0}),r);var m=(r,e,t)=>new Promise((n,i)=>{var a=l=>{try{o(t.next(l))}catch(c){i(c)}},s=l=>{try{o(t.throw(l))}catch(c){i(c)}},o=l=>l.done?n(l.value):Promise.resolve(l.value).then(a,s);o((t=t.apply(r,e)).next())});var Mt={};et(Mt,{Compression:()=>Fe,EtagMismatch:()=>H,FetchSource:()=>V,FileSource:()=>oe,PMTiles:()=>U,Protocol:()=>ie,ResolvedValueCache:()=>ue,SharedPromiseCache:()=>K,TileType:()=>se,bytesToHeader:()=>Ve,findTile:()=>ke,getUint64:()=>b,leafletRasterLayer:()=>bt,readVarint:()=>S,tileIdToZxy:()=>Ct,tileTypeExt:()=>$e,zxyToTileId:()=>Ze});var w=Uint8Array,E=Uint16Array,nt=Int32Array,Ee=new w([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Ue=new w([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),it=new w([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Le=f(function(r,e){for(var t=new E(31),n=0;n<31;++n)t[n]=e+=1<<r[n-1];for(var i=new nt(t[30]),n=1;n<30;++n)for(var a=t[n];a<t[n+1];++a)i[a]=a-t[n]<<5|n;return{b:t,r:i}},"freb"),Pe=Le(Ee,2),Se=Pe.b,at=Pe.r;Se[28]=258,at[258]=28;var He=Le(Ue,0),st=He.b,Ut=He.r,te=new E(32768);for(g=0;g<32768;++g)T=(g&43690)>>1|(g&21845)<<1,T=(T&52428)>>2|(T&13107)<<2,T=(T&61680)>>4|(T&3855)<<4,te[g]=((T&65280)>>8|(T&255)<<8)>>1;var T,g,Z=f(function(r,e,t){for(var n=r.length,i=0,a=new E(e);i<n;++i)r[i]&&++a[r[i]-1];var s=new E(e);for(i=1;i<e;++i)s[i]=s[i-1]+a[i-1]<<1;var o;if(t){o=new E(1<<e);var l=15-e;for(i=0;i<n;++i)if(r[i])for(var c=i<<4|r[i],h=e-r[i],u=s[r[i]-1]++<<h,v=u|(1<<h)-1;u<=v;++u)o[te[u]>>l]=c}else for(o=new E(n),i=0;i<n;++i)r[i]&&(o[i]=te[s[r[i]-1]++]>>15-r[i]);return o},"hMap"),F=new w(288);for(g=0;g<144;++g)F[g]=8;var g;for(g=144;g<256;++g)F[g]=9;var g;for(g=256;g<280;++g)F[g]=7;var g;for(g=280;g<288;++g)F[g]=8;var g,Re=new w(32);for(g=0;g<32;++g)Re[g]=5;var g;var ot=Z(F,9,1);var ut=Z(Re,5,1),_=f(function(r){for(var e=r[0],t=1;t<r.length;++t)r[t]>e&&(e=r[t]);return e},"max"),z=f(function(r,e,t){var n=e/8|0;return(r[n]|r[n+1]<<8)>>(e&7)&t},"bits"),ee=f(function(r,e){var t=e/8|0;return(r[t]|r[t+1]<<8|r[t+2]<<16)>>(e&7)},"bits16"),ft=f(function(r){return(r+7)/8|0},"shft"),lt=f(function(r,e,t){return(e==null||e<0)&&(e=0),(t==null||t>r.length)&&(t=r.length),new w(r.subarray(e,t))},"slc");var ct=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],d=f(function(r,e,t){var n=new Error(e||ct[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,d),!t)throw n;return n},"err"),re=f(function(r,e,t,n){var i=r.length,a=n?n.length:0;if(!i||e.f&&!e.l)return t||new w(0);var s=!t,o=s||e.i!=2,l=e.i;s&&(t=new w(i*3));var c=f(function(Te){var Ce=t.length;if(Te>Ce){var De=new w(Math.max(Ce*2,Te));De.set(t),t=De}},"cbuf"),h=e.f||0,u=e.p||0,v=e.b||0,y=e.l,p=e.d,R=e.m,B=e.n,G=i*8;do{if(!y){h=z(r,u,1);var j=z(r,u+1,3);if(u+=3,j)if(j==1)y=ot,p=ut,R=9,B=5;else if(j==2){var N=z(r,u,31)+257,me=z(r,u+10,15)+4,ye=N+z(r,u+5,31)+1;u+=14;for(var O=new w(ye),J=new w(19),x=0;x<me;++x)J[it[x]]=z(r,u+x*3,7);u+=me*3;for(var de=_(J),qe=(1<<de)-1,We=Z(J,de,1),x=0;x<ye;){var we=We[z(r,u,qe)];u+=we&15;var A=we>>4;if(A<16)O[x++]=A;else{var D=0,$=0;for(A==16?($=3+z(r,u,3),u+=2,D=O[x-1]):A==17?($=3+z(r,u,7),u+=3):A==18&&($=11+z(r,u,127),u+=7);$--;)O[x++]=D}}var xe=O.subarray(0,N),C=O.subarray(N);R=_(xe),B=_(C),y=Z(xe,R,1),p=Z(C,B,1)}else d(1);else{var A=ft(u)+4,q=r[A-4]|r[A-3]<<8,W=A+q;if(W>i){l&&d(0);break}o&&c(v+q),t.set(r.subarray(A,W),v),e.b=v+=q,e.p=u=W*8,e.f=h;continue}if(u>G){l&&d(0);break}}o&&c(v+131072);for(var Ne=(1<<R)-1,Je=(1<<B)-1,Y=u;;Y=u){var D=y[ee(r,u)&Ne],M=D>>4;if(u+=D&15,u>G){l&&d(0);break}if(D||d(2),M<256)t[v++]=M;else if(M==256){Y=u,y=null;break}else{var be=M-254;if(M>264){var x=M-257,I=Ee[x];be=z(r,u,(1<<I)-1)+Se[x],u+=I}var Q=p[ee(r,u)&Je],X=Q>>4;Q||d(3),u+=Q&15;var C=st[X];if(X>3){var I=Ue[X];C+=ee(r,u)&(1<<I)-1,u+=I}if(u>G){l&&d(0);break}o&&c(v+131072);var ze=v+be;if(v<C){var Ae=a-C,Ye=Math.min(C,ze);for(Ae+v<0&&d(3);v<Ye;++v)t[v]=n[Ae+v]}for(;v<ze;++v)t[v]=t[v-C]}}e.l=y,e.p=Y,e.b=v,e.f=h,y&&(h=1,e.m=R,e.d=p,e.n=B)}while(!h);return v!=t.length&&s?lt(t,0,v):t.subarray(0,v)},"inflt");var ht=new w(0);var vt=f(function(r){(r[0]!=31||r[1]!=139||r[2]!=8)&&d(6,"invalid gzip data");var e=r[3],t=10;e&4&&(t+=(r[10]|r[11]<<8)+2);for(var n=(e>>3&1)+(e>>4&1);n>0;n-=!r[t++]);return t+(e&2)},"gzs"),gt=f(function(r){var e=r.length;return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0},"gzl");var pt=f(function(r,e){return((r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31)&&d(6,"invalid zlib data"),(r[1]>>5&1)==+!e&&d(6,"invalid zlib data: "+(r[1]&32?"need":"unexpected")+" dictionary"),(r[1]>>3&4)+2},"zls");function mt(r,e){return re(r,{i:2},e&&e.out,e&&e.dictionary)}f(mt,"inflateSync");function yt(r,e){var t=vt(r);return t+8>r.length&&d(6,"invalid gzip data"),re(r.subarray(t,-8),{i:2},e&&e.out||new w(gt(r)),e&&e.dictionary)}f(yt,"gunzipSync");function dt(r,e){return re(r.subarray(pt(r,e&&e.dictionary),-4),{i:2},e&&e.out,e&&e.dictionary)}f(dt,"unzlibSync");function Be(r,e){return r[0]==31&&r[1]==139&&r[2]==8?yt(r,e):(r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31?mt(r,e):dt(r,e)}f(Be,"decompressSync");var wt=typeof TextDecoder!="undefined"&&new TextDecoder,xt=0;try{wt.decode(ht,{stream:!0}),xt=1}catch(r){}var bt=f((r,e)=>{let t=!1,n="",i=L.GridLayer.extend({createTile:f((a,s)=>{let o=document.createElement("img"),l=new AbortController,c=l.signal;return o.cancel=()=>{l.abort()},t||(r.getHeader().then(h=>{h.tileType===1?console.error("Error: archive contains MVT vector tiles, but leafletRasterLayer is for displaying raster tiles. See https://github.com/protomaps/PMTiles/tree/main/js for details."):h.tileType===2?n="image/png":h.tileType===3?n="image/jpeg":h.tileType===4?n="image/webp":h.tileType===5&&(n="image/avif")}),t=!0),r.getZxy(a.z,a.x,a.y,c).then(h=>{if(h){let u=new Blob([h.data],{type:n}),v=window.URL.createObjectURL(u);o.src=v,o.cancel=void 0,s(void 0,o)}}).catch(h=>{if(h.name!=="AbortError")throw h}),o},"createTile"),_removeTile:f(function(a){let s=this._tiles[a];s&&(s.el.cancel&&s.el.cancel(),s.el.width=0,s.el.height=0,s.el.deleted=!0,L.DomUtil.remove(s.el),delete this._tiles[a],this.fire("tileunload",{tile:s.el,coords:this._keyToTileCoords(a)}))},"_removeTile")});return new i(e)},"leafletRasterLayer"),ne=f((r,e)=>{let t=Object.keys(r),n=Object.keys(e);if(t.length!==n.length)return!1;for(var i of t){let a=r[i],s=e[i],o=Oe(a)&&Oe(s);if(o&&!ne(a,s)||!o&&a!==s)return!1}return!0},"isDeepEqual"),Oe=f(r=>r!=null&&typeof r=="object","isObject"),zt=f(r=>(e,t)=>{if(t instanceof AbortController)return r(e,t);let n=new AbortController;return r(e,n).then(i=>t(void 0,i.data,i.cacheControl||"",i.expires||""),i=>t(i)).catch(i=>t(i)),{cancel:f(()=>n.abort(),"cancel")}},"v3compat"),ae=class ae{constructor(e){this.tilev4=f((e,t)=>m(this,null,function*(){if(e.type==="json"){let v=e.url.substr(10),y=this.tiles.get(v);if((!y||!ne(y.source.customHeaders,e.headers))&&(y=new U(v,e.headers),this.tiles.set(v,y)),this.metadata)return{data:yield y.getTileJson(e.url)};let p=yield y.getHeader();return(p.minLon>=p.maxLon||p.minLat>=p.maxLat)&&console.error(`Bounds of PMTiles archive ${p.minLon},${p.minLat},${p.maxLon},${p.maxLat} are not valid.`),{data:{tiles:[`${e.url}/{z}/{x}/{y}`],minzoom:p.minZoom,maxzoom:p.maxZoom,bounds:[p.minLon,p.minLat,p.maxLon,p.maxLat]}}}let n=new RegExp(/pmtiles:\/\/(.+)\/(\d+)\/(\d+)\/(\d+)/),i=e.url.match(n);if(!i)throw new Error("Invalid PMTiles protocol URL");let a=i[1],s=this.tiles.get(a);(!s||!ne(s.source.customHeaders,e.headers))&&(s=new U(a,e.headers),this.tiles.set(a,s));let o=i[2],l=i[3],c=i[4],h=yield s.getHeader(),u=yield s==null?void 0:s.getZxy(+o,+l,+c,t.signal);if(u)return{data:new Uint8Array(u.data),cacheControl:u.cacheControl,expires:u.expires};if(h.tileType===1){if(this.errorOnMissingTile)throw new Error("Tile not found.");return{data:new Uint8Array}}return{data:null}}),"tilev4");this.tile=zt(this.tilev4);this.tiles=new Map,this.metadata=(e==null?void 0:e.metadata)||!1,this.errorOnMissingTile=(e==null?void 0:e.errorOnMissingTile)||!1}add(e){this.tiles.set(e.source.getKey(),e)}get(e){return this.tiles.get(e)}};f(ae,"Protocol");var ie=ae;function P(r,e){return(e>>>0)*4294967296+(r>>>0)}f(P,"toNum");function At(r,e){let t=e.buf,n=t[e.pos++],i=(n&112)>>4;if(n<128||(n=t[e.pos++],i|=(n&127)<<3,n<128)||(n=t[e.pos++],i|=(n&127)<<10,n<128)||(n=t[e.pos++],i|=(n&127)<<17,n<128)||(n=t[e.pos++],i|=(n&127)<<24,n<128)||(n=t[e.pos++],i|=(n&1)<<31,n<128))return P(r,i);throw new Error("Expected varint not more than 10 bytes")}f(At,"readVarintRemainder");function S(r){let e=r.buf,t=e[r.pos++],n=t&127;return t<128||(t=e[r.pos++],n|=(t&127)<<7,t<128)||(t=e[r.pos++],n|=(t&127)<<14,t<128)||(t=e[r.pos++],n|=(t&127)<<21,t<128)?n:(t=e[r.pos],n|=(t&15)<<28,At(n,r))}f(S,"readVarint");function Ie(r,e,t,n,i){return i===0?n!==0?[r-1-t,r-1-e]:[t,e]:[e,t]}f(Ie,"rotate");function Ze(r,e,t){if(r>26)throw new Error("Tile zoom level exceeds max safe number limit (26)");if(e>=1<<r||t>=1<<r)throw new Error("tile x/y outside zoom level bounds");let n=((1<<r)*(1<<r)-1)/3,i=r-1,[a,s]=[e,t];for(let o=1<<i;o>0;o>>=1){let l=a&o,c=s&o;n+=(3*l^c)*(1<<i),[a,s]=Ie(o,a,s,l,c),i--}return n}f(Ze,"zxyToTileId");function Tt(r){let e=3*r+1;return e<4294967296?31-Math.clz32(e):63-Math.clz32(e/4294967296)}f(Tt,"tileIdToZ");function Ct(r){let e=Tt(r)>>1;if(e>26)throw new Error("Tile zoom level exceeds max safe number limit (26)");let t=((1<<e)*(1<<e)-1)/3,n=r-t,i=0,a=0,s=1<<e;for(let o=1;o<s;o<<=1){let l=o&n/2,c=o&(n^l);[i,a]=Ie(o,i,a,l,c),n=n/2,i+=l,a+=c}return[e,i,a]}f(Ct,"tileIdToZxy");var Fe=(a=>(a[a.Unknown=0]="Unknown",a[a.None=1]="None",a[a.Gzip=2]="Gzip",a[a.Brotli=3]="Brotli",a[a.Zstd=4]="Zstd",a))(Fe||{});function fe(r,e){return m(this,null,function*(){if(e===1||e===0)return r;if(e===2){if(typeof globalThis.DecompressionStream=="undefined")return Be(new Uint8Array(r));let t=new Response(r).body;if(!t)throw new Error("Failed to read response stream");let n=t.pipeThrough(new globalThis.DecompressionStream("gzip"));return new Response(n).arrayBuffer()}throw new Error("Compression method not supported")})}f(fe,"defaultDecompress");var se=(s=>(s[s.Unknown=0]="Unknown",s[s.Mvt=1]="Mvt",s[s.Png=2]="Png",s[s.Jpeg=3]="Jpeg",s[s.Webp=4]="Webp",s[s.Avif=5]="Avif",s))(se||{});function $e(r){return r===1?".mvt":r===2?".png":r===3?".jpg":r===4?".webp":r===5?".avif":""}f($e,"tileTypeExt");var Dt=127;function ke(r,e){let t=0,n=r.length-1;for(;t<=n;){let i=n+t>>1,a=e-r[i].tileId;if(a>0)t=i+1;else if(a<0)n=i-1;else return r[i]}return n>=0&&(r[n].runLength===0||e-r[n].tileId<r[n].runLength)?r[n]:null}f(ke,"findTile");var le=class le{constructor(e){this.file=e}getKey(){return this.file.name}getBytes(e,t){return m(this,null,function*(){return{data:yield this.file.slice(e,e+t).arrayBuffer()}})}};f(le,"FileSource");var oe=le,ce=class ce{constructor(e,t=new Headers){this.url=e,this.customHeaders=t,this.mustReload=!1;let n="";"navigator"in globalThis&&(n=globalThis.navigator.userAgent||"");let i=n.indexOf("Windows")>-1,a=/Chrome|Chromium|Edg|OPR|Brave/.test(n);this.chromeWindowsNoCache=!1,i&&a&&(this.chromeWindowsNoCache=!0)}getKey(){return this.url}setHeaders(e){this.customHeaders=e}getBytes(e,t,n,i){return m(this,null,function*(){let a,s;n?s=n:(a=new AbortController,s=a.signal);let o=new Headers(this.customHeaders);o.set("range",`bytes=${e}-${e+t-1}`);let l;this.mustReload?l="reload":this.chromeWindowsNoCache&&(l="no-store");let c=yield fetch(this.url,{signal:s,cache:l,headers:o});if(e===0&&c.status===416){let y=c.headers.get("Content-Range");if(!y||!y.startsWith("bytes */"))throw new Error("Missing content-length on 416 response");let p=+y.substr(8);c=yield fetch(this.url,{signal:s,cache:"reload",headers:{range:`bytes=0-${p-1}`}})}let h=c.headers.get("Etag");if(h!=null&&h.startsWith("W/")&&(h=null),c.status===416||i&&h&&h!==i)throw this.mustReload=!0,new H(`Server returned non-matching ETag ${i} after one retry. Check browser extensions and servers for issues that may affect correct ETag headers.`);if(c.status>=300)throw new Error(`Bad response code: ${c.status}`);let u=c.headers.get("Content-Length");if(c.status===200&&(!u||+u>t))throw a&&a.abort(),new Error("Server returned no content-length header or content-length exceeding request. Check that your storage backend supports HTTP Byte Serving.");return{data:yield c.arrayBuffer(),etag:h||void 0,cacheControl:c.headers.get("Cache-Control")||void 0,expires:c.headers.get("Expires")||void 0}})}};f(ce,"FetchSource");var V=ce;function b(r,e){let t=r.getUint32(e+4,!0),n=r.getUint32(e+0,!0);return t*Me(2,32)+n}f(b,"getUint64");function Ve(r,e){let t=new DataView(r),n=t.getUint8(7);if(n>3)throw new Error(`Archive is spec version ${n} but this library supports up to spec version 3`);return{specVersion:n,rootDirectoryOffset:b(t,8),rootDirectoryLength:b(t,16),jsonMetadataOffset:b(t,24),jsonMetadataLength:b(t,32),leafDirectoryOffset:b(t,40),leafDirectoryLength:b(t,48),tileDataOffset:b(t,56),tileDataLength:b(t,64),numAddressedTiles:b(t,72),numTileEntries:b(t,80),numTileContents:b(t,88),clustered:t.getUint8(96)===1,internalCompression:t.getUint8(97),tileCompression:t.getUint8(98),tileType:t.getUint8(99),minZoom:t.getUint8(100),maxZoom:t.getUint8(101),minLon:t.getInt32(102,!0)/1e7,minLat:t.getInt32(106,!0)/1e7,maxLon:t.getInt32(110,!0)/1e7,maxLat:t.getInt32(114,!0)/1e7,centerZoom:t.getUint8(118),centerLon:t.getInt32(119,!0)/1e7,centerLat:t.getInt32(123,!0)/1e7,etag:e}}f(Ve,"bytesToHeader");function Ke(r){let e={buf:new Uint8Array(r),pos:0},t=S(e),n=[],i=0;for(let a=0;a<t;a++){let s=S(e);n.push({tileId:i+s,offset:0,length:0,runLength:1}),i+=s}for(let a=0;a<t;a++)n[a].runLength=S(e);for(let a=0;a<t;a++)n[a].length=S(e);for(let a=0;a<t;a++){let s=S(e);s===0&&a>0?n[a].offset=n[a-1].offset+n[a-1].length:n[a].offset=s-1}return n}f(Ke,"deserializeIndex");var he=class he extends Error{};f(he,"EtagMismatch");var H=he;function Ge(r,e){return m(this,null,function*(){let t=yield r.getBytes(0,16384);if(new DataView(t.data).getUint16(0,!0)!==19792)throw new Error("Wrong magic number for PMTiles archive");let i=t.data.slice(0,Dt),a=Ve(i,t.etag),s=t.data.slice(a.rootDirectoryOffset,a.rootDirectoryOffset+a.rootDirectoryLength),o=`${r.getKey()}|${a.etag||""}|${a.rootDirectoryOffset}|${a.rootDirectoryLength}`,l=Ke(yield e(s,a.internalCompression));return[a,[o,l.length,l]]})}f(Ge,"getHeaderAndRoot");function je(r,e,t,n,i){return m(this,null,function*(){let a=yield r.getBytes(t,n,void 0,i.etag),s=yield e(a.data,i.internalCompression),o=Ke(s);if(o.length===0)throw new Error("Empty directory is invalid");return o})}f(je,"getDirectory");var ve=class ve{constructor(e=100,t=!0,n=fe){this.cache=new Map,this.maxCacheEntries=e,this.counter=1,this.decompress=n}getHeader(e){return m(this,null,function*(){let t=e.getKey(),n=this.cache.get(t);if(n)return n.lastUsed=this.counter++,n.data;let i=yield Ge(e,this.decompress);return i[1]&&this.cache.set(i[1][0],{lastUsed:this.counter++,data:i[1][2]}),this.cache.set(t,{lastUsed:this.counter++,data:i[0]}),this.prune(),i[0]})}getDirectory(e,t,n,i){return m(this,null,function*(){let a=`${e.getKey()}|${i.etag||""}|${t}|${n}`,s=this.cache.get(a);if(s)return s.lastUsed=this.counter++,s.data;let o=yield je(e,this.decompress,t,n,i);return this.cache.set(a,{lastUsed:this.counter++,data:o}),this.prune(),o})}prune(){if(this.cache.size>this.maxCacheEntries){let e=1/0,t;this.cache.forEach((n,i)=>{n.lastUsed<e&&(e=n.lastUsed,t=i)}),t&&this.cache.delete(t)}}invalidate(e){return m(this,null,function*(){this.cache.delete(e.getKey())})}};f(ve,"ResolvedValueCache");var ue=ve,ge=class ge{constructor(e=100,t=!0,n=fe){this.cache=new Map,this.invalidations=new Map,this.maxCacheEntries=e,this.counter=1,this.decompress=n}getHeader(e){return m(this,null,function*(){let t=e.getKey(),n=this.cache.get(t);if(n)return n.lastUsed=this.counter++,yield n.data;let i=new Promise((a,s)=>{Ge(e,this.decompress).then(o=>{o[1]&&this.cache.set(o[1][0],{lastUsed:this.counter++,data:Promise.resolve(o[1][2])}),a(o[0]),this.prune()}).catch(o=>{s(o)})});return this.cache.set(t,{lastUsed:this.counter++,data:i}),i})}getDirectory(e,t,n,i){return m(this,null,function*(){let a=`${e.getKey()}|${i.etag||""}|${t}|${n}`,s=this.cache.get(a);if(s)return s.lastUsed=this.counter++,yield s.data;let o=new Promise((l,c)=>{je(e,this.decompress,t,n,i).then(h=>{l(h),this.prune()}).catch(h=>{c(h)})});return this.cache.set(a,{lastUsed:this.counter++,data:o}),o})}prune(){if(this.cache.size>=this.maxCacheEntries){let e=1/0,t;this.cache.forEach((n,i)=>{n.lastUsed<e&&(e=n.lastUsed,t=i)}),t&&this.cache.delete(t)}}invalidate(e){return m(this,null,function*(){let t=e.getKey();if(this.invalidations.get(t))return yield this.invalidations.get(t);this.cache.delete(e.getKey());let n=new Promise((i,a)=>{this.getHeader(e).then(s=>{i(),this.invalidations.delete(t)}).catch(s=>{a(s)})});this.invalidations.set(t,n)})}};f(ge,"SharedPromiseCache");var K=ge,pe=class pe{constructor(e,t,n,i){typeof e=="string"?this.source=new V(e,t):this.source=e,i?this.decompress=i:this.decompress=fe,n?this.cache=n:this.cache=new K}getHeader(){return m(this,null,function*(){return yield this.cache.getHeader(this.source)})}getZxyAttempt(e,t,n,i){return m(this,null,function*(){let a=Ze(e,t,n),s=yield this.cache.getHeader(this.source);if(e<s.minZoom||e>s.maxZoom)return;let o=s.rootDirectoryOffset,l=s.rootDirectoryLength;for(let c=0;c<=3;c++){let h=yield this.cache.getDirectory(this.source,o,l,s),u=ke(h,a);if(u){if(u.runLength>0){let v=yield this.source.getBytes(s.tileDataOffset+u.offset,u.length,i,s.etag);return{data:yield this.decompress(v.data,s.tileCompression),cacheControl:v.cacheControl,expires:v.expires}}o=s.leafDirectoryOffset+u.offset,l=u.length}else return}throw new Error("Maximum directory depth exceeded")})}getZxy(e,t,n,i){return m(this,null,function*(){try{return yield this.getZxyAttempt(e,t,n,i)}catch(a){if(a instanceof H)return this.cache.invalidate(this.source),yield this.getZxyAttempt(e,t,n,i);throw a}})}getMetadataAttempt(){return m(this,null,function*(){let e=yield this.cache.getHeader(this.source),t=yield this.source.getBytes(e.jsonMetadataOffset,e.jsonMetadataLength,void 0,e.etag),n=yield this.decompress(t.data,e.internalCompression),i=new TextDecoder("utf-8");return JSON.parse(i.decode(n))})}getMetadata(){return m(this,null,function*(){try{return yield this.getMetadataAttempt()}catch(e){if(e instanceof H)return this.cache.invalidate(this.source),yield this.getMetadataAttempt();throw e}})}getTileJson(e){return m(this,null,function*(){let t=yield this.getHeader(),n=yield this.getMetadata(),i=$e(t.tileType);return{tilejson:"3.0.0",scheme:"xyz",tiles:[`${e}/{z}/{x}/{y}${i}`],vector_layers:n.vector_layers,attribution:n.attribution,description:n.description,name:n.name,version:n.version,bounds:[t.minLon,t.minLat,t.maxLon,t.maxLat],center:[t.centerLon,t.centerLat,t.centerZoom],minzoom:t.minZoom,maxzoom:t.maxZoom}})}};f(pe,"PMTiles");var U=pe;return rt(Mt);})();
 //# sourceMappingURL=pmtiles.js.map
\ No newline at end of file
diff --git a/node_modules/pmtiles/dist/pmtiles.js.map b/node_modules/pmtiles/dist/pmtiles.js.map
index 982a12c..32925de 100644
--- a/node_modules/pmtiles/dist/pmtiles.js.map
+++ b/node_modules/pmtiles/dist/pmtiles.js.map
@@ -1 +1 @@
-{"version":3,"sources":["../src/index.ts","../node_modules/fflate/esm/browser.js","../src/adapters.ts"],"sourcesContent":["import { decompressSync } from \"fflate\";\nexport * from \"./adapters\";\n\n/** @hidden */\nexport interface BufferPosition {\n  buf: Uint8Array;\n  pos: number;\n}\n\nfunction toNum(low: number, high: number): number {\n  return (high >>> 0) * 0x100000000 + (low >>> 0);\n}\n\nfunction readVarintRemainder(l: number, p: BufferPosition): number {\n  const buf = p.buf;\n  let b = buf[p.pos++];\n  let h = (b & 0x70) >> 4;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x7f) << 3;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x7f) << 10;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x7f) << 17;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x7f) << 24;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x01) << 31;\n  if (b < 0x80) return toNum(l, h);\n  throw new Error(\"Expected varint not more than 10 bytes\");\n}\n\n/** @hidden */\nexport function readVarint(p: BufferPosition): number {\n  const buf = p.buf;\n  let b = buf[p.pos++];\n  let val = b & 0x7f;\n  if (b < 0x80) return val;\n  b = buf[p.pos++];\n  val |= (b & 0x7f) << 7;\n  if (b < 0x80) return val;\n  b = buf[p.pos++];\n  val |= (b & 0x7f) << 14;\n  if (b < 0x80) return val;\n  b = buf[p.pos++];\n  val |= (b & 0x7f) << 21;\n  if (b < 0x80) return val;\n  b = buf[p.pos];\n  val |= (b & 0x0f) << 28;\n\n  return readVarintRemainder(val, p);\n}\n\nfunction rotate(n: number, xy: number[], rx: number, ry: number): void {\n  if (ry === 0) {\n    if (rx === 1) {\n      xy[0] = n - 1 - xy[0];\n      xy[1] = n - 1 - xy[1];\n    }\n    const t = xy[0];\n    xy[0] = xy[1];\n    xy[1] = t;\n  }\n}\n\nfunction idOnLevel(z: number, pos: number): [number, number, number] {\n  const n = 2 ** z;\n  let rx = pos;\n  let ry = pos;\n  let t = pos;\n  const xy = [0, 0];\n  let s = 1;\n  while (s < n) {\n    rx = 1 & (t / 2);\n    ry = 1 & (t ^ rx);\n    rotate(s, xy, rx, ry);\n    xy[0] += s * rx;\n    xy[1] += s * ry;\n    t = t / 4;\n    s *= 2;\n  }\n  return [z, xy[0], xy[1]];\n}\n\nconst tzValues: number[] = [\n  0, 1, 5, 21, 85, 341, 1365, 5461, 21845, 87381, 349525, 1398101, 5592405,\n  22369621, 89478485, 357913941, 1431655765, 5726623061, 22906492245,\n  91625968981, 366503875925, 1466015503701, 5864062014805, 23456248059221,\n  93824992236885, 375299968947541, 1501199875790165,\n];\n\n/**\n * Convert Z,X,Y to a Hilbert TileID.\n */\nexport function zxyToTileId(z: number, x: number, y: number): number {\n  if (z > 26) {\n    throw new Error(\"Tile zoom level exceeds max safe number limit (26)\");\n  }\n  if (x > 2 ** z - 1 || y > 2 ** z - 1) {\n    throw new Error(\"tile x/y outside zoom level bounds\");\n  }\n\n  const acc = tzValues[z];\n  const n = 2 ** z;\n  let rx = 0;\n  let ry = 0;\n  let d = 0;\n  const xy = [x, y];\n  let s = n / 2;\n  while (s > 0) {\n    rx = (xy[0] & s) > 0 ? 1 : 0;\n    ry = (xy[1] & s) > 0 ? 1 : 0;\n    d += s * s * ((3 * rx) ^ ry);\n    rotate(s, xy, rx, ry);\n    s = s / 2;\n  }\n  return acc + d;\n}\n\n/**\n * Convert a Hilbert TileID to Z,X,Y.\n */\nexport function tileIdToZxy(i: number): [number, number, number] {\n  let acc = 0;\n  const z = 0;\n\n  for (let z = 0; z < 27; z++) {\n    const numTiles = (0x1 << z) * (0x1 << z);\n    if (acc + numTiles > i) {\n      return idOnLevel(z, i - acc);\n    }\n    acc += numTiles;\n  }\n\n  throw new Error(\"Tile zoom level exceeds max safe number limit (26)\");\n}\n\n/**\n * PMTiles v3 directory entry.\n */\nexport interface Entry {\n  tileId: number;\n  offset: number;\n  length: number;\n  runLength: number;\n}\n\ninterface MetadataLike {\n  attribution?: string;\n  name?: string;\n  version?: string;\n  // biome-ignore lint: TileJSON spec\n  vector_layers?: string;\n  description?: string;\n}\n\n/**\n * Enum representing a compression algorithm used.\n * 0 = unknown compression, for if you must use a different or unspecified algorithm.\n * 1 = no compression.\n */\nexport enum Compression {\n  Unknown = 0,\n  None = 1,\n  Gzip = 2,\n  Brotli = 3,\n  Zstd = 4,\n}\n\n/**\n * Provide a decompression implementation that acts on `buf` and returns decompressed data.\n *\n * Should use the native DecompressionStream on browsers, zlib on node.\n * Should throw if the compression algorithm is not supported.\n */\nexport type DecompressFunc = (\n  buf: ArrayBuffer,\n  compression: Compression\n) => Promise<ArrayBuffer>;\n\nasync function defaultDecompress(\n  buf: ArrayBuffer,\n  compression: Compression\n): Promise<ArrayBuffer> {\n  if (compression === Compression.None || compression === Compression.Unknown) {\n    return buf;\n  }\n  if (compression === Compression.Gzip) {\n    // biome-ignore lint: needed to detect DecompressionStream in browser+node+cloudflare workers\n    if (typeof (globalThis as any).DecompressionStream === \"undefined\") {\n      return decompressSync(new Uint8Array(buf));\n    }\n    const stream = new Response(buf).body;\n    if (!stream) {\n      throw new Error(\"Failed to read response stream\");\n    }\n    const result: ReadableStream<Uint8Array> = stream.pipeThrough(\n      // biome-ignore lint: needed to detect DecompressionStream in browser+node+cloudflare workers\n      new (globalThis as any).DecompressionStream(\"gzip\")\n    );\n    return new Response(result).arrayBuffer();\n  }\n  throw new Error(\"Compression method not supported\");\n}\n\n/**\n * Describe the type of tiles stored in the archive.\n * 0 is unknown/other, 1 is \"MVT\" vector tiles.\n */\nexport enum TileType {\n  Unknown = 0,\n  Mvt = 1,\n  Png = 2,\n  Jpeg = 3,\n  Webp = 4,\n  Avif = 5,\n}\n\nexport function tileTypeExt(t: TileType): string {\n  if (t === TileType.Mvt) return \".mvt\";\n  if (t === TileType.Png) return \".png\";\n  if (t === TileType.Jpeg) return \".jpg\";\n  if (t === TileType.Webp) return \".webp\";\n  if (t === TileType.Avif) return \".avif\";\n  return \"\";\n}\n\nconst HEADER_SIZE_BYTES = 127;\n\n/**\n * PMTiles v3 header storing basic archive-level information.\n */\nexport interface Header {\n  specVersion: number;\n  rootDirectoryOffset: number;\n  rootDirectoryLength: number;\n  jsonMetadataOffset: number;\n  jsonMetadataLength: number;\n  leafDirectoryOffset: number;\n  leafDirectoryLength?: number;\n  tileDataOffset: number;\n  tileDataLength?: number;\n  numAddressedTiles: number;\n  numTileEntries: number;\n  numTileContents: number;\n  clustered: boolean;\n  internalCompression: Compression;\n  tileCompression: Compression;\n  tileType: TileType;\n  minZoom: number;\n  maxZoom: number;\n  minLon: number;\n  minLat: number;\n  maxLon: number;\n  maxLat: number;\n  centerZoom: number;\n  centerLon: number;\n  centerLat: number;\n  etag?: string;\n}\n\n/**\n * Low-level function for looking up a TileID or leaf directory inside a directory.\n */\nexport function findTile(entries: Entry[], tileId: number): Entry | null {\n  let m = 0;\n  let n = entries.length - 1;\n  while (m <= n) {\n    const k = (n + m) >> 1;\n    const cmp = tileId - entries[k].tileId;\n    if (cmp > 0) {\n      m = k + 1;\n    } else if (cmp < 0) {\n      n = k - 1;\n    } else {\n      return entries[k];\n    }\n  }\n\n  // at this point, m > n\n  if (n >= 0) {\n    if (entries[n].runLength === 0) {\n      return entries[n];\n    }\n    if (tileId - entries[n].tileId < entries[n].runLength) {\n      return entries[n];\n    }\n  }\n  return null;\n}\n\nexport interface RangeResponse {\n  data: ArrayBuffer;\n  etag?: string;\n  expires?: string;\n  cacheControl?: string;\n}\n\n/**\n * Interface for retrieving an archive from remote or local storage.\n */\nexport interface Source {\n  getBytes: (\n    offset: number,\n    length: number,\n    signal?: AbortSignal,\n    etag?: string\n  ) => Promise<RangeResponse>;\n\n  /**\n   * Return a unique string key for the archive e.g. a URL.\n   */\n  getKey: () => string;\n}\n\n/**\n * Use the Browser's File API, which is different from the NodeJS file API.\n * see https://developer.mozilla.org/en-US/docs/Web/API/File_API\n */\nexport class FileSource implements Source {\n  file: File;\n\n  constructor(file: File) {\n    this.file = file;\n  }\n\n  getKey() {\n    return this.file.name;\n  }\n\n  async getBytes(offset: number, length: number): Promise<RangeResponse> {\n    const blob = this.file.slice(offset, offset + length);\n    const a = await blob.arrayBuffer();\n    return { data: a };\n  }\n}\n\n/**\n * Uses the browser Fetch API to make tile requests via HTTP.\n *\n * This method does not send conditional request headers If-Match because of CORS.\n * Instead, it detects ETag mismatches via the response ETag or the 416 response code.\n *\n * This also works around browser and storage-specific edge cases.\n */\nexport class FetchSource implements Source {\n  url: string;\n\n  /**\n   * A [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) object, specfying custom [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) set for all requests to the remote archive.\n   *\n   * This should be used instead of maplibre's [transformRequest](https://maplibre.org/maplibre-gl-js/docs/API/classes/Map/#example) for PMTiles archives.\n   */\n  customHeaders: Headers;\n  /** @hidden */\n  mustReload: boolean;\n  /** @hidden */\n  chromeWindowsNoCache: boolean;\n\n  constructor(url: string, customHeaders: Headers = new Headers()) {\n    this.url = url;\n    this.customHeaders = customHeaders;\n    this.mustReload = false;\n    let userAgent = \"\";\n    if (\"navigator\" in globalThis) {\n      //biome-ignore lint: cf workers\n      userAgent = (globalThis as any).navigator.userAgent || \"\";\n    }\n    const isWindows = userAgent.indexOf(\"Windows\") > -1;\n    const isChromiumBased = /Chrome|Chromium|Edg|OPR|Brave/.test(userAgent);\n    this.chromeWindowsNoCache = false;\n    if (isWindows && isChromiumBased) {\n      this.chromeWindowsNoCache = true;\n    }\n  }\n\n  getKey() {\n    return this.url;\n  }\n\n  /**\n   * Mutate the custom [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) set for all requests to the remote archive.\n   */\n  setHeaders(customHeaders: Headers) {\n    this.customHeaders = customHeaders;\n  }\n\n  async getBytes(\n    offset: number,\n    length: number,\n    passedSignal?: AbortSignal,\n    etag?: string\n  ): Promise<RangeResponse> {\n    let controller: AbortController | undefined;\n    let signal: AbortSignal | undefined;\n    if (passedSignal) {\n      signal = passedSignal;\n    } else {\n      controller = new AbortController();\n      signal = controller.signal;\n    }\n\n    const requestHeaders = new Headers(this.customHeaders);\n    requestHeaders.set(\"range\", `bytes=${offset}-${offset + length - 1}`);\n\n    // we don't send if match because:\n    // * it disables browser caching completely (Chromium)\n    // * it requires a preflight request for every tile request\n    // * it requires CORS configuration becasue If-Match is not a CORs-safelisted header\n    // CORs configuration should expose ETag.\n    // if any etag mismatch is detected, we need to ignore the browser cache\n    let cache: string | undefined;\n    if (this.mustReload) {\n      cache = \"reload\";\n    } else if (this.chromeWindowsNoCache) {\n      cache = \"no-store\";\n    }\n\n    let resp = await fetch(this.url, {\n      signal: signal,\n      cache: cache,\n      headers: requestHeaders,\n      //biome-ignore lint: \"cache\" is incompatible between cloudflare workers and browser\n    } as any);\n\n    // handle edge case where the archive is < 16384 kb total.\n    if (offset === 0 && resp.status === 416) {\n      const contentRange = resp.headers.get(\"Content-Range\");\n      if (!contentRange || !contentRange.startsWith(\"bytes */\")) {\n        throw new Error(\"Missing content-length on 416 response\");\n      }\n      const actualLength = +contentRange.substr(8);\n      resp = await fetch(this.url, {\n        signal: signal,\n        cache: \"reload\",\n        headers: { range: `bytes=0-${actualLength - 1}` },\n        //biome-ignore lint: \"cache\" is incompatible between cloudflare workers and browser\n      } as any);\n    }\n\n    // if it's a weak etag, it's not useful for us, so ignore it.\n    let newEtag = resp.headers.get(\"Etag\");\n    if (newEtag?.startsWith(\"W/\")) {\n      newEtag = null;\n    }\n\n    // some storage systems are misbehaved (Cloudflare R2)\n    if (resp.status === 416 || (etag && newEtag && newEtag !== etag)) {\n      this.mustReload = true;\n      throw new EtagMismatch(\n        `Server returned non-matching ETag ${etag} after one retry. Check browser extensions and servers for issues that may affect correct ETag headers.`\n      );\n    }\n\n    if (resp.status >= 300) {\n      throw new Error(`Bad response code: ${resp.status}`);\n    }\n\n    // some well-behaved backends, e.g. DigitalOcean CDN, respond with 200 instead of 206\n    // but we also need to detect no support for Byte Serving which is returning the whole file\n    const contentLength = resp.headers.get(\"Content-Length\");\n    if (resp.status === 200 && (!contentLength || +contentLength > length)) {\n      if (controller) controller.abort();\n      throw new Error(\n        \"Server returned no content-length header or content-length exceeding request. Check that your storage backend supports HTTP Byte Serving.\"\n      );\n    }\n\n    const a = await resp.arrayBuffer();\n    return {\n      data: a,\n      etag: newEtag || undefined,\n      cacheControl: resp.headers.get(\"Cache-Control\") || undefined,\n      expires: resp.headers.get(\"Expires\") || undefined,\n    };\n  }\n}\n\n/** @hidden */\nexport function getUint64(v: DataView, offset: number): number {\n  const wh = v.getUint32(offset + 4, true);\n  const wl = v.getUint32(offset + 0, true);\n  return wh * 2 ** 32 + wl;\n}\n\n/**\n * Parse raw header bytes into a Header object.\n */\nexport function bytesToHeader(bytes: ArrayBuffer, etag?: string): Header {\n  const v = new DataView(bytes);\n  const specVersion = v.getUint8(7);\n  if (specVersion > 3) {\n    throw new Error(\n      `Archive is spec version ${specVersion} but this library supports up to spec version 3`\n    );\n  }\n\n  return {\n    specVersion: specVersion,\n    rootDirectoryOffset: getUint64(v, 8),\n    rootDirectoryLength: getUint64(v, 16),\n    jsonMetadataOffset: getUint64(v, 24),\n    jsonMetadataLength: getUint64(v, 32),\n    leafDirectoryOffset: getUint64(v, 40),\n    leafDirectoryLength: getUint64(v, 48),\n    tileDataOffset: getUint64(v, 56),\n    tileDataLength: getUint64(v, 64),\n    numAddressedTiles: getUint64(v, 72),\n    numTileEntries: getUint64(v, 80),\n    numTileContents: getUint64(v, 88),\n    clustered: v.getUint8(96) === 1,\n    internalCompression: v.getUint8(97),\n    tileCompression: v.getUint8(98),\n    tileType: v.getUint8(99),\n    minZoom: v.getUint8(100),\n    maxZoom: v.getUint8(101),\n    minLon: v.getInt32(102, true) / 10000000,\n    minLat: v.getInt32(106, true) / 10000000,\n    maxLon: v.getInt32(110, true) / 10000000,\n    maxLat: v.getInt32(114, true) / 10000000,\n    centerZoom: v.getUint8(118),\n    centerLon: v.getInt32(119, true) / 10000000,\n    centerLat: v.getInt32(123, true) / 10000000,\n    etag: etag,\n  };\n}\n\nfunction deserializeIndex(buffer: ArrayBuffer): Entry[] {\n  const p = { buf: new Uint8Array(buffer), pos: 0 };\n  const numEntries = readVarint(p);\n\n  const entries: Entry[] = [];\n\n  let lastId = 0;\n  for (let i = 0; i < numEntries; i++) {\n    const v = readVarint(p);\n    entries.push({ tileId: lastId + v, offset: 0, length: 0, runLength: 1 });\n    lastId += v;\n  }\n\n  for (let i = 0; i < numEntries; i++) {\n    entries[i].runLength = readVarint(p);\n  }\n\n  for (let i = 0; i < numEntries; i++) {\n    entries[i].length = readVarint(p);\n  }\n\n  for (let i = 0; i < numEntries; i++) {\n    const v = readVarint(p);\n    if (v === 0 && i > 0) {\n      entries[i].offset = entries[i - 1].offset + entries[i - 1].length;\n    } else {\n      entries[i].offset = v - 1;\n    }\n  }\n\n  return entries;\n}\n\nfunction detectVersion(a: ArrayBuffer): number {\n  const v = new DataView(a);\n  if (v.getUint16(2, true) === 2) {\n    console.error(\n      \"PMTiles spec version 2 is not supported; please see github.com/protomaps/PMTiles for tools to upgrade\"\n    );\n    return 2;\n  }\n  if (v.getUint16(2, true) === 1) {\n    console.error(\n      \"PMTiles spec version 1 is not supported; please see github.com/protomaps/PMTiles for tools to upgrade\"\n    );\n    return 1;\n  }\n  return 3;\n}\n\n/**\n * Error thrown when a response for PMTiles over HTTP does not match previous, cached parts of the archive.\n * The default PMTiles implementation will catch this error once internally and retry a request.\n */\nexport class EtagMismatch extends Error {}\n\n/**\n * Interface for caches of parts (headers, directories) of a PMTiles archive.\n */\nexport interface Cache {\n  getHeader: (source: Source) => Promise<Header>;\n  getDirectory: (\n    source: Source,\n    offset: number,\n    length: number,\n    header: Header\n  ) => Promise<Entry[]>;\n  invalidate: (source: Source) => Promise<void>;\n}\n\nasync function getHeaderAndRoot(\n  source: Source,\n  decompress: DecompressFunc\n): Promise<[Header, [string, number, Entry[] | ArrayBuffer]?]> {\n  const resp = await source.getBytes(0, 16384);\n\n  const v = new DataView(resp.data);\n  if (v.getUint16(0, true) !== 0x4d50) {\n    throw new Error(\"Wrong magic number for PMTiles archive\");\n  }\n\n  const headerData = resp.data.slice(0, HEADER_SIZE_BYTES);\n\n  const header = bytesToHeader(headerData, resp.etag);\n\n  // optimistically set the root directory\n  // TODO check root bounds\n  const rootDirData = resp.data.slice(\n    header.rootDirectoryOffset,\n    header.rootDirectoryOffset + header.rootDirectoryLength\n  );\n  const dirKey = `${source.getKey()}|${header.etag || \"\"}|${\n    header.rootDirectoryOffset\n  }|${header.rootDirectoryLength}`;\n\n  const rootDir = deserializeIndex(\n    await decompress(rootDirData, header.internalCompression)\n  );\n  return [header, [dirKey, rootDir.length, rootDir]];\n}\n\nasync function getDirectory(\n  source: Source,\n  decompress: DecompressFunc,\n  offset: number,\n  length: number,\n  header: Header\n): Promise<Entry[]> {\n  const resp = await source.getBytes(offset, length, undefined, header.etag);\n  const data = await decompress(resp.data, header.internalCompression);\n  const directory = deserializeIndex(data);\n  if (directory.length === 0) {\n    throw new Error(\"Empty directory is invalid\");\n  }\n\n  return directory;\n}\n\ninterface ResolvedValue {\n  lastUsed: number;\n  data: Header | Entry[] | ArrayBuffer;\n}\n\n/**\n * A cache for parts of a PMTiles archive where promises are never shared between requests.\n *\n * Runtimes such as Cloudflare Workers cannot share promises between different requests.\n *\n * Only caches headers and directories, not individual tile contents.\n */\nexport class ResolvedValueCache {\n  cache: Map<string, ResolvedValue>;\n  maxCacheEntries: number;\n  counter: number;\n  decompress: DecompressFunc;\n\n  constructor(\n    maxCacheEntries = 100,\n    prefetch = true, // deprecated\n    decompress: DecompressFunc = defaultDecompress\n  ) {\n    this.cache = new Map<string, ResolvedValue>();\n    this.maxCacheEntries = maxCacheEntries;\n    this.counter = 1;\n    this.decompress = decompress;\n  }\n\n  async getHeader(source: Source): Promise<Header> {\n    const cacheKey = source.getKey();\n    const cacheValue = this.cache.get(cacheKey);\n    if (cacheValue) {\n      cacheValue.lastUsed = this.counter++;\n      const data = cacheValue.data;\n      return data as Header;\n    }\n\n    const res = await getHeaderAndRoot(source, this.decompress);\n    if (res[1]) {\n      this.cache.set(res[1][0], {\n        lastUsed: this.counter++,\n        data: res[1][2],\n      });\n    }\n\n    this.cache.set(cacheKey, {\n      lastUsed: this.counter++,\n      data: res[0],\n    });\n    this.prune();\n    return res[0];\n  }\n\n  async getDirectory(\n    source: Source,\n    offset: number,\n    length: number,\n    header: Header\n  ): Promise<Entry[]> {\n    const cacheKey = `${source.getKey()}|${\n      header.etag || \"\"\n    }|${offset}|${length}`;\n    const cacheValue = this.cache.get(cacheKey);\n    if (cacheValue) {\n      cacheValue.lastUsed = this.counter++;\n      const data = cacheValue.data;\n      return data as Entry[];\n    }\n\n    const directory = await getDirectory(\n      source,\n      this.decompress,\n      offset,\n      length,\n      header\n    );\n    this.cache.set(cacheKey, {\n      lastUsed: this.counter++,\n      data: directory,\n    });\n    this.prune();\n    return directory;\n  }\n\n  prune() {\n    if (this.cache.size > this.maxCacheEntries) {\n      let minUsed = Infinity;\n      let minKey = undefined;\n      this.cache.forEach((cacheValue: ResolvedValue, key: string) => {\n        if (cacheValue.lastUsed < minUsed) {\n          minUsed = cacheValue.lastUsed;\n          minKey = key;\n        }\n      });\n      if (minKey) {\n        this.cache.delete(minKey);\n      }\n    }\n  }\n\n  async invalidate(source: Source) {\n    this.cache.delete(source.getKey());\n  }\n}\n\ninterface SharedPromiseCacheValue {\n  lastUsed: number;\n  data: Promise<Header | Entry[] | ArrayBuffer>;\n}\n\n/**\n * A cache for parts of a PMTiles archive where promises can be shared between requests.\n *\n * Only caches headers and directories, not individual tile contents.\n */\nexport class SharedPromiseCache {\n  cache: Map<string, SharedPromiseCacheValue>;\n  invalidations: Map<string, Promise<void>>;\n  maxCacheEntries: number;\n  counter: number;\n  decompress: DecompressFunc;\n\n  constructor(\n    maxCacheEntries = 100,\n    prefetch = true, // deprecated\n    decompress: DecompressFunc = defaultDecompress\n  ) {\n    this.cache = new Map<string, SharedPromiseCacheValue>();\n    this.invalidations = new Map<string, Promise<void>>();\n    this.maxCacheEntries = maxCacheEntries;\n    this.counter = 1;\n    this.decompress = decompress;\n  }\n\n  async getHeader(source: Source): Promise<Header> {\n    const cacheKey = source.getKey();\n    const cacheValue = this.cache.get(cacheKey);\n    if (cacheValue) {\n      cacheValue.lastUsed = this.counter++;\n      const data = await cacheValue.data;\n      return data as Header;\n    }\n\n    const p = new Promise<Header>((resolve, reject) => {\n      getHeaderAndRoot(source, this.decompress)\n        .then((res) => {\n          if (res[1]) {\n            this.cache.set(res[1][0], {\n              lastUsed: this.counter++,\n              data: Promise.resolve(res[1][2]),\n            });\n          }\n          resolve(res[0]);\n          this.prune();\n        })\n        .catch((e) => {\n          reject(e);\n        });\n    });\n    this.cache.set(cacheKey, { lastUsed: this.counter++, data: p });\n    return p;\n  }\n\n  async getDirectory(\n    source: Source,\n    offset: number,\n    length: number,\n    header: Header\n  ): Promise<Entry[]> {\n    const cacheKey = `${source.getKey()}|${\n      header.etag || \"\"\n    }|${offset}|${length}`;\n    const cacheValue = this.cache.get(cacheKey);\n    if (cacheValue) {\n      cacheValue.lastUsed = this.counter++;\n      const data = await cacheValue.data;\n      return data as Entry[];\n    }\n\n    const p = new Promise<Entry[]>((resolve, reject) => {\n      getDirectory(source, this.decompress, offset, length, header)\n        .then((directory) => {\n          resolve(directory);\n          this.prune();\n        })\n        .catch((e) => {\n          reject(e);\n        });\n    });\n    this.cache.set(cacheKey, { lastUsed: this.counter++, data: p });\n    return p;\n  }\n\n  prune() {\n    if (this.cache.size >= this.maxCacheEntries) {\n      let minUsed = Infinity;\n      let minKey = undefined;\n      this.cache.forEach((cacheValue: SharedPromiseCacheValue, key: string) => {\n        if (cacheValue.lastUsed < minUsed) {\n          minUsed = cacheValue.lastUsed;\n          minKey = key;\n        }\n      });\n      if (minKey) {\n        this.cache.delete(minKey);\n      }\n    }\n  }\n\n  async invalidate(source: Source) {\n    const key = source.getKey();\n    if (this.invalidations.get(key)) {\n      return await this.invalidations.get(key);\n    }\n    this.cache.delete(source.getKey());\n    const p = new Promise<void>((resolve, reject) => {\n      this.getHeader(source)\n        .then((h) => {\n          resolve();\n          this.invalidations.delete(key);\n        })\n        .catch((e) => {\n          reject(e);\n        });\n    });\n    this.invalidations.set(key, p);\n  }\n}\n\n/**\n * Main class encapsulating PMTiles decoding logic.\n *\n * if `source` is a string, creates a FetchSource using that string as the URL to a remote PMTiles.\n * if no `cache` is passed, use a SharedPromiseCache.\n * if no `decompress` is passed, default to the browser DecompressionStream API with a fallback to `fflate`.\n */\n// biome-ignore lint: that's just how its capitalized\nexport class PMTiles {\n  source: Source;\n  cache: Cache;\n  decompress: DecompressFunc;\n\n  constructor(\n    source: Source | string,\n    cache?: Cache,\n    decompress?: DecompressFunc\n  ) {\n    if (typeof source === \"string\") {\n      this.source = new FetchSource(source);\n    } else {\n      this.source = source;\n    }\n    if (decompress) {\n      this.decompress = decompress;\n    } else {\n      this.decompress = defaultDecompress;\n    }\n    if (cache) {\n      this.cache = cache;\n    } else {\n      this.cache = new SharedPromiseCache();\n    }\n  }\n\n  /**\n   * Return the header of the archive,\n   * including information such as tile type, min/max zoom, bounds, and summary statistics.\n   */\n  async getHeader() {\n    return await this.cache.getHeader(this.source);\n  }\n\n  /** @hidden */\n  async getZxyAttempt(\n    z: number,\n    x: number,\n    y: number,\n    signal?: AbortSignal\n  ): Promise<RangeResponse | undefined> {\n    const tileId = zxyToTileId(z, x, y);\n    const header = await this.cache.getHeader(this.source);\n\n    if (z < header.minZoom || z > header.maxZoom) {\n      return undefined;\n    }\n\n    let dO = header.rootDirectoryOffset;\n    let dL = header.rootDirectoryLength;\n    for (let depth = 0; depth <= 3; depth++) {\n      const directory = await this.cache.getDirectory(\n        this.source,\n        dO,\n        dL,\n        header\n      );\n      const entry = findTile(directory, tileId);\n      if (entry) {\n        if (entry.runLength > 0) {\n          const resp = await this.source.getBytes(\n            header.tileDataOffset + entry.offset,\n            entry.length,\n            signal,\n            header.etag\n          );\n          return {\n            data: await this.decompress(resp.data, header.tileCompression),\n            cacheControl: resp.cacheControl,\n            expires: resp.expires,\n          };\n        }\n        dO = header.leafDirectoryOffset + entry.offset;\n        dL = entry.length;\n      } else {\n        // TODO: We should in fact return a valid RangeResponse\n        // with empty data, but filled in cache control / expires headers\n        return undefined;\n      }\n    }\n    throw new Error(\"Maximum directory depth exceeded\");\n  }\n\n  /**\n   * Primary method to get a single tile's bytes from an archive.\n   *\n   * Returns undefined if the tile does not exist in the archive.\n   */\n  async getZxy(\n    z: number,\n    x: number,\n    y: number,\n    signal?: AbortSignal\n  ): Promise<RangeResponse | undefined> {\n    try {\n      return await this.getZxyAttempt(z, x, y, signal);\n    } catch (e) {\n      if (e instanceof EtagMismatch) {\n        this.cache.invalidate(this.source);\n        return await this.getZxyAttempt(z, x, y, signal);\n      }\n      throw e;\n    }\n  }\n\n  /** @hidden */\n  async getMetadataAttempt(): Promise<unknown> {\n    const header = await this.cache.getHeader(this.source);\n\n    const resp = await this.source.getBytes(\n      header.jsonMetadataOffset,\n      header.jsonMetadataLength,\n      undefined,\n      header.etag\n    );\n    const decompressed = await this.decompress(\n      resp.data,\n      header.internalCompression\n    );\n    const dec = new TextDecoder(\"utf-8\");\n    return JSON.parse(dec.decode(decompressed));\n  }\n\n  /**\n   * Return the arbitrary JSON metadata of the archive.\n   */\n  async getMetadata(): Promise<unknown> {\n    try {\n      return await this.getMetadataAttempt();\n    } catch (e) {\n      if (e instanceof EtagMismatch) {\n        this.cache.invalidate(this.source);\n        return await this.getMetadataAttempt();\n      }\n      throw e;\n    }\n  }\n\n  /**\n   * Construct a [TileJSON](https://github.com/mapbox/tilejson-spec) object.\n   *\n   * baseTilesUrl is the desired tiles URL, excluding the suffix `/{z}/{x}/{y}.{ext}`.\n   * For example, if the desired URL is `http://example.com/tileset/{z}/{x}/{y}.mvt`,\n   * the baseTilesUrl should be `https://example.com/tileset`.\n   */\n  async getTileJson(baseTilesUrl: string): Promise<unknown> {\n    const header = await this.getHeader();\n    const metadata = (await this.getMetadata()) as MetadataLike;\n    const ext = tileTypeExt(header.tileType);\n\n    return {\n      tilejson: \"3.0.0\",\n      scheme: \"xyz\",\n      tiles: [`${baseTilesUrl}/{z}/{x}/{y}${ext}`],\n      // biome-ignore lint: TileJSON spec\n      vector_layers: metadata.vector_layers,\n      attribution: metadata.attribution,\n      description: metadata.description,\n      name: metadata.name,\n      version: metadata.version,\n      bounds: [header.minLon, header.minLat, header.maxLon, header.maxLat],\n      center: [header.centerLon, header.centerLat, header.centerZoom],\n      minzoom: header.minZoom,\n      maxzoom: header.maxZoom,\n    };\n  }\n}\n","// DEFLATE is a complex format; to read this code, you should probably check the RFC first:\n// https://tools.ietf.org/html/rfc1951\n// You may also wish to take a look at the guide I made about this program:\n// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad\n// Some of the following code is similar to that of UZIP.js:\n// https://github.com/photopea/UZIP.js\n// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size.\n// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint\n// is better for memory in most engines (I *think*).\nvar ch2 = {};\nvar wk = (function (c, id, msg, transfer, cb) {\n    var w = new Worker(ch2[id] || (ch2[id] = URL.createObjectURL(new Blob([\n        c + ';addEventListener(\"error\",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'\n    ], { type: 'text/javascript' }))));\n    w.onmessage = function (e) {\n        var d = e.data, ed = d.$e$;\n        if (ed) {\n            var err = new Error(ed[0]);\n            err['code'] = ed[1];\n            err.stack = ed[2];\n            cb(err, null);\n        }\n        else\n            cb(null, d);\n    };\n    w.postMessage(msg, transfer);\n    return w;\n});\n\n// aliases for shorter compressed code (most minifers don't do this)\nvar u8 = Uint8Array, u16 = Uint16Array, i32 = Int32Array;\n// fixed length extra bits\nvar fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]);\n// fixed distance extra bits\nvar fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]);\n// code length index map\nvar clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);\n// get base, reverse index map from extra bits\nvar freb = function (eb, start) {\n    var b = new u16(31);\n    for (var i = 0; i < 31; ++i) {\n        b[i] = start += 1 << eb[i - 1];\n    }\n    // numbers here are at max 18 bits\n    var r = new i32(b[30]);\n    for (var i = 1; i < 30; ++i) {\n        for (var j = b[i]; j < b[i + 1]; ++j) {\n            r[j] = ((j - b[i]) << 5) | i;\n        }\n    }\n    return { b: b, r: r };\n};\nvar _a = freb(fleb, 2), fl = _a.b, revfl = _a.r;\n// we can ignore the fact that the other numbers are wrong; they never happen anyway\nfl[28] = 258, revfl[258] = 28;\nvar _b = freb(fdeb, 0), fd = _b.b, revfd = _b.r;\n// map of value to reverse (assuming 16 bits)\nvar rev = new u16(32768);\nfor (var i = 0; i < 32768; ++i) {\n    // reverse table algorithm from SO\n    var x = ((i & 0xAAAA) >> 1) | ((i & 0x5555) << 1);\n    x = ((x & 0xCCCC) >> 2) | ((x & 0x3333) << 2);\n    x = ((x & 0xF0F0) >> 4) | ((x & 0x0F0F) << 4);\n    rev[i] = (((x & 0xFF00) >> 8) | ((x & 0x00FF) << 8)) >> 1;\n}\n// create huffman tree from u8 \"map\": index -> code length for code index\n// mb (max bits) must be at most 15\n// TODO: optimize/split up?\nvar hMap = (function (cd, mb, r) {\n    var s = cd.length;\n    // index\n    var i = 0;\n    // u16 \"map\": index -> # of codes with bit length = index\n    var l = new u16(mb);\n    // length of cd must be 288 (total # of codes)\n    for (; i < s; ++i) {\n        if (cd[i])\n            ++l[cd[i] - 1];\n    }\n    // u16 \"map\": index -> minimum code for bit length = index\n    var le = new u16(mb);\n    for (i = 1; i < mb; ++i) {\n        le[i] = (le[i - 1] + l[i - 1]) << 1;\n    }\n    var co;\n    if (r) {\n        // u16 \"map\": index -> number of actual bits, symbol for code\n        co = new u16(1 << mb);\n        // bits to remove for reverser\n        var rvb = 15 - mb;\n        for (i = 0; i < s; ++i) {\n            // ignore 0 lengths\n            if (cd[i]) {\n                // num encoding both symbol and bits read\n                var sv = (i << 4) | cd[i];\n                // free bits\n                var r_1 = mb - cd[i];\n                // start value\n                var v = le[cd[i] - 1]++ << r_1;\n                // m is end value\n                for (var m = v | ((1 << r_1) - 1); v <= m; ++v) {\n                    // every 16 bit value starting with the code yields the same result\n                    co[rev[v] >> rvb] = sv;\n                }\n            }\n        }\n    }\n    else {\n        co = new u16(s);\n        for (i = 0; i < s; ++i) {\n            if (cd[i]) {\n                co[i] = rev[le[cd[i] - 1]++] >> (15 - cd[i]);\n            }\n        }\n    }\n    return co;\n});\n// fixed length tree\nvar flt = new u8(288);\nfor (var i = 0; i < 144; ++i)\n    flt[i] = 8;\nfor (var i = 144; i < 256; ++i)\n    flt[i] = 9;\nfor (var i = 256; i < 280; ++i)\n    flt[i] = 7;\nfor (var i = 280; i < 288; ++i)\n    flt[i] = 8;\n// fixed distance tree\nvar fdt = new u8(32);\nfor (var i = 0; i < 32; ++i)\n    fdt[i] = 5;\n// fixed length map\nvar flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1);\n// fixed distance map\nvar fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);\n// find max of array\nvar max = function (a) {\n    var m = a[0];\n    for (var i = 1; i < a.length; ++i) {\n        if (a[i] > m)\n            m = a[i];\n    }\n    return m;\n};\n// read d, starting at bit p and mask with m\nvar bits = function (d, p, m) {\n    var o = (p / 8) | 0;\n    return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m;\n};\n// read d, starting at bit p continuing for at least 16 bits\nvar bits16 = function (d, p) {\n    var o = (p / 8) | 0;\n    return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7));\n};\n// get end of byte\nvar shft = function (p) { return ((p + 7) / 8) | 0; };\n// typed array slice - allows garbage collector to free original reference,\n// while being more compatible than .slice\nvar slc = function (v, s, e) {\n    if (s == null || s < 0)\n        s = 0;\n    if (e == null || e > v.length)\n        e = v.length;\n    // can't use .constructor in case user-supplied\n    return new u8(v.subarray(s, e));\n};\n/**\n * Codes for errors generated within this library\n */\nexport var FlateErrorCode = {\n    UnexpectedEOF: 0,\n    InvalidBlockType: 1,\n    InvalidLengthLiteral: 2,\n    InvalidDistance: 3,\n    StreamFinished: 4,\n    NoStreamHandler: 5,\n    InvalidHeader: 6,\n    NoCallback: 7,\n    InvalidUTF8: 8,\n    ExtraFieldTooLong: 9,\n    InvalidDate: 10,\n    FilenameTooLong: 11,\n    StreamFinishing: 12,\n    InvalidZipData: 13,\n    UnknownCompressionMethod: 14\n};\n// error codes\nvar ec = [\n    'unexpected EOF',\n    'invalid block type',\n    'invalid length/literal',\n    'invalid distance',\n    'stream finished',\n    'no stream handler',\n    ,\n    'no callback',\n    'invalid UTF-8 data',\n    'extra field too long',\n    'date not in range 1980-2099',\n    'filename too long',\n    'stream finishing',\n    'invalid zip data'\n    // determined by unknown compression method\n];\n;\nvar err = function (ind, msg, nt) {\n    var e = new Error(msg || ec[ind]);\n    e.code = ind;\n    if (Error.captureStackTrace)\n        Error.captureStackTrace(e, err);\n    if (!nt)\n        throw e;\n    return e;\n};\n// expands raw DEFLATE data\nvar inflt = function (dat, st, buf, dict) {\n    // source length       dict length\n    var sl = dat.length, dl = dict ? dict.length : 0;\n    if (!sl || st.f && !st.l)\n        return buf || new u8(0);\n    var noBuf = !buf;\n    // have to estimate size\n    var resize = noBuf || st.i != 2;\n    // no state\n    var noSt = st.i;\n    // Assumes roughly 33% compression ratio average\n    if (noBuf)\n        buf = new u8(sl * 3);\n    // ensure buffer can fit at least l elements\n    var cbuf = function (l) {\n        var bl = buf.length;\n        // need to increase size to fit\n        if (l > bl) {\n            // Double or set to necessary, whichever is greater\n            var nbuf = new u8(Math.max(bl * 2, l));\n            nbuf.set(buf);\n            buf = nbuf;\n        }\n    };\n    //  last chunk         bitpos           bytes\n    var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;\n    // total bits\n    var tbts = sl * 8;\n    do {\n        if (!lm) {\n            // BFINAL - this is only 1 when last chunk is next\n            final = bits(dat, pos, 1);\n            // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman\n            var type = bits(dat, pos + 1, 3);\n            pos += 3;\n            if (!type) {\n                // go to end of byte boundary\n                var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;\n                if (t > sl) {\n                    if (noSt)\n                        err(0);\n                    break;\n                }\n                // ensure size\n                if (resize)\n                    cbuf(bt + l);\n                // Copy over uncompressed data\n                buf.set(dat.subarray(s, t), bt);\n                // Get new bitpos, update byte count\n                st.b = bt += l, st.p = pos = t * 8, st.f = final;\n                continue;\n            }\n            else if (type == 1)\n                lm = flrm, dm = fdrm, lbt = 9, dbt = 5;\n            else if (type == 2) {\n                //  literal                            lengths\n                var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;\n                var tl = hLit + bits(dat, pos + 5, 31) + 1;\n                pos += 14;\n                // length+distance tree\n                var ldt = new u8(tl);\n                // code length tree\n                var clt = new u8(19);\n                for (var i = 0; i < hcLen; ++i) {\n                    // use index map to get real code\n                    clt[clim[i]] = bits(dat, pos + i * 3, 7);\n                }\n                pos += hcLen * 3;\n                // code lengths bits\n                var clb = max(clt), clbmsk = (1 << clb) - 1;\n                // code lengths map\n                var clm = hMap(clt, clb, 1);\n                for (var i = 0; i < tl;) {\n                    var r = clm[bits(dat, pos, clbmsk)];\n                    // bits read\n                    pos += r & 15;\n                    // symbol\n                    var s = r >> 4;\n                    // code length to copy\n                    if (s < 16) {\n                        ldt[i++] = s;\n                    }\n                    else {\n                        //  copy   count\n                        var c = 0, n = 0;\n                        if (s == 16)\n                            n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];\n                        else if (s == 17)\n                            n = 3 + bits(dat, pos, 7), pos += 3;\n                        else if (s == 18)\n                            n = 11 + bits(dat, pos, 127), pos += 7;\n                        while (n--)\n                            ldt[i++] = c;\n                    }\n                }\n                //    length tree                 distance tree\n                var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);\n                // max length bits\n                lbt = max(lt);\n                // max dist bits\n                dbt = max(dt);\n                lm = hMap(lt, lbt, 1);\n                dm = hMap(dt, dbt, 1);\n            }\n            else\n                err(1);\n            if (pos > tbts) {\n                if (noSt)\n                    err(0);\n                break;\n            }\n        }\n        // Make sure the buffer can hold this + the largest possible addition\n        // Maximum chunk size (practically, theoretically infinite) is 2^17\n        if (resize)\n            cbuf(bt + 131072);\n        var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;\n        var lpos = pos;\n        for (;; lpos = pos) {\n            // bits read, code\n            var c = lm[bits16(dat, pos) & lms], sym = c >> 4;\n            pos += c & 15;\n            if (pos > tbts) {\n                if (noSt)\n                    err(0);\n                break;\n            }\n            if (!c)\n                err(2);\n            if (sym < 256)\n                buf[bt++] = sym;\n            else if (sym == 256) {\n                lpos = pos, lm = null;\n                break;\n            }\n            else {\n                var add = sym - 254;\n                // no extra bits needed if less\n                if (sym > 264) {\n                    // index\n                    var i = sym - 257, b = fleb[i];\n                    add = bits(dat, pos, (1 << b) - 1) + fl[i];\n                    pos += b;\n                }\n                // dist\n                var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;\n                if (!d)\n                    err(3);\n                pos += d & 15;\n                var dt = fd[dsym];\n                if (dsym > 3) {\n                    var b = fdeb[dsym];\n                    dt += bits16(dat, pos) & (1 << b) - 1, pos += b;\n                }\n                if (pos > tbts) {\n                    if (noSt)\n                        err(0);\n                    break;\n                }\n                if (resize)\n                    cbuf(bt + 131072);\n                var end = bt + add;\n                if (bt < dt) {\n                    var shift = dl - dt, dend = Math.min(dt, end);\n                    if (shift + bt < 0)\n                        err(3);\n                    for (; bt < dend; ++bt)\n                        buf[bt] = dict[shift + bt];\n                }\n                for (; bt < end; ++bt)\n                    buf[bt] = buf[bt - dt];\n            }\n        }\n        st.l = lm, st.p = lpos, st.b = bt, st.f = final;\n        if (lm)\n            final = 1, st.m = lbt, st.d = dm, st.n = dbt;\n    } while (!final);\n    // don't reallocate for streams or user buffers\n    return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);\n};\n// starting at p, write the minimum number of bits that can hold v to d\nvar wbits = function (d, p, v) {\n    v <<= p & 7;\n    var o = (p / 8) | 0;\n    d[o] |= v;\n    d[o + 1] |= v >> 8;\n};\n// starting at p, write the minimum number of bits (>8) that can hold v to d\nvar wbits16 = function (d, p, v) {\n    v <<= p & 7;\n    var o = (p / 8) | 0;\n    d[o] |= v;\n    d[o + 1] |= v >> 8;\n    d[o + 2] |= v >> 16;\n};\n// creates code lengths from a frequency table\nvar hTree = function (d, mb) {\n    // Need extra info to make a tree\n    var t = [];\n    for (var i = 0; i < d.length; ++i) {\n        if (d[i])\n            t.push({ s: i, f: d[i] });\n    }\n    var s = t.length;\n    var t2 = t.slice();\n    if (!s)\n        return { t: et, l: 0 };\n    if (s == 1) {\n        var v = new u8(t[0].s + 1);\n        v[t[0].s] = 1;\n        return { t: v, l: 1 };\n    }\n    t.sort(function (a, b) { return a.f - b.f; });\n    // after i2 reaches last ind, will be stopped\n    // freq must be greater than largest possible number of symbols\n    t.push({ s: -1, f: 25001 });\n    var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;\n    t[0] = { s: -1, f: l.f + r.f, l: l, r: r };\n    // efficient algorithm from UZIP.js\n    // i0 is lookbehind, i2 is lookahead - after processing two low-freq\n    // symbols that combined have high freq, will start processing i2 (high-freq,\n    // non-composite) symbols instead\n    // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/\n    while (i1 != s - 1) {\n        l = t[t[i0].f < t[i2].f ? i0++ : i2++];\n        r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];\n        t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r };\n    }\n    var maxSym = t2[0].s;\n    for (var i = 1; i < s; ++i) {\n        if (t2[i].s > maxSym)\n            maxSym = t2[i].s;\n    }\n    // code lengths\n    var tr = new u16(maxSym + 1);\n    // max bits in tree\n    var mbt = ln(t[i1 - 1], tr, 0);\n    if (mbt > mb) {\n        // more algorithms from UZIP.js\n        // TODO: find out how this code works (debt)\n        //  ind    debt\n        var i = 0, dt = 0;\n        //    left            cost\n        var lft = mbt - mb, cst = 1 << lft;\n        t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; });\n        for (; i < s; ++i) {\n            var i2_1 = t2[i].s;\n            if (tr[i2_1] > mb) {\n                dt += cst - (1 << (mbt - tr[i2_1]));\n                tr[i2_1] = mb;\n            }\n            else\n                break;\n        }\n        dt >>= lft;\n        while (dt > 0) {\n            var i2_2 = t2[i].s;\n            if (tr[i2_2] < mb)\n                dt -= 1 << (mb - tr[i2_2]++ - 1);\n            else\n                ++i;\n        }\n        for (; i >= 0 && dt; --i) {\n            var i2_3 = t2[i].s;\n            if (tr[i2_3] == mb) {\n                --tr[i2_3];\n                ++dt;\n            }\n        }\n        mbt = mb;\n    }\n    return { t: new u8(tr), l: mbt };\n};\n// get the max length and assign length codes\nvar ln = function (n, l, d) {\n    return n.s == -1\n        ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1))\n        : (l[n.s] = d);\n};\n// length codes generation\nvar lc = function (c) {\n    var s = c.length;\n    // Note that the semicolon was intentional\n    while (s && !c[--s])\n        ;\n    var cl = new u16(++s);\n    //  ind      num         streak\n    var cli = 0, cln = c[0], cls = 1;\n    var w = function (v) { cl[cli++] = v; };\n    for (var i = 1; i <= s; ++i) {\n        if (c[i] == cln && i != s)\n            ++cls;\n        else {\n            if (!cln && cls > 2) {\n                for (; cls > 138; cls -= 138)\n                    w(32754);\n                if (cls > 2) {\n                    w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305);\n                    cls = 0;\n                }\n            }\n            else if (cls > 3) {\n                w(cln), --cls;\n                for (; cls > 6; cls -= 6)\n                    w(8304);\n                if (cls > 2)\n                    w(((cls - 3) << 5) | 8208), cls = 0;\n            }\n            while (cls--)\n                w(cln);\n            cls = 1;\n            cln = c[i];\n        }\n    }\n    return { c: cl.subarray(0, cli), n: s };\n};\n// calculate the length of output from tree, code lengths\nvar clen = function (cf, cl) {\n    var l = 0;\n    for (var i = 0; i < cl.length; ++i)\n        l += cf[i] * cl[i];\n    return l;\n};\n// writes a fixed block\n// returns the new bit pos\nvar wfblk = function (out, pos, dat) {\n    // no need to write 00 as type: TypedArray defaults to 0\n    var s = dat.length;\n    var o = shft(pos + 2);\n    out[o] = s & 255;\n    out[o + 1] = s >> 8;\n    out[o + 2] = out[o] ^ 255;\n    out[o + 3] = out[o + 1] ^ 255;\n    for (var i = 0; i < s; ++i)\n        out[o + i + 4] = dat[i];\n    return (o + 4 + s) * 8;\n};\n// writes a block\nvar wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) {\n    wbits(out, p++, final);\n    ++lf[256];\n    var _a = hTree(lf, 15), dlt = _a.t, mlb = _a.l;\n    var _b = hTree(df, 15), ddt = _b.t, mdb = _b.l;\n    var _c = lc(dlt), lclt = _c.c, nlc = _c.n;\n    var _d = lc(ddt), lcdt = _d.c, ndc = _d.n;\n    var lcfreq = new u16(19);\n    for (var i = 0; i < lclt.length; ++i)\n        ++lcfreq[lclt[i] & 31];\n    for (var i = 0; i < lcdt.length; ++i)\n        ++lcfreq[lcdt[i] & 31];\n    var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l;\n    var nlcc = 19;\n    for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)\n        ;\n    var flen = (bl + 5) << 3;\n    var ftlen = clen(lf, flt) + clen(df, fdt) + eb;\n    var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18];\n    if (bs >= 0 && flen <= ftlen && flen <= dtlen)\n        return wfblk(out, p, dat.subarray(bs, bs + bl));\n    var lm, ll, dm, dl;\n    wbits(out, p, 1 + (dtlen < ftlen)), p += 2;\n    if (dtlen < ftlen) {\n        lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;\n        var llm = hMap(lct, mlcb, 0);\n        wbits(out, p, nlc - 257);\n        wbits(out, p + 5, ndc - 1);\n        wbits(out, p + 10, nlcc - 4);\n        p += 14;\n        for (var i = 0; i < nlcc; ++i)\n            wbits(out, p + 3 * i, lct[clim[i]]);\n        p += 3 * nlcc;\n        var lcts = [lclt, lcdt];\n        for (var it = 0; it < 2; ++it) {\n            var clct = lcts[it];\n            for (var i = 0; i < clct.length; ++i) {\n                var len = clct[i] & 31;\n                wbits(out, p, llm[len]), p += lct[len];\n                if (len > 15)\n                    wbits(out, p, (clct[i] >> 5) & 127), p += clct[i] >> 12;\n            }\n        }\n    }\n    else {\n        lm = flm, ll = flt, dm = fdm, dl = fdt;\n    }\n    for (var i = 0; i < li; ++i) {\n        var sym = syms[i];\n        if (sym > 255) {\n            var len = (sym >> 18) & 31;\n            wbits16(out, p, lm[len + 257]), p += ll[len + 257];\n            if (len > 7)\n                wbits(out, p, (sym >> 23) & 31), p += fleb[len];\n            var dst = sym & 31;\n            wbits16(out, p, dm[dst]), p += dl[dst];\n            if (dst > 3)\n                wbits16(out, p, (sym >> 5) & 8191), p += fdeb[dst];\n        }\n        else {\n            wbits16(out, p, lm[sym]), p += ll[sym];\n        }\n    }\n    wbits16(out, p, lm[256]);\n    return p + ll[256];\n};\n// deflate options (nice << 13) | chain\nvar deo = /*#__PURE__*/ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);\n// empty\nvar et = /*#__PURE__*/ new u8(0);\n// compresses data into a raw DEFLATE buffer\nvar dflt = function (dat, lvl, plvl, pre, post, st) {\n    var s = st.z || dat.length;\n    var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post);\n    // writing to this writes to the output buffer\n    var w = o.subarray(pre, o.length - post);\n    var lst = st.l;\n    var pos = (st.r || 0) & 7;\n    if (lvl) {\n        if (pos)\n            w[0] = st.r >> 3;\n        var opt = deo[lvl - 1];\n        var n = opt >> 13, c = opt & 8191;\n        var msk_1 = (1 << plvl) - 1;\n        //    prev 2-byte val map    curr 2-byte val map\n        var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1);\n        var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;\n        var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; };\n        // 24576 is an arbitrary number of maximum symbols per block\n        // 424 buffer for last block\n        var syms = new i32(25000);\n        // length/literal freq   distance freq\n        var lf = new u16(288), df = new u16(32);\n        //  l/lcnt  exbits  index          l/lind  waitdx          blkpos\n        var lc_1 = 0, eb = 0, i = st.i || 0, li = 0, wi = st.w || 0, bs = 0;\n        for (; i + 2 < s; ++i) {\n            // hash value\n            var hv = hsh(i);\n            // index mod 32768    previous index mod\n            var imod = i & 32767, pimod = head[hv];\n            prev[imod] = pimod;\n            head[hv] = imod;\n            // We always should modify head and prev, but only add symbols if\n            // this data is not yet processed (\"wait\" for wait index)\n            if (wi <= i) {\n                // bytes remaining\n                var rem = s - i;\n                if ((lc_1 > 7000 || li > 24576) && (rem > 423 || !lst)) {\n                    pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);\n                    li = lc_1 = eb = 0, bs = i;\n                    for (var j = 0; j < 286; ++j)\n                        lf[j] = 0;\n                    for (var j = 0; j < 30; ++j)\n                        df[j] = 0;\n                }\n                //  len    dist   chain\n                var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767;\n                if (rem > 2 && hv == hsh(i - dif)) {\n                    var maxn = Math.min(n, rem) - 1;\n                    var maxd = Math.min(32767, i);\n                    // max possible length\n                    // not capped at dif because decompressors implement \"rolling\" index population\n                    var ml = Math.min(258, rem);\n                    while (dif <= maxd && --ch_1 && imod != pimod) {\n                        if (dat[i + l] == dat[i + l - dif]) {\n                            var nl = 0;\n                            for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)\n                                ;\n                            if (nl > l) {\n                                l = nl, d = dif;\n                                // break out early when we reach \"nice\" (we are satisfied enough)\n                                if (nl > maxn)\n                                    break;\n                                // now, find the rarest 2-byte sequence within this\n                                // length of literals and search for that instead.\n                                // Much faster than just using the start\n                                var mmd = Math.min(dif, nl - 2);\n                                var md = 0;\n                                for (var j = 0; j < mmd; ++j) {\n                                    var ti = i - dif + j & 32767;\n                                    var pti = prev[ti];\n                                    var cd = ti - pti & 32767;\n                                    if (cd > md)\n                                        md = cd, pimod = ti;\n                                }\n                            }\n                        }\n                        // check the previous match\n                        imod = pimod, pimod = prev[imod];\n                        dif += imod - pimod & 32767;\n                    }\n                }\n                // d will be nonzero only when a match was found\n                if (d) {\n                    // store both dist and len data in one int32\n                    // Make sure this is recognized as a len/dist with 28th bit (2^28)\n                    syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d];\n                    var lin = revfl[l] & 31, din = revfd[d] & 31;\n                    eb += fleb[lin] + fdeb[din];\n                    ++lf[257 + lin];\n                    ++df[din];\n                    wi = i + l;\n                    ++lc_1;\n                }\n                else {\n                    syms[li++] = dat[i];\n                    ++lf[dat[i]];\n                }\n            }\n        }\n        for (i = Math.max(i, wi); i < s; ++i) {\n            syms[li++] = dat[i];\n            ++lf[dat[i]];\n        }\n        pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);\n        if (!lst) {\n            st.r = (pos & 7) | w[(pos / 8) | 0] << 3;\n            // shft(pos) now 1 less if pos & 7 != 0\n            pos -= 7;\n            st.h = head, st.p = prev, st.i = i, st.w = wi;\n        }\n    }\n    else {\n        for (var i = st.w || 0; i < s + lst; i += 65535) {\n            // end\n            var e = i + 65535;\n            if (e >= s) {\n                // write final block\n                w[(pos / 8) | 0] = lst;\n                e = s;\n            }\n            pos = wfblk(w, pos + 1, dat.subarray(i, e));\n        }\n        st.i = s;\n    }\n    return slc(o, 0, pre + shft(pos) + post);\n};\n// CRC32 table\nvar crct = /*#__PURE__*/ (function () {\n    var t = new Int32Array(256);\n    for (var i = 0; i < 256; ++i) {\n        var c = i, k = 9;\n        while (--k)\n            c = ((c & 1) && -306674912) ^ (c >>> 1);\n        t[i] = c;\n    }\n    return t;\n})();\n// CRC32\nvar crc = function () {\n    var c = -1;\n    return {\n        p: function (d) {\n            // closures have awful performance\n            var cr = c;\n            for (var i = 0; i < d.length; ++i)\n                cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8);\n            c = cr;\n        },\n        d: function () { return ~c; }\n    };\n};\n// Adler32\nvar adler = function () {\n    var a = 1, b = 0;\n    return {\n        p: function (d) {\n            // closures have awful performance\n            var n = a, m = b;\n            var l = d.length | 0;\n            for (var i = 0; i != l;) {\n                var e = Math.min(i + 2655, l);\n                for (; i < e; ++i)\n                    m += n += d[i];\n                n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16);\n            }\n            a = n, b = m;\n        },\n        d: function () {\n            a %= 65521, b %= 65521;\n            return (a & 255) << 24 | (a & 0xFF00) << 8 | (b & 255) << 8 | (b >> 8);\n        }\n    };\n};\n;\n// deflate with opts\nvar dopt = function (dat, opt, pre, post, st) {\n    if (!st) {\n        st = { l: 1 };\n        if (opt.dictionary) {\n            var dict = opt.dictionary.subarray(-32768);\n            var newDat = new u8(dict.length + dat.length);\n            newDat.set(dict);\n            newDat.set(dat, dict.length);\n            dat = newDat;\n            st.w = dict.length;\n        }\n    }\n    return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? (st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20) : (12 + opt.mem), pre, post, st);\n};\n// Walmart object spread\nvar mrg = function (a, b) {\n    var o = {};\n    for (var k in a)\n        o[k] = a[k];\n    for (var k in b)\n        o[k] = b[k];\n    return o;\n};\n// worker clone\n// This is possibly the craziest part of the entire codebase, despite how simple it may seem.\n// The only parameter to this function is a closure that returns an array of variables outside of the function scope.\n// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization.\n// We will return an object mapping of true variable name to value (basically, the current scope as a JS object).\n// The reason we can't just use the original variable names is minifiers mangling the toplevel scope.\n// This took me three weeks to figure out how to do.\nvar wcln = function (fn, fnStr, td) {\n    var dt = fn();\n    var st = fn.toString();\n    var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/\\s+/g, '').split(',');\n    for (var i = 0; i < dt.length; ++i) {\n        var v = dt[i], k = ks[i];\n        if (typeof v == 'function') {\n            fnStr += ';' + k + '=';\n            var st_1 = v.toString();\n            if (v.prototype) {\n                // for global objects\n                if (st_1.indexOf('[native code]') != -1) {\n                    var spInd = st_1.indexOf(' ', 8) + 1;\n                    fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd));\n                }\n                else {\n                    fnStr += st_1;\n                    for (var t in v.prototype)\n                        fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString();\n                }\n            }\n            else\n                fnStr += st_1;\n        }\n        else\n            td[k] = v;\n    }\n    return fnStr;\n};\nvar ch = [];\n// clone bufs\nvar cbfs = function (v) {\n    var tl = [];\n    for (var k in v) {\n        if (v[k].buffer) {\n            tl.push((v[k] = new v[k].constructor(v[k])).buffer);\n        }\n    }\n    return tl;\n};\n// use a worker to execute code\nvar wrkr = function (fns, init, id, cb) {\n    if (!ch[id]) {\n        var fnStr = '', td_1 = {}, m = fns.length - 1;\n        for (var i = 0; i < m; ++i)\n            fnStr = wcln(fns[i], fnStr, td_1);\n        ch[id] = { c: wcln(fns[m], fnStr, td_1), e: td_1 };\n    }\n    var td = mrg({}, ch[id].e);\n    return wk(ch[id].c + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb);\n};\n// base async inflate fn\nvar bInflt = function () { return [u8, u16, i32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gopt]; };\nvar bDflt = function () { return [u8, u16, i32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; };\n// gzip extra\nvar gze = function () { return [gzh, gzhl, wbytes, crc, crct]; };\n// gunzip extra\nvar guze = function () { return [gzs, gzl]; };\n// zlib extra\nvar zle = function () { return [zlh, wbytes, adler]; };\n// unzlib extra\nvar zule = function () { return [zls]; };\n// post buf\nvar pbf = function (msg) { return postMessage(msg, [msg.buffer]); };\n// get opts\nvar gopt = function (o) { return o && {\n    out: o.size && new u8(o.size),\n    dictionary: o.dictionary\n}; };\n// async helper\nvar cbify = function (dat, opts, fns, init, id, cb) {\n    var w = wrkr(fns, init, id, function (err, dat) {\n        w.terminate();\n        cb(err, dat);\n    });\n    w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []);\n    return function () { w.terminate(); };\n};\n// auto stream\nvar astrm = function (strm) {\n    strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); };\n    return function (ev) {\n        if (ev.data.length) {\n            strm.push(ev.data[0], ev.data[1]);\n            postMessage([ev.data[0].length]);\n        }\n        else\n            strm.flush();\n    };\n};\n// async stream attach\nvar astrmify = function (fns, strm, opts, init, id, flush, ext) {\n    var t;\n    var w = wrkr(fns, init, id, function (err, dat) {\n        if (err)\n            w.terminate(), strm.ondata.call(strm, err);\n        else if (!Array.isArray(dat))\n            ext(dat);\n        else if (dat.length == 1) {\n            strm.queuedSize -= dat[0];\n            if (strm.ondrain)\n                strm.ondrain(dat[0]);\n        }\n        else {\n            if (dat[1])\n                w.terminate();\n            strm.ondata.call(strm, err, dat[0], dat[1]);\n        }\n    });\n    w.postMessage(opts);\n    strm.queuedSize = 0;\n    strm.push = function (d, f) {\n        if (!strm.ondata)\n            err(5);\n        if (t)\n            strm.ondata(err(4, 0, 1), null, !!f);\n        strm.queuedSize += d.length;\n        w.postMessage([d, t = f], [d.buffer]);\n    };\n    strm.terminate = function () { w.terminate(); };\n    if (flush) {\n        strm.flush = function () { w.postMessage([]); };\n    }\n};\n// read 2 bytes\nvar b2 = function (d, b) { return d[b] | (d[b + 1] << 8); };\n// read 4 bytes\nvar b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; };\nvar b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); };\n// write bytes\nvar wbytes = function (d, b, v) {\n    for (; v; ++b)\n        d[b] = v, v >>>= 8;\n};\n// gzip header\nvar gzh = function (c, o) {\n    var fn = o.filename;\n    c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix\n    if (o.mtime != 0)\n        wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000));\n    if (fn) {\n        c[3] = 8;\n        for (var i = 0; i <= fn.length; ++i)\n            c[i + 10] = fn.charCodeAt(i);\n    }\n};\n// gzip footer: -8 to -4 = CRC, -4 to -0 is length\n// gzip start\nvar gzs = function (d) {\n    if (d[0] != 31 || d[1] != 139 || d[2] != 8)\n        err(6, 'invalid gzip data');\n    var flg = d[3];\n    var st = 10;\n    if (flg & 4)\n        st += (d[10] | d[11] << 8) + 2;\n    for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])\n        ;\n    return st + (flg & 2);\n};\n// gzip length\nvar gzl = function (d) {\n    var l = d.length;\n    return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16 | d[l - 1] << 24) >>> 0;\n};\n// gzip header length\nvar gzhl = function (o) { return 10 + (o.filename ? o.filename.length + 1 : 0); };\n// zlib header\nvar zlh = function (c, o) {\n    var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;\n    c[0] = 120, c[1] = (fl << 6) | (o.dictionary && 32);\n    c[1] |= 31 - ((c[0] << 8) | c[1]) % 31;\n    if (o.dictionary) {\n        var h = adler();\n        h.p(o.dictionary);\n        wbytes(c, 2, h.d());\n    }\n};\n// zlib start\nvar zls = function (d, dict) {\n    if ((d[0] & 15) != 8 || (d[0] >> 4) > 7 || ((d[0] << 8 | d[1]) % 31))\n        err(6, 'invalid zlib data');\n    if ((d[1] >> 5 & 1) == +!dict)\n        err(6, 'invalid zlib data: ' + (d[1] & 32 ? 'need' : 'unexpected') + ' dictionary');\n    return (d[1] >> 3 & 4) + 2;\n};\nfunction StrmOpt(opts, cb) {\n    if (typeof opts == 'function')\n        cb = opts, opts = {};\n    this.ondata = cb;\n    return opts;\n}\n/**\n * Streaming DEFLATE compression\n */\nvar Deflate = /*#__PURE__*/ (function () {\n    function Deflate(opts, cb) {\n        if (typeof opts == 'function')\n            cb = opts, opts = {};\n        this.ondata = cb;\n        this.o = opts || {};\n        this.s = { l: 0, i: 32768, w: 32768, z: 32768 };\n        // Buffer length must always be 0 mod 32768 for index calculations to be correct when modifying head and prev\n        // 98304 = 32768 (lookback) + 65536 (common chunk size)\n        this.b = new u8(98304);\n        if (this.o.dictionary) {\n            var dict = this.o.dictionary.subarray(-32768);\n            this.b.set(dict, 32768 - dict.length);\n            this.s.i = 32768 - dict.length;\n        }\n    }\n    Deflate.prototype.p = function (c, f) {\n        this.ondata(dopt(c, this.o, 0, 0, this.s), f);\n    };\n    /**\n     * Pushes a chunk to be deflated\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Deflate.prototype.push = function (chunk, final) {\n        if (!this.ondata)\n            err(5);\n        if (this.s.l)\n            err(4);\n        var endLen = chunk.length + this.s.z;\n        if (endLen > this.b.length) {\n            if (endLen > 2 * this.b.length - 32768) {\n                var newBuf = new u8(endLen & -32768);\n                newBuf.set(this.b.subarray(0, this.s.z));\n                this.b = newBuf;\n            }\n            var split = this.b.length - this.s.z;\n            this.b.set(chunk.subarray(0, split), this.s.z);\n            this.s.z = this.b.length;\n            this.p(this.b, false);\n            this.b.set(this.b.subarray(-32768));\n            this.b.set(chunk.subarray(split), 32768);\n            this.s.z = chunk.length - split + 32768;\n            this.s.i = 32766, this.s.w = 32768;\n        }\n        else {\n            this.b.set(chunk, this.s.z);\n            this.s.z += chunk.length;\n        }\n        this.s.l = final & 1;\n        if (this.s.z > this.s.w + 8191 || final) {\n            this.p(this.b, final || false);\n            this.s.w = this.s.i, this.s.i -= 2;\n        }\n    };\n    /**\n     * Flushes buffered uncompressed data. Useful to immediately retrieve the\n     * deflated output for small inputs.\n     */\n    Deflate.prototype.flush = function () {\n        if (!this.ondata)\n            err(5);\n        if (this.s.l)\n            err(4);\n        this.p(this.b, false);\n        this.s.w = this.s.i, this.s.i -= 2;\n    };\n    return Deflate;\n}());\nexport { Deflate };\n/**\n * Asynchronous streaming DEFLATE compression\n */\nvar AsyncDeflate = /*#__PURE__*/ (function () {\n    function AsyncDeflate(opts, cb) {\n        astrmify([\n            bDflt,\n            function () { return [astrm, Deflate]; }\n        ], this, StrmOpt.call(this, opts, cb), function (ev) {\n            var strm = new Deflate(ev.data);\n            onmessage = astrm(strm);\n        }, 6, 1);\n    }\n    return AsyncDeflate;\n}());\nexport { AsyncDeflate };\nexport function deflate(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    return cbify(data, opts, [\n        bDflt,\n    ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb);\n}\n/**\n * Compresses data with DEFLATE without any wrapper\n * @param data The data to compress\n * @param opts The compression options\n * @returns The deflated version of the data\n */\nexport function deflateSync(data, opts) {\n    return dopt(data, opts || {}, 0, 0);\n}\n/**\n * Streaming DEFLATE decompression\n */\nvar Inflate = /*#__PURE__*/ (function () {\n    function Inflate(opts, cb) {\n        // no StrmOpt here to avoid adding to workerizer\n        if (typeof opts == 'function')\n            cb = opts, opts = {};\n        this.ondata = cb;\n        var dict = opts && opts.dictionary && opts.dictionary.subarray(-32768);\n        this.s = { i: 0, b: dict ? dict.length : 0 };\n        this.o = new u8(32768);\n        this.p = new u8(0);\n        if (dict)\n            this.o.set(dict);\n    }\n    Inflate.prototype.e = function (c) {\n        if (!this.ondata)\n            err(5);\n        if (this.d)\n            err(4);\n        if (!this.p.length)\n            this.p = c;\n        else if (c.length) {\n            var n = new u8(this.p.length + c.length);\n            n.set(this.p), n.set(c, this.p.length), this.p = n;\n        }\n    };\n    Inflate.prototype.c = function (final) {\n        this.s.i = +(this.d = final || false);\n        var bts = this.s.b;\n        var dt = inflt(this.p, this.s, this.o);\n        this.ondata(slc(dt, bts, this.s.b), this.d);\n        this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;\n        this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7;\n    };\n    /**\n     * Pushes a chunk to be inflated\n     * @param chunk The chunk to push\n     * @param final Whether this is the final chunk\n     */\n    Inflate.prototype.push = function (chunk, final) {\n        this.e(chunk), this.c(final);\n    };\n    return Inflate;\n}());\nexport { Inflate };\n/**\n * Asynchronous streaming DEFLATE decompression\n */\nvar AsyncInflate = /*#__PURE__*/ (function () {\n    function AsyncInflate(opts, cb) {\n        astrmify([\n            bInflt,\n            function () { return [astrm, Inflate]; }\n        ], this, StrmOpt.call(this, opts, cb), function (ev) {\n            var strm = new Inflate(ev.data);\n            onmessage = astrm(strm);\n        }, 7, 0);\n    }\n    return AsyncInflate;\n}());\nexport { AsyncInflate };\nexport function inflate(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    return cbify(data, opts, [\n        bInflt\n    ], function (ev) { return pbf(inflateSync(ev.data[0], gopt(ev.data[1]))); }, 1, cb);\n}\n/**\n * Expands DEFLATE data with no wrapper\n * @param data The data to decompress\n * @param opts The decompression options\n * @returns The decompressed version of the data\n */\nexport function inflateSync(data, opts) {\n    return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);\n}\n// before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize.\n/**\n * Streaming GZIP compression\n */\nvar Gzip = /*#__PURE__*/ (function () {\n    function Gzip(opts, cb) {\n        this.c = crc();\n        this.l = 0;\n        this.v = 1;\n        Deflate.call(this, opts, cb);\n    }\n    /**\n     * Pushes a chunk to be GZIPped\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Gzip.prototype.push = function (chunk, final) {\n        this.c.p(chunk);\n        this.l += chunk.length;\n        Deflate.prototype.push.call(this, chunk, final);\n    };\n    Gzip.prototype.p = function (c, f) {\n        var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, this.s);\n        if (this.v)\n            gzh(raw, this.o), this.v = 0;\n        if (f)\n            wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l);\n        this.ondata(raw, f);\n    };\n    /**\n     * Flushes buffered uncompressed data. Useful to immediately retrieve the\n     * GZIPped output for small inputs.\n     */\n    Gzip.prototype.flush = function () {\n        Deflate.prototype.flush.call(this);\n    };\n    return Gzip;\n}());\nexport { Gzip };\n/**\n * Asynchronous streaming GZIP compression\n */\nvar AsyncGzip = /*#__PURE__*/ (function () {\n    function AsyncGzip(opts, cb) {\n        astrmify([\n            bDflt,\n            gze,\n            function () { return [astrm, Deflate, Gzip]; }\n        ], this, StrmOpt.call(this, opts, cb), function (ev) {\n            var strm = new Gzip(ev.data);\n            onmessage = astrm(strm);\n        }, 8, 1);\n    }\n    return AsyncGzip;\n}());\nexport { AsyncGzip };\nexport function gzip(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    return cbify(data, opts, [\n        bDflt,\n        gze,\n        function () { return [gzipSync]; }\n    ], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb);\n}\n/**\n * Compresses data with GZIP\n * @param data The data to compress\n * @param opts The compression options\n * @returns The gzipped version of the data\n */\nexport function gzipSync(data, opts) {\n    if (!opts)\n        opts = {};\n    var c = crc(), l = data.length;\n    c.p(data);\n    var d = dopt(data, opts, gzhl(opts), 8), s = d.length;\n    return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d;\n}\n/**\n * Streaming single or multi-member GZIP decompression\n */\nvar Gunzip = /*#__PURE__*/ (function () {\n    function Gunzip(opts, cb) {\n        this.v = 1;\n        this.r = 0;\n        Inflate.call(this, opts, cb);\n    }\n    /**\n     * Pushes a chunk to be GUNZIPped\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Gunzip.prototype.push = function (chunk, final) {\n        Inflate.prototype.e.call(this, chunk);\n        this.r += chunk.length;\n        if (this.v) {\n            var p = this.p.subarray(this.v - 1);\n            var s = p.length > 3 ? gzs(p) : 4;\n            if (s > p.length) {\n                if (!final)\n                    return;\n            }\n            else if (this.v > 1 && this.onmember) {\n                this.onmember(this.r - p.length);\n            }\n            this.p = p.subarray(s), this.v = 0;\n        }\n        // necessary to prevent TS from using the closure value\n        // This allows for workerization to function correctly\n        Inflate.prototype.c.call(this, final);\n        // process concatenated GZIP\n        if (this.s.f && !this.s.l && !final) {\n            this.v = shft(this.s.p) + 9;\n            this.s = { i: 0 };\n            this.o = new u8(0);\n            this.push(new u8(0), final);\n        }\n    };\n    return Gunzip;\n}());\nexport { Gunzip };\n/**\n * Asynchronous streaming single or multi-member GZIP decompression\n */\nvar AsyncGunzip = /*#__PURE__*/ (function () {\n    function AsyncGunzip(opts, cb) {\n        var _this = this;\n        astrmify([\n            bInflt,\n            guze,\n            function () { return [astrm, Inflate, Gunzip]; }\n        ], this, StrmOpt.call(this, opts, cb), function (ev) {\n            var strm = new Gunzip(ev.data);\n            strm.onmember = function (offset) { return postMessage(offset); };\n            onmessage = astrm(strm);\n        }, 9, 0, function (offset) { return _this.onmember && _this.onmember(offset); });\n    }\n    return AsyncGunzip;\n}());\nexport { AsyncGunzip };\nexport function gunzip(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    return cbify(data, opts, [\n        bInflt,\n        guze,\n        function () { return [gunzipSync]; }\n    ], function (ev) { return pbf(gunzipSync(ev.data[0], ev.data[1])); }, 3, cb);\n}\n/**\n * Expands GZIP data\n * @param data The data to decompress\n * @param opts The decompression options\n * @returns The decompressed version of the data\n */\nexport function gunzipSync(data, opts) {\n    var st = gzs(data);\n    if (st + 8 > data.length)\n        err(6, 'invalid gzip data');\n    return inflt(data.subarray(st, -8), { i: 2 }, opts && opts.out || new u8(gzl(data)), opts && opts.dictionary);\n}\n/**\n * Streaming Zlib compression\n */\nvar Zlib = /*#__PURE__*/ (function () {\n    function Zlib(opts, cb) {\n        this.c = adler();\n        this.v = 1;\n        Deflate.call(this, opts, cb);\n    }\n    /**\n     * Pushes a chunk to be zlibbed\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Zlib.prototype.push = function (chunk, final) {\n        this.c.p(chunk);\n        Deflate.prototype.push.call(this, chunk, final);\n    };\n    Zlib.prototype.p = function (c, f) {\n        var raw = dopt(c, this.o, this.v && (this.o.dictionary ? 6 : 2), f && 4, this.s);\n        if (this.v)\n            zlh(raw, this.o), this.v = 0;\n        if (f)\n            wbytes(raw, raw.length - 4, this.c.d());\n        this.ondata(raw, f);\n    };\n    /**\n     * Flushes buffered uncompressed data. Useful to immediately retrieve the\n     * zlibbed output for small inputs.\n     */\n    Zlib.prototype.flush = function () {\n        Deflate.prototype.flush.call(this);\n    };\n    return Zlib;\n}());\nexport { Zlib };\n/**\n * Asynchronous streaming Zlib compression\n */\nvar AsyncZlib = /*#__PURE__*/ (function () {\n    function AsyncZlib(opts, cb) {\n        astrmify([\n            bDflt,\n            zle,\n            function () { return [astrm, Deflate, Zlib]; }\n        ], this, StrmOpt.call(this, opts, cb), function (ev) {\n            var strm = new Zlib(ev.data);\n            onmessage = astrm(strm);\n        }, 10, 1);\n    }\n    return AsyncZlib;\n}());\nexport { AsyncZlib };\nexport function zlib(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    return cbify(data, opts, [\n        bDflt,\n        zle,\n        function () { return [zlibSync]; }\n    ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb);\n}\n/**\n * Compress data with Zlib\n * @param data The data to compress\n * @param opts The compression options\n * @returns The zlib-compressed version of the data\n */\nexport function zlibSync(data, opts) {\n    if (!opts)\n        opts = {};\n    var a = adler();\n    a.p(data);\n    var d = dopt(data, opts, opts.dictionary ? 6 : 2, 4);\n    return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d;\n}\n/**\n * Streaming Zlib decompression\n */\nvar Unzlib = /*#__PURE__*/ (function () {\n    function Unzlib(opts, cb) {\n        Inflate.call(this, opts, cb);\n        this.v = opts && opts.dictionary ? 2 : 1;\n    }\n    /**\n     * Pushes a chunk to be unzlibbed\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Unzlib.prototype.push = function (chunk, final) {\n        Inflate.prototype.e.call(this, chunk);\n        if (this.v) {\n            if (this.p.length < 6 && !final)\n                return;\n            this.p = this.p.subarray(zls(this.p, this.v - 1)), this.v = 0;\n        }\n        if (final) {\n            if (this.p.length < 4)\n                err(6, 'invalid zlib data');\n            this.p = this.p.subarray(0, -4);\n        }\n        // necessary to prevent TS from using the closure value\n        // This allows for workerization to function correctly\n        Inflate.prototype.c.call(this, final);\n    };\n    return Unzlib;\n}());\nexport { Unzlib };\n/**\n * Asynchronous streaming Zlib decompression\n */\nvar AsyncUnzlib = /*#__PURE__*/ (function () {\n    function AsyncUnzlib(opts, cb) {\n        astrmify([\n            bInflt,\n            zule,\n            function () { return [astrm, Inflate, Unzlib]; }\n        ], this, StrmOpt.call(this, opts, cb), function (ev) {\n            var strm = new Unzlib(ev.data);\n            onmessage = astrm(strm);\n        }, 11, 0);\n    }\n    return AsyncUnzlib;\n}());\nexport { AsyncUnzlib };\nexport function unzlib(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    return cbify(data, opts, [\n        bInflt,\n        zule,\n        function () { return [unzlibSync]; }\n    ], function (ev) { return pbf(unzlibSync(ev.data[0], gopt(ev.data[1]))); }, 5, cb);\n}\n/**\n * Expands Zlib data\n * @param data The data to decompress\n * @param opts The decompression options\n * @returns The decompressed version of the data\n */\nexport function unzlibSync(data, opts) {\n    return inflt(data.subarray(zls(data, opts && opts.dictionary), -4), { i: 2 }, opts && opts.out, opts && opts.dictionary);\n}\n// Default algorithm for compression (used because having a known output size allows faster decompression)\nexport { gzip as compress, AsyncGzip as AsyncCompress };\nexport { gzipSync as compressSync, Gzip as Compress };\n/**\n * Streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar Decompress = /*#__PURE__*/ (function () {\n    function Decompress(opts, cb) {\n        this.o = StrmOpt.call(this, opts, cb) || {};\n        this.G = Gunzip;\n        this.I = Inflate;\n        this.Z = Unzlib;\n    }\n    // init substream\n    // overriden by AsyncDecompress\n    Decompress.prototype.i = function () {\n        var _this = this;\n        this.s.ondata = function (dat, final) {\n            _this.ondata(dat, final);\n        };\n    };\n    /**\n     * Pushes a chunk to be decompressed\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Decompress.prototype.push = function (chunk, final) {\n        if (!this.ondata)\n            err(5);\n        if (!this.s) {\n            if (this.p && this.p.length) {\n                var n = new u8(this.p.length + chunk.length);\n                n.set(this.p), n.set(chunk, this.p.length);\n            }\n            else\n                this.p = chunk;\n            if (this.p.length > 2) {\n                this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8)\n                    ? new this.G(this.o)\n                    : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31))\n                        ? new this.I(this.o)\n                        : new this.Z(this.o);\n                this.i();\n                this.s.push(this.p, final);\n                this.p = null;\n            }\n        }\n        else\n            this.s.push(chunk, final);\n    };\n    return Decompress;\n}());\nexport { Decompress };\n/**\n * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar AsyncDecompress = /*#__PURE__*/ (function () {\n    function AsyncDecompress(opts, cb) {\n        Decompress.call(this, opts, cb);\n        this.queuedSize = 0;\n        this.G = AsyncGunzip;\n        this.I = AsyncInflate;\n        this.Z = AsyncUnzlib;\n    }\n    AsyncDecompress.prototype.i = function () {\n        var _this = this;\n        this.s.ondata = function (err, dat, final) {\n            _this.ondata(err, dat, final);\n        };\n        this.s.ondrain = function (size) {\n            _this.queuedSize -= size;\n            if (_this.ondrain)\n                _this.ondrain(size);\n        };\n    };\n    /**\n     * Pushes a chunk to be decompressed\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    AsyncDecompress.prototype.push = function (chunk, final) {\n        this.queuedSize += chunk.length;\n        Decompress.prototype.push.call(this, chunk, final);\n    };\n    return AsyncDecompress;\n}());\nexport { AsyncDecompress };\nexport function decompress(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n        ? gunzip(data, opts, cb)\n        : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n            ? inflate(data, opts, cb)\n            : unzlib(data, opts, cb);\n}\n/**\n * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format\n * @param data The data to decompress\n * @param opts The decompression options\n * @returns The decompressed version of the data\n */\nexport function decompressSync(data, opts) {\n    return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n        ? gunzipSync(data, opts)\n        : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n            ? inflateSync(data, opts)\n            : unzlibSync(data, opts);\n}\n// flatten a directory structure\nvar fltn = function (d, p, t, o) {\n    for (var k in d) {\n        var val = d[k], n = p + k, op = o;\n        if (Array.isArray(val))\n            op = mrg(o, val[1]), val = val[0];\n        if (val instanceof u8)\n            t[n] = [val, op];\n        else {\n            t[n += '/'] = [new u8(0), op];\n            fltn(val, n, t, o);\n        }\n    }\n};\n// text encoder\nvar te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder();\n// text decoder\nvar td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder();\n// text decoder stream\nvar tds = 0;\ntry {\n    td.decode(et, { stream: true });\n    tds = 1;\n}\ncatch (e) { }\n// decode UTF8\nvar dutf8 = function (d) {\n    for (var r = '', i = 0;;) {\n        var c = d[i++];\n        var eb = (c > 127) + (c > 223) + (c > 239);\n        if (i + eb > d.length)\n            return { s: r, r: slc(d, i - 1) };\n        if (!eb)\n            r += String.fromCharCode(c);\n        else if (eb == 3) {\n            c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536,\n                r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023));\n        }\n        else if (eb & 1)\n            r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63));\n        else\n            r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63));\n    }\n};\n/**\n * Streaming UTF-8 decoding\n */\nvar DecodeUTF8 = /*#__PURE__*/ (function () {\n    /**\n     * Creates a UTF-8 decoding stream\n     * @param cb The callback to call whenever data is decoded\n     */\n    function DecodeUTF8(cb) {\n        this.ondata = cb;\n        if (tds)\n            this.t = new TextDecoder();\n        else\n            this.p = et;\n    }\n    /**\n     * Pushes a chunk to be decoded from UTF-8 binary\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    DecodeUTF8.prototype.push = function (chunk, final) {\n        if (!this.ondata)\n            err(5);\n        final = !!final;\n        if (this.t) {\n            this.ondata(this.t.decode(chunk, { stream: true }), final);\n            if (final) {\n                if (this.t.decode().length)\n                    err(8);\n                this.t = null;\n            }\n            return;\n        }\n        if (!this.p)\n            err(4);\n        var dat = new u8(this.p.length + chunk.length);\n        dat.set(this.p);\n        dat.set(chunk, this.p.length);\n        var _a = dutf8(dat), s = _a.s, r = _a.r;\n        if (final) {\n            if (r.length)\n                err(8);\n            this.p = null;\n        }\n        else\n            this.p = r;\n        this.ondata(s, final);\n    };\n    return DecodeUTF8;\n}());\nexport { DecodeUTF8 };\n/**\n * Streaming UTF-8 encoding\n */\nvar EncodeUTF8 = /*#__PURE__*/ (function () {\n    /**\n     * Creates a UTF-8 decoding stream\n     * @param cb The callback to call whenever data is encoded\n     */\n    function EncodeUTF8(cb) {\n        this.ondata = cb;\n    }\n    /**\n     * Pushes a chunk to be encoded to UTF-8\n     * @param chunk The string data to push\n     * @param final Whether this is the last chunk\n     */\n    EncodeUTF8.prototype.push = function (chunk, final) {\n        if (!this.ondata)\n            err(5);\n        if (this.d)\n            err(4);\n        this.ondata(strToU8(chunk), this.d = final || false);\n    };\n    return EncodeUTF8;\n}());\nexport { EncodeUTF8 };\n/**\n * Converts a string into a Uint8Array for use with compression/decompression methods\n * @param str The string to encode\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n *               not need to be true unless decoding a binary string.\n * @returns The string encoded in UTF-8/Latin-1 binary\n */\nexport function strToU8(str, latin1) {\n    if (latin1) {\n        var ar_1 = new u8(str.length);\n        for (var i = 0; i < str.length; ++i)\n            ar_1[i] = str.charCodeAt(i);\n        return ar_1;\n    }\n    if (te)\n        return te.encode(str);\n    var l = str.length;\n    var ar = new u8(str.length + (str.length >> 1));\n    var ai = 0;\n    var w = function (v) { ar[ai++] = v; };\n    for (var i = 0; i < l; ++i) {\n        if (ai + 5 > ar.length) {\n            var n = new u8(ai + 8 + ((l - i) << 1));\n            n.set(ar);\n            ar = n;\n        }\n        var c = str.charCodeAt(i);\n        if (c < 128 || latin1)\n            w(c);\n        else if (c < 2048)\n            w(192 | (c >> 6)), w(128 | (c & 63));\n        else if (c > 55295 && c < 57344)\n            c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023),\n                w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));\n        else\n            w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));\n    }\n    return slc(ar, 0, ai);\n}\n/**\n * Converts a Uint8Array to a string\n * @param dat The data to decode to string\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n *               not need to be true unless encoding to binary string.\n * @returns The original UTF-8/Latin-1 string\n */\nexport function strFromU8(dat, latin1) {\n    if (latin1) {\n        var r = '';\n        for (var i = 0; i < dat.length; i += 16384)\n            r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384));\n        return r;\n    }\n    else if (td) {\n        return td.decode(dat);\n    }\n    else {\n        var _a = dutf8(dat), s = _a.s, r = _a.r;\n        if (r.length)\n            err(8);\n        return s;\n    }\n}\n;\n// deflate bit flag\nvar dbf = function (l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; };\n// skip local zip header\nvar slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); };\n// read zip header\nvar zh = function (d, b, z) {\n    var fnl = b2(d, b + 28), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl, bs = b4(d, b + 20);\n    var _a = z && bs == 4294967295 ? z64e(d, es) : [bs, b4(d, b + 24), b4(d, b + 42)], sc = _a[0], su = _a[1], off = _a[2];\n    return [b2(d, b + 10), sc, su, fn, es + b2(d, b + 30) + b2(d, b + 32), off];\n};\n// read zip64 extra field\nvar z64e = function (d, b) {\n    for (; b2(d, b) != 1; b += 4 + b2(d, b + 2))\n        ;\n    return [b8(d, b + 12), b8(d, b + 4), b8(d, b + 20)];\n};\n// extra field length\nvar exfl = function (ex) {\n    var le = 0;\n    if (ex) {\n        for (var k in ex) {\n            var l = ex[k].length;\n            if (l > 65535)\n                err(9);\n            le += l + 4;\n        }\n    }\n    return le;\n};\n// write zip header\nvar wzh = function (d, b, f, fn, u, c, ce, co) {\n    var fl = fn.length, ex = f.extra, col = co && co.length;\n    var exl = exfl(ex);\n    wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4;\n    if (ce != null)\n        d[b++] = 20, d[b++] = f.os;\n    d[b] = 20, b += 2; // spec compliance? what's that?\n    d[b++] = (f.flag << 1) | (c < 0 && 8), d[b++] = u && 8;\n    d[b++] = f.compression & 255, d[b++] = f.compression >> 8;\n    var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;\n    if (y < 0 || y > 119)\n        err(10);\n    wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >> 1)), b += 4;\n    if (c != -1) {\n        wbytes(d, b, f.crc);\n        wbytes(d, b + 4, c < 0 ? -c - 2 : c);\n        wbytes(d, b + 8, f.size);\n    }\n    wbytes(d, b + 12, fl);\n    wbytes(d, b + 14, exl), b += 16;\n    if (ce != null) {\n        wbytes(d, b, col);\n        wbytes(d, b + 6, f.attrs);\n        wbytes(d, b + 10, ce), b += 14;\n    }\n    d.set(fn, b);\n    b += fl;\n    if (exl) {\n        for (var k in ex) {\n            var exf = ex[k], l = exf.length;\n            wbytes(d, b, +k);\n            wbytes(d, b + 2, l);\n            d.set(exf, b + 4), b += 4 + l;\n        }\n    }\n    if (col)\n        d.set(co, b), b += col;\n    return b;\n};\n// write zip footer (end of central directory)\nvar wzf = function (o, b, c, d, e) {\n    wbytes(o, b, 0x6054B50); // skip disk\n    wbytes(o, b + 8, c);\n    wbytes(o, b + 10, c);\n    wbytes(o, b + 12, d);\n    wbytes(o, b + 16, e);\n};\n/**\n * A pass-through stream to keep data uncompressed in a ZIP archive.\n */\nvar ZipPassThrough = /*#__PURE__*/ (function () {\n    /**\n     * Creates a pass-through stream that can be added to ZIP archives\n     * @param filename The filename to associate with this data stream\n     */\n    function ZipPassThrough(filename) {\n        this.filename = filename;\n        this.c = crc();\n        this.size = 0;\n        this.compression = 0;\n    }\n    /**\n     * Processes a chunk and pushes to the output stream. You can override this\n     * method in a subclass for custom behavior, but by default this passes\n     * the data through. You must call this.ondata(err, chunk, final) at some\n     * point in this method.\n     * @param chunk The chunk to process\n     * @param final Whether this is the last chunk\n     */\n    ZipPassThrough.prototype.process = function (chunk, final) {\n        this.ondata(null, chunk, final);\n    };\n    /**\n     * Pushes a chunk to be added. If you are subclassing this with a custom\n     * compression algorithm, note that you must push data from the source\n     * file only, pre-compression.\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    ZipPassThrough.prototype.push = function (chunk, final) {\n        if (!this.ondata)\n            err(5);\n        this.c.p(chunk);\n        this.size += chunk.length;\n        if (final)\n            this.crc = this.c.d();\n        this.process(chunk, final || false);\n    };\n    return ZipPassThrough;\n}());\nexport { ZipPassThrough };\n// I don't extend because TypeScript extension adds 1kB of runtime bloat\n/**\n * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate\n * for better performance\n */\nvar ZipDeflate = /*#__PURE__*/ (function () {\n    /**\n     * Creates a DEFLATE stream that can be added to ZIP archives\n     * @param filename The filename to associate with this data stream\n     * @param opts The compression options\n     */\n    function ZipDeflate(filename, opts) {\n        var _this = this;\n        if (!opts)\n            opts = {};\n        ZipPassThrough.call(this, filename);\n        this.d = new Deflate(opts, function (dat, final) {\n            _this.ondata(null, dat, final);\n        });\n        this.compression = 8;\n        this.flag = dbf(opts.level);\n    }\n    ZipDeflate.prototype.process = function (chunk, final) {\n        try {\n            this.d.push(chunk, final);\n        }\n        catch (e) {\n            this.ondata(e, null, final);\n        }\n    };\n    /**\n     * Pushes a chunk to be deflated\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    ZipDeflate.prototype.push = function (chunk, final) {\n        ZipPassThrough.prototype.push.call(this, chunk, final);\n    };\n    return ZipDeflate;\n}());\nexport { ZipDeflate };\n/**\n * Asynchronous streaming DEFLATE compression for ZIP archives\n */\nvar AsyncZipDeflate = /*#__PURE__*/ (function () {\n    /**\n     * Creates an asynchronous DEFLATE stream that can be added to ZIP archives\n     * @param filename The filename to associate with this data stream\n     * @param opts The compression options\n     */\n    function AsyncZipDeflate(filename, opts) {\n        var _this = this;\n        if (!opts)\n            opts = {};\n        ZipPassThrough.call(this, filename);\n        this.d = new AsyncDeflate(opts, function (err, dat, final) {\n            _this.ondata(err, dat, final);\n        });\n        this.compression = 8;\n        this.flag = dbf(opts.level);\n        this.terminate = this.d.terminate;\n    }\n    AsyncZipDeflate.prototype.process = function (chunk, final) {\n        this.d.push(chunk, final);\n    };\n    /**\n     * Pushes a chunk to be deflated\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    AsyncZipDeflate.prototype.push = function (chunk, final) {\n        ZipPassThrough.prototype.push.call(this, chunk, final);\n    };\n    return AsyncZipDeflate;\n}());\nexport { AsyncZipDeflate };\n// TODO: Better tree shaking\n/**\n * A zippable archive to which files can incrementally be added\n */\nvar Zip = /*#__PURE__*/ (function () {\n    /**\n     * Creates an empty ZIP archive to which files can be added\n     * @param cb The callback to call whenever data for the generated ZIP archive\n     *           is available\n     */\n    function Zip(cb) {\n        this.ondata = cb;\n        this.u = [];\n        this.d = 1;\n    }\n    /**\n     * Adds a file to the ZIP archive\n     * @param file The file stream to add\n     */\n    Zip.prototype.add = function (file) {\n        var _this = this;\n        if (!this.ondata)\n            err(5);\n        // finishing or finished\n        if (this.d & 2)\n            this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false);\n        else {\n            var f = strToU8(file.filename), fl_1 = f.length;\n            var com = file.comment, o = com && strToU8(com);\n            var u = fl_1 != file.filename.length || (o && (com.length != o.length));\n            var hl_1 = fl_1 + exfl(file.extra) + 30;\n            if (fl_1 > 65535)\n                this.ondata(err(11, 0, 1), null, false);\n            var header = new u8(hl_1);\n            wzh(header, 0, file, f, u, -1);\n            var chks_1 = [header];\n            var pAll_1 = function () {\n                for (var _i = 0, chks_2 = chks_1; _i < chks_2.length; _i++) {\n                    var chk = chks_2[_i];\n                    _this.ondata(null, chk, false);\n                }\n                chks_1 = [];\n            };\n            var tr_1 = this.d;\n            this.d = 0;\n            var ind_1 = this.u.length;\n            var uf_1 = mrg(file, {\n                f: f,\n                u: u,\n                o: o,\n                t: function () {\n                    if (file.terminate)\n                        file.terminate();\n                },\n                r: function () {\n                    pAll_1();\n                    if (tr_1) {\n                        var nxt = _this.u[ind_1 + 1];\n                        if (nxt)\n                            nxt.r();\n                        else\n                            _this.d = 1;\n                    }\n                    tr_1 = 1;\n                }\n            });\n            var cl_1 = 0;\n            file.ondata = function (err, dat, final) {\n                if (err) {\n                    _this.ondata(err, dat, final);\n                    _this.terminate();\n                }\n                else {\n                    cl_1 += dat.length;\n                    chks_1.push(dat);\n                    if (final) {\n                        var dd = new u8(16);\n                        wbytes(dd, 0, 0x8074B50);\n                        wbytes(dd, 4, file.crc);\n                        wbytes(dd, 8, cl_1);\n                        wbytes(dd, 12, file.size);\n                        chks_1.push(dd);\n                        uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file.crc, uf_1.size = file.size;\n                        if (tr_1)\n                            uf_1.r();\n                        tr_1 = 1;\n                    }\n                    else if (tr_1)\n                        pAll_1();\n                }\n            };\n            this.u.push(uf_1);\n        }\n    };\n    /**\n     * Ends the process of adding files and prepares to emit the final chunks.\n     * This *must* be called after adding all desired files for the resulting\n     * ZIP file to work properly.\n     */\n    Zip.prototype.end = function () {\n        var _this = this;\n        if (this.d & 2) {\n            this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true);\n            return;\n        }\n        if (this.d)\n            this.e();\n        else\n            this.u.push({\n                r: function () {\n                    if (!(_this.d & 1))\n                        return;\n                    _this.u.splice(-1, 1);\n                    _this.e();\n                },\n                t: function () { }\n            });\n        this.d = 3;\n    };\n    Zip.prototype.e = function () {\n        var bt = 0, l = 0, tl = 0;\n        for (var _i = 0, _a = this.u; _i < _a.length; _i++) {\n            var f = _a[_i];\n            tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0);\n        }\n        var out = new u8(tl + 22);\n        for (var _b = 0, _c = this.u; _b < _c.length; _b++) {\n            var f = _c[_b];\n            wzh(out, bt, f, f.f, f.u, -f.c - 2, l, f.o);\n            bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b;\n        }\n        wzf(out, bt, this.u.length, tl, l);\n        this.ondata(null, out, true);\n        this.d = 2;\n    };\n    /**\n     * A method to terminate any internal workers used by the stream. Subsequent\n     * calls to add() will fail.\n     */\n    Zip.prototype.terminate = function () {\n        for (var _i = 0, _a = this.u; _i < _a.length; _i++) {\n            var f = _a[_i];\n            f.t();\n        }\n        this.d = 2;\n    };\n    return Zip;\n}());\nexport { Zip };\nexport function zip(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    var r = {};\n    fltn(data, '', r, opts);\n    var k = Object.keys(r);\n    var lft = k.length, o = 0, tot = 0;\n    var slft = lft, files = new Array(lft);\n    var term = [];\n    var tAll = function () {\n        for (var i = 0; i < term.length; ++i)\n            term[i]();\n    };\n    var cbd = function (a, b) {\n        mt(function () { cb(a, b); });\n    };\n    mt(function () { cbd = cb; });\n    var cbf = function () {\n        var out = new u8(tot + 22), oe = o, cdl = tot - o;\n        tot = 0;\n        for (var i = 0; i < slft; ++i) {\n            var f = files[i];\n            try {\n                var l = f.c.length;\n                wzh(out, tot, f, f.f, f.u, l);\n                var badd = 30 + f.f.length + exfl(f.extra);\n                var loc = tot + badd;\n                out.set(f.c, loc);\n                wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l;\n            }\n            catch (e) {\n                return cbd(e, null);\n            }\n        }\n        wzf(out, o, files.length, cdl, oe);\n        cbd(null, out);\n    };\n    if (!lft)\n        cbf();\n    var _loop_1 = function (i) {\n        var fn = k[i];\n        var _a = r[fn], file = _a[0], p = _a[1];\n        var c = crc(), size = file.length;\n        c.p(file);\n        var f = strToU8(fn), s = f.length;\n        var com = p.comment, m = com && strToU8(com), ms = m && m.length;\n        var exl = exfl(p.extra);\n        var compression = p.level == 0 ? 0 : 8;\n        var cbl = function (e, d) {\n            if (e) {\n                tAll();\n                cbd(e, null);\n            }\n            else {\n                var l = d.length;\n                files[i] = mrg(p, {\n                    size: size,\n                    crc: c.d(),\n                    c: d,\n                    f: f,\n                    m: m,\n                    u: s != fn.length || (m && (com.length != ms)),\n                    compression: compression\n                });\n                o += 30 + s + exl + l;\n                tot += 76 + 2 * (s + exl) + (ms || 0) + l;\n                if (!--lft)\n                    cbf();\n            }\n        };\n        if (s > 65535)\n            cbl(err(11, 0, 1), null);\n        if (!compression)\n            cbl(null, file);\n        else if (size < 160000) {\n            try {\n                cbl(null, deflateSync(file, p));\n            }\n            catch (e) {\n                cbl(e, null);\n            }\n        }\n        else\n            term.push(deflate(file, p, cbl));\n    };\n    // Cannot use lft because it can decrease\n    for (var i = 0; i < slft; ++i) {\n        _loop_1(i);\n    }\n    return tAll;\n}\n/**\n * Synchronously creates a ZIP file. Prefer using `zip` for better performance\n * with more than one file.\n * @param data The directory structure for the ZIP archive\n * @param opts The main options, merged with per-file options\n * @returns The generated ZIP archive\n */\nexport function zipSync(data, opts) {\n    if (!opts)\n        opts = {};\n    var r = {};\n    var files = [];\n    fltn(data, '', r, opts);\n    var o = 0;\n    var tot = 0;\n    for (var fn in r) {\n        var _a = r[fn], file = _a[0], p = _a[1];\n        var compression = p.level == 0 ? 0 : 8;\n        var f = strToU8(fn), s = f.length;\n        var com = p.comment, m = com && strToU8(com), ms = m && m.length;\n        var exl = exfl(p.extra);\n        if (s > 65535)\n            err(11);\n        var d = compression ? deflateSync(file, p) : file, l = d.length;\n        var c = crc();\n        c.p(file);\n        files.push(mrg(p, {\n            size: file.length,\n            crc: c.d(),\n            c: d,\n            f: f,\n            m: m,\n            u: s != fn.length || (m && (com.length != ms)),\n            o: o,\n            compression: compression\n        }));\n        o += 30 + s + exl + l;\n        tot += 76 + 2 * (s + exl) + (ms || 0) + l;\n    }\n    var out = new u8(tot + 22), oe = o, cdl = tot - o;\n    for (var i = 0; i < files.length; ++i) {\n        var f = files[i];\n        wzh(out, f.o, f, f.f, f.u, f.c.length);\n        var badd = 30 + f.f.length + exfl(f.extra);\n        out.set(f.c, f.o + badd);\n        wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);\n    }\n    wzf(out, o, files.length, cdl, oe);\n    return out;\n}\n/**\n * Streaming pass-through decompression for ZIP archives\n */\nvar UnzipPassThrough = /*#__PURE__*/ (function () {\n    function UnzipPassThrough() {\n    }\n    UnzipPassThrough.prototype.push = function (data, final) {\n        this.ondata(null, data, final);\n    };\n    UnzipPassThrough.compression = 0;\n    return UnzipPassThrough;\n}());\nexport { UnzipPassThrough };\n/**\n * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for\n * better performance.\n */\nvar UnzipInflate = /*#__PURE__*/ (function () {\n    /**\n     * Creates a DEFLATE decompression that can be used in ZIP archives\n     */\n    function UnzipInflate() {\n        var _this = this;\n        this.i = new Inflate(function (dat, final) {\n            _this.ondata(null, dat, final);\n        });\n    }\n    UnzipInflate.prototype.push = function (data, final) {\n        try {\n            this.i.push(data, final);\n        }\n        catch (e) {\n            this.ondata(e, null, final);\n        }\n    };\n    UnzipInflate.compression = 8;\n    return UnzipInflate;\n}());\nexport { UnzipInflate };\n/**\n * Asynchronous streaming DEFLATE decompression for ZIP archives\n */\nvar AsyncUnzipInflate = /*#__PURE__*/ (function () {\n    /**\n     * Creates a DEFLATE decompression that can be used in ZIP archives\n     */\n    function AsyncUnzipInflate(_, sz) {\n        var _this = this;\n        if (sz < 320000) {\n            this.i = new Inflate(function (dat, final) {\n                _this.ondata(null, dat, final);\n            });\n        }\n        else {\n            this.i = new AsyncInflate(function (err, dat, final) {\n                _this.ondata(err, dat, final);\n            });\n            this.terminate = this.i.terminate;\n        }\n    }\n    AsyncUnzipInflate.prototype.push = function (data, final) {\n        if (this.i.terminate)\n            data = slc(data, 0);\n        this.i.push(data, final);\n    };\n    AsyncUnzipInflate.compression = 8;\n    return AsyncUnzipInflate;\n}());\nexport { AsyncUnzipInflate };\n/**\n * A ZIP archive decompression stream that emits files as they are discovered\n */\nvar Unzip = /*#__PURE__*/ (function () {\n    /**\n     * Creates a ZIP decompression stream\n     * @param cb The callback to call whenever a file in the ZIP archive is found\n     */\n    function Unzip(cb) {\n        this.onfile = cb;\n        this.k = [];\n        this.o = {\n            0: UnzipPassThrough\n        };\n        this.p = et;\n    }\n    /**\n     * Pushes a chunk to be unzipped\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Unzip.prototype.push = function (chunk, final) {\n        var _this = this;\n        if (!this.onfile)\n            err(5);\n        if (!this.p)\n            err(4);\n        if (this.c > 0) {\n            var len = Math.min(this.c, chunk.length);\n            var toAdd = chunk.subarray(0, len);\n            this.c -= len;\n            if (this.d)\n                this.d.push(toAdd, !this.c);\n            else\n                this.k[0].push(toAdd);\n            chunk = chunk.subarray(len);\n            if (chunk.length)\n                return this.push(chunk, final);\n        }\n        else {\n            var f = 0, i = 0, is = void 0, buf = void 0;\n            if (!this.p.length)\n                buf = chunk;\n            else if (!chunk.length)\n                buf = this.p;\n            else {\n                buf = new u8(this.p.length + chunk.length);\n                buf.set(this.p), buf.set(chunk, this.p.length);\n            }\n            var l = buf.length, oc = this.c, add = oc && this.d;\n            var _loop_2 = function () {\n                var _a;\n                var sig = b4(buf, i);\n                if (sig == 0x4034B50) {\n                    f = 1, is = i;\n                    this_1.d = null;\n                    this_1.c = 0;\n                    var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28);\n                    if (l > i + 30 + fnl + es) {\n                        var chks_3 = [];\n                        this_1.k.unshift(chks_3);\n                        f = 2;\n                        var sc_1 = b4(buf, i + 18), su_1 = b4(buf, i + 22);\n                        var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u);\n                        if (sc_1 == 4294967295) {\n                            _a = dd ? [-2] : z64e(buf, i), sc_1 = _a[0], su_1 = _a[1];\n                        }\n                        else if (dd)\n                            sc_1 = -1;\n                        i += es;\n                        this_1.c = sc_1;\n                        var d_1;\n                        var file_1 = {\n                            name: fn_1,\n                            compression: cmp_1,\n                            start: function () {\n                                if (!file_1.ondata)\n                                    err(5);\n                                if (!sc_1)\n                                    file_1.ondata(null, et, true);\n                                else {\n                                    var ctr = _this.o[cmp_1];\n                                    if (!ctr)\n                                        file_1.ondata(err(14, 'unknown compression type ' + cmp_1, 1), null, false);\n                                    d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1);\n                                    d_1.ondata = function (err, dat, final) { file_1.ondata(err, dat, final); };\n                                    for (var _i = 0, chks_4 = chks_3; _i < chks_4.length; _i++) {\n                                        var dat = chks_4[_i];\n                                        d_1.push(dat, false);\n                                    }\n                                    if (_this.k[0] == chks_3 && _this.c)\n                                        _this.d = d_1;\n                                    else\n                                        d_1.push(et, true);\n                                }\n                            },\n                            terminate: function () {\n                                if (d_1 && d_1.terminate)\n                                    d_1.terminate();\n                            }\n                        };\n                        if (sc_1 >= 0)\n                            file_1.size = sc_1, file_1.originalSize = su_1;\n                        this_1.onfile(file_1);\n                    }\n                    return \"break\";\n                }\n                else if (oc) {\n                    if (sig == 0x8074B50) {\n                        is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0;\n                        return \"break\";\n                    }\n                    else if (sig == 0x2014B50) {\n                        is = i -= 4, f = 3, this_1.c = 0;\n                        return \"break\";\n                    }\n                }\n            };\n            var this_1 = this;\n            for (; i < l - 4; ++i) {\n                var state_1 = _loop_2();\n                if (state_1 === \"break\")\n                    break;\n            }\n            this.p = et;\n            if (oc < 0) {\n                var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i);\n                if (add)\n                    add.push(dat, !!f);\n                else\n                    this.k[+(f == 2)].push(dat);\n            }\n            if (f & 2)\n                return this.push(buf.subarray(i), final);\n            this.p = buf.subarray(i);\n        }\n        if (final) {\n            if (this.c)\n                err(13);\n            this.p = null;\n        }\n    };\n    /**\n     * Registers a decoder with the stream, allowing for files compressed with\n     * the compression type provided to be expanded correctly\n     * @param decoder The decoder constructor\n     */\n    Unzip.prototype.register = function (decoder) {\n        this.o[decoder.compression] = decoder;\n    };\n    return Unzip;\n}());\nexport { Unzip };\nvar mt = typeof queueMicrotask == 'function' ? queueMicrotask : typeof setTimeout == 'function' ? setTimeout : function (fn) { fn(); };\nexport function unzip(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    var term = [];\n    var tAll = function () {\n        for (var i = 0; i < term.length; ++i)\n            term[i]();\n    };\n    var files = {};\n    var cbd = function (a, b) {\n        mt(function () { cb(a, b); });\n    };\n    mt(function () { cbd = cb; });\n    var e = data.length - 22;\n    for (; b4(data, e) != 0x6054B50; --e) {\n        if (!e || data.length - e > 65558) {\n            cbd(err(13, 0, 1), null);\n            return tAll;\n        }\n    }\n    ;\n    var lft = b2(data, e + 8);\n    if (lft) {\n        var c = lft;\n        var o = b4(data, e + 16);\n        var z = o == 4294967295 || c == 65535;\n        if (z) {\n            var ze = b4(data, e - 12);\n            z = b4(data, ze) == 0x6064B50;\n            if (z) {\n                c = lft = b4(data, ze + 32);\n                o = b4(data, ze + 48);\n            }\n        }\n        var fltr = opts && opts.filter;\n        var _loop_3 = function (i) {\n            var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n            o = no;\n            var cbl = function (e, d) {\n                if (e) {\n                    tAll();\n                    cbd(e, null);\n                }\n                else {\n                    if (d)\n                        files[fn] = d;\n                    if (!--lft)\n                        cbd(null, files);\n                }\n            };\n            if (!fltr || fltr({\n                name: fn,\n                size: sc,\n                originalSize: su,\n                compression: c_1\n            })) {\n                if (!c_1)\n                    cbl(null, slc(data, b, b + sc));\n                else if (c_1 == 8) {\n                    var infl = data.subarray(b, b + sc);\n                    // Synchronously decompress under 512KB, or barely-compressed data\n                    if (su < 524288 || sc > 0.8 * su) {\n                        try {\n                            cbl(null, inflateSync(infl, { out: new u8(su) }));\n                        }\n                        catch (e) {\n                            cbl(e, null);\n                        }\n                    }\n                    else\n                        term.push(inflate(infl, { size: su }, cbl));\n                }\n                else\n                    cbl(err(14, 'unknown compression type ' + c_1, 1), null);\n            }\n            else\n                cbl(null, null);\n        };\n        for (var i = 0; i < c; ++i) {\n            _loop_3(i);\n        }\n    }\n    else\n        cbd(null, {});\n    return tAll;\n}\n/**\n * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better\n * performance with more than one file.\n * @param data The raw compressed ZIP file\n * @param opts The ZIP extraction options\n * @returns The decompressed files\n */\nexport function unzipSync(data, opts) {\n    var files = {};\n    var e = data.length - 22;\n    for (; b4(data, e) != 0x6054B50; --e) {\n        if (!e || data.length - e > 65558)\n            err(13);\n    }\n    ;\n    var c = b2(data, e + 8);\n    if (!c)\n        return {};\n    var o = b4(data, e + 16);\n    var z = o == 4294967295 || c == 65535;\n    if (z) {\n        var ze = b4(data, e - 12);\n        z = b4(data, ze) == 0x6064B50;\n        if (z) {\n            c = b4(data, ze + 32);\n            o = b4(data, ze + 48);\n        }\n    }\n    var fltr = opts && opts.filter;\n    for (var i = 0; i < c; ++i) {\n        var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n        o = no;\n        if (!fltr || fltr({\n            name: fn,\n            size: sc,\n            originalSize: su,\n            compression: c_2\n        })) {\n            if (!c_2)\n                files[fn] = slc(data, b, b + sc);\n            else if (c_2 == 8)\n                files[fn] = inflateSync(data.subarray(b, b + sc), { out: new u8(su) });\n            else\n                err(14, 'unknown compression type ' + c_2);\n        }\n    }\n    return files;\n}\n","// biome-ignore lint: needed for Leaflet + IIFE to work\ndeclare const L: any;\n// biome-ignore lint: needed for window.URL to disambiguate from cloudflare workers\ndeclare const window: any;\ndeclare const document: DocumentLike;\n\nimport type { Coords } from \"leaflet\";\nimport { PMTiles, TileType } from \"./index\";\n\ninterface DocumentLike {\n  // biome-ignore lint: we don't want to bring in the entire document type\n  createElement: (s: string) => any;\n}\n\n// biome-ignore lint: we don't want to bring in the entire document type\ntype DoneCallback = (error?: Error, tile?: any) => void;\n\n/**\n * Add a raster PMTiles as a layer to a Leaflet map.\n *\n * For vector tiles see https://github.com/protomaps/protomaps-leaflet\n */\nexport const leafletRasterLayer = (source: PMTiles, options: unknown) => {\n  let loaded = false;\n  let mimeType = \"\";\n  const cls = L.GridLayer.extend({\n    createTile: (coord: Coords, done: DoneCallback) => {\n      const el = document.createElement(\"img\");\n      const controller = new AbortController();\n      const signal = controller.signal;\n      el.cancel = () => {\n        controller.abort();\n      };\n      if (!loaded) {\n        source.getHeader().then((header) => {\n          if (header.tileType === TileType.Mvt) {\n            console.error(\n              \"Error: archive contains MVT vector tiles, but leafletRasterLayer is for displaying raster tiles. See https://github.com/protomaps/PMTiles/tree/main/js for details.\"\n            );\n          } else if (header.tileType === 2) {\n            mimeType = \"image/png\";\n          } else if (header.tileType === 3) {\n            mimeType = \"image/jpeg\";\n          } else if (header.tileType === 4) {\n            mimeType = \"image/webp\";\n          } else if (header.tileType === 5) {\n            mimeType = \"image/avif\";\n          }\n        });\n        loaded = true;\n      }\n      source\n        .getZxy(coord.z, coord.x, coord.y, signal)\n        .then((arr) => {\n          if (arr) {\n            const blob = new Blob([arr.data], { type: mimeType });\n            const imageUrl = window.URL.createObjectURL(blob);\n            el.src = imageUrl;\n            el.cancel = undefined;\n            done(undefined, el);\n          }\n        })\n        .catch((e) => {\n          if (e.name !== \"AbortError\") {\n            throw e;\n          }\n        });\n      return el;\n    },\n\n    _removeTile: function (key: string) {\n      const tile = this._tiles[key];\n      if (!tile) {\n        return;\n      }\n\n      if (tile.el.cancel) tile.el.cancel();\n\n      tile.el.width = 0;\n      tile.el.height = 0;\n      tile.el.deleted = true;\n      L.DomUtil.remove(tile.el);\n      delete this._tiles[key];\n      this.fire(\"tileunload\", {\n        tile: tile.el,\n        coords: this._keyToTileCoords(key),\n      });\n    },\n  });\n  return new cls(options);\n};\n\ntype GetResourceResponse<T> = ExpiryData & {\n  data: T;\n};\ntype AddProtocolAction = (\n  requestParameters: RequestParameters,\n  abortController: AbortController\n) => Promise<GetResourceResponse<unknown>>;\n\ntype ExpiryData = {\n  cacheControl?: string | null;\n  expires?: string | null; // MapLibre can be a Date object\n};\n\n// copied from MapLibre /util/ajax.ts\ntype RequestParameters = {\n  url: string;\n  headers?: unknown;\n  method?: \"GET\" | \"POST\" | \"PUT\";\n  body?: string;\n  type?: \"string\" | \"json\" | \"arrayBuffer\" | \"image\";\n  credentials?: \"same-origin\" | \"include\";\n  collectResourceTiming?: boolean;\n};\n\n// for legacy maplibre-3 interop\ntype ResponseCallbackV3 = (\n  error?: Error | undefined,\n  data?: unknown | undefined,\n  cacheControl?: string | undefined,\n  expires?: string | undefined\n) => void;\n\ntype V3OrV4Protocol = <\n  T extends AbortController | ResponseCallbackV3,\n  R = T extends AbortController\n    ? Promise<GetResourceResponse<unknown>>\n    : { cancel: () => void },\n>(\n  requestParameters: RequestParameters,\n  arg2: T\n) => R;\n\nconst v3compat =\n  (v4: AddProtocolAction): V3OrV4Protocol =>\n  (requestParameters, arg2) => {\n    if (arg2 instanceof AbortController) {\n      // biome-ignore lint: overloading return type not handled by compiler\n      return v4(requestParameters, arg2) as any;\n    }\n    const abortController = new AbortController();\n    v4(requestParameters, abortController)\n      .then(\n        (result) => {\n          return arg2(\n            undefined,\n            result.data,\n            result.cacheControl || \"\",\n            result.expires || \"\"\n          );\n        },\n        (err) => {\n          return arg2(err);\n        }\n      )\n      .catch((e) => {\n        return arg2(e);\n      });\n    return { cancel: () => abortController.abort() };\n  };\n\n/**\n * MapLibre GL JS protocol. Must be added once globally.\n */\nexport class Protocol {\n  /** @hidden */\n  tiles: Map<string, PMTiles>;\n  metadata: boolean;\n  errorOnMissingTile: boolean;\n\n  /**\n   * Initialize the MapLibre PMTiles protocol.\n   *\n   * * metadata: also load the metadata section of the PMTiles. required for some \"inspect\" functionality\n   * and to automatically populate the map attribution. Requires an extra HTTP request.\n   * * errorOnMissingTile: When a vector MVT tile is missing from the archive, raise an error instead of\n   * returning the empty array. Not recommended. This is only to reproduce the behavior of ZXY tile APIs\n   * which some applications depend on when overzooming.\n   */\n  constructor(options?: { metadata?: boolean; errorOnMissingTile?: boolean }) {\n    this.tiles = new Map<string, PMTiles>();\n    this.metadata = options?.metadata || false;\n    this.errorOnMissingTile = options?.errorOnMissingTile || false;\n  }\n\n  /**\n   * Add a {@link PMTiles} instance to the global protocol instance.\n   *\n   * For remote fetch sources, references in MapLibre styles like pmtiles://http://...\n   * will resolve to the same instance if the URLs match.\n   */\n  add(p: PMTiles) {\n    this.tiles.set(p.source.getKey(), p);\n  }\n\n  /**\n   * Fetch a {@link PMTiles} instance by URL, for remote PMTiles instances.\n   */\n  get(url: string) {\n    return this.tiles.get(url);\n  }\n\n  /** @hidden */\n  tilev4 = async (\n    params: RequestParameters,\n    abortController: AbortController\n  ) => {\n    if (params.type === \"json\") {\n      const pmtilesUrl = params.url.substr(10);\n      let instance = this.tiles.get(pmtilesUrl);\n      if (!instance) {\n        instance = new PMTiles(pmtilesUrl);\n        this.tiles.set(pmtilesUrl, instance);\n      }\n\n      if (this.metadata) {\n        return {\n          data: await instance.getTileJson(params.url),\n        };\n      }\n\n      const h = await instance.getHeader();\n\n      if (h.minLon >= h.maxLon || h.minLat >= h.maxLat) {\n        console.error(\n          `Bounds of PMTiles archive ${h.minLon},${h.minLat},${h.maxLon},${h.maxLat} are not valid.`\n        );\n      }\n\n      return {\n        data: {\n          tiles: [`${params.url}/{z}/{x}/{y}`],\n          minzoom: h.minZoom,\n          maxzoom: h.maxZoom,\n          bounds: [h.minLon, h.minLat, h.maxLon, h.maxLat],\n        },\n      };\n    }\n    const re = new RegExp(/pmtiles:\\/\\/(.+)\\/(\\d+)\\/(\\d+)\\/(\\d+)/);\n    const result = params.url.match(re);\n    if (!result) {\n      throw new Error(\"Invalid PMTiles protocol URL\");\n    }\n    const pmtilesUrl = result[1];\n\n    let instance = this.tiles.get(pmtilesUrl);\n    if (!instance) {\n      instance = new PMTiles(pmtilesUrl);\n      this.tiles.set(pmtilesUrl, instance);\n    }\n    const z = result[2];\n    const x = result[3];\n    const y = result[4];\n\n    const header = await instance.getHeader();\n    const resp = await instance?.getZxy(+z, +x, +y, abortController.signal);\n    if (resp) {\n      return {\n        data: new Uint8Array(resp.data),\n        cacheControl: resp.cacheControl,\n        expires: resp.expires,\n      };\n    }\n    if (header.tileType === TileType.Mvt) {\n      if (this.errorOnMissingTile) {\n        throw new Error(\"Tile not found.\");\n      }\n      return { data: new Uint8Array() };\n    }\n    return { data: null };\n  };\n\n  tile = v3compat(this.tilev4);\n}\n"],"mappings":"otBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,iBAAAE,GAA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M,EACnE,OAAQ,CAACA,EAAO,UAAWA,EAAO,UAAWA,EAAO,UAAU,EAC9D,QAASA,EAAO,QAChB,QAASA,EAAO,OAClB,CACF,GACF,EAvKqBT,EAAAsC,GAAA,WAAd,IAAMoB,EAANpB","names":["src_exports","__export","Compression","EtagMismatch","FetchSource","FileSource","PMTiles","Protocol","ResolvedValueCache","SharedPromiseCache","TileType","bytesToHeader","findTile","getUint64","leafletRasterLayer","readVarint","tileIdToZxy","tileTypeExt","zxyToTileId","u8","u16","i32","fleb","fdeb","clim","freb","__name","eb","start","b","i","r","j","_a","fl","revfl","_b","fd","revfd","rev","x","hMap","cd","mb","s","l","le","co","rvb","sv","r_1","v","m","flt","fdt","flrm","hMap","flt","fdrm","hMap","fdt","max","__name","a","m","i","bits","d","p","o","bits16","shft","slc","v","s","e","u8","ec","err","__name","ind","msg","nt","e","inflt","dat","st","buf","dict","sl","dl","u8","noBuf","resize","noSt","cbuf","l","bl","nbuf","final","pos","bt","lm","dm","lbt","dbt","tbts","bits","type","flrm","fdrm","hLit","hcLen","tl","ldt","clt","i","clim","clb","max","clbmsk","clm","hMap","r","s","c","n","lt","dt","shft","t","lms","dms","lpos","bits16","sym","add","b","fleb","fl","d","dsym","fd","fdeb","end","shift","dend","slc","et","u8","gzs","__name","d","err","flg","st","zs","gzl","l","zls","__name","d","dict","err","inflateSync","data","opts","inflt","__name","gunzipSync","data","opts","st","gzs","err","inflt","u8","gzl","__name","unzlibSync","data","opts","inflt","zls","__name","decompressSync","data","opts","gunzipSync","inflateSync","unzlibSync","__name","td","tds","et","e","leafletRasterLayer","__name","source","options","loaded","mimeType","cls","coord","done","el","controller","signal","header","arr","blob","imageUrl","e","key","tile","v3compat","v4","requestParameters","arg2","abortController","result","err","_Protocol","params","__async","pmtilesUrl","instance","PMTiles","h","re","z","x","y","resp","p","url","Protocol","toNum","low","high","__name","readVarintRemainder","l","p","buf","b","h","readVarint","val","rotate","n","xy","rx","ry","t","idOnLevel","z","pos","__pow","s","tzValues","zxyToTileId","x","y","acc","d","tileIdToZxy","i","numTiles","Compression","defaultDecompress","compression","__async","decompressSync","stream","result","TileType","tileTypeExt","HEADER_SIZE_BYTES","findTile","entries","tileId","m","k","cmp","_FileSource","file","offset","length","FileSource","_FetchSource","url","customHeaders","userAgent","isWindows","isChromiumBased","passedSignal","etag","controller","signal","requestHeaders","cache","resp","contentRange","actualLength","newEtag","EtagMismatch","contentLength","FetchSource","getUint64","v","wh","wl","bytesToHeader","bytes","specVersion","deserializeIndex","buffer","numEntries","lastId","_EtagMismatch","__name","EtagMismatch","getHeaderAndRoot","source","decompress","__async","resp","headerData","HEADER_SIZE_BYTES","header","bytesToHeader","rootDirData","dirKey","rootDir","deserializeIndex","getDirectory","offset","length","data","directory","_ResolvedValueCache","maxCacheEntries","prefetch","defaultDecompress","cacheKey","cacheValue","res","minUsed","minKey","key","ResolvedValueCache","_SharedPromiseCache","p","resolve","reject","e","h","SharedPromiseCache","_PMTiles","cache","FetchSource","z","x","y","signal","tileId","zxyToTileId","dO","dL","depth","entry","findTile","decompressed","dec","baseTilesUrl","metadata","ext","tileTypeExt","PMTiles"]}
\ No newline at end of file
+{"version":3,"sources":["../src/index.ts","../node_modules/fflate/esm/browser.js","../src/adapters.ts"],"sourcesContent":["import { decompressSync } from \"fflate\";\nexport * from \"./adapters\";\n\n/** @hidden */\nexport interface BufferPosition {\n  buf: Uint8Array;\n  pos: number;\n}\n\nfunction toNum(low: number, high: number): number {\n  return (high >>> 0) * 0x100000000 + (low >>> 0);\n}\n\nfunction readVarintRemainder(l: number, p: BufferPosition): number {\n  const buf = p.buf;\n  let b = buf[p.pos++];\n  let h = (b & 0x70) >> 4;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x7f) << 3;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x7f) << 10;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x7f) << 17;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x7f) << 24;\n  if (b < 0x80) return toNum(l, h);\n  b = buf[p.pos++];\n  h |= (b & 0x01) << 31;\n  if (b < 0x80) return toNum(l, h);\n  throw new Error(\"Expected varint not more than 10 bytes\");\n}\n\n/** @hidden */\nexport function readVarint(p: BufferPosition): number {\n  const buf = p.buf;\n  let b = buf[p.pos++];\n  let val = b & 0x7f;\n  if (b < 0x80) return val;\n  b = buf[p.pos++];\n  val |= (b & 0x7f) << 7;\n  if (b < 0x80) return val;\n  b = buf[p.pos++];\n  val |= (b & 0x7f) << 14;\n  if (b < 0x80) return val;\n  b = buf[p.pos++];\n  val |= (b & 0x7f) << 21;\n  if (b < 0x80) return val;\n  b = buf[p.pos];\n  val |= (b & 0x0f) << 28;\n\n  return readVarintRemainder(val, p);\n}\n\nfunction rotate(\n  n: number,\n  x: number,\n  y: number,\n  rx: number,\n  ry: number\n): [number, number] {\n  if (ry === 0) {\n    if (rx !== 0) {\n      return [n - 1 - y, n - 1 - x];\n    }\n    return [y, x];\n  }\n  return [x, y];\n}\n\n/**\n * Convert Z,X,Y to a Hilbert TileID.\n */\nexport function zxyToTileId(z: number, x: number, y: number): number {\n  if (z > 26) {\n    throw new Error(\"Tile zoom level exceeds max safe number limit (26)\");\n  }\n  if (x >= 1 << z || y >= 1 << z) {\n    throw new Error(\"tile x/y outside zoom level bounds\");\n  }\n  let acc = ((1 << z) * (1 << z) - 1) / 3;\n  let a = z - 1;\n  let [tx, ty] = [x, y];\n  for (let s = 1 << a; s > 0; s >>= 1) {\n    const rx = tx & s;\n    const ry = ty & s;\n    acc += ((3 * rx) ^ ry) * (1 << a);\n    [tx, ty] = rotate(s, tx, ty, rx, ry);\n    a--;\n  }\n  return acc;\n}\n\nfunction tileIdToZ(i: number): number {\n  const c = 3 * i + 1;\n  if (c < 0x100000000) {\n    return 31 - Math.clz32(c);\n  }\n  return 63 - Math.clz32(c / 0x100000000);\n}\n\n/**\n * Convert a Hilbert TileID to Z,X,Y.\n */\nexport function tileIdToZxy(i: number): [number, number, number] {\n  const z = tileIdToZ(i) >> 1;\n  if (z > 26)\n    throw new Error(\"Tile zoom level exceeds max safe number limit (26)\");\n  const acc = ((1 << z) * (1 << z) - 1) / 3;\n\n  let t = i - acc;\n  let x = 0;\n  let y = 0;\n  const n = 1 << z;\n  for (let s = 1; s < n; s <<= 1) {\n    const rx = s & (t / 2);\n    const ry = s & (t ^ rx);\n    [x, y] = rotate(s, x, y, rx, ry);\n    t = t / 2;\n    x += rx;\n    y += ry;\n  }\n  return [z, x, y];\n}\n\n/**\n * PMTiles v3 directory entry.\n */\nexport interface Entry {\n  tileId: number;\n  offset: number;\n  length: number;\n  runLength: number;\n}\n\ninterface MetadataLike {\n  attribution?: string;\n  name?: string;\n  version?: string;\n  // biome-ignore lint: TileJSON spec\n  vector_layers?: string;\n  description?: string;\n}\n\n/**\n * Enum representing a compression algorithm used.\n * 0 = unknown compression, for if you must use a different or unspecified algorithm.\n * 1 = no compression.\n */\nexport enum Compression {\n  Unknown = 0,\n  None = 1,\n  Gzip = 2,\n  Brotli = 3,\n  Zstd = 4,\n}\n\n/**\n * Provide a decompression implementation that acts on `buf` and returns decompressed data.\n *\n * Should use the native DecompressionStream on browsers, zlib on node.\n * Should throw if the compression algorithm is not supported.\n */\nexport type DecompressFunc = (\n  buf: ArrayBuffer,\n  compression: Compression\n) => Promise<ArrayBuffer>;\n\nasync function defaultDecompress(\n  buf: ArrayBuffer,\n  compression: Compression\n): Promise<ArrayBuffer> {\n  if (compression === Compression.None || compression === Compression.Unknown) {\n    return buf;\n  }\n  if (compression === Compression.Gzip) {\n    // biome-ignore lint: needed to detect DecompressionStream in browser+node+cloudflare workers\n    if (typeof (globalThis as any).DecompressionStream === \"undefined\") {\n      return decompressSync(new Uint8Array(buf));\n    }\n    const stream = new Response(buf).body;\n    if (!stream) {\n      throw new Error(\"Failed to read response stream\");\n    }\n    const result: ReadableStream<Uint8Array> = stream.pipeThrough(\n      // biome-ignore lint: needed to detect DecompressionStream in browser+node+cloudflare workers\n      new (globalThis as any).DecompressionStream(\"gzip\")\n    );\n    return new Response(result).arrayBuffer();\n  }\n  throw new Error(\"Compression method not supported\");\n}\n\n/**\n * Describe the type of tiles stored in the archive.\n * 0 is unknown/other, 1 is \"MVT\" vector tiles.\n */\nexport enum TileType {\n  Unknown = 0,\n  Mvt = 1,\n  Png = 2,\n  Jpeg = 3,\n  Webp = 4,\n  Avif = 5,\n}\n\nexport function tileTypeExt(t: TileType): string {\n  if (t === TileType.Mvt) return \".mvt\";\n  if (t === TileType.Png) return \".png\";\n  if (t === TileType.Jpeg) return \".jpg\";\n  if (t === TileType.Webp) return \".webp\";\n  if (t === TileType.Avif) return \".avif\";\n  return \"\";\n}\n\nconst HEADER_SIZE_BYTES = 127;\n\n/**\n * PMTiles v3 header storing basic archive-level information.\n */\nexport interface Header {\n  specVersion: number;\n  rootDirectoryOffset: number;\n  rootDirectoryLength: number;\n  jsonMetadataOffset: number;\n  jsonMetadataLength: number;\n  leafDirectoryOffset: number;\n  leafDirectoryLength?: number;\n  tileDataOffset: number;\n  tileDataLength?: number;\n  numAddressedTiles: number;\n  numTileEntries: number;\n  numTileContents: number;\n  clustered: boolean;\n  internalCompression: Compression;\n  tileCompression: Compression;\n  tileType: TileType;\n  minZoom: number;\n  maxZoom: number;\n  minLon: number;\n  minLat: number;\n  maxLon: number;\n  maxLat: number;\n  centerZoom: number;\n  centerLon: number;\n  centerLat: number;\n  etag?: string;\n}\n\n/**\n * Low-level function for looking up a TileID or leaf directory inside a directory.\n */\nexport function findTile(entries: Entry[], tileId: number): Entry | null {\n  let m = 0;\n  let n = entries.length - 1;\n  while (m <= n) {\n    const k = (n + m) >> 1;\n    const cmp = tileId - entries[k].tileId;\n    if (cmp > 0) {\n      m = k + 1;\n    } else if (cmp < 0) {\n      n = k - 1;\n    } else {\n      return entries[k];\n    }\n  }\n\n  // at this point, m > n\n  if (n >= 0) {\n    if (entries[n].runLength === 0) {\n      return entries[n];\n    }\n    if (tileId - entries[n].tileId < entries[n].runLength) {\n      return entries[n];\n    }\n  }\n  return null;\n}\n\nexport interface RangeResponse {\n  data: ArrayBuffer;\n  etag?: string;\n  expires?: string;\n  cacheControl?: string;\n}\n\n/**\n * Interface for retrieving an archive from remote or local storage.\n */\nexport interface Source {\n  getBytes: (\n    offset: number,\n    length: number,\n    signal?: AbortSignal,\n    etag?: string\n  ) => Promise<RangeResponse>;\n\n  /**\n   * Return a unique string key for the archive e.g. a URL.\n   */\n  getKey: () => string;\n}\n\n/**\n * Use the Browser's File API, which is different from the NodeJS file API.\n * see https://developer.mozilla.org/en-US/docs/Web/API/File_API\n */\nexport class FileSource implements Source {\n  file: File;\n\n  constructor(file: File) {\n    this.file = file;\n  }\n\n  getKey() {\n    return this.file.name;\n  }\n\n  async getBytes(offset: number, length: number): Promise<RangeResponse> {\n    const blob = this.file.slice(offset, offset + length);\n    const a = await blob.arrayBuffer();\n    return { data: a };\n  }\n}\n\n/**\n * Uses the browser Fetch API to make tile requests via HTTP.\n *\n * This method does not send conditional request headers If-Match because of CORS.\n * Instead, it detects ETag mismatches via the response ETag or the 416 response code.\n *\n * This also works around browser and storage-specific edge cases.\n */\nexport class FetchSource implements Source {\n  url: string;\n\n  /**\n   * A [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) object, specfying custom [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) set for all requests to the remote archive.\n   *\n   * This should be used instead of maplibre's [transformRequest](https://maplibre.org/maplibre-gl-js/docs/API/classes/Map/#example) for PMTiles archives.\n   */\n  customHeaders: Headers;\n  /** @hidden */\n  mustReload: boolean;\n  /** @hidden */\n  chromeWindowsNoCache: boolean;\n\n  constructor(url: string, customHeaders: Headers = new Headers()) {\n    this.url = url;\n    this.customHeaders = customHeaders;\n    this.mustReload = false;\n    let userAgent = \"\";\n    if (\"navigator\" in globalThis) {\n      //biome-ignore lint: cf workers\n      userAgent = (globalThis as any).navigator.userAgent || \"\";\n    }\n    const isWindows = userAgent.indexOf(\"Windows\") > -1;\n    const isChromiumBased = /Chrome|Chromium|Edg|OPR|Brave/.test(userAgent);\n    this.chromeWindowsNoCache = false;\n    if (isWindows && isChromiumBased) {\n      this.chromeWindowsNoCache = true;\n    }\n  }\n\n  getKey() {\n    return this.url;\n  }\n\n  /**\n   * Mutate the custom [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) set for all requests to the remote archive.\n   */\n  setHeaders(customHeaders: Headers) {\n    this.customHeaders = customHeaders;\n  }\n\n  async getBytes(\n    offset: number,\n    length: number,\n    passedSignal?: AbortSignal,\n    etag?: string\n  ): Promise<RangeResponse> {\n    let controller: AbortController | undefined;\n    let signal: AbortSignal | undefined;\n    if (passedSignal) {\n      signal = passedSignal;\n    } else {\n      controller = new AbortController();\n      signal = controller.signal;\n    }\n\n    const requestHeaders = new Headers(this.customHeaders);\n    requestHeaders.set(\"range\", `bytes=${offset}-${offset + length - 1}`);\n\n    // we don't send if match because:\n    // * it disables browser caching completely (Chromium)\n    // * it requires a preflight request for every tile request\n    // * it requires CORS configuration becasue If-Match is not a CORs-safelisted header\n    // CORs configuration should expose ETag.\n    // if any etag mismatch is detected, we need to ignore the browser cache\n    let cache: string | undefined;\n    if (this.mustReload) {\n      cache = \"reload\";\n    } else if (this.chromeWindowsNoCache) {\n      cache = \"no-store\";\n    }\n\n    let resp = await fetch(this.url, {\n      signal: signal,\n      cache: cache,\n      headers: requestHeaders,\n      //biome-ignore lint: \"cache\" is incompatible between cloudflare workers and browser\n    } as any);\n\n    // handle edge case where the archive is < 16384 kb total.\n    if (offset === 0 && resp.status === 416) {\n      const contentRange = resp.headers.get(\"Content-Range\");\n      if (!contentRange || !contentRange.startsWith(\"bytes */\")) {\n        throw new Error(\"Missing content-length on 416 response\");\n      }\n      const actualLength = +contentRange.substr(8);\n      resp = await fetch(this.url, {\n        signal: signal,\n        cache: \"reload\",\n        headers: { range: `bytes=0-${actualLength - 1}` },\n        //biome-ignore lint: \"cache\" is incompatible between cloudflare workers and browser\n      } as any);\n    }\n\n    // if it's a weak etag, it's not useful for us, so ignore it.\n    let newEtag = resp.headers.get(\"Etag\");\n    if (newEtag?.startsWith(\"W/\")) {\n      newEtag = null;\n    }\n\n    // some storage systems are misbehaved (Cloudflare R2)\n    if (resp.status === 416 || (etag && newEtag && newEtag !== etag)) {\n      this.mustReload = true;\n      throw new EtagMismatch(\n        `Server returned non-matching ETag ${etag} after one retry. Check browser extensions and servers for issues that may affect correct ETag headers.`\n      );\n    }\n\n    if (resp.status >= 300) {\n      throw new Error(`Bad response code: ${resp.status}`);\n    }\n\n    // some well-behaved backends, e.g. DigitalOcean CDN, respond with 200 instead of 206\n    // but we also need to detect no support for Byte Serving which is returning the whole file\n    const contentLength = resp.headers.get(\"Content-Length\");\n    if (resp.status === 200 && (!contentLength || +contentLength > length)) {\n      if (controller) controller.abort();\n      throw new Error(\n        \"Server returned no content-length header or content-length exceeding request. Check that your storage backend supports HTTP Byte Serving.\"\n      );\n    }\n\n    const a = await resp.arrayBuffer();\n    return {\n      data: a,\n      etag: newEtag || undefined,\n      cacheControl: resp.headers.get(\"Cache-Control\") || undefined,\n      expires: resp.headers.get(\"Expires\") || undefined,\n    };\n  }\n}\n\n/** @hidden */\nexport function getUint64(v: DataView, offset: number): number {\n  const wh = v.getUint32(offset + 4, true);\n  const wl = v.getUint32(offset + 0, true);\n  return wh * 2 ** 32 + wl;\n}\n\n/**\n * Parse raw header bytes into a Header object.\n */\nexport function bytesToHeader(bytes: ArrayBuffer, etag?: string): Header {\n  const v = new DataView(bytes);\n  const specVersion = v.getUint8(7);\n  if (specVersion > 3) {\n    throw new Error(\n      `Archive is spec version ${specVersion} but this library supports up to spec version 3`\n    );\n  }\n\n  return {\n    specVersion: specVersion,\n    rootDirectoryOffset: getUint64(v, 8),\n    rootDirectoryLength: getUint64(v, 16),\n    jsonMetadataOffset: getUint64(v, 24),\n    jsonMetadataLength: getUint64(v, 32),\n    leafDirectoryOffset: getUint64(v, 40),\n    leafDirectoryLength: getUint64(v, 48),\n    tileDataOffset: getUint64(v, 56),\n    tileDataLength: getUint64(v, 64),\n    numAddressedTiles: getUint64(v, 72),\n    numTileEntries: getUint64(v, 80),\n    numTileContents: getUint64(v, 88),\n    clustered: v.getUint8(96) === 1,\n    internalCompression: v.getUint8(97),\n    tileCompression: v.getUint8(98),\n    tileType: v.getUint8(99),\n    minZoom: v.getUint8(100),\n    maxZoom: v.getUint8(101),\n    minLon: v.getInt32(102, true) / 10000000,\n    minLat: v.getInt32(106, true) / 10000000,\n    maxLon: v.getInt32(110, true) / 10000000,\n    maxLat: v.getInt32(114, true) / 10000000,\n    centerZoom: v.getUint8(118),\n    centerLon: v.getInt32(119, true) / 10000000,\n    centerLat: v.getInt32(123, true) / 10000000,\n    etag: etag,\n  };\n}\n\nfunction deserializeIndex(buffer: ArrayBuffer): Entry[] {\n  const p = { buf: new Uint8Array(buffer), pos: 0 };\n  const numEntries = readVarint(p);\n\n  const entries: Entry[] = [];\n\n  let lastId = 0;\n  for (let i = 0; i < numEntries; i++) {\n    const v = readVarint(p);\n    entries.push({ tileId: lastId + v, offset: 0, length: 0, runLength: 1 });\n    lastId += v;\n  }\n\n  for (let i = 0; i < numEntries; i++) {\n    entries[i].runLength = readVarint(p);\n  }\n\n  for (let i = 0; i < numEntries; i++) {\n    entries[i].length = readVarint(p);\n  }\n\n  for (let i = 0; i < numEntries; i++) {\n    const v = readVarint(p);\n    if (v === 0 && i > 0) {\n      entries[i].offset = entries[i - 1].offset + entries[i - 1].length;\n    } else {\n      entries[i].offset = v - 1;\n    }\n  }\n\n  return entries;\n}\n\nfunction detectVersion(a: ArrayBuffer): number {\n  const v = new DataView(a);\n  if (v.getUint16(2, true) === 2) {\n    console.error(\n      \"PMTiles spec version 2 is not supported; please see github.com/protomaps/PMTiles for tools to upgrade\"\n    );\n    return 2;\n  }\n  if (v.getUint16(2, true) === 1) {\n    console.error(\n      \"PMTiles spec version 1 is not supported; please see github.com/protomaps/PMTiles for tools to upgrade\"\n    );\n    return 1;\n  }\n  return 3;\n}\n\n/**\n * Error thrown when a response for PMTiles over HTTP does not match previous, cached parts of the archive.\n * The default PMTiles implementation will catch this error once internally and retry a request.\n */\nexport class EtagMismatch extends Error {}\n\n/**\n * Interface for caches of parts (headers, directories) of a PMTiles archive.\n */\nexport interface Cache {\n  getHeader: (source: Source) => Promise<Header>;\n  getDirectory: (\n    source: Source,\n    offset: number,\n    length: number,\n    header: Header\n  ) => Promise<Entry[]>;\n  invalidate: (source: Source) => Promise<void>;\n}\n\nasync function getHeaderAndRoot(\n  source: Source,\n  decompress: DecompressFunc\n): Promise<[Header, [string, number, Entry[] | ArrayBuffer]?]> {\n  const resp = await source.getBytes(0, 16384);\n\n  const v = new DataView(resp.data);\n  if (v.getUint16(0, true) !== 0x4d50) {\n    throw new Error(\"Wrong magic number for PMTiles archive\");\n  }\n\n  const headerData = resp.data.slice(0, HEADER_SIZE_BYTES);\n\n  const header = bytesToHeader(headerData, resp.etag);\n\n  // optimistically set the root directory\n  // TODO check root bounds\n  const rootDirData = resp.data.slice(\n    header.rootDirectoryOffset,\n    header.rootDirectoryOffset + header.rootDirectoryLength\n  );\n  const dirKey = `${source.getKey()}|${header.etag || \"\"}|${\n    header.rootDirectoryOffset\n  }|${header.rootDirectoryLength}`;\n\n  const rootDir = deserializeIndex(\n    await decompress(rootDirData, header.internalCompression)\n  );\n  return [header, [dirKey, rootDir.length, rootDir]];\n}\n\nasync function getDirectory(\n  source: Source,\n  decompress: DecompressFunc,\n  offset: number,\n  length: number,\n  header: Header\n): Promise<Entry[]> {\n  const resp = await source.getBytes(offset, length, undefined, header.etag);\n  const data = await decompress(resp.data, header.internalCompression);\n  const directory = deserializeIndex(data);\n  if (directory.length === 0) {\n    throw new Error(\"Empty directory is invalid\");\n  }\n\n  return directory;\n}\n\ninterface ResolvedValue {\n  lastUsed: number;\n  data: Header | Entry[] | ArrayBuffer;\n}\n\n/**\n * A cache for parts of a PMTiles archive where promises are never shared between requests.\n *\n * Runtimes such as Cloudflare Workers cannot share promises between different requests.\n *\n * Only caches headers and directories, not individual tile contents.\n */\nexport class ResolvedValueCache {\n  cache: Map<string, ResolvedValue>;\n  maxCacheEntries: number;\n  counter: number;\n  decompress: DecompressFunc;\n\n  constructor(\n    maxCacheEntries = 100,\n    prefetch = true, // deprecated\n    decompress: DecompressFunc = defaultDecompress\n  ) {\n    this.cache = new Map<string, ResolvedValue>();\n    this.maxCacheEntries = maxCacheEntries;\n    this.counter = 1;\n    this.decompress = decompress;\n  }\n\n  async getHeader(source: Source): Promise<Header> {\n    const cacheKey = source.getKey();\n    const cacheValue = this.cache.get(cacheKey);\n    if (cacheValue) {\n      cacheValue.lastUsed = this.counter++;\n      const data = cacheValue.data;\n      return data as Header;\n    }\n\n    const res = await getHeaderAndRoot(source, this.decompress);\n    if (res[1]) {\n      this.cache.set(res[1][0], {\n        lastUsed: this.counter++,\n        data: res[1][2],\n      });\n    }\n\n    this.cache.set(cacheKey, {\n      lastUsed: this.counter++,\n      data: res[0],\n    });\n    this.prune();\n    return res[0];\n  }\n\n  async getDirectory(\n    source: Source,\n    offset: number,\n    length: number,\n    header: Header\n  ): Promise<Entry[]> {\n    const cacheKey = `${source.getKey()}|${\n      header.etag || \"\"\n    }|${offset}|${length}`;\n    const cacheValue = this.cache.get(cacheKey);\n    if (cacheValue) {\n      cacheValue.lastUsed = this.counter++;\n      const data = cacheValue.data;\n      return data as Entry[];\n    }\n\n    const directory = await getDirectory(\n      source,\n      this.decompress,\n      offset,\n      length,\n      header\n    );\n    this.cache.set(cacheKey, {\n      lastUsed: this.counter++,\n      data: directory,\n    });\n    this.prune();\n    return directory;\n  }\n\n  prune() {\n    if (this.cache.size > this.maxCacheEntries) {\n      let minUsed = Infinity;\n      let minKey = undefined;\n      this.cache.forEach((cacheValue: ResolvedValue, key: string) => {\n        if (cacheValue.lastUsed < minUsed) {\n          minUsed = cacheValue.lastUsed;\n          minKey = key;\n        }\n      });\n      if (minKey) {\n        this.cache.delete(minKey);\n      }\n    }\n  }\n\n  async invalidate(source: Source) {\n    this.cache.delete(source.getKey());\n  }\n}\n\ninterface SharedPromiseCacheValue {\n  lastUsed: number;\n  data: Promise<Header | Entry[] | ArrayBuffer>;\n}\n\n/**\n * A cache for parts of a PMTiles archive where promises can be shared between requests.\n *\n * Only caches headers and directories, not individual tile contents.\n */\nexport class SharedPromiseCache {\n  cache: Map<string, SharedPromiseCacheValue>;\n  invalidations: Map<string, Promise<void>>;\n  maxCacheEntries: number;\n  counter: number;\n  decompress: DecompressFunc;\n\n  constructor(\n    maxCacheEntries = 100,\n    prefetch = true, // deprecated\n    decompress: DecompressFunc = defaultDecompress\n  ) {\n    this.cache = new Map<string, SharedPromiseCacheValue>();\n    this.invalidations = new Map<string, Promise<void>>();\n    this.maxCacheEntries = maxCacheEntries;\n    this.counter = 1;\n    this.decompress = decompress;\n  }\n\n  async getHeader(source: Source): Promise<Header> {\n    const cacheKey = source.getKey();\n    const cacheValue = this.cache.get(cacheKey);\n    if (cacheValue) {\n      cacheValue.lastUsed = this.counter++;\n      const data = await cacheValue.data;\n      return data as Header;\n    }\n\n    const p = new Promise<Header>((resolve, reject) => {\n      getHeaderAndRoot(source, this.decompress)\n        .then((res) => {\n          if (res[1]) {\n            this.cache.set(res[1][0], {\n              lastUsed: this.counter++,\n              data: Promise.resolve(res[1][2]),\n            });\n          }\n          resolve(res[0]);\n          this.prune();\n        })\n        .catch((e) => {\n          reject(e);\n        });\n    });\n    this.cache.set(cacheKey, { lastUsed: this.counter++, data: p });\n    return p;\n  }\n\n  async getDirectory(\n    source: Source,\n    offset: number,\n    length: number,\n    header: Header\n  ): Promise<Entry[]> {\n    const cacheKey = `${source.getKey()}|${\n      header.etag || \"\"\n    }|${offset}|${length}`;\n    const cacheValue = this.cache.get(cacheKey);\n    if (cacheValue) {\n      cacheValue.lastUsed = this.counter++;\n      const data = await cacheValue.data;\n      return data as Entry[];\n    }\n\n    const p = new Promise<Entry[]>((resolve, reject) => {\n      getDirectory(source, this.decompress, offset, length, header)\n        .then((directory) => {\n          resolve(directory);\n          this.prune();\n        })\n        .catch((e) => {\n          reject(e);\n        });\n    });\n    this.cache.set(cacheKey, { lastUsed: this.counter++, data: p });\n    return p;\n  }\n\n  prune() {\n    if (this.cache.size >= this.maxCacheEntries) {\n      let minUsed = Infinity;\n      let minKey = undefined;\n      this.cache.forEach((cacheValue: SharedPromiseCacheValue, key: string) => {\n        if (cacheValue.lastUsed < minUsed) {\n          minUsed = cacheValue.lastUsed;\n          minKey = key;\n        }\n      });\n      if (minKey) {\n        this.cache.delete(minKey);\n      }\n    }\n  }\n\n  async invalidate(source: Source) {\n    const key = source.getKey();\n    if (this.invalidations.get(key)) {\n      return await this.invalidations.get(key);\n    }\n    this.cache.delete(source.getKey());\n    const p = new Promise<void>((resolve, reject) => {\n      this.getHeader(source)\n        .then((h) => {\n          resolve();\n          this.invalidations.delete(key);\n        })\n        .catch((e) => {\n          reject(e);\n        });\n    });\n    this.invalidations.set(key, p);\n  }\n}\n\n/**\n * Main class encapsulating PMTiles decoding logic.\n *\n * if `source` is a string, creates a FetchSource using that string as the URL to a remote PMTiles.\n * if no `cache` is passed, use a SharedPromiseCache.\n * if no `decompress` is passed, default to the browser DecompressionStream API with a fallback to `fflate`.\n */\n// biome-ignore lint: that's just how its capitalized\nexport class PMTiles {\n  source: Source;\n  cache: Cache;\n  decompress: DecompressFunc;\n\n  constructor(\n    source: Source | string,\n    customHeaders: Headers,\n    cache?: Cache,\n    decompress?: DecompressFunc\n  ) {\n    if (typeof source === \"string\") {\n      this.source = new FetchSource(source, customHeaders);\n    } else {\n      this.source = source;\n    }\n    if (decompress) {\n      this.decompress = decompress;\n    } else {\n      this.decompress = defaultDecompress;\n    }\n    if (cache) {\n      this.cache = cache;\n    } else {\n      this.cache = new SharedPromiseCache();\n    }\n  }\n\n  /**\n   * Return the header of the archive,\n   * including information such as tile type, min/max zoom, bounds, and summary statistics.\n   */\n  async getHeader() {\n    return await this.cache.getHeader(this.source);\n  }\n\n  /** @hidden */\n  async getZxyAttempt(\n    z: number,\n    x: number,\n    y: number,\n    signal?: AbortSignal\n  ): Promise<RangeResponse | undefined> {\n    const tileId = zxyToTileId(z, x, y);\n    const header = await this.cache.getHeader(this.source);\n\n    if (z < header.minZoom || z > header.maxZoom) {\n      return undefined;\n    }\n\n    let dO = header.rootDirectoryOffset;\n    let dL = header.rootDirectoryLength;\n    for (let depth = 0; depth <= 3; depth++) {\n      const directory = await this.cache.getDirectory(\n        this.source,\n        dO,\n        dL,\n        header\n      );\n      const entry = findTile(directory, tileId);\n      if (entry) {\n        if (entry.runLength > 0) {\n          const resp = await this.source.getBytes(\n            header.tileDataOffset + entry.offset,\n            entry.length,\n            signal,\n            header.etag\n          );\n          return {\n            data: await this.decompress(resp.data, header.tileCompression),\n            cacheControl: resp.cacheControl,\n            expires: resp.expires,\n          };\n        }\n        dO = header.leafDirectoryOffset + entry.offset;\n        dL = entry.length;\n      } else {\n        // TODO: We should in fact return a valid RangeResponse\n        // with empty data, but filled in cache control / expires headers\n        return undefined;\n      }\n    }\n    throw new Error(\"Maximum directory depth exceeded\");\n  }\n\n  /**\n   * Primary method to get a single tile's bytes from an archive.\n   *\n   * Returns undefined if the tile does not exist in the archive.\n   */\n  async getZxy(\n    z: number,\n    x: number,\n    y: number,\n    signal?: AbortSignal\n  ): Promise<RangeResponse | undefined> {\n    try {\n      return await this.getZxyAttempt(z, x, y, signal);\n    } catch (e) {\n      if (e instanceof EtagMismatch) {\n        this.cache.invalidate(this.source);\n        return await this.getZxyAttempt(z, x, y, signal);\n      }\n      throw e;\n    }\n  }\n\n  /** @hidden */\n  async getMetadataAttempt(): Promise<unknown> {\n    const header = await this.cache.getHeader(this.source);\n\n    const resp = await this.source.getBytes(\n      header.jsonMetadataOffset,\n      header.jsonMetadataLength,\n      undefined,\n      header.etag\n    );\n    const decompressed = await this.decompress(\n      resp.data,\n      header.internalCompression\n    );\n    const dec = new TextDecoder(\"utf-8\");\n    return JSON.parse(dec.decode(decompressed));\n  }\n\n  /**\n   * Return the arbitrary JSON metadata of the archive.\n   */\n  async getMetadata(): Promise<unknown> {\n    try {\n      return await this.getMetadataAttempt();\n    } catch (e) {\n      if (e instanceof EtagMismatch) {\n        this.cache.invalidate(this.source);\n        return await this.getMetadataAttempt();\n      }\n      throw e;\n    }\n  }\n\n  /**\n   * Construct a [TileJSON](https://github.com/mapbox/tilejson-spec) object.\n   *\n   * baseTilesUrl is the desired tiles URL, excluding the suffix `/{z}/{x}/{y}.{ext}`.\n   * For example, if the desired URL is `http://example.com/tileset/{z}/{x}/{y}.mvt`,\n   * the baseTilesUrl should be `https://example.com/tileset`.\n   */\n  async getTileJson(baseTilesUrl: string): Promise<unknown> {\n    const header = await this.getHeader();\n    const metadata = (await this.getMetadata()) as MetadataLike;\n    const ext = tileTypeExt(header.tileType);\n\n    return {\n      tilejson: \"3.0.0\",\n      scheme: \"xyz\",\n      tiles: [`${baseTilesUrl}/{z}/{x}/{y}${ext}`],\n      // biome-ignore lint: TileJSON spec\n      vector_layers: metadata.vector_layers,\n      attribution: metadata.attribution,\n      description: metadata.description,\n      name: metadata.name,\n      version: metadata.version,\n      bounds: [header.minLon, header.minLat, header.maxLon, header.maxLat],\n      center: [header.centerLon, header.centerLat, header.centerZoom],\n      minzoom: header.minZoom,\n      maxzoom: header.maxZoom,\n    };\n  }\n}\n","// DEFLATE is a complex format; to read this code, you should probably check the RFC first:\n// https://tools.ietf.org/html/rfc1951\n// You may also wish to take a look at the guide I made about this program:\n// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad\n// Some of the following code is similar to that of UZIP.js:\n// https://github.com/photopea/UZIP.js\n// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size.\n// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint\n// is better for memory in most engines (I *think*).\nvar ch2 = {};\nvar wk = (function (c, id, msg, transfer, cb) {\n    var w = new Worker(ch2[id] || (ch2[id] = URL.createObjectURL(new Blob([\n        c + ';addEventListener(\"error\",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'\n    ], { type: 'text/javascript' }))));\n    w.onmessage = function (e) {\n        var d = e.data, ed = d.$e$;\n        if (ed) {\n            var err = new Error(ed[0]);\n            err['code'] = ed[1];\n            err.stack = ed[2];\n            cb(err, null);\n        }\n        else\n            cb(null, d);\n    };\n    w.postMessage(msg, transfer);\n    return w;\n});\n\n// aliases for shorter compressed code (most minifers don't do this)\nvar u8 = Uint8Array, u16 = Uint16Array, i32 = Int32Array;\n// fixed length extra bits\nvar fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]);\n// fixed distance extra bits\nvar fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]);\n// code length index map\nvar clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);\n// get base, reverse index map from extra bits\nvar freb = function (eb, start) {\n    var b = new u16(31);\n    for (var i = 0; i < 31; ++i) {\n        b[i] = start += 1 << eb[i - 1];\n    }\n    // numbers here are at max 18 bits\n    var r = new i32(b[30]);\n    for (var i = 1; i < 30; ++i) {\n        for (var j = b[i]; j < b[i + 1]; ++j) {\n            r[j] = ((j - b[i]) << 5) | i;\n        }\n    }\n    return { b: b, r: r };\n};\nvar _a = freb(fleb, 2), fl = _a.b, revfl = _a.r;\n// we can ignore the fact that the other numbers are wrong; they never happen anyway\nfl[28] = 258, revfl[258] = 28;\nvar _b = freb(fdeb, 0), fd = _b.b, revfd = _b.r;\n// map of value to reverse (assuming 16 bits)\nvar rev = new u16(32768);\nfor (var i = 0; i < 32768; ++i) {\n    // reverse table algorithm from SO\n    var x = ((i & 0xAAAA) >> 1) | ((i & 0x5555) << 1);\n    x = ((x & 0xCCCC) >> 2) | ((x & 0x3333) << 2);\n    x = ((x & 0xF0F0) >> 4) | ((x & 0x0F0F) << 4);\n    rev[i] = (((x & 0xFF00) >> 8) | ((x & 0x00FF) << 8)) >> 1;\n}\n// create huffman tree from u8 \"map\": index -> code length for code index\n// mb (max bits) must be at most 15\n// TODO: optimize/split up?\nvar hMap = (function (cd, mb, r) {\n    var s = cd.length;\n    // index\n    var i = 0;\n    // u16 \"map\": index -> # of codes with bit length = index\n    var l = new u16(mb);\n    // length of cd must be 288 (total # of codes)\n    for (; i < s; ++i) {\n        if (cd[i])\n            ++l[cd[i] - 1];\n    }\n    // u16 \"map\": index -> minimum code for bit length = index\n    var le = new u16(mb);\n    for (i = 1; i < mb; ++i) {\n        le[i] = (le[i - 1] + l[i - 1]) << 1;\n    }\n    var co;\n    if (r) {\n        // u16 \"map\": index -> number of actual bits, symbol for code\n        co = new u16(1 << mb);\n        // bits to remove for reverser\n        var rvb = 15 - mb;\n        for (i = 0; i < s; ++i) {\n            // ignore 0 lengths\n            if (cd[i]) {\n                // num encoding both symbol and bits read\n                var sv = (i << 4) | cd[i];\n                // free bits\n                var r_1 = mb - cd[i];\n                // start value\n                var v = le[cd[i] - 1]++ << r_1;\n                // m is end value\n                for (var m = v | ((1 << r_1) - 1); v <= m; ++v) {\n                    // every 16 bit value starting with the code yields the same result\n                    co[rev[v] >> rvb] = sv;\n                }\n            }\n        }\n    }\n    else {\n        co = new u16(s);\n        for (i = 0; i < s; ++i) {\n            if (cd[i]) {\n                co[i] = rev[le[cd[i] - 1]++] >> (15 - cd[i]);\n            }\n        }\n    }\n    return co;\n});\n// fixed length tree\nvar flt = new u8(288);\nfor (var i = 0; i < 144; ++i)\n    flt[i] = 8;\nfor (var i = 144; i < 256; ++i)\n    flt[i] = 9;\nfor (var i = 256; i < 280; ++i)\n    flt[i] = 7;\nfor (var i = 280; i < 288; ++i)\n    flt[i] = 8;\n// fixed distance tree\nvar fdt = new u8(32);\nfor (var i = 0; i < 32; ++i)\n    fdt[i] = 5;\n// fixed length map\nvar flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1);\n// fixed distance map\nvar fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);\n// find max of array\nvar max = function (a) {\n    var m = a[0];\n    for (var i = 1; i < a.length; ++i) {\n        if (a[i] > m)\n            m = a[i];\n    }\n    return m;\n};\n// read d, starting at bit p and mask with m\nvar bits = function (d, p, m) {\n    var o = (p / 8) | 0;\n    return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m;\n};\n// read d, starting at bit p continuing for at least 16 bits\nvar bits16 = function (d, p) {\n    var o = (p / 8) | 0;\n    return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7));\n};\n// get end of byte\nvar shft = function (p) { return ((p + 7) / 8) | 0; };\n// typed array slice - allows garbage collector to free original reference,\n// while being more compatible than .slice\nvar slc = function (v, s, e) {\n    if (s == null || s < 0)\n        s = 0;\n    if (e == null || e > v.length)\n        e = v.length;\n    // can't use .constructor in case user-supplied\n    return new u8(v.subarray(s, e));\n};\n/**\n * Codes for errors generated within this library\n */\nexport var FlateErrorCode = {\n    UnexpectedEOF: 0,\n    InvalidBlockType: 1,\n    InvalidLengthLiteral: 2,\n    InvalidDistance: 3,\n    StreamFinished: 4,\n    NoStreamHandler: 5,\n    InvalidHeader: 6,\n    NoCallback: 7,\n    InvalidUTF8: 8,\n    ExtraFieldTooLong: 9,\n    InvalidDate: 10,\n    FilenameTooLong: 11,\n    StreamFinishing: 12,\n    InvalidZipData: 13,\n    UnknownCompressionMethod: 14\n};\n// error codes\nvar ec = [\n    'unexpected EOF',\n    'invalid block type',\n    'invalid length/literal',\n    'invalid distance',\n    'stream finished',\n    'no stream handler',\n    ,\n    'no callback',\n    'invalid UTF-8 data',\n    'extra field too long',\n    'date not in range 1980-2099',\n    'filename too long',\n    'stream finishing',\n    'invalid zip data'\n    // determined by unknown compression method\n];\n;\nvar err = function (ind, msg, nt) {\n    var e = new Error(msg || ec[ind]);\n    e.code = ind;\n    if (Error.captureStackTrace)\n        Error.captureStackTrace(e, err);\n    if (!nt)\n        throw e;\n    return e;\n};\n// expands raw DEFLATE data\nvar inflt = function (dat, st, buf, dict) {\n    // source length       dict length\n    var sl = dat.length, dl = dict ? dict.length : 0;\n    if (!sl || st.f && !st.l)\n        return buf || new u8(0);\n    var noBuf = !buf;\n    // have to estimate size\n    var resize = noBuf || st.i != 2;\n    // no state\n    var noSt = st.i;\n    // Assumes roughly 33% compression ratio average\n    if (noBuf)\n        buf = new u8(sl * 3);\n    // ensure buffer can fit at least l elements\n    var cbuf = function (l) {\n        var bl = buf.length;\n        // need to increase size to fit\n        if (l > bl) {\n            // Double or set to necessary, whichever is greater\n            var nbuf = new u8(Math.max(bl * 2, l));\n            nbuf.set(buf);\n            buf = nbuf;\n        }\n    };\n    //  last chunk         bitpos           bytes\n    var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;\n    // total bits\n    var tbts = sl * 8;\n    do {\n        if (!lm) {\n            // BFINAL - this is only 1 when last chunk is next\n            final = bits(dat, pos, 1);\n            // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman\n            var type = bits(dat, pos + 1, 3);\n            pos += 3;\n            if (!type) {\n                // go to end of byte boundary\n                var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;\n                if (t > sl) {\n                    if (noSt)\n                        err(0);\n                    break;\n                }\n                // ensure size\n                if (resize)\n                    cbuf(bt + l);\n                // Copy over uncompressed data\n                buf.set(dat.subarray(s, t), bt);\n                // Get new bitpos, update byte count\n                st.b = bt += l, st.p = pos = t * 8, st.f = final;\n                continue;\n            }\n            else if (type == 1)\n                lm = flrm, dm = fdrm, lbt = 9, dbt = 5;\n            else if (type == 2) {\n                //  literal                            lengths\n                var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;\n                var tl = hLit + bits(dat, pos + 5, 31) + 1;\n                pos += 14;\n                // length+distance tree\n                var ldt = new u8(tl);\n                // code length tree\n                var clt = new u8(19);\n                for (var i = 0; i < hcLen; ++i) {\n                    // use index map to get real code\n                    clt[clim[i]] = bits(dat, pos + i * 3, 7);\n                }\n                pos += hcLen * 3;\n                // code lengths bits\n                var clb = max(clt), clbmsk = (1 << clb) - 1;\n                // code lengths map\n                var clm = hMap(clt, clb, 1);\n                for (var i = 0; i < tl;) {\n                    var r = clm[bits(dat, pos, clbmsk)];\n                    // bits read\n                    pos += r & 15;\n                    // symbol\n                    var s = r >> 4;\n                    // code length to copy\n                    if (s < 16) {\n                        ldt[i++] = s;\n                    }\n                    else {\n                        //  copy   count\n                        var c = 0, n = 0;\n                        if (s == 16)\n                            n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];\n                        else if (s == 17)\n                            n = 3 + bits(dat, pos, 7), pos += 3;\n                        else if (s == 18)\n                            n = 11 + bits(dat, pos, 127), pos += 7;\n                        while (n--)\n                            ldt[i++] = c;\n                    }\n                }\n                //    length tree                 distance tree\n                var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);\n                // max length bits\n                lbt = max(lt);\n                // max dist bits\n                dbt = max(dt);\n                lm = hMap(lt, lbt, 1);\n                dm = hMap(dt, dbt, 1);\n            }\n            else\n                err(1);\n            if (pos > tbts) {\n                if (noSt)\n                    err(0);\n                break;\n            }\n        }\n        // Make sure the buffer can hold this + the largest possible addition\n        // Maximum chunk size (practically, theoretically infinite) is 2^17\n        if (resize)\n            cbuf(bt + 131072);\n        var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;\n        var lpos = pos;\n        for (;; lpos = pos) {\n            // bits read, code\n            var c = lm[bits16(dat, pos) & lms], sym = c >> 4;\n            pos += c & 15;\n            if (pos > tbts) {\n                if (noSt)\n                    err(0);\n                break;\n            }\n            if (!c)\n                err(2);\n            if (sym < 256)\n                buf[bt++] = sym;\n            else if (sym == 256) {\n                lpos = pos, lm = null;\n                break;\n            }\n            else {\n                var add = sym - 254;\n                // no extra bits needed if less\n                if (sym > 264) {\n                    // index\n                    var i = sym - 257, b = fleb[i];\n                    add = bits(dat, pos, (1 << b) - 1) + fl[i];\n                    pos += b;\n                }\n                // dist\n                var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;\n                if (!d)\n                    err(3);\n                pos += d & 15;\n                var dt = fd[dsym];\n                if (dsym > 3) {\n                    var b = fdeb[dsym];\n                    dt += bits16(dat, pos) & (1 << b) - 1, pos += b;\n                }\n                if (pos > tbts) {\n                    if (noSt)\n                        err(0);\n                    break;\n                }\n                if (resize)\n                    cbuf(bt + 131072);\n                var end = bt + add;\n                if (bt < dt) {\n                    var shift = dl - dt, dend = Math.min(dt, end);\n                    if (shift + bt < 0)\n                        err(3);\n                    for (; bt < dend; ++bt)\n                        buf[bt] = dict[shift + bt];\n                }\n                for (; bt < end; ++bt)\n                    buf[bt] = buf[bt - dt];\n            }\n        }\n        st.l = lm, st.p = lpos, st.b = bt, st.f = final;\n        if (lm)\n            final = 1, st.m = lbt, st.d = dm, st.n = dbt;\n    } while (!final);\n    // don't reallocate for streams or user buffers\n    return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);\n};\n// starting at p, write the minimum number of bits that can hold v to d\nvar wbits = function (d, p, v) {\n    v <<= p & 7;\n    var o = (p / 8) | 0;\n    d[o] |= v;\n    d[o + 1] |= v >> 8;\n};\n// starting at p, write the minimum number of bits (>8) that can hold v to d\nvar wbits16 = function (d, p, v) {\n    v <<= p & 7;\n    var o = (p / 8) | 0;\n    d[o] |= v;\n    d[o + 1] |= v >> 8;\n    d[o + 2] |= v >> 16;\n};\n// creates code lengths from a frequency table\nvar hTree = function (d, mb) {\n    // Need extra info to make a tree\n    var t = [];\n    for (var i = 0; i < d.length; ++i) {\n        if (d[i])\n            t.push({ s: i, f: d[i] });\n    }\n    var s = t.length;\n    var t2 = t.slice();\n    if (!s)\n        return { t: et, l: 0 };\n    if (s == 1) {\n        var v = new u8(t[0].s + 1);\n        v[t[0].s] = 1;\n        return { t: v, l: 1 };\n    }\n    t.sort(function (a, b) { return a.f - b.f; });\n    // after i2 reaches last ind, will be stopped\n    // freq must be greater than largest possible number of symbols\n    t.push({ s: -1, f: 25001 });\n    var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;\n    t[0] = { s: -1, f: l.f + r.f, l: l, r: r };\n    // efficient algorithm from UZIP.js\n    // i0 is lookbehind, i2 is lookahead - after processing two low-freq\n    // symbols that combined have high freq, will start processing i2 (high-freq,\n    // non-composite) symbols instead\n    // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/\n    while (i1 != s - 1) {\n        l = t[t[i0].f < t[i2].f ? i0++ : i2++];\n        r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];\n        t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r };\n    }\n    var maxSym = t2[0].s;\n    for (var i = 1; i < s; ++i) {\n        if (t2[i].s > maxSym)\n            maxSym = t2[i].s;\n    }\n    // code lengths\n    var tr = new u16(maxSym + 1);\n    // max bits in tree\n    var mbt = ln(t[i1 - 1], tr, 0);\n    if (mbt > mb) {\n        // more algorithms from UZIP.js\n        // TODO: find out how this code works (debt)\n        //  ind    debt\n        var i = 0, dt = 0;\n        //    left            cost\n        var lft = mbt - mb, cst = 1 << lft;\n        t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; });\n        for (; i < s; ++i) {\n            var i2_1 = t2[i].s;\n            if (tr[i2_1] > mb) {\n                dt += cst - (1 << (mbt - tr[i2_1]));\n                tr[i2_1] = mb;\n            }\n            else\n                break;\n        }\n        dt >>= lft;\n        while (dt > 0) {\n            var i2_2 = t2[i].s;\n            if (tr[i2_2] < mb)\n                dt -= 1 << (mb - tr[i2_2]++ - 1);\n            else\n                ++i;\n        }\n        for (; i >= 0 && dt; --i) {\n            var i2_3 = t2[i].s;\n            if (tr[i2_3] == mb) {\n                --tr[i2_3];\n                ++dt;\n            }\n        }\n        mbt = mb;\n    }\n    return { t: new u8(tr), l: mbt };\n};\n// get the max length and assign length codes\nvar ln = function (n, l, d) {\n    return n.s == -1\n        ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1))\n        : (l[n.s] = d);\n};\n// length codes generation\nvar lc = function (c) {\n    var s = c.length;\n    // Note that the semicolon was intentional\n    while (s && !c[--s])\n        ;\n    var cl = new u16(++s);\n    //  ind      num         streak\n    var cli = 0, cln = c[0], cls = 1;\n    var w = function (v) { cl[cli++] = v; };\n    for (var i = 1; i <= s; ++i) {\n        if (c[i] == cln && i != s)\n            ++cls;\n        else {\n            if (!cln && cls > 2) {\n                for (; cls > 138; cls -= 138)\n                    w(32754);\n                if (cls > 2) {\n                    w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305);\n                    cls = 0;\n                }\n            }\n            else if (cls > 3) {\n                w(cln), --cls;\n                for (; cls > 6; cls -= 6)\n                    w(8304);\n                if (cls > 2)\n                    w(((cls - 3) << 5) | 8208), cls = 0;\n            }\n            while (cls--)\n                w(cln);\n            cls = 1;\n            cln = c[i];\n        }\n    }\n    return { c: cl.subarray(0, cli), n: s };\n};\n// calculate the length of output from tree, code lengths\nvar clen = function (cf, cl) {\n    var l = 0;\n    for (var i = 0; i < cl.length; ++i)\n        l += cf[i] * cl[i];\n    return l;\n};\n// writes a fixed block\n// returns the new bit pos\nvar wfblk = function (out, pos, dat) {\n    // no need to write 00 as type: TypedArray defaults to 0\n    var s = dat.length;\n    var o = shft(pos + 2);\n    out[o] = s & 255;\n    out[o + 1] = s >> 8;\n    out[o + 2] = out[o] ^ 255;\n    out[o + 3] = out[o + 1] ^ 255;\n    for (var i = 0; i < s; ++i)\n        out[o + i + 4] = dat[i];\n    return (o + 4 + s) * 8;\n};\n// writes a block\nvar wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) {\n    wbits(out, p++, final);\n    ++lf[256];\n    var _a = hTree(lf, 15), dlt = _a.t, mlb = _a.l;\n    var _b = hTree(df, 15), ddt = _b.t, mdb = _b.l;\n    var _c = lc(dlt), lclt = _c.c, nlc = _c.n;\n    var _d = lc(ddt), lcdt = _d.c, ndc = _d.n;\n    var lcfreq = new u16(19);\n    for (var i = 0; i < lclt.length; ++i)\n        ++lcfreq[lclt[i] & 31];\n    for (var i = 0; i < lcdt.length; ++i)\n        ++lcfreq[lcdt[i] & 31];\n    var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l;\n    var nlcc = 19;\n    for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)\n        ;\n    var flen = (bl + 5) << 3;\n    var ftlen = clen(lf, flt) + clen(df, fdt) + eb;\n    var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18];\n    if (bs >= 0 && flen <= ftlen && flen <= dtlen)\n        return wfblk(out, p, dat.subarray(bs, bs + bl));\n    var lm, ll, dm, dl;\n    wbits(out, p, 1 + (dtlen < ftlen)), p += 2;\n    if (dtlen < ftlen) {\n        lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;\n        var llm = hMap(lct, mlcb, 0);\n        wbits(out, p, nlc - 257);\n        wbits(out, p + 5, ndc - 1);\n        wbits(out, p + 10, nlcc - 4);\n        p += 14;\n        for (var i = 0; i < nlcc; ++i)\n            wbits(out, p + 3 * i, lct[clim[i]]);\n        p += 3 * nlcc;\n        var lcts = [lclt, lcdt];\n        for (var it = 0; it < 2; ++it) {\n            var clct = lcts[it];\n            for (var i = 0; i < clct.length; ++i) {\n                var len = clct[i] & 31;\n                wbits(out, p, llm[len]), p += lct[len];\n                if (len > 15)\n                    wbits(out, p, (clct[i] >> 5) & 127), p += clct[i] >> 12;\n            }\n        }\n    }\n    else {\n        lm = flm, ll = flt, dm = fdm, dl = fdt;\n    }\n    for (var i = 0; i < li; ++i) {\n        var sym = syms[i];\n        if (sym > 255) {\n            var len = (sym >> 18) & 31;\n            wbits16(out, p, lm[len + 257]), p += ll[len + 257];\n            if (len > 7)\n                wbits(out, p, (sym >> 23) & 31), p += fleb[len];\n            var dst = sym & 31;\n            wbits16(out, p, dm[dst]), p += dl[dst];\n            if (dst > 3)\n                wbits16(out, p, (sym >> 5) & 8191), p += fdeb[dst];\n        }\n        else {\n            wbits16(out, p, lm[sym]), p += ll[sym];\n        }\n    }\n    wbits16(out, p, lm[256]);\n    return p + ll[256];\n};\n// deflate options (nice << 13) | chain\nvar deo = /*#__PURE__*/ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);\n// empty\nvar et = /*#__PURE__*/ new u8(0);\n// compresses data into a raw DEFLATE buffer\nvar dflt = function (dat, lvl, plvl, pre, post, st) {\n    var s = st.z || dat.length;\n    var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post);\n    // writing to this writes to the output buffer\n    var w = o.subarray(pre, o.length - post);\n    var lst = st.l;\n    var pos = (st.r || 0) & 7;\n    if (lvl) {\n        if (pos)\n            w[0] = st.r >> 3;\n        var opt = deo[lvl - 1];\n        var n = opt >> 13, c = opt & 8191;\n        var msk_1 = (1 << plvl) - 1;\n        //    prev 2-byte val map    curr 2-byte val map\n        var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1);\n        var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;\n        var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; };\n        // 24576 is an arbitrary number of maximum symbols per block\n        // 424 buffer for last block\n        var syms = new i32(25000);\n        // length/literal freq   distance freq\n        var lf = new u16(288), df = new u16(32);\n        //  l/lcnt  exbits  index          l/lind  waitdx          blkpos\n        var lc_1 = 0, eb = 0, i = st.i || 0, li = 0, wi = st.w || 0, bs = 0;\n        for (; i + 2 < s; ++i) {\n            // hash value\n            var hv = hsh(i);\n            // index mod 32768    previous index mod\n            var imod = i & 32767, pimod = head[hv];\n            prev[imod] = pimod;\n            head[hv] = imod;\n            // We always should modify head and prev, but only add symbols if\n            // this data is not yet processed (\"wait\" for wait index)\n            if (wi <= i) {\n                // bytes remaining\n                var rem = s - i;\n                if ((lc_1 > 7000 || li > 24576) && (rem > 423 || !lst)) {\n                    pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);\n                    li = lc_1 = eb = 0, bs = i;\n                    for (var j = 0; j < 286; ++j)\n                        lf[j] = 0;\n                    for (var j = 0; j < 30; ++j)\n                        df[j] = 0;\n                }\n                //  len    dist   chain\n                var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767;\n                if (rem > 2 && hv == hsh(i - dif)) {\n                    var maxn = Math.min(n, rem) - 1;\n                    var maxd = Math.min(32767, i);\n                    // max possible length\n                    // not capped at dif because decompressors implement \"rolling\" index population\n                    var ml = Math.min(258, rem);\n                    while (dif <= maxd && --ch_1 && imod != pimod) {\n                        if (dat[i + l] == dat[i + l - dif]) {\n                            var nl = 0;\n                            for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)\n                                ;\n                            if (nl > l) {\n                                l = nl, d = dif;\n                                // break out early when we reach \"nice\" (we are satisfied enough)\n                                if (nl > maxn)\n                                    break;\n                                // now, find the rarest 2-byte sequence within this\n                                // length of literals and search for that instead.\n                                // Much faster than just using the start\n                                var mmd = Math.min(dif, nl - 2);\n                                var md = 0;\n                                for (var j = 0; j < mmd; ++j) {\n                                    var ti = i - dif + j & 32767;\n                                    var pti = prev[ti];\n                                    var cd = ti - pti & 32767;\n                                    if (cd > md)\n                                        md = cd, pimod = ti;\n                                }\n                            }\n                        }\n                        // check the previous match\n                        imod = pimod, pimod = prev[imod];\n                        dif += imod - pimod & 32767;\n                    }\n                }\n                // d will be nonzero only when a match was found\n                if (d) {\n                    // store both dist and len data in one int32\n                    // Make sure this is recognized as a len/dist with 28th bit (2^28)\n                    syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d];\n                    var lin = revfl[l] & 31, din = revfd[d] & 31;\n                    eb += fleb[lin] + fdeb[din];\n                    ++lf[257 + lin];\n                    ++df[din];\n                    wi = i + l;\n                    ++lc_1;\n                }\n                else {\n                    syms[li++] = dat[i];\n                    ++lf[dat[i]];\n                }\n            }\n        }\n        for (i = Math.max(i, wi); i < s; ++i) {\n            syms[li++] = dat[i];\n            ++lf[dat[i]];\n        }\n        pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);\n        if (!lst) {\n            st.r = (pos & 7) | w[(pos / 8) | 0] << 3;\n            // shft(pos) now 1 less if pos & 7 != 0\n            pos -= 7;\n            st.h = head, st.p = prev, st.i = i, st.w = wi;\n        }\n    }\n    else {\n        for (var i = st.w || 0; i < s + lst; i += 65535) {\n            // end\n            var e = i + 65535;\n            if (e >= s) {\n                // write final block\n                w[(pos / 8) | 0] = lst;\n                e = s;\n            }\n            pos = wfblk(w, pos + 1, dat.subarray(i, e));\n        }\n        st.i = s;\n    }\n    return slc(o, 0, pre + shft(pos) + post);\n};\n// CRC32 table\nvar crct = /*#__PURE__*/ (function () {\n    var t = new Int32Array(256);\n    for (var i = 0; i < 256; ++i) {\n        var c = i, k = 9;\n        while (--k)\n            c = ((c & 1) && -306674912) ^ (c >>> 1);\n        t[i] = c;\n    }\n    return t;\n})();\n// CRC32\nvar crc = function () {\n    var c = -1;\n    return {\n        p: function (d) {\n            // closures have awful performance\n            var cr = c;\n            for (var i = 0; i < d.length; ++i)\n                cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8);\n            c = cr;\n        },\n        d: function () { return ~c; }\n    };\n};\n// Adler32\nvar adler = function () {\n    var a = 1, b = 0;\n    return {\n        p: function (d) {\n            // closures have awful performance\n            var n = a, m = b;\n            var l = d.length | 0;\n            for (var i = 0; i != l;) {\n                var e = Math.min(i + 2655, l);\n                for (; i < e; ++i)\n                    m += n += d[i];\n                n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16);\n            }\n            a = n, b = m;\n        },\n        d: function () {\n            a %= 65521, b %= 65521;\n            return (a & 255) << 24 | (a & 0xFF00) << 8 | (b & 255) << 8 | (b >> 8);\n        }\n    };\n};\n;\n// deflate with opts\nvar dopt = function (dat, opt, pre, post, st) {\n    if (!st) {\n        st = { l: 1 };\n        if (opt.dictionary) {\n            var dict = opt.dictionary.subarray(-32768);\n            var newDat = new u8(dict.length + dat.length);\n            newDat.set(dict);\n            newDat.set(dat, dict.length);\n            dat = newDat;\n            st.w = dict.length;\n        }\n    }\n    return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? (st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20) : (12 + opt.mem), pre, post, st);\n};\n// Walmart object spread\nvar mrg = function (a, b) {\n    var o = {};\n    for (var k in a)\n        o[k] = a[k];\n    for (var k in b)\n        o[k] = b[k];\n    return o;\n};\n// worker clone\n// This is possibly the craziest part of the entire codebase, despite how simple it may seem.\n// The only parameter to this function is a closure that returns an array of variables outside of the function scope.\n// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization.\n// We will return an object mapping of true variable name to value (basically, the current scope as a JS object).\n// The reason we can't just use the original variable names is minifiers mangling the toplevel scope.\n// This took me three weeks to figure out how to do.\nvar wcln = function (fn, fnStr, td) {\n    var dt = fn();\n    var st = fn.toString();\n    var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/\\s+/g, '').split(',');\n    for (var i = 0; i < dt.length; ++i) {\n        var v = dt[i], k = ks[i];\n        if (typeof v == 'function') {\n            fnStr += ';' + k + '=';\n            var st_1 = v.toString();\n            if (v.prototype) {\n                // for global objects\n                if (st_1.indexOf('[native code]') != -1) {\n                    var spInd = st_1.indexOf(' ', 8) + 1;\n                    fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd));\n                }\n                else {\n                    fnStr += st_1;\n                    for (var t in v.prototype)\n                        fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString();\n                }\n            }\n            else\n                fnStr += st_1;\n        }\n        else\n            td[k] = v;\n    }\n    return fnStr;\n};\nvar ch = [];\n// clone bufs\nvar cbfs = function (v) {\n    var tl = [];\n    for (var k in v) {\n        if (v[k].buffer) {\n            tl.push((v[k] = new v[k].constructor(v[k])).buffer);\n        }\n    }\n    return tl;\n};\n// use a worker to execute code\nvar wrkr = function (fns, init, id, cb) {\n    if (!ch[id]) {\n        var fnStr = '', td_1 = {}, m = fns.length - 1;\n        for (var i = 0; i < m; ++i)\n            fnStr = wcln(fns[i], fnStr, td_1);\n        ch[id] = { c: wcln(fns[m], fnStr, td_1), e: td_1 };\n    }\n    var td = mrg({}, ch[id].e);\n    return wk(ch[id].c + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb);\n};\n// base async inflate fn\nvar bInflt = function () { return [u8, u16, i32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gopt]; };\nvar bDflt = function () { return [u8, u16, i32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; };\n// gzip extra\nvar gze = function () { return [gzh, gzhl, wbytes, crc, crct]; };\n// gunzip extra\nvar guze = function () { return [gzs, gzl]; };\n// zlib extra\nvar zle = function () { return [zlh, wbytes, adler]; };\n// unzlib extra\nvar zule = function () { return [zls]; };\n// post buf\nvar pbf = function (msg) { return postMessage(msg, [msg.buffer]); };\n// get opts\nvar gopt = function (o) { return o && {\n    out: o.size && new u8(o.size),\n    dictionary: o.dictionary\n}; };\n// async helper\nvar cbify = function (dat, opts, fns, init, id, cb) {\n    var w = wrkr(fns, init, id, function (err, dat) {\n        w.terminate();\n        cb(err, dat);\n    });\n    w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []);\n    return function () { w.terminate(); };\n};\n// auto stream\nvar astrm = function (strm) {\n    strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); };\n    return function (ev) {\n        if (ev.data.length) {\n            strm.push(ev.data[0], ev.data[1]);\n            postMessage([ev.data[0].length]);\n        }\n        else\n            strm.flush();\n    };\n};\n// async stream attach\nvar astrmify = function (fns, strm, opts, init, id, flush, ext) {\n    var t;\n    var w = wrkr(fns, init, id, function (err, dat) {\n        if (err)\n            w.terminate(), strm.ondata.call(strm, err);\n        else if (!Array.isArray(dat))\n            ext(dat);\n        else if (dat.length == 1) {\n            strm.queuedSize -= dat[0];\n            if (strm.ondrain)\n                strm.ondrain(dat[0]);\n        }\n        else {\n            if (dat[1])\n                w.terminate();\n            strm.ondata.call(strm, err, dat[0], dat[1]);\n        }\n    });\n    w.postMessage(opts);\n    strm.queuedSize = 0;\n    strm.push = function (d, f) {\n        if (!strm.ondata)\n            err(5);\n        if (t)\n            strm.ondata(err(4, 0, 1), null, !!f);\n        strm.queuedSize += d.length;\n        w.postMessage([d, t = f], [d.buffer]);\n    };\n    strm.terminate = function () { w.terminate(); };\n    if (flush) {\n        strm.flush = function () { w.postMessage([]); };\n    }\n};\n// read 2 bytes\nvar b2 = function (d, b) { return d[b] | (d[b + 1] << 8); };\n// read 4 bytes\nvar b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; };\nvar b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); };\n// write bytes\nvar wbytes = function (d, b, v) {\n    for (; v; ++b)\n        d[b] = v, v >>>= 8;\n};\n// gzip header\nvar gzh = function (c, o) {\n    var fn = o.filename;\n    c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix\n    if (o.mtime != 0)\n        wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000));\n    if (fn) {\n        c[3] = 8;\n        for (var i = 0; i <= fn.length; ++i)\n            c[i + 10] = fn.charCodeAt(i);\n    }\n};\n// gzip footer: -8 to -4 = CRC, -4 to -0 is length\n// gzip start\nvar gzs = function (d) {\n    if (d[0] != 31 || d[1] != 139 || d[2] != 8)\n        err(6, 'invalid gzip data');\n    var flg = d[3];\n    var st = 10;\n    if (flg & 4)\n        st += (d[10] | d[11] << 8) + 2;\n    for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])\n        ;\n    return st + (flg & 2);\n};\n// gzip length\nvar gzl = function (d) {\n    var l = d.length;\n    return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16 | d[l - 1] << 24) >>> 0;\n};\n// gzip header length\nvar gzhl = function (o) { return 10 + (o.filename ? o.filename.length + 1 : 0); };\n// zlib header\nvar zlh = function (c, o) {\n    var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;\n    c[0] = 120, c[1] = (fl << 6) | (o.dictionary && 32);\n    c[1] |= 31 - ((c[0] << 8) | c[1]) % 31;\n    if (o.dictionary) {\n        var h = adler();\n        h.p(o.dictionary);\n        wbytes(c, 2, h.d());\n    }\n};\n// zlib start\nvar zls = function (d, dict) {\n    if ((d[0] & 15) != 8 || (d[0] >> 4) > 7 || ((d[0] << 8 | d[1]) % 31))\n        err(6, 'invalid zlib data');\n    if ((d[1] >> 5 & 1) == +!dict)\n        err(6, 'invalid zlib data: ' + (d[1] & 32 ? 'need' : 'unexpected') + ' dictionary');\n    return (d[1] >> 3 & 4) + 2;\n};\nfunction StrmOpt(opts, cb) {\n    if (typeof opts == 'function')\n        cb = opts, opts = {};\n    this.ondata = cb;\n    return opts;\n}\n/**\n * Streaming DEFLATE compression\n */\nvar Deflate = /*#__PURE__*/ (function () {\n    function Deflate(opts, cb) {\n        if (typeof opts == 'function')\n            cb = opts, opts = {};\n        this.ondata = cb;\n        this.o = opts || {};\n        this.s = { l: 0, i: 32768, w: 32768, z: 32768 };\n        // Buffer length must always be 0 mod 32768 for index calculations to be correct when modifying head and prev\n        // 98304 = 32768 (lookback) + 65536 (common chunk size)\n        this.b = new u8(98304);\n        if (this.o.dictionary) {\n            var dict = this.o.dictionary.subarray(-32768);\n            this.b.set(dict, 32768 - dict.length);\n            this.s.i = 32768 - dict.length;\n        }\n    }\n    Deflate.prototype.p = function (c, f) {\n        this.ondata(dopt(c, this.o, 0, 0, this.s), f);\n    };\n    /**\n     * Pushes a chunk to be deflated\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Deflate.prototype.push = function (chunk, final) {\n        if (!this.ondata)\n            err(5);\n        if (this.s.l)\n            err(4);\n        var endLen = chunk.length + this.s.z;\n        if (endLen > this.b.length) {\n            if (endLen > 2 * this.b.length - 32768) {\n                var newBuf = new u8(endLen & -32768);\n                newBuf.set(this.b.subarray(0, this.s.z));\n                this.b = newBuf;\n            }\n            var split = this.b.length - this.s.z;\n            this.b.set(chunk.subarray(0, split), this.s.z);\n            this.s.z = this.b.length;\n            this.p(this.b, false);\n            this.b.set(this.b.subarray(-32768));\n            this.b.set(chunk.subarray(split), 32768);\n            this.s.z = chunk.length - split + 32768;\n            this.s.i = 32766, this.s.w = 32768;\n        }\n        else {\n            this.b.set(chunk, this.s.z);\n            this.s.z += chunk.length;\n        }\n        this.s.l = final & 1;\n        if (this.s.z > this.s.w + 8191 || final) {\n            this.p(this.b, final || false);\n            this.s.w = this.s.i, this.s.i -= 2;\n        }\n    };\n    /**\n     * Flushes buffered uncompressed data. Useful to immediately retrieve the\n     * deflated output for small inputs.\n     */\n    Deflate.prototype.flush = function () {\n        if (!this.ondata)\n            err(5);\n        if (this.s.l)\n            err(4);\n        this.p(this.b, false);\n        this.s.w = this.s.i, this.s.i -= 2;\n    };\n    return Deflate;\n}());\nexport { Deflate };\n/**\n * Asynchronous streaming DEFLATE compression\n */\nvar AsyncDeflate = /*#__PURE__*/ (function () {\n    function AsyncDeflate(opts, cb) {\n        astrmify([\n            bDflt,\n            function () { return [astrm, Deflate]; }\n        ], this, StrmOpt.call(this, opts, cb), function (ev) {\n            var strm = new Deflate(ev.data);\n            onmessage = astrm(strm);\n        }, 6, 1);\n    }\n    return AsyncDeflate;\n}());\nexport { AsyncDeflate };\nexport function deflate(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    return cbify(data, opts, [\n        bDflt,\n    ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb);\n}\n/**\n * Compresses data with DEFLATE without any wrapper\n * @param data The data to compress\n * @param opts The compression options\n * @returns The deflated version of the data\n */\nexport function deflateSync(data, opts) {\n    return dopt(data, opts || {}, 0, 0);\n}\n/**\n * Streaming DEFLATE decompression\n */\nvar Inflate = /*#__PURE__*/ (function () {\n    function Inflate(opts, cb) {\n        // no StrmOpt here to avoid adding to workerizer\n        if (typeof opts == 'function')\n            cb = opts, opts = {};\n        this.ondata = cb;\n        var dict = opts && opts.dictionary && opts.dictionary.subarray(-32768);\n        this.s = { i: 0, b: dict ? dict.length : 0 };\n        this.o = new u8(32768);\n        this.p = new u8(0);\n        if (dict)\n            this.o.set(dict);\n    }\n    Inflate.prototype.e = function (c) {\n        if (!this.ondata)\n            err(5);\n        if (this.d)\n            err(4);\n        if (!this.p.length)\n            this.p = c;\n        else if (c.length) {\n            var n = new u8(this.p.length + c.length);\n            n.set(this.p), n.set(c, this.p.length), this.p = n;\n        }\n    };\n    Inflate.prototype.c = function (final) {\n        this.s.i = +(this.d = final || false);\n        var bts = this.s.b;\n        var dt = inflt(this.p, this.s, this.o);\n        this.ondata(slc(dt, bts, this.s.b), this.d);\n        this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;\n        this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7;\n    };\n    /**\n     * Pushes a chunk to be inflated\n     * @param chunk The chunk to push\n     * @param final Whether this is the final chunk\n     */\n    Inflate.prototype.push = function (chunk, final) {\n        this.e(chunk), this.c(final);\n    };\n    return Inflate;\n}());\nexport { Inflate };\n/**\n * Asynchronous streaming DEFLATE decompression\n */\nvar AsyncInflate = /*#__PURE__*/ (function () {\n    function AsyncInflate(opts, cb) {\n        astrmify([\n            bInflt,\n            function () { return [astrm, Inflate]; }\n        ], this, StrmOpt.call(this, opts, cb), function (ev) {\n            var strm = new Inflate(ev.data);\n            onmessage = astrm(strm);\n        }, 7, 0);\n    }\n    return AsyncInflate;\n}());\nexport { AsyncInflate };\nexport function inflate(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    return cbify(data, opts, [\n        bInflt\n    ], function (ev) { return pbf(inflateSync(ev.data[0], gopt(ev.data[1]))); }, 1, cb);\n}\n/**\n * Expands DEFLATE data with no wrapper\n * @param data The data to decompress\n * @param opts The decompression options\n * @returns The decompressed version of the data\n */\nexport function inflateSync(data, opts) {\n    return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);\n}\n// before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize.\n/**\n * Streaming GZIP compression\n */\nvar Gzip = /*#__PURE__*/ (function () {\n    function Gzip(opts, cb) {\n        this.c = crc();\n        this.l = 0;\n        this.v = 1;\n        Deflate.call(this, opts, cb);\n    }\n    /**\n     * Pushes a chunk to be GZIPped\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Gzip.prototype.push = function (chunk, final) {\n        this.c.p(chunk);\n        this.l += chunk.length;\n        Deflate.prototype.push.call(this, chunk, final);\n    };\n    Gzip.prototype.p = function (c, f) {\n        var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, this.s);\n        if (this.v)\n            gzh(raw, this.o), this.v = 0;\n        if (f)\n            wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l);\n        this.ondata(raw, f);\n    };\n    /**\n     * Flushes buffered uncompressed data. Useful to immediately retrieve the\n     * GZIPped output for small inputs.\n     */\n    Gzip.prototype.flush = function () {\n        Deflate.prototype.flush.call(this);\n    };\n    return Gzip;\n}());\nexport { Gzip };\n/**\n * Asynchronous streaming GZIP compression\n */\nvar AsyncGzip = /*#__PURE__*/ (function () {\n    function AsyncGzip(opts, cb) {\n        astrmify([\n            bDflt,\n            gze,\n            function () { return [astrm, Deflate, Gzip]; }\n        ], this, StrmOpt.call(this, opts, cb), function (ev) {\n            var strm = new Gzip(ev.data);\n            onmessage = astrm(strm);\n        }, 8, 1);\n    }\n    return AsyncGzip;\n}());\nexport { AsyncGzip };\nexport function gzip(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    return cbify(data, opts, [\n        bDflt,\n        gze,\n        function () { return [gzipSync]; }\n    ], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb);\n}\n/**\n * Compresses data with GZIP\n * @param data The data to compress\n * @param opts The compression options\n * @returns The gzipped version of the data\n */\nexport function gzipSync(data, opts) {\n    if (!opts)\n        opts = {};\n    var c = crc(), l = data.length;\n    c.p(data);\n    var d = dopt(data, opts, gzhl(opts), 8), s = d.length;\n    return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d;\n}\n/**\n * Streaming single or multi-member GZIP decompression\n */\nvar Gunzip = /*#__PURE__*/ (function () {\n    function Gunzip(opts, cb) {\n        this.v = 1;\n        this.r = 0;\n        Inflate.call(this, opts, cb);\n    }\n    /**\n     * Pushes a chunk to be GUNZIPped\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Gunzip.prototype.push = function (chunk, final) {\n        Inflate.prototype.e.call(this, chunk);\n        this.r += chunk.length;\n        if (this.v) {\n            var p = this.p.subarray(this.v - 1);\n            var s = p.length > 3 ? gzs(p) : 4;\n            if (s > p.length) {\n                if (!final)\n                    return;\n            }\n            else if (this.v > 1 && this.onmember) {\n                this.onmember(this.r - p.length);\n            }\n            this.p = p.subarray(s), this.v = 0;\n        }\n        // necessary to prevent TS from using the closure value\n        // This allows for workerization to function correctly\n        Inflate.prototype.c.call(this, final);\n        // process concatenated GZIP\n        if (this.s.f && !this.s.l && !final) {\n            this.v = shft(this.s.p) + 9;\n            this.s = { i: 0 };\n            this.o = new u8(0);\n            this.push(new u8(0), final);\n        }\n    };\n    return Gunzip;\n}());\nexport { Gunzip };\n/**\n * Asynchronous streaming single or multi-member GZIP decompression\n */\nvar AsyncGunzip = /*#__PURE__*/ (function () {\n    function AsyncGunzip(opts, cb) {\n        var _this = this;\n        astrmify([\n            bInflt,\n            guze,\n            function () { return [astrm, Inflate, Gunzip]; }\n        ], this, StrmOpt.call(this, opts, cb), function (ev) {\n            var strm = new Gunzip(ev.data);\n            strm.onmember = function (offset) { return postMessage(offset); };\n            onmessage = astrm(strm);\n        }, 9, 0, function (offset) { return _this.onmember && _this.onmember(offset); });\n    }\n    return AsyncGunzip;\n}());\nexport { AsyncGunzip };\nexport function gunzip(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    return cbify(data, opts, [\n        bInflt,\n        guze,\n        function () { return [gunzipSync]; }\n    ], function (ev) { return pbf(gunzipSync(ev.data[0], ev.data[1])); }, 3, cb);\n}\n/**\n * Expands GZIP data\n * @param data The data to decompress\n * @param opts The decompression options\n * @returns The decompressed version of the data\n */\nexport function gunzipSync(data, opts) {\n    var st = gzs(data);\n    if (st + 8 > data.length)\n        err(6, 'invalid gzip data');\n    return inflt(data.subarray(st, -8), { i: 2 }, opts && opts.out || new u8(gzl(data)), opts && opts.dictionary);\n}\n/**\n * Streaming Zlib compression\n */\nvar Zlib = /*#__PURE__*/ (function () {\n    function Zlib(opts, cb) {\n        this.c = adler();\n        this.v = 1;\n        Deflate.call(this, opts, cb);\n    }\n    /**\n     * Pushes a chunk to be zlibbed\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Zlib.prototype.push = function (chunk, final) {\n        this.c.p(chunk);\n        Deflate.prototype.push.call(this, chunk, final);\n    };\n    Zlib.prototype.p = function (c, f) {\n        var raw = dopt(c, this.o, this.v && (this.o.dictionary ? 6 : 2), f && 4, this.s);\n        if (this.v)\n            zlh(raw, this.o), this.v = 0;\n        if (f)\n            wbytes(raw, raw.length - 4, this.c.d());\n        this.ondata(raw, f);\n    };\n    /**\n     * Flushes buffered uncompressed data. Useful to immediately retrieve the\n     * zlibbed output for small inputs.\n     */\n    Zlib.prototype.flush = function () {\n        Deflate.prototype.flush.call(this);\n    };\n    return Zlib;\n}());\nexport { Zlib };\n/**\n * Asynchronous streaming Zlib compression\n */\nvar AsyncZlib = /*#__PURE__*/ (function () {\n    function AsyncZlib(opts, cb) {\n        astrmify([\n            bDflt,\n            zle,\n            function () { return [astrm, Deflate, Zlib]; }\n        ], this, StrmOpt.call(this, opts, cb), function (ev) {\n            var strm = new Zlib(ev.data);\n            onmessage = astrm(strm);\n        }, 10, 1);\n    }\n    return AsyncZlib;\n}());\nexport { AsyncZlib };\nexport function zlib(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    return cbify(data, opts, [\n        bDflt,\n        zle,\n        function () { return [zlibSync]; }\n    ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb);\n}\n/**\n * Compress data with Zlib\n * @param data The data to compress\n * @param opts The compression options\n * @returns The zlib-compressed version of the data\n */\nexport function zlibSync(data, opts) {\n    if (!opts)\n        opts = {};\n    var a = adler();\n    a.p(data);\n    var d = dopt(data, opts, opts.dictionary ? 6 : 2, 4);\n    return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d;\n}\n/**\n * Streaming Zlib decompression\n */\nvar Unzlib = /*#__PURE__*/ (function () {\n    function Unzlib(opts, cb) {\n        Inflate.call(this, opts, cb);\n        this.v = opts && opts.dictionary ? 2 : 1;\n    }\n    /**\n     * Pushes a chunk to be unzlibbed\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Unzlib.prototype.push = function (chunk, final) {\n        Inflate.prototype.e.call(this, chunk);\n        if (this.v) {\n            if (this.p.length < 6 && !final)\n                return;\n            this.p = this.p.subarray(zls(this.p, this.v - 1)), this.v = 0;\n        }\n        if (final) {\n            if (this.p.length < 4)\n                err(6, 'invalid zlib data');\n            this.p = this.p.subarray(0, -4);\n        }\n        // necessary to prevent TS from using the closure value\n        // This allows for workerization to function correctly\n        Inflate.prototype.c.call(this, final);\n    };\n    return Unzlib;\n}());\nexport { Unzlib };\n/**\n * Asynchronous streaming Zlib decompression\n */\nvar AsyncUnzlib = /*#__PURE__*/ (function () {\n    function AsyncUnzlib(opts, cb) {\n        astrmify([\n            bInflt,\n            zule,\n            function () { return [astrm, Inflate, Unzlib]; }\n        ], this, StrmOpt.call(this, opts, cb), function (ev) {\n            var strm = new Unzlib(ev.data);\n            onmessage = astrm(strm);\n        }, 11, 0);\n    }\n    return AsyncUnzlib;\n}());\nexport { AsyncUnzlib };\nexport function unzlib(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    return cbify(data, opts, [\n        bInflt,\n        zule,\n        function () { return [unzlibSync]; }\n    ], function (ev) { return pbf(unzlibSync(ev.data[0], gopt(ev.data[1]))); }, 5, cb);\n}\n/**\n * Expands Zlib data\n * @param data The data to decompress\n * @param opts The decompression options\n * @returns The decompressed version of the data\n */\nexport function unzlibSync(data, opts) {\n    return inflt(data.subarray(zls(data, opts && opts.dictionary), -4), { i: 2 }, opts && opts.out, opts && opts.dictionary);\n}\n// Default algorithm for compression (used because having a known output size allows faster decompression)\nexport { gzip as compress, AsyncGzip as AsyncCompress };\nexport { gzipSync as compressSync, Gzip as Compress };\n/**\n * Streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar Decompress = /*#__PURE__*/ (function () {\n    function Decompress(opts, cb) {\n        this.o = StrmOpt.call(this, opts, cb) || {};\n        this.G = Gunzip;\n        this.I = Inflate;\n        this.Z = Unzlib;\n    }\n    // init substream\n    // overriden by AsyncDecompress\n    Decompress.prototype.i = function () {\n        var _this = this;\n        this.s.ondata = function (dat, final) {\n            _this.ondata(dat, final);\n        };\n    };\n    /**\n     * Pushes a chunk to be decompressed\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Decompress.prototype.push = function (chunk, final) {\n        if (!this.ondata)\n            err(5);\n        if (!this.s) {\n            if (this.p && this.p.length) {\n                var n = new u8(this.p.length + chunk.length);\n                n.set(this.p), n.set(chunk, this.p.length);\n            }\n            else\n                this.p = chunk;\n            if (this.p.length > 2) {\n                this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8)\n                    ? new this.G(this.o)\n                    : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31))\n                        ? new this.I(this.o)\n                        : new this.Z(this.o);\n                this.i();\n                this.s.push(this.p, final);\n                this.p = null;\n            }\n        }\n        else\n            this.s.push(chunk, final);\n    };\n    return Decompress;\n}());\nexport { Decompress };\n/**\n * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar AsyncDecompress = /*#__PURE__*/ (function () {\n    function AsyncDecompress(opts, cb) {\n        Decompress.call(this, opts, cb);\n        this.queuedSize = 0;\n        this.G = AsyncGunzip;\n        this.I = AsyncInflate;\n        this.Z = AsyncUnzlib;\n    }\n    AsyncDecompress.prototype.i = function () {\n        var _this = this;\n        this.s.ondata = function (err, dat, final) {\n            _this.ondata(err, dat, final);\n        };\n        this.s.ondrain = function (size) {\n            _this.queuedSize -= size;\n            if (_this.ondrain)\n                _this.ondrain(size);\n        };\n    };\n    /**\n     * Pushes a chunk to be decompressed\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    AsyncDecompress.prototype.push = function (chunk, final) {\n        this.queuedSize += chunk.length;\n        Decompress.prototype.push.call(this, chunk, final);\n    };\n    return AsyncDecompress;\n}());\nexport { AsyncDecompress };\nexport function decompress(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n        ? gunzip(data, opts, cb)\n        : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n            ? inflate(data, opts, cb)\n            : unzlib(data, opts, cb);\n}\n/**\n * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format\n * @param data The data to decompress\n * @param opts The decompression options\n * @returns The decompressed version of the data\n */\nexport function decompressSync(data, opts) {\n    return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n        ? gunzipSync(data, opts)\n        : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n            ? inflateSync(data, opts)\n            : unzlibSync(data, opts);\n}\n// flatten a directory structure\nvar fltn = function (d, p, t, o) {\n    for (var k in d) {\n        var val = d[k], n = p + k, op = o;\n        if (Array.isArray(val))\n            op = mrg(o, val[1]), val = val[0];\n        if (val instanceof u8)\n            t[n] = [val, op];\n        else {\n            t[n += '/'] = [new u8(0), op];\n            fltn(val, n, t, o);\n        }\n    }\n};\n// text encoder\nvar te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder();\n// text decoder\nvar td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder();\n// text decoder stream\nvar tds = 0;\ntry {\n    td.decode(et, { stream: true });\n    tds = 1;\n}\ncatch (e) { }\n// decode UTF8\nvar dutf8 = function (d) {\n    for (var r = '', i = 0;;) {\n        var c = d[i++];\n        var eb = (c > 127) + (c > 223) + (c > 239);\n        if (i + eb > d.length)\n            return { s: r, r: slc(d, i - 1) };\n        if (!eb)\n            r += String.fromCharCode(c);\n        else if (eb == 3) {\n            c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536,\n                r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023));\n        }\n        else if (eb & 1)\n            r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63));\n        else\n            r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63));\n    }\n};\n/**\n * Streaming UTF-8 decoding\n */\nvar DecodeUTF8 = /*#__PURE__*/ (function () {\n    /**\n     * Creates a UTF-8 decoding stream\n     * @param cb The callback to call whenever data is decoded\n     */\n    function DecodeUTF8(cb) {\n        this.ondata = cb;\n        if (tds)\n            this.t = new TextDecoder();\n        else\n            this.p = et;\n    }\n    /**\n     * Pushes a chunk to be decoded from UTF-8 binary\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    DecodeUTF8.prototype.push = function (chunk, final) {\n        if (!this.ondata)\n            err(5);\n        final = !!final;\n        if (this.t) {\n            this.ondata(this.t.decode(chunk, { stream: true }), final);\n            if (final) {\n                if (this.t.decode().length)\n                    err(8);\n                this.t = null;\n            }\n            return;\n        }\n        if (!this.p)\n            err(4);\n        var dat = new u8(this.p.length + chunk.length);\n        dat.set(this.p);\n        dat.set(chunk, this.p.length);\n        var _a = dutf8(dat), s = _a.s, r = _a.r;\n        if (final) {\n            if (r.length)\n                err(8);\n            this.p = null;\n        }\n        else\n            this.p = r;\n        this.ondata(s, final);\n    };\n    return DecodeUTF8;\n}());\nexport { DecodeUTF8 };\n/**\n * Streaming UTF-8 encoding\n */\nvar EncodeUTF8 = /*#__PURE__*/ (function () {\n    /**\n     * Creates a UTF-8 decoding stream\n     * @param cb The callback to call whenever data is encoded\n     */\n    function EncodeUTF8(cb) {\n        this.ondata = cb;\n    }\n    /**\n     * Pushes a chunk to be encoded to UTF-8\n     * @param chunk The string data to push\n     * @param final Whether this is the last chunk\n     */\n    EncodeUTF8.prototype.push = function (chunk, final) {\n        if (!this.ondata)\n            err(5);\n        if (this.d)\n            err(4);\n        this.ondata(strToU8(chunk), this.d = final || false);\n    };\n    return EncodeUTF8;\n}());\nexport { EncodeUTF8 };\n/**\n * Converts a string into a Uint8Array for use with compression/decompression methods\n * @param str The string to encode\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n *               not need to be true unless decoding a binary string.\n * @returns The string encoded in UTF-8/Latin-1 binary\n */\nexport function strToU8(str, latin1) {\n    if (latin1) {\n        var ar_1 = new u8(str.length);\n        for (var i = 0; i < str.length; ++i)\n            ar_1[i] = str.charCodeAt(i);\n        return ar_1;\n    }\n    if (te)\n        return te.encode(str);\n    var l = str.length;\n    var ar = new u8(str.length + (str.length >> 1));\n    var ai = 0;\n    var w = function (v) { ar[ai++] = v; };\n    for (var i = 0; i < l; ++i) {\n        if (ai + 5 > ar.length) {\n            var n = new u8(ai + 8 + ((l - i) << 1));\n            n.set(ar);\n            ar = n;\n        }\n        var c = str.charCodeAt(i);\n        if (c < 128 || latin1)\n            w(c);\n        else if (c < 2048)\n            w(192 | (c >> 6)), w(128 | (c & 63));\n        else if (c > 55295 && c < 57344)\n            c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023),\n                w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));\n        else\n            w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));\n    }\n    return slc(ar, 0, ai);\n}\n/**\n * Converts a Uint8Array to a string\n * @param dat The data to decode to string\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n *               not need to be true unless encoding to binary string.\n * @returns The original UTF-8/Latin-1 string\n */\nexport function strFromU8(dat, latin1) {\n    if (latin1) {\n        var r = '';\n        for (var i = 0; i < dat.length; i += 16384)\n            r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384));\n        return r;\n    }\n    else if (td) {\n        return td.decode(dat);\n    }\n    else {\n        var _a = dutf8(dat), s = _a.s, r = _a.r;\n        if (r.length)\n            err(8);\n        return s;\n    }\n}\n;\n// deflate bit flag\nvar dbf = function (l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; };\n// skip local zip header\nvar slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); };\n// read zip header\nvar zh = function (d, b, z) {\n    var fnl = b2(d, b + 28), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl, bs = b4(d, b + 20);\n    var _a = z && bs == 4294967295 ? z64e(d, es) : [bs, b4(d, b + 24), b4(d, b + 42)], sc = _a[0], su = _a[1], off = _a[2];\n    return [b2(d, b + 10), sc, su, fn, es + b2(d, b + 30) + b2(d, b + 32), off];\n};\n// read zip64 extra field\nvar z64e = function (d, b) {\n    for (; b2(d, b) != 1; b += 4 + b2(d, b + 2))\n        ;\n    return [b8(d, b + 12), b8(d, b + 4), b8(d, b + 20)];\n};\n// extra field length\nvar exfl = function (ex) {\n    var le = 0;\n    if (ex) {\n        for (var k in ex) {\n            var l = ex[k].length;\n            if (l > 65535)\n                err(9);\n            le += l + 4;\n        }\n    }\n    return le;\n};\n// write zip header\nvar wzh = function (d, b, f, fn, u, c, ce, co) {\n    var fl = fn.length, ex = f.extra, col = co && co.length;\n    var exl = exfl(ex);\n    wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4;\n    if (ce != null)\n        d[b++] = 20, d[b++] = f.os;\n    d[b] = 20, b += 2; // spec compliance? what's that?\n    d[b++] = (f.flag << 1) | (c < 0 && 8), d[b++] = u && 8;\n    d[b++] = f.compression & 255, d[b++] = f.compression >> 8;\n    var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;\n    if (y < 0 || y > 119)\n        err(10);\n    wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >> 1)), b += 4;\n    if (c != -1) {\n        wbytes(d, b, f.crc);\n        wbytes(d, b + 4, c < 0 ? -c - 2 : c);\n        wbytes(d, b + 8, f.size);\n    }\n    wbytes(d, b + 12, fl);\n    wbytes(d, b + 14, exl), b += 16;\n    if (ce != null) {\n        wbytes(d, b, col);\n        wbytes(d, b + 6, f.attrs);\n        wbytes(d, b + 10, ce), b += 14;\n    }\n    d.set(fn, b);\n    b += fl;\n    if (exl) {\n        for (var k in ex) {\n            var exf = ex[k], l = exf.length;\n            wbytes(d, b, +k);\n            wbytes(d, b + 2, l);\n            d.set(exf, b + 4), b += 4 + l;\n        }\n    }\n    if (col)\n        d.set(co, b), b += col;\n    return b;\n};\n// write zip footer (end of central directory)\nvar wzf = function (o, b, c, d, e) {\n    wbytes(o, b, 0x6054B50); // skip disk\n    wbytes(o, b + 8, c);\n    wbytes(o, b + 10, c);\n    wbytes(o, b + 12, d);\n    wbytes(o, b + 16, e);\n};\n/**\n * A pass-through stream to keep data uncompressed in a ZIP archive.\n */\nvar ZipPassThrough = /*#__PURE__*/ (function () {\n    /**\n     * Creates a pass-through stream that can be added to ZIP archives\n     * @param filename The filename to associate with this data stream\n     */\n    function ZipPassThrough(filename) {\n        this.filename = filename;\n        this.c = crc();\n        this.size = 0;\n        this.compression = 0;\n    }\n    /**\n     * Processes a chunk and pushes to the output stream. You can override this\n     * method in a subclass for custom behavior, but by default this passes\n     * the data through. You must call this.ondata(err, chunk, final) at some\n     * point in this method.\n     * @param chunk The chunk to process\n     * @param final Whether this is the last chunk\n     */\n    ZipPassThrough.prototype.process = function (chunk, final) {\n        this.ondata(null, chunk, final);\n    };\n    /**\n     * Pushes a chunk to be added. If you are subclassing this with a custom\n     * compression algorithm, note that you must push data from the source\n     * file only, pre-compression.\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    ZipPassThrough.prototype.push = function (chunk, final) {\n        if (!this.ondata)\n            err(5);\n        this.c.p(chunk);\n        this.size += chunk.length;\n        if (final)\n            this.crc = this.c.d();\n        this.process(chunk, final || false);\n    };\n    return ZipPassThrough;\n}());\nexport { ZipPassThrough };\n// I don't extend because TypeScript extension adds 1kB of runtime bloat\n/**\n * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate\n * for better performance\n */\nvar ZipDeflate = /*#__PURE__*/ (function () {\n    /**\n     * Creates a DEFLATE stream that can be added to ZIP archives\n     * @param filename The filename to associate with this data stream\n     * @param opts The compression options\n     */\n    function ZipDeflate(filename, opts) {\n        var _this = this;\n        if (!opts)\n            opts = {};\n        ZipPassThrough.call(this, filename);\n        this.d = new Deflate(opts, function (dat, final) {\n            _this.ondata(null, dat, final);\n        });\n        this.compression = 8;\n        this.flag = dbf(opts.level);\n    }\n    ZipDeflate.prototype.process = function (chunk, final) {\n        try {\n            this.d.push(chunk, final);\n        }\n        catch (e) {\n            this.ondata(e, null, final);\n        }\n    };\n    /**\n     * Pushes a chunk to be deflated\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    ZipDeflate.prototype.push = function (chunk, final) {\n        ZipPassThrough.prototype.push.call(this, chunk, final);\n    };\n    return ZipDeflate;\n}());\nexport { ZipDeflate };\n/**\n * Asynchronous streaming DEFLATE compression for ZIP archives\n */\nvar AsyncZipDeflate = /*#__PURE__*/ (function () {\n    /**\n     * Creates an asynchronous DEFLATE stream that can be added to ZIP archives\n     * @param filename The filename to associate with this data stream\n     * @param opts The compression options\n     */\n    function AsyncZipDeflate(filename, opts) {\n        var _this = this;\n        if (!opts)\n            opts = {};\n        ZipPassThrough.call(this, filename);\n        this.d = new AsyncDeflate(opts, function (err, dat, final) {\n            _this.ondata(err, dat, final);\n        });\n        this.compression = 8;\n        this.flag = dbf(opts.level);\n        this.terminate = this.d.terminate;\n    }\n    AsyncZipDeflate.prototype.process = function (chunk, final) {\n        this.d.push(chunk, final);\n    };\n    /**\n     * Pushes a chunk to be deflated\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    AsyncZipDeflate.prototype.push = function (chunk, final) {\n        ZipPassThrough.prototype.push.call(this, chunk, final);\n    };\n    return AsyncZipDeflate;\n}());\nexport { AsyncZipDeflate };\n// TODO: Better tree shaking\n/**\n * A zippable archive to which files can incrementally be added\n */\nvar Zip = /*#__PURE__*/ (function () {\n    /**\n     * Creates an empty ZIP archive to which files can be added\n     * @param cb The callback to call whenever data for the generated ZIP archive\n     *           is available\n     */\n    function Zip(cb) {\n        this.ondata = cb;\n        this.u = [];\n        this.d = 1;\n    }\n    /**\n     * Adds a file to the ZIP archive\n     * @param file The file stream to add\n     */\n    Zip.prototype.add = function (file) {\n        var _this = this;\n        if (!this.ondata)\n            err(5);\n        // finishing or finished\n        if (this.d & 2)\n            this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false);\n        else {\n            var f = strToU8(file.filename), fl_1 = f.length;\n            var com = file.comment, o = com && strToU8(com);\n            var u = fl_1 != file.filename.length || (o && (com.length != o.length));\n            var hl_1 = fl_1 + exfl(file.extra) + 30;\n            if (fl_1 > 65535)\n                this.ondata(err(11, 0, 1), null, false);\n            var header = new u8(hl_1);\n            wzh(header, 0, file, f, u, -1);\n            var chks_1 = [header];\n            var pAll_1 = function () {\n                for (var _i = 0, chks_2 = chks_1; _i < chks_2.length; _i++) {\n                    var chk = chks_2[_i];\n                    _this.ondata(null, chk, false);\n                }\n                chks_1 = [];\n            };\n            var tr_1 = this.d;\n            this.d = 0;\n            var ind_1 = this.u.length;\n            var uf_1 = mrg(file, {\n                f: f,\n                u: u,\n                o: o,\n                t: function () {\n                    if (file.terminate)\n                        file.terminate();\n                },\n                r: function () {\n                    pAll_1();\n                    if (tr_1) {\n                        var nxt = _this.u[ind_1 + 1];\n                        if (nxt)\n                            nxt.r();\n                        else\n                            _this.d = 1;\n                    }\n                    tr_1 = 1;\n                }\n            });\n            var cl_1 = 0;\n            file.ondata = function (err, dat, final) {\n                if (err) {\n                    _this.ondata(err, dat, final);\n                    _this.terminate();\n                }\n                else {\n                    cl_1 += dat.length;\n                    chks_1.push(dat);\n                    if (final) {\n                        var dd = new u8(16);\n                        wbytes(dd, 0, 0x8074B50);\n                        wbytes(dd, 4, file.crc);\n                        wbytes(dd, 8, cl_1);\n                        wbytes(dd, 12, file.size);\n                        chks_1.push(dd);\n                        uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file.crc, uf_1.size = file.size;\n                        if (tr_1)\n                            uf_1.r();\n                        tr_1 = 1;\n                    }\n                    else if (tr_1)\n                        pAll_1();\n                }\n            };\n            this.u.push(uf_1);\n        }\n    };\n    /**\n     * Ends the process of adding files and prepares to emit the final chunks.\n     * This *must* be called after adding all desired files for the resulting\n     * ZIP file to work properly.\n     */\n    Zip.prototype.end = function () {\n        var _this = this;\n        if (this.d & 2) {\n            this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true);\n            return;\n        }\n        if (this.d)\n            this.e();\n        else\n            this.u.push({\n                r: function () {\n                    if (!(_this.d & 1))\n                        return;\n                    _this.u.splice(-1, 1);\n                    _this.e();\n                },\n                t: function () { }\n            });\n        this.d = 3;\n    };\n    Zip.prototype.e = function () {\n        var bt = 0, l = 0, tl = 0;\n        for (var _i = 0, _a = this.u; _i < _a.length; _i++) {\n            var f = _a[_i];\n            tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0);\n        }\n        var out = new u8(tl + 22);\n        for (var _b = 0, _c = this.u; _b < _c.length; _b++) {\n            var f = _c[_b];\n            wzh(out, bt, f, f.f, f.u, -f.c - 2, l, f.o);\n            bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b;\n        }\n        wzf(out, bt, this.u.length, tl, l);\n        this.ondata(null, out, true);\n        this.d = 2;\n    };\n    /**\n     * A method to terminate any internal workers used by the stream. Subsequent\n     * calls to add() will fail.\n     */\n    Zip.prototype.terminate = function () {\n        for (var _i = 0, _a = this.u; _i < _a.length; _i++) {\n            var f = _a[_i];\n            f.t();\n        }\n        this.d = 2;\n    };\n    return Zip;\n}());\nexport { Zip };\nexport function zip(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    var r = {};\n    fltn(data, '', r, opts);\n    var k = Object.keys(r);\n    var lft = k.length, o = 0, tot = 0;\n    var slft = lft, files = new Array(lft);\n    var term = [];\n    var tAll = function () {\n        for (var i = 0; i < term.length; ++i)\n            term[i]();\n    };\n    var cbd = function (a, b) {\n        mt(function () { cb(a, b); });\n    };\n    mt(function () { cbd = cb; });\n    var cbf = function () {\n        var out = new u8(tot + 22), oe = o, cdl = tot - o;\n        tot = 0;\n        for (var i = 0; i < slft; ++i) {\n            var f = files[i];\n            try {\n                var l = f.c.length;\n                wzh(out, tot, f, f.f, f.u, l);\n                var badd = 30 + f.f.length + exfl(f.extra);\n                var loc = tot + badd;\n                out.set(f.c, loc);\n                wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l;\n            }\n            catch (e) {\n                return cbd(e, null);\n            }\n        }\n        wzf(out, o, files.length, cdl, oe);\n        cbd(null, out);\n    };\n    if (!lft)\n        cbf();\n    var _loop_1 = function (i) {\n        var fn = k[i];\n        var _a = r[fn], file = _a[0], p = _a[1];\n        var c = crc(), size = file.length;\n        c.p(file);\n        var f = strToU8(fn), s = f.length;\n        var com = p.comment, m = com && strToU8(com), ms = m && m.length;\n        var exl = exfl(p.extra);\n        var compression = p.level == 0 ? 0 : 8;\n        var cbl = function (e, d) {\n            if (e) {\n                tAll();\n                cbd(e, null);\n            }\n            else {\n                var l = d.length;\n                files[i] = mrg(p, {\n                    size: size,\n                    crc: c.d(),\n                    c: d,\n                    f: f,\n                    m: m,\n                    u: s != fn.length || (m && (com.length != ms)),\n                    compression: compression\n                });\n                o += 30 + s + exl + l;\n                tot += 76 + 2 * (s + exl) + (ms || 0) + l;\n                if (!--lft)\n                    cbf();\n            }\n        };\n        if (s > 65535)\n            cbl(err(11, 0, 1), null);\n        if (!compression)\n            cbl(null, file);\n        else if (size < 160000) {\n            try {\n                cbl(null, deflateSync(file, p));\n            }\n            catch (e) {\n                cbl(e, null);\n            }\n        }\n        else\n            term.push(deflate(file, p, cbl));\n    };\n    // Cannot use lft because it can decrease\n    for (var i = 0; i < slft; ++i) {\n        _loop_1(i);\n    }\n    return tAll;\n}\n/**\n * Synchronously creates a ZIP file. Prefer using `zip` for better performance\n * with more than one file.\n * @param data The directory structure for the ZIP archive\n * @param opts The main options, merged with per-file options\n * @returns The generated ZIP archive\n */\nexport function zipSync(data, opts) {\n    if (!opts)\n        opts = {};\n    var r = {};\n    var files = [];\n    fltn(data, '', r, opts);\n    var o = 0;\n    var tot = 0;\n    for (var fn in r) {\n        var _a = r[fn], file = _a[0], p = _a[1];\n        var compression = p.level == 0 ? 0 : 8;\n        var f = strToU8(fn), s = f.length;\n        var com = p.comment, m = com && strToU8(com), ms = m && m.length;\n        var exl = exfl(p.extra);\n        if (s > 65535)\n            err(11);\n        var d = compression ? deflateSync(file, p) : file, l = d.length;\n        var c = crc();\n        c.p(file);\n        files.push(mrg(p, {\n            size: file.length,\n            crc: c.d(),\n            c: d,\n            f: f,\n            m: m,\n            u: s != fn.length || (m && (com.length != ms)),\n            o: o,\n            compression: compression\n        }));\n        o += 30 + s + exl + l;\n        tot += 76 + 2 * (s + exl) + (ms || 0) + l;\n    }\n    var out = new u8(tot + 22), oe = o, cdl = tot - o;\n    for (var i = 0; i < files.length; ++i) {\n        var f = files[i];\n        wzh(out, f.o, f, f.f, f.u, f.c.length);\n        var badd = 30 + f.f.length + exfl(f.extra);\n        out.set(f.c, f.o + badd);\n        wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);\n    }\n    wzf(out, o, files.length, cdl, oe);\n    return out;\n}\n/**\n * Streaming pass-through decompression for ZIP archives\n */\nvar UnzipPassThrough = /*#__PURE__*/ (function () {\n    function UnzipPassThrough() {\n    }\n    UnzipPassThrough.prototype.push = function (data, final) {\n        this.ondata(null, data, final);\n    };\n    UnzipPassThrough.compression = 0;\n    return UnzipPassThrough;\n}());\nexport { UnzipPassThrough };\n/**\n * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for\n * better performance.\n */\nvar UnzipInflate = /*#__PURE__*/ (function () {\n    /**\n     * Creates a DEFLATE decompression that can be used in ZIP archives\n     */\n    function UnzipInflate() {\n        var _this = this;\n        this.i = new Inflate(function (dat, final) {\n            _this.ondata(null, dat, final);\n        });\n    }\n    UnzipInflate.prototype.push = function (data, final) {\n        try {\n            this.i.push(data, final);\n        }\n        catch (e) {\n            this.ondata(e, null, final);\n        }\n    };\n    UnzipInflate.compression = 8;\n    return UnzipInflate;\n}());\nexport { UnzipInflate };\n/**\n * Asynchronous streaming DEFLATE decompression for ZIP archives\n */\nvar AsyncUnzipInflate = /*#__PURE__*/ (function () {\n    /**\n     * Creates a DEFLATE decompression that can be used in ZIP archives\n     */\n    function AsyncUnzipInflate(_, sz) {\n        var _this = this;\n        if (sz < 320000) {\n            this.i = new Inflate(function (dat, final) {\n                _this.ondata(null, dat, final);\n            });\n        }\n        else {\n            this.i = new AsyncInflate(function (err, dat, final) {\n                _this.ondata(err, dat, final);\n            });\n            this.terminate = this.i.terminate;\n        }\n    }\n    AsyncUnzipInflate.prototype.push = function (data, final) {\n        if (this.i.terminate)\n            data = slc(data, 0);\n        this.i.push(data, final);\n    };\n    AsyncUnzipInflate.compression = 8;\n    return AsyncUnzipInflate;\n}());\nexport { AsyncUnzipInflate };\n/**\n * A ZIP archive decompression stream that emits files as they are discovered\n */\nvar Unzip = /*#__PURE__*/ (function () {\n    /**\n     * Creates a ZIP decompression stream\n     * @param cb The callback to call whenever a file in the ZIP archive is found\n     */\n    function Unzip(cb) {\n        this.onfile = cb;\n        this.k = [];\n        this.o = {\n            0: UnzipPassThrough\n        };\n        this.p = et;\n    }\n    /**\n     * Pushes a chunk to be unzipped\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Unzip.prototype.push = function (chunk, final) {\n        var _this = this;\n        if (!this.onfile)\n            err(5);\n        if (!this.p)\n            err(4);\n        if (this.c > 0) {\n            var len = Math.min(this.c, chunk.length);\n            var toAdd = chunk.subarray(0, len);\n            this.c -= len;\n            if (this.d)\n                this.d.push(toAdd, !this.c);\n            else\n                this.k[0].push(toAdd);\n            chunk = chunk.subarray(len);\n            if (chunk.length)\n                return this.push(chunk, final);\n        }\n        else {\n            var f = 0, i = 0, is = void 0, buf = void 0;\n            if (!this.p.length)\n                buf = chunk;\n            else if (!chunk.length)\n                buf = this.p;\n            else {\n                buf = new u8(this.p.length + chunk.length);\n                buf.set(this.p), buf.set(chunk, this.p.length);\n            }\n            var l = buf.length, oc = this.c, add = oc && this.d;\n            var _loop_2 = function () {\n                var _a;\n                var sig = b4(buf, i);\n                if (sig == 0x4034B50) {\n                    f = 1, is = i;\n                    this_1.d = null;\n                    this_1.c = 0;\n                    var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28);\n                    if (l > i + 30 + fnl + es) {\n                        var chks_3 = [];\n                        this_1.k.unshift(chks_3);\n                        f = 2;\n                        var sc_1 = b4(buf, i + 18), su_1 = b4(buf, i + 22);\n                        var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u);\n                        if (sc_1 == 4294967295) {\n                            _a = dd ? [-2] : z64e(buf, i), sc_1 = _a[0], su_1 = _a[1];\n                        }\n                        else if (dd)\n                            sc_1 = -1;\n                        i += es;\n                        this_1.c = sc_1;\n                        var d_1;\n                        var file_1 = {\n                            name: fn_1,\n                            compression: cmp_1,\n                            start: function () {\n                                if (!file_1.ondata)\n                                    err(5);\n                                if (!sc_1)\n                                    file_1.ondata(null, et, true);\n                                else {\n                                    var ctr = _this.o[cmp_1];\n                                    if (!ctr)\n                                        file_1.ondata(err(14, 'unknown compression type ' + cmp_1, 1), null, false);\n                                    d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1);\n                                    d_1.ondata = function (err, dat, final) { file_1.ondata(err, dat, final); };\n                                    for (var _i = 0, chks_4 = chks_3; _i < chks_4.length; _i++) {\n                                        var dat = chks_4[_i];\n                                        d_1.push(dat, false);\n                                    }\n                                    if (_this.k[0] == chks_3 && _this.c)\n                                        _this.d = d_1;\n                                    else\n                                        d_1.push(et, true);\n                                }\n                            },\n                            terminate: function () {\n                                if (d_1 && d_1.terminate)\n                                    d_1.terminate();\n                            }\n                        };\n                        if (sc_1 >= 0)\n                            file_1.size = sc_1, file_1.originalSize = su_1;\n                        this_1.onfile(file_1);\n                    }\n                    return \"break\";\n                }\n                else if (oc) {\n                    if (sig == 0x8074B50) {\n                        is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0;\n                        return \"break\";\n                    }\n                    else if (sig == 0x2014B50) {\n                        is = i -= 4, f = 3, this_1.c = 0;\n                        return \"break\";\n                    }\n                }\n            };\n            var this_1 = this;\n            for (; i < l - 4; ++i) {\n                var state_1 = _loop_2();\n                if (state_1 === \"break\")\n                    break;\n            }\n            this.p = et;\n            if (oc < 0) {\n                var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i);\n                if (add)\n                    add.push(dat, !!f);\n                else\n                    this.k[+(f == 2)].push(dat);\n            }\n            if (f & 2)\n                return this.push(buf.subarray(i), final);\n            this.p = buf.subarray(i);\n        }\n        if (final) {\n            if (this.c)\n                err(13);\n            this.p = null;\n        }\n    };\n    /**\n     * Registers a decoder with the stream, allowing for files compressed with\n     * the compression type provided to be expanded correctly\n     * @param decoder The decoder constructor\n     */\n    Unzip.prototype.register = function (decoder) {\n        this.o[decoder.compression] = decoder;\n    };\n    return Unzip;\n}());\nexport { Unzip };\nvar mt = typeof queueMicrotask == 'function' ? queueMicrotask : typeof setTimeout == 'function' ? setTimeout : function (fn) { fn(); };\nexport function unzip(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    var term = [];\n    var tAll = function () {\n        for (var i = 0; i < term.length; ++i)\n            term[i]();\n    };\n    var files = {};\n    var cbd = function (a, b) {\n        mt(function () { cb(a, b); });\n    };\n    mt(function () { cbd = cb; });\n    var e = data.length - 22;\n    for (; b4(data, e) != 0x6054B50; --e) {\n        if (!e || data.length - e > 65558) {\n            cbd(err(13, 0, 1), null);\n            return tAll;\n        }\n    }\n    ;\n    var lft = b2(data, e + 8);\n    if (lft) {\n        var c = lft;\n        var o = b4(data, e + 16);\n        var z = o == 4294967295 || c == 65535;\n        if (z) {\n            var ze = b4(data, e - 12);\n            z = b4(data, ze) == 0x6064B50;\n            if (z) {\n                c = lft = b4(data, ze + 32);\n                o = b4(data, ze + 48);\n            }\n        }\n        var fltr = opts && opts.filter;\n        var _loop_3 = function (i) {\n            var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n            o = no;\n            var cbl = function (e, d) {\n                if (e) {\n                    tAll();\n                    cbd(e, null);\n                }\n                else {\n                    if (d)\n                        files[fn] = d;\n                    if (!--lft)\n                        cbd(null, files);\n                }\n            };\n            if (!fltr || fltr({\n                name: fn,\n                size: sc,\n                originalSize: su,\n                compression: c_1\n            })) {\n                if (!c_1)\n                    cbl(null, slc(data, b, b + sc));\n                else if (c_1 == 8) {\n                    var infl = data.subarray(b, b + sc);\n                    // Synchronously decompress under 512KB, or barely-compressed data\n                    if (su < 524288 || sc > 0.8 * su) {\n                        try {\n                            cbl(null, inflateSync(infl, { out: new u8(su) }));\n                        }\n                        catch (e) {\n                            cbl(e, null);\n                        }\n                    }\n                    else\n                        term.push(inflate(infl, { size: su }, cbl));\n                }\n                else\n                    cbl(err(14, 'unknown compression type ' + c_1, 1), null);\n            }\n            else\n                cbl(null, null);\n        };\n        for (var i = 0; i < c; ++i) {\n            _loop_3(i);\n        }\n    }\n    else\n        cbd(null, {});\n    return tAll;\n}\n/**\n * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better\n * performance with more than one file.\n * @param data The raw compressed ZIP file\n * @param opts The ZIP extraction options\n * @returns The decompressed files\n */\nexport function unzipSync(data, opts) {\n    var files = {};\n    var e = data.length - 22;\n    for (; b4(data, e) != 0x6054B50; --e) {\n        if (!e || data.length - e > 65558)\n            err(13);\n    }\n    ;\n    var c = b2(data, e + 8);\n    if (!c)\n        return {};\n    var o = b4(data, e + 16);\n    var z = o == 4294967295 || c == 65535;\n    if (z) {\n        var ze = b4(data, e - 12);\n        z = b4(data, ze) == 0x6064B50;\n        if (z) {\n            c = b4(data, ze + 32);\n            o = b4(data, ze + 48);\n        }\n    }\n    var fltr = opts && opts.filter;\n    for (var i = 0; i < c; ++i) {\n        var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n        o = no;\n        if (!fltr || fltr({\n            name: fn,\n            size: sc,\n            originalSize: su,\n            compression: c_2\n        })) {\n            if (!c_2)\n                files[fn] = slc(data, b, b + sc);\n            else if (c_2 == 8)\n                files[fn] = inflateSync(data.subarray(b, b + sc), { out: new u8(su) });\n            else\n                err(14, 'unknown compression type ' + c_2);\n        }\n    }\n    return files;\n}\n","// biome-ignore lint: needed for Leaflet + IIFE to work\ndeclare const L: any;\n// biome-ignore lint: needed for window.URL to disambiguate from cloudflare workers\ndeclare const window: any;\ndeclare const document: DocumentLike;\n\nimport type { Coords } from \"leaflet\";\nimport { PMTiles, TileType } from \"./index\";\n\ninterface DocumentLike {\n  // biome-ignore lint: we don't want to bring in the entire document type\n  createElement: (s: string) => any;\n}\n\n// biome-ignore lint: we don't want to bring in the entire document type\ntype DoneCallback = (error?: Error, tile?: any) => void;\n\n/**\n * Add a raster PMTiles as a layer to a Leaflet map.\n *\n * For vector tiles see https://github.com/protomaps/protomaps-leaflet\n */\nexport const leafletRasterLayer = (source: PMTiles, options: unknown) => {\n  let loaded = false;\n  let mimeType = \"\";\n  const cls = L.GridLayer.extend({\n    createTile: (coord: Coords, done: DoneCallback) => {\n      const el = document.createElement(\"img\");\n      const controller = new AbortController();\n      const signal = controller.signal;\n      el.cancel = () => {\n        controller.abort();\n      };\n      if (!loaded) {\n        source.getHeader().then((header) => {\n          if (header.tileType === TileType.Mvt) {\n            console.error(\n              \"Error: archive contains MVT vector tiles, but leafletRasterLayer is for displaying raster tiles. See https://github.com/protomaps/PMTiles/tree/main/js for details.\"\n            );\n          } else if (header.tileType === 2) {\n            mimeType = \"image/png\";\n          } else if (header.tileType === 3) {\n            mimeType = \"image/jpeg\";\n          } else if (header.tileType === 4) {\n            mimeType = \"image/webp\";\n          } else if (header.tileType === 5) {\n            mimeType = \"image/avif\";\n          }\n        });\n        loaded = true;\n      }\n      source\n        .getZxy(coord.z, coord.x, coord.y, signal)\n        .then((arr) => {\n          if (arr) {\n            const blob = new Blob([arr.data], { type: mimeType });\n            const imageUrl = window.URL.createObjectURL(blob);\n            el.src = imageUrl;\n            el.cancel = undefined;\n            done(undefined, el);\n          }\n        })\n        .catch((e) => {\n          if (e.name !== \"AbortError\") {\n            throw e;\n          }\n        });\n      return el;\n    },\n\n    _removeTile: function (key: string) {\n      const tile = this._tiles[key];\n      if (!tile) {\n        return;\n      }\n\n      if (tile.el.cancel) tile.el.cancel();\n\n      tile.el.width = 0;\n      tile.el.height = 0;\n      tile.el.deleted = true;\n      L.DomUtil.remove(tile.el);\n      delete this._tiles[key];\n      this.fire(\"tileunload\", {\n        tile: tile.el,\n        coords: this._keyToTileCoords(key),\n      });\n    },\n  });\n  return new cls(options);\n};\n\nconst isDeepEqual = (object1: any, object2: any) => {\n  const objKeys1 = Object.keys(object1);\n  const objKeys2 = Object.keys(object2);\n  if (objKeys1.length !== objKeys2.length)\n    return false;\n  for (var key of objKeys1) {\n    const value1 = object1[key];\n    const value2 = object2[key];\n    const isObjects = isObject(value1) && isObject(value2);\n    if (isObjects && !isDeepEqual(value1, value2) || !isObjects && value1 !== value2) {\n      return false;\n    }\n  }\n  return true;\n};\n\nconst isObject = (object: any) => {\n  return object != null && typeof object === \"object\";\n};\n\ntype GetResourceResponse<T> = ExpiryData & {\n  data: T;\n};\ntype AddProtocolAction = (\n  requestParameters: RequestParameters,\n  abortController: AbortController\n) => Promise<GetResourceResponse<unknown>>;\n\ntype ExpiryData = {\n  cacheControl?: string | null;\n  expires?: string | null; // MapLibre can be a Date object\n};\n\n// copied from MapLibre /util/ajax.ts\ntype RequestParameters = {\n  url: string;\n  headers?: unknown;\n  method?: \"GET\" | \"POST\" | \"PUT\";\n  body?: string;\n  type?: \"string\" | \"json\" | \"arrayBuffer\" | \"image\";\n  credentials?: \"same-origin\" | \"include\";\n  collectResourceTiming?: boolean;\n};\n\n// for legacy maplibre-3 interop\ntype ResponseCallbackV3 = (\n  error?: Error | undefined,\n  data?: unknown | undefined,\n  cacheControl?: string | undefined,\n  expires?: string | undefined\n) => void;\n\ntype V3OrV4Protocol = <\n  T extends AbortController | ResponseCallbackV3,\n  R = T extends AbortController\n    ? Promise<GetResourceResponse<unknown>>\n    : { cancel: () => void },\n>(\n  requestParameters: RequestParameters,\n  arg2: T\n) => R;\n\nconst v3compat =\n  (v4: AddProtocolAction): V3OrV4Protocol =>\n  (requestParameters, arg2) => {\n    if (arg2 instanceof AbortController) {\n      // biome-ignore lint: overloading return type not handled by compiler\n      return v4(requestParameters, arg2) as any;\n    }\n    const abortController = new AbortController();\n    v4(requestParameters, abortController)\n      .then(\n        (result) => {\n          return arg2(\n            undefined,\n            result.data,\n            result.cacheControl || \"\",\n            result.expires || \"\"\n          );\n        },\n        (err) => {\n          return arg2(err);\n        }\n      )\n      .catch((e) => {\n        return arg2(e);\n      });\n    return { cancel: () => abortController.abort() };\n  };\n\n/**\n * MapLibre GL JS protocol. Must be added once globally.\n */\nexport class Protocol {\n  /** @hidden */\n  tiles: Map<string, PMTiles>;\n  metadata: boolean;\n  errorOnMissingTile: boolean;\n\n  /**\n   * Initialize the MapLibre PMTiles protocol.\n   *\n   * * metadata: also load the metadata section of the PMTiles. required for some \"inspect\" functionality\n   * and to automatically populate the map attribution. Requires an extra HTTP request.\n   * * errorOnMissingTile: When a vector MVT tile is missing from the archive, raise an error instead of\n   * returning the empty array. Not recommended. This is only to reproduce the behavior of ZXY tile APIs\n   * which some applications depend on when overzooming.\n   */\n  constructor(options?: { metadata?: boolean; errorOnMissingTile?: boolean }) {\n    this.tiles = new Map<string, PMTiles>();\n    this.metadata = options?.metadata || false;\n    this.errorOnMissingTile = options?.errorOnMissingTile || false;\n  }\n\n  /**\n   * Add a {@link PMTiles} instance to the global protocol instance.\n   *\n   * For remote fetch sources, references in MapLibre styles like pmtiles://http://...\n   * will resolve to the same instance if the URLs match.\n   */\n  add(p: PMTiles) {\n    this.tiles.set(p.source.getKey(), p);\n  }\n\n  /**\n   * Fetch a {@link PMTiles} instance by URL, for remote PMTiles instances.\n   */\n  get(url: string) {\n    return this.tiles.get(url);\n  }\n\n  /** @hidden */\n  tilev4 = async (\n    params: RequestParameters,\n    abortController: AbortController\n  ) => {\n    if (params.type === \"json\") {\n      const pmtilesUrl = params.url.substr(10);\n      let instance = this.tiles.get(pmtilesUrl);\n      if (!instance || !isDeepEqual((instance.source as any).customHeaders, params.headers)) {\n        instance = new PMTiles(pmtilesUrl, params.headers as Headers);\n        this.tiles.set(pmtilesUrl, instance);\n      }\n\n      if (this.metadata) {\n        return {\n          data: await instance.getTileJson(params.url),\n        };\n      }\n\n      const h = await instance.getHeader();\n\n      if (h.minLon >= h.maxLon || h.minLat >= h.maxLat) {\n        console.error(\n          `Bounds of PMTiles archive ${h.minLon},${h.minLat},${h.maxLon},${h.maxLat} are not valid.`\n        );\n      }\n\n      return {\n        data: {\n          tiles: [`${params.url}/{z}/{x}/{y}`],\n          minzoom: h.minZoom,\n          maxzoom: h.maxZoom,\n          bounds: [h.minLon, h.minLat, h.maxLon, h.maxLat],\n        },\n      };\n    }\n    const re = new RegExp(/pmtiles:\\/\\/(.+)\\/(\\d+)\\/(\\d+)\\/(\\d+)/);\n    const result = params.url.match(re);\n    if (!result) {\n      throw new Error(\"Invalid PMTiles protocol URL\");\n    }\n    const pmtilesUrl = result[1];\n\n    let instance = this.tiles.get(pmtilesUrl);\n    if (!instance || !isDeepEqual((instance.source as any).customHeaders, params.headers)) {\n      instance = new PMTiles(pmtilesUrl, params.headers as Headers);\n      this.tiles.set(pmtilesUrl, instance);\n    }\n    const z = result[2];\n    const x = result[3];\n    const y = result[4];\n\n    const header = await instance.getHeader();\n    const resp = await instance?.getZxy(+z, +x, +y, abortController.signal);\n    if (resp) {\n      return {\n        data: new Uint8Array(resp.data),\n        cacheControl: resp.cacheControl,\n        expires: resp.expires,\n      };\n    }\n    if (header.tileType === TileType.Mvt) {\n      if (this.errorOnMissingTile) {\n        throw new Error(\"Tile not found.\");\n      }\n      return { data: new Uint8Array() };\n    }\n    return { data: null };\n  };\n\n  tile = v3compat(this.tilev4);\n}\n"],"mappings":"qtBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,iBAAAE,GAAA,iBAAAC,EAAA,gBAAAC,EAAA,eAAAC,GAAA,YAAAC,EAAA,aAAAC,GAAA,uBAAAC,GAAA,uBAAAC,EAAA,aAAAC,GAAA,kBAAAC,GAAA,aAAAC,GAAA,cAAAC,EAAA,uBAAAC,GAAA,eAAAC,EAAA,gBAAAC,GAAA,gBAAAC,GAAA,gBAAAC,KC8BA,IAAIC,EAAK,WAAYC,EAAM,YAAaC,GAAM,WAE1CC,GAAO,IAAIH,EAAG,CAAC,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAgB,EAAG,EAAoB,CAAC,CAAC,EAE5II,GAAO,IAAIJ,EAAG,CAAC,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAA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,oBAAuC,QAAA9B,EAAA,sBAC3C,IAAMI,EAAS,MAAM,KAAK,MAAM,UAAU,KAAK,MAAM,EAE/CH,EAAO,MAAM,KAAK,OAAO,SAC7BG,EAAO,mBACPA,EAAO,mBACP,OACAA,EAAO,IACT,EACM4C,EAAe,MAAM,KAAK,WAC9B/C,EAAK,KACLG,EAAO,mBACT,EACM6C,EAAM,IAAI,YAAY,OAAO,EACnC,OAAO,KAAK,MAAMA,EAAI,OAAOD,CAAY,CAAC,CAC5C,GAKM,aAAgC,QAAAhD,EAAA,sBACpC,GAAI,CACF,OAAO,MAAM,KAAK,mBAAmB,CACvC,OAAS,EAAG,CACV,GAAI,aAAaJ,EACf,YAAK,MAAM,WAAW,KAAK,MAAM,EAC1B,MAAM,KAAK,mBAAmB,EAEvC,MAAM,CACR,CACF,GASM,YAAYsD,EAAwC,QAAAlD,EAAA,sBACxD,IAAMI,EAAS,MAAM,KAAK,UAAU,EAC9B+C,EAAY,MAAM,KAAK,YAAY,EACnCC,EAAMC,GAAYjD,EAAO,QAAQ,EAEvC,MAAO,CACL,SAAU,QACV,OAAQ,MACR,MAAO,CAAC,GAAG8C,CAAY,eAAeE,CAAG,EAAE,EAE3C,cAAeD,EAAS,cACxB,YAAaA,EAAS,YACtB,YAAaA,EAAS,YACtB,KAAMA,EAAS,KACf,QAASA,EAAS,QAClB,OAAQ,CAAC/C,EAAO,OAAQA,EAAO,OAAQA,EAAO,OAAQA,EAAO,MAAM,EACnE,OAAQ,CAACA,EAAO,UAAWA,EAAO,UAAWA,EAAO,UAAU,EAC9D,QAASA,EAAO,QAChB,QAASA,EAAO,OAClB,CACF,GACF,EAxKqBT,EAAAsC,GAAA,WAAd,IAAMqB,EAANrB","names":["src_exports","__export","Compression","EtagMismatch","FetchSource","FileSource","PMTiles","Protocol","ResolvedValueCache","SharedPromiseCache","TileType","bytesToHeader","findTile","getUint64","leafletRasterLayer","readVarint","tileIdToZxy","tileTypeExt","zxyToTileId","u8","u16","i32","fleb","fdeb","clim","freb","__name","eb","start","b","i","r","j","_a","fl","revfl","_b","fd","revfd","rev","x","hMap","cd","mb","s","l","le","co","rvb","sv","r_1","v","m","flt","fdt","flrm","hMap","flt","fdrm","hMap","fdt","max","__name","a","m","i","bits","d","p","o","bits16","shft","slc","v","s","e","u8","ec","err","__name","ind","msg","nt","e","inflt","dat","st","buf","dict","sl","dl","u8","noBuf","resize","noSt","cbuf","l","bl","nbuf","final","pos","bt","lm","dm","lbt","dbt","tbts","bits","type","flrm","fdrm","hLit","hcLen","tl","ldt","clt","i","clim","clb","max","clbmsk","clm","hMap","r","s","c","n","lt","dt","shft","t","lms","dms","lpos","bits16","sym","add","b","fleb","fl","d","dsym","fd","fdeb","end","shift","dend","slc","et","u8","gzs","__name","d","err","flg","st","zs","gzl","l","zls","__name","d","dict","err","inflateSync","data","opts","inflt","__name","gunzipSync","data","opts","st","gzs","err","inflt","u8","gzl","__name","unzlibSync","data","opts","inflt","zls","__name","decompressSync","data","opts","gunzipSync","inflateSync","unzlibSync","__name","td","tds","et","e","leafletRasterLayer","__name","source","options","loaded","mimeType","cls","coord","done","el","controller","signal","header","arr","blob","imageUrl","e","key","tile","isDeepEqual","object1","object2","objKeys1","objKeys2","value1","value2","isObjects","isObject","object","v3compat","v4","requestParameters","arg2","abortController","result","err","_Protocol","params","__async","pmtilesUrl","instance","PMTiles","h","re","z","x","y","resp","p","url","Protocol","toNum","low","high","__name","readVarintRemainder","l","p","buf","b","h","readVarint","val","rotate","n","x","y","rx","ry","zxyToTileId","z","acc","a","tx","ty","s","tileIdToZ","i","c","tileIdToZxy","t","Compression","defaultDecompress","compression","__async","decompressSync","stream","result","TileType","tileTypeExt","HEADER_SIZE_BYTES","findTile","entries","tileId","m","k","cmp","_FileSource","file","offset","length","FileSource","_FetchSource","url","customHeaders","userAgent","isWindows","isChromiumBased","passedSignal","etag","controller","signal","requestHeaders","cache","resp","contentRange","actualLength","newEtag","EtagMismatch","contentLength","FetchSource","getUint64","v","wh","wl","__pow","bytesToHeader","bytes","specVersion","deserializeIndex","buffer","numEntries","lastId","_EtagMismatch","__name","EtagMismatch","getHeaderAndRoot","source","decompress","__async","resp","headerData","HEADER_SIZE_BYTES","header","bytesToHeader","rootDirData","dirKey","rootDir","deserializeIndex","getDirectory","offset","length","data","directory","_ResolvedValueCache","maxCacheEntries","prefetch","defaultDecompress","cacheKey","cacheValue","res","minUsed","minKey","key","ResolvedValueCache","_SharedPromiseCache","p","resolve","reject","e","h","SharedPromiseCache","_PMTiles","customHeaders","cache","FetchSource","z","x","y","signal","tileId","zxyToTileId","dO","dL","depth","entry","findTile","decompressed","dec","baseTilesUrl","metadata","ext","tileTypeExt","PMTiles"]}
\ No newline at end of file
diff --git a/node_modules/pmtiles/src/adapters.ts b/node_modules/pmtiles/src/adapters.ts
index 60bc976..c2ff9a6 100644
--- a/node_modules/pmtiles/src/adapters.ts
+++ b/node_modules/pmtiles/src/adapters.ts
@@ -90,6 +90,26 @@ export const leafletRasterLayer = (source: PMTiles, options: unknown) => {
   return new cls(options);
 };
 
+const isDeepEqual = (object1: any, object2: any) => {
+  const objKeys1 = Object.keys(object1);
+  const objKeys2 = Object.keys(object2);
+  if (objKeys1.length !== objKeys2.length)
+    return false;
+  for (var key of objKeys1) {
+    const value1 = object1[key];
+    const value2 = object2[key];
+    const isObjects = isObject(value1) && isObject(value2);
+    if (isObjects && !isDeepEqual(value1, value2) || !isObjects && value1 !== value2) {
+      return false;
+    }
+  }
+  return true;
+};
+
+const isObject = (object: any) => {
+  return object != null && typeof object === "object";
+};
+
 type GetResourceResponse<T> = ExpiryData & {
   data: T;
 };
@@ -209,8 +229,8 @@ export class Protocol {
     if (params.type === "json") {
       const pmtilesUrl = params.url.substr(10);
       let instance = this.tiles.get(pmtilesUrl);
-      if (!instance) {
-        instance = new PMTiles(pmtilesUrl);
+      if (!instance || !isDeepEqual((instance.source as any).customHeaders, params.headers)) {
+        instance = new PMTiles(pmtilesUrl, params.headers as Headers);
         this.tiles.set(pmtilesUrl, instance);
       }
 
@@ -245,8 +265,8 @@ export class Protocol {
     const pmtilesUrl = result[1];
 
     let instance = this.tiles.get(pmtilesUrl);
-    if (!instance) {
-      instance = new PMTiles(pmtilesUrl);
+    if (!instance || !isDeepEqual((instance.source as any).customHeaders, params.headers)) {
+      instance = new PMTiles(pmtilesUrl, params.headers as Headers);
       this.tiles.set(pmtilesUrl, instance);
     }
     const z = result[2];
diff --git a/node_modules/pmtiles/src/index.ts b/node_modules/pmtiles/src/index.ts
index 437ed2f..b6941ce 100644
--- a/node_modules/pmtiles/src/index.ts
+++ b/node_modules/pmtiles/src/index.ts
@@ -879,11 +879,12 @@ export class PMTiles {
 
   constructor(
     source: Source | string,
+    customHeaders: Headers,
     cache?: Cache,
     decompress?: DecompressFunc
   ) {
     if (typeof source === "string") {
-      this.source = new FetchSource(source);
+      this.source = new FetchSource(source, customHeaders);
     } else {
       this.source = source;
     }
