"use strict";var pmtiles=(()=>{var k=Object.defineProperty;var Je=Object.getOwnPropertyDescriptor;var Ye=Object.getOwnPropertyNames;var Qe=Object.prototype.hasOwnProperty;var De=Math.pow;var l=(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 d=(r,e,t)=>new Promise((n,i)=>{var a=f=>{try{s(t.next(f))}catch(h){i(h)}},o=f=>{try{s(t.throw(f))}catch(h){i(h)}},s=f=>f.done?n(f.value):Promise.resolve(f.value).then(a,o);s((t=t.apply(r,e)).next())});var Tt={};Xe(Tt,{Compression:()=>Ie,EtagMismatch:()=>B,FetchSource:()=>V,FileSource:()=>oe,PMTiles:()=>S,Protocol:()=>ne,ResolvedValueCache:()=>se,SharedPromiseCache:()=>G,TileType:()=>ae,bytesToHeader:()=>$e,findTile:()=>Ze,getUint64:()=>b,leafletRasterLayer:()=>wt,readVarint:()=>R,tileIdToZxy:()=>zt,tileTypeExt:()=>Oe,zxyToTileId:()=>He});var w=Uint8Array,U=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]),Ee=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]),Ue=l(function(r,e){for(var t=new U(31),n=0;n<31;++n)t[n]=e+=1<>1|(g&21845)<<1,C=(C&52428)>>2|(C&13107)<<2,C=(C&61680)>>4|(C&3855)<<4,te[g]=((C&65280)>>8|(C&255)<<8)>>1;var C,g,O=l(function(r,e,t){for(var n=r.length,i=0,a=new U(e);i>f]=h}else for(s=new U(n),i=0;i>15-r[i]);return s},"hMap"),Z=new w(288);for(g=0;g<144;++g)Z[g]=8;var g;for(g=144;g<256;++g)Z[g]=9;var g;for(g=256;g<280;++g)Z[g]=7;var g;for(g=280;g<288;++g)Z[g]=8;var g,Re=new w(32);for(g=0;g<32;++g)Re[g]=5;var g;var at=O(Z,9,1);var ot=O(Re,5,1),_=l(function(r){for(var e=r[0],t=1;te&&(e=r[t]);return e},"max"),A=l(function(r,e,t){var n=e/8|0;return(r[n]|r[n+1]<<8)>>(e&7)&t},"bits"),ee=l(function(r,e){var t=e/8|0;return(r[t]|r[t+1]<<8|r[t+2]<<16)>>(e&7)},"bits16"),st=l(function(r){return(r+7)/8|0},"shft"),ut=l(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=l(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"),re=l(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 o=!t,s=o||e.i!=2,f=e.i;o&&(t=new w(i*3));var h=l(function(ze){var Ce=t.length;if(ze>Ce){var Te=new w(Math.max(Ce*2,ze));Te.set(t),t=Te}},"cbuf"),c=e.f||0,u=e.p||0,v=e.b||0,p=e.l,m=e.d,D=e.m,F=e.n,K=i*8;do{if(!p){c=A(r,u,1);var q=A(r,u+1,3);if(u+=3,q)if(q==1)p=at,m=ot,D=9,F=5;else if(q==2){var N=A(r,u,31)+257,pe=A(r,u+10,15)+4,me=N+A(r,u+5,31)+1;u+=14;for(var H=new w(me),J=new w(19),x=0;x>4;if(z<16)H[x++]=z;else{var M=0,$=0;for(z==16?($=3+A(r,u,3),u+=2,M=H[x-1]):z==17?($=3+A(r,u,7),u+=3):z==18&&($=11+A(r,u,127),u+=7);$--;)H[x++]=M}}var we=H.subarray(0,N),T=H.subarray(N);D=_(we),F=_(T),p=O(we,D,1),m=O(T,F,1)}else y(1);else{var z=st(u)+4,j=r[z-4]|r[z-3]<<8,W=z+j;if(W>i){f&&y(0);break}s&&h(v+j),t.set(r.subarray(z,W),v),e.b=v+=j,e.p=u=W*8,e.f=c;continue}if(u>K){f&&y(0);break}}s&&h(v+131072);for(var je=(1<>4;if(u+=M&15,u>K){f&&y(0);break}if(M||y(2),E<256)t[v++]=E;else if(E==256){Y=u,p=null;break}else{var xe=E-254;if(E>264){var x=E-257,I=Me[x];xe=A(r,u,(1<>4;Q||y(3),u+=Q&15;var T=it[X];if(X>3){var I=Ee[X];T+=ee(r,u)&(1<K){f&&y(0);break}s&&h(v+131072);var be=v+xe;if(v>3&1)+(e>>4&1);n>0;n-=!r[t++]);return t+(e&2)},"gzs"),ct=l(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=l(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 re(r,{i:2},e&&e.out,e&&e.dictionary)}l(gt,"inflateSync");function pt(r,e){var t=ht(r);return t+8>r.length&&y(6,"invalid gzip data"),re(r.subarray(t,-8),{i:2},e&&e.out||new w(ct(r)),e&&e.dictionary)}l(pt,"gunzipSync");function mt(r,e){return re(r.subarray(vt(r,e&&e.dictionary),-4),{i:2},e&&e.out,e&&e.dictionary)}l(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)}l(Be,"decompressSync");var dt=typeof TextDecoder!="undefined"&&new TextDecoder,yt=0;try{dt.decode(lt,{stream:!0}),yt=1}catch(r){}var wt=l((r,e)=>{let t=!1,n="",i=L.GridLayer.extend({createTile:l((a,o)=>{let s=document.createElement("img"),f=new AbortController,h=f.signal;return s.cancel=()=>{f.abort()},t||(r.getHeader().then(c=>{c.tileType===1||c.tileType===6?console.error("Error: archive contains 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,h).then(c=>{if(c){let u=new Blob([c.data],{type:n}),v=window.URL.createObjectURL(u);s.src=v}else s.style.display="none";s.cancel=void 0,o(void 0,s)}).catch(c=>{if(c.name!=="AbortError")throw c}),s},"createTile"),_removeTile:l(function(a){let o=this._tiles[a];o&&(o.el.cancel&&o.el.cancel(),o.el.src&&window.URL.revokeObjectURL(o.el.src),o.el.width=0,o.el.height=0,o.el.deleted=!0,L.DomUtil.remove(o.el),delete this._tiles[a],this.fire("tileunload",{tile:o.el,coords:this._keyToTileCoords(a)}))},"_removeTile")});return new i(e)},"leafletRasterLayer"),xt=l(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:l(()=>n.abort(),"cancel")}},"v3compat"),ie=class ie{constructor(e){this.tilev4=l((e,t)=>d(this,null,function*(){if(e.type==="json"){let v=e.url.substr(10),p=this.tiles.get(v);if(p||(p=new S(v),this.tiles.set(v,p)),this.metadata){let D=yield p.getTileJson(e.url);return t.signal.throwIfAborted(),{data:D}}let m=yield p.getHeader();return t.signal.throwIfAborted(),(m.minLon>=m.maxLon||m.minLat>=m.maxLat)&&console.error(`Bounds of PMTiles archive ${m.minLon},${m.minLat},${m.maxLon},${m.maxLat} are not valid.`),{data:{tiles:[`${e.url}/{z}/{x}/{y}`],minzoom:m.minZoom,maxzoom:m.maxZoom,bounds:[m.minLon,m.minLat,m.maxLon,m.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],o=this.tiles.get(a);o||(o=new S(a),this.tiles.set(a,o));let s=i[2],f=i[3],h=i[4],c=yield o==null?void 0:o.getZxy(+s,+f,+h,t.signal);if(t.signal.throwIfAborted(),c)return{data:new Uint8Array(c.data),cacheControl:c.cacheControl,expires:c.expires};let u=yield o.getHeader();if(u.tileType===1||u.tileType===6){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)}};l(ie,"Protocol");var ne=ie;function P(r,e){return(e>>>0)*4294967296+(r>>>0)}l(P,"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 P(r,i);throw new Error("Expected varint not more than 10 bytes")}l(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))}l(R,"readVarint");function Fe(r,e,t,n,i){return i===0?n!==0?[r-1-t,r-1-e]:[t,e]:[e,t]}l(Fe,"rotate");function He(r,e,t){if(r>26)throw new Error("Tile zoom level exceeds max safe number limit (26)");if(e>=1<=1<0;s>>=1){let f=a&s,h=o&s;n+=(3*f^h)*(1<>1;if(e>26)throw new Error("Tile zoom level exceeds max safe number limit (26)");let t=((1<(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))(Ie||{});function ue(r,e){return d(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")})}l(ue,"defaultDecompress");var ae=(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[s.Mlt=6]="Mlt",s))(ae||{});function Oe(r){return r===1?".mvt":r===2?".png":r===3?".jpg":r===4?".webp":r===5?".avif":r===6?".mlt":""}l(Oe,"tileTypeExt");var Ct=127;function Ze(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-1,o=/Chrome|Chromium|Edg|OPR|Brave/.test(i);this.chromeWindowsNoCache=!1,a&&o&&(this.chromeWindowsNoCache=!0)}getKey(){return this.url}setHeaders(e){this.customHeaders=e}getBytes(e,t,n,i){return d(this,null,function*(){let a,o;n?o=n:(a=new AbortController,o=a.signal);let s=new Headers(this.customHeaders);s.set("range",`bytes=${e}-${e+t-1}`);let f;this.mustReload?f="reload":this.chromeWindowsNoCache&&(f="no-store");let h=yield fetch(this.url,{signal:o,cache:f,headers:s,credentials:this.credentials});if(e===0&&h.status===416){let p=h.headers.get("Content-Range");if(!p||!p.startsWith("bytes */"))throw new Error("Missing content-length on 416 response");let m=+p.substr(8);s.set("range",`bytes=0-${m-1}`),h=yield fetch(this.url,{signal:o,cache:"reload",headers:s,credentials:this.credentials})}let c=h.headers.get("Etag");if(c!=null&&c.startsWith("W/")&&(c=null),h.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(h.status>=300)throw new Error(`Bad response code: ${h.status}`);let u=h.headers.get("Content-Length");if(h.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 h.arrayBuffer(),etag:c||void 0,cacheControl:h.headers.get("Cache-Control")||void 0,expires:h.headers.get("Expires")||void 0}})}};l(le,"FetchSource");var V=le;function b(r,e){let t=r.getUint32(e+4,!0),n=r.getUint32(e+0,!0);return t*De(2,32)+n}l(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}}l($e,"bytesToHeader");function ke(r){let e={buf:new Uint8Array(r),pos:0},t=R(e),n=[],i=0;for(let a=0;a0?n[a].offset=n[a-1].offset+n[a-1].length:n[a].offset=o-1}return n}l(ke,"deserializeIndex");var he=class he extends Error{};l(he,"EtagMismatch");var B=he;function Ve(r,e){return d(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),o=t.data.slice(a.rootDirectoryOffset,a.rootDirectoryOffset+a.rootDirectoryLength),s=`${r.getKey()}|${a.etag||""}|${a.rootDirectoryOffset}|${a.rootDirectoryLength}`,f=ke(yield e(o,a.internalCompression));return[a,[s,f.length,f]]})}l(Ve,"getHeaderAndRoot");function Ge(r,e,t,n,i,a){return d(this,null,function*(){let o=yield r.getBytes(t,n,a,i.etag),s=yield e(o.data,i.internalCompression),f=ke(s);if(f.length===0)throw new Error("Empty directory is invalid");return f})}l(Ge,"getDirectory");var ce=class ce{constructor(e=100,t=!0,n=ue){this.cache=new Map,this.maxCacheEntries=e,this.counter=1,this.decompress=n}getHeader(e){return d(this,null,function*(){let t=e.getKey(),n=this.cache.get(t);if(n)return n.lastUsed=this.counter++,n.data;let i=yield Ve(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,a){return d(this,null,function*(){let o=`${e.getKey()}|${i.etag||""}|${t}|${n}`,s=this.cache.get(o);if(s)return s.lastUsed=this.counter++,s.data;let f=yield Ge(e,this.decompress,t,n,i,a);return this.cache.set(o,{lastUsed:this.counter++,data:f}),this.prune(),f})}prune(){if(this.cache.size>this.maxCacheEntries){let e=1/0,t;this.cache.forEach((n,i)=>{n.lastUsed{Ve(e,this.decompress).then(s=>{s[1]&&this.cache.set(s[1][0],{lastUsed:this.counter++,data:Promise.resolve(s[1][2])}),a(s[0]),this.prune()}).catch(s=>{o(s)})});return this.cache.set(t,{lastUsed:this.counter++,data:i}),i})}trackSignal(e,t,n){t.refs++,n.addEventListener("abort",()=>{--t.refs<=0&&this.pendingFetches.get(e)===t&&(t.controller.abort(),this.cache.delete(e),this.pendingFetches.delete(e))},{once:!0})}getDirectory(e,t,n,i,a){return d(this,null,function*(){let o=`${e.getKey()}|${i.etag||""}|${t}|${n}`,s=this.cache.get(o);if(s){s.lastUsed=this.counter++;let u=this.pendingFetches.get(o);return u&&this.trackSignal(o,u,a!=null?a:new AbortController().signal),yield s.data}let f=new AbortController,h={controller:f,refs:0};this.trackSignal(o,h,a!=null?a:new AbortController().signal),this.pendingFetches.set(o,h);let c=new Promise((u,v)=>{Ge(e,this.decompress,t,n,i,f.signal).then(p=>{this.pendingFetches.delete(o),u(p),this.prune()}).catch(p=>{v(p)})});return this.cache.set(o,{lastUsed:this.counter++,data:c}),c})}prune(){if(this.cache.size>=this.maxCacheEntries){let e=1/0,t;this.cache.forEach((n,i)=>{n.lastUsed{this.getHeader(e).then(o=>{i(),this.invalidations.delete(t)}).catch(o=>{a(o)})});this.invalidations.set(t,n)})}};l(ve,"SharedPromiseCache");var G=ve,ge=class ge{constructor(e,t,n){typeof e=="string"?this.source=new V(e):this.source=e,n?this.decompress=n:this.decompress=ue,t?this.cache=t:this.cache=new G}getHeader(){return d(this,null,function*(){return yield this.cache.getHeader(this.source)})}getZxyAttempt(e,t,n,i){return d(this,null,function*(){let a=He(e,t,n),o=yield this.cache.getHeader(this.source);if(i==null||i.throwIfAborted(),eo.maxZoom)return;let s=o.rootDirectoryOffset,f=o.rootDirectoryLength;for(let h=0;h<=3;h++){let c=yield this.cache.getDirectory(this.source,s,f,o,i);i==null||i.throwIfAborted();let u=Ze(c,a);if(u){if(u.runLength>0){let v=yield this.source.getBytes(o.tileDataOffset+u.offset,u.length,i,o.etag);return{data:yield this.decompress(v.data,o.tileCompression),cacheControl:v.cacheControl,expires:v.expires}}s=o.leafDirectoryOffset+u.offset,f=u.length}else return}throw new Error("Maximum directory depth exceeded")})}getZxy(e,t,n,i){return d(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 d(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 d(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 d(this,null,function*(){let t=yield this.getHeader(),n=yield this.getMetadata(),i=Oe(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}})}};l(ge,"PMTiles");var S=ge;return et(Tt);})(); //# sourceMappingURL=pmtiles.js.map