signalk-binnacle 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -746,7 +746,7 @@ precision highp float;
746
746
  in vec3 view_direction;uniform vec3 u_sun_pos;uniform vec3 u_globe_position;uniform float u_globe_radius;uniform float u_atmosphere_blend;/**Shader use from https:*Made some change to adapt to MapLibre Globe geometry*/const float PI=3.141592653589793;const int iSteps=5;const int jSteps=3;/*radius of the planet*/const float EARTH_RADIUS=6371e3;/*radius of the atmosphere*/const float ATMOS_RADIUS=6471e3;vec2 rsi(vec3 r0,vec3 rd,float sr) {float a=dot(rd,rd);float b=2.0*dot(rd,r0);float c=dot(r0,r0)-(sr*sr);float d=(b*b)-4.0*a*c;if (d < 0.0) return vec2(1e5,-1e5);return vec2((-b-sqrt(d))/(2.0*a),(-b+sqrt(d))/(2.0*a));}vec4 atmosphere(vec3 r,vec3 r0,vec3 pSun,float iSun,float rPlanet,float rAtmos,vec3 kRlh,float kMie,float shRlh,float shMie,float g) {pSun=normalize(pSun);r=normalize(r);vec2 p=rsi(r0,r,rAtmos);if (p.x > p.y) {return vec4(0.0,0.0,0.0,1.0);}if (p.x < 0.0) {p.x=0.0;}vec3 pos=r0+r*p.x;vec2 p2=rsi(r0,r,rPlanet);if (p2.x <=p2.y && p2.x > 0.0) {p.y=min(p.y,p2.x);}float iStepSize=(p.y-p.x)/float(iSteps);float iTime=p.x+iStepSize*0.5;vec3 totalRlh=vec3(0,0,0);vec3 totalMie=vec3(0,0,0);float iOdRlh=0.0;float iOdMie=0.0;float mu=dot(r,pSun);float mumu=mu*mu;float gg=g*g;float pRlh=3.0/(16.0*PI)*(1.0+mumu);float pMie=3.0/(8.0*PI)*((1.0-gg)*(mumu+1.0))/(pow(1.0+gg-2.0*mu*g,1.5)*(2.0+gg));for (int i=0; i < iSteps; i++) {vec3 iPos=r0+r*iTime;float iHeight=length(iPos)-rPlanet;float odStepRlh=exp(-iHeight/shRlh)*iStepSize;float odStepMie=exp(-iHeight/shMie)*iStepSize;iOdRlh+=odStepRlh;iOdMie+=odStepMie;float jStepSize=rsi(iPos,pSun,rAtmos).y/float(jSteps);float jTime=jStepSize*0.5;float jOdRlh=0.0;float jOdMie=0.0;for (int j=0; j < jSteps; j++) {vec3 jPos=iPos+pSun*jTime;float jHeight=length(jPos)-rPlanet;jOdRlh+=exp(-jHeight/shRlh)*jStepSize;jOdMie+=exp(-jHeight/shMie)*jStepSize;jTime+=jStepSize;}vec3 attn=exp(-(kMie*(iOdMie+jOdMie)+kRlh*(iOdRlh+jOdRlh)));totalRlh+=odStepRlh*attn;totalMie+=odStepMie*attn;iTime+=iStepSize;}float opacity=exp(-(length(kRlh)*length(totalRlh)+kMie*length(totalMie)));vec3 color=iSun*(pRlh*kRlh*totalRlh+pMie*kMie*totalMie);return vec4(color,opacity);}void main() {vec3 scale_camera_pos=-u_globe_position*EARTH_RADIUS/u_globe_radius;vec4 color=atmosphere(normalize(view_direction),scale_camera_pos,u_sun_pos,22.0,EARTH_RADIUS,ATMOS_RADIUS,vec3(5.5e-6,13.0e-6,22.4e-6),21e-6,8e3,1.2e3,0.758
747
747
  );color.rgb=1.0-exp(-1.0*color.rgb);color=pow(color,vec4(1.0/2.2));fragColor=vec4(color.rgb,1.0-color.a)*u_atmosphere_blend;}`,`in vec2 a_pos;uniform mat4 u_inv_proj_matrix;out vec3 view_direction;void main() {view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,0.0,1.0);}`),sky:qt(`uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform vec2 u_horizon;uniform vec2 u_horizon_normal;uniform float u_sky_horizon_blend;uniform float u_sky_blend;void main() {float x=gl_FragCoord.x;float y=gl_FragCoord.y;float blend=(y-u_horizon.y)*u_horizon_normal.y+(x-u_horizon.x)*u_horizon_normal.x;if (blend > 0.0) {if (blend < u_sky_horizon_blend) {fragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {fragColor=u_sky_color;}}fragColor=mix(fragColor,vec4(vec3(0.0),0.0),u_sky_blend);}`,`in vec2 a_pos;void main() {gl_Position=vec4(a_pos,1.0,1.0);}`)};function qt(e,t){let n=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,r=t.match(/in ([\w]+) ([\w]+)/g),i=e.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),a=t.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),o=a?a.concat(i):i,s={};return{fragmentSource:e=e.replace(n,((e,t,n,r,i)=>(s[i]=!0,t===`define`?`\n#ifndef HAS_UNIFORM_u_${i}\nin ${n} ${r} ${i};\n#else\nuniform ${n} ${r} u_${i};\n#endif\n`:`\n#ifdef HAS_UNIFORM_u_${i}\n ${n} ${r} ${i} = u_${i};\n#endif\n`))),vertexSource:t=t.replace(n,((e,t,n,r,i)=>{let a=r===`float`?`vec2`:`vec4`,o=i.match(/color/)?`color`:a;return s[i]?t===`define`?`\n#ifndef HAS_UNIFORM_u_${i}\nuniform lowp float u_${i}_t;\nin ${n} ${a} a_${i};\nout ${n} ${r} ${i};\n#else\nuniform ${n} ${r} u_${i};\n#endif\n`:o===`vec4`?`\n#ifndef HAS_UNIFORM_u_${i}\n ${i} = a_${i};\n#else\n ${n} ${r} ${i} = u_${i};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${i}\n ${i} = unpack_mix_${o}(a_${i}, u_${i}_t);\n#else\n ${n} ${r} ${i} = u_${i};\n#endif\n`:t===`define`?`\n#ifndef HAS_UNIFORM_u_${i}\nuniform lowp float u_${i}_t;\nin ${n} ${a} a_${i};\n#else\nuniform ${n} ${r} u_${i};\n#endif\n`:o===`vec4`?`\n#ifndef HAS_UNIFORM_u_${i}\n ${n} ${r} ${i} = a_${i};\n#else\n ${n} ${r} ${i} = u_${i};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${i}\n ${n} ${r} ${i} = unpack_mix_${o}(a_${i}, u_${i}_t);\n#else\n ${n} ${r} ${i} = u_${i};\n#endif\n`})),staticAttributes:r,staticUniforms:o}}class Jt{constructor(e,t,n){this.vertexBuffer=e,this.indexBuffer=t,this.segments=n}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.vertexBuffer=null,this.indexBuffer=null,this.segments=null}}var Yt=t.aS([{name:`a_pos`,type:`Int16`,components:2}]);let Xt=`#define PROJECTION_MERCATOR`,Zt=`mercator`;class Qt{constructor(){this._cachedMesh=null}get name(){return`mercator`}get useSubdivision(){return!1}get shaderVariantName(){return Zt}get shaderDefine(){return Xt}get shaderPreludeCode(){return Kt.projectionMercator}get vertexShaderPreludeCode(){return Kt.projectionMercator.vertexSource}get subdivisionGranularity(){return t.aT.noSubdivision}get useGlobeControls(){return!1}get transitionState(){return 0}get latitudeErrorCorrectionRadians(){return 0}destroy(){}updateGPUdependent(e){}getMeshFromTileID(e,n,r,i,a){if(this._cachedMesh)return this._cachedMesh;let o=new t.aU;o.emplaceBack(0,0),o.emplaceBack(t.a6,0),o.emplaceBack(0,t.a6),o.emplaceBack(t.a6,t.a6);let s=e.createVertexBuffer(o,Yt.members),c=t.aV.simpleSegment(0,0,4,2),l=new t.aW;l.emplaceBack(1,0,2),l.emplaceBack(1,2,3);let u=e.createIndexBuffer(l);return this._cachedMesh=new Jt(s,u,c),this._cachedMesh}recalculate(){}hasTransition(){return!1}setErrorQueryLatitudeDegrees(e){}}class $t{constructor(e=0,t=0,n=0,r=0){if(isNaN(e)||e<0||isNaN(t)||t<0||isNaN(n)||n<0||isNaN(r)||r<0)throw Error(`Invalid value for edge-insets, top, bottom, left and right must all be numbers`);this.top=e,this.bottom=t,this.left=n,this.right=r}interpolate(e,n,r){return n.top!=null&&e.top!=null&&(this.top=t.H.number(e.top,n.top,r)),n.bottom!=null&&e.bottom!=null&&(this.bottom=t.H.number(e.bottom,n.bottom,r)),n.left!=null&&e.left!=null&&(this.left=t.H.number(e.left,n.left,r)),n.right!=null&&e.right!=null&&(this.right=t.H.number(e.right,n.right,r)),this}getCenter(e,n){let r=t.al((this.left+e-this.right)/2,0,e),i=t.al((this.top+n-this.bottom)/2,0,n);return new t.P(r,i)}equals(e){return this.top===e.top&&this.bottom===e.bottom&&this.left===e.left&&this.right===e.right}clone(){return new $t(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}function en(e,t){if(!e.renderWorldCopies||e.lngRange)return;let n=t.lng-e.center.lng;t.lng+=n>180?-360:n<-180?360:0}function tn(e){return Math.max(0,Math.floor(e))}class nn{constructor(e,n){this.applyConstrain=(e,t)=>this._constrainOverride===null?this._callbacks.defaultConstrain(e,t):this._constrainOverride(e,t),this._callbacks=e,this._tileSize=512,this._renderWorldCopies=n?.renderWorldCopies===void 0||!!n?.renderWorldCopies,this._minZoom=n?.minZoom||0,this._maxZoom=n?.maxZoom||22,this._minPitch=n?.minPitch==null?0:n?.minPitch,this._maxPitch=n?.maxPitch==null?60:n?.maxPitch,this._constrainOverride=n?.constrainOverride??null,this.setMaxBounds(),this._width=0,this._height=0,this._center=new t.W(0,0),this._elevation=0,this._zoom=0,this._tileZoom=tn(this._zoom),this._scale=t.ao(this._zoom),this._bearingInRadians=0,this._fovInRadians=.6435011087932844,this._pitchInRadians=0,this._rollInRadians=0,this._unmodified=!0,this._edgeInsets=new $t,this._minElevationForCurrentTile=0,this._autoCalculateNearFarZ=!0}apply(e,n,r){this._constrainOverride=e.constrainOverride,this._latRange=e.latRange,this._lngRange=e.lngRange,this._width=e.width,this._height=e.height,this._center=e.center,this._elevation=e.elevation,this._minElevationForCurrentTile=e.minElevationForCurrentTile,this._zoom=e.zoom,this._tileZoom=tn(this._zoom),this._scale=t.ao(this._zoom),this._bearingInRadians=e.bearingInRadians,this._fovInRadians=e.fovInRadians,this._pitchInRadians=e.pitchInRadians,this._rollInRadians=e.rollInRadians,this._unmodified=e.unmodified,this._edgeInsets=new $t(e.padding.top,e.padding.bottom,e.padding.left,e.padding.right),this._minZoom=e.minZoom,this._maxZoom=e.maxZoom,this._minPitch=e.minPitch,this._maxPitch=e.maxPitch,this._renderWorldCopies=e.renderWorldCopies,this._cameraToCenterDistance=e.cameraToCenterDistance,this._nearZ=e.nearZ,this._farZ=e.farZ,this._autoCalculateNearFarZ=!r&&e.autoCalculateNearFarZ,n&&this.constrainInternal(),this._calcMatrices()}get pixelsToClipSpaceMatrix(){return this._pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._clipSpaceToPixelsMatrix}get minElevationForCurrentTile(){return this._minElevationForCurrentTile}setMinElevationForCurrentTile(e){this._minElevationForCurrentTile=e}get tileSize(){return this._tileSize}get tileZoom(){return this._tileZoom}get scale(){return this._scale}get width(){return this._width}get height(){return this._height}get bearingInRadians(){return this._bearingInRadians}get lngRange(){return this._lngRange}get latRange(){return this._latRange}get pixelsToGLUnits(){return this._pixelsToGLUnits}get minZoom(){return this._minZoom}setMinZoom(e){this._minZoom!==e&&(this._minZoom=e,this.setZoom(this.applyConstrain(this._center,this.zoom).zoom))}get maxZoom(){return this._maxZoom}setMaxZoom(e){this._maxZoom!==e&&(this._maxZoom=e,this.setZoom(this.applyConstrain(this._center,this.zoom).zoom))}get minPitch(){return this._minPitch}setMinPitch(e){this._minPitch!==e&&(this._minPitch=e,this.setPitch(Math.max(this.pitch,e)))}get maxPitch(){return this._maxPitch}setMaxPitch(e){this._maxPitch!==e&&(this._maxPitch=e,this.setPitch(Math.min(this.pitch,e)))}get renderWorldCopies(){return this._renderWorldCopies}setRenderWorldCopies(e){e===void 0?e=!0:e===null&&(e=!1),this._renderWorldCopies=e}get constrainOverride(){return this._constrainOverride}setConstrainOverride(e){e===void 0&&(e=null),this._constrainOverride!==e&&(this._constrainOverride=e,this.constrainInternal(),this._calcMatrices())}get worldSize(){return this._tileSize*this._scale}get centerOffset(){return this.centerPoint._sub(this.size._div(2))}get size(){return new t.P(this._width,this._height)}get bearing(){return this._bearingInRadians/Math.PI*180}setBearing(e){let n=t.X(e,-180,180)*Math.PI/180;var i,a,o,s,c,l,u,d,f;this._bearingInRadians!==n&&(this._unmodified=!1,this._bearingInRadians=n,this._calcMatrices(),this._rotationMatrix=r(),i=this._rotationMatrix,o=-this._bearingInRadians,s=(a=this._rotationMatrix)[0],c=a[1],l=a[2],u=a[3],d=Math.sin(o),f=Math.cos(o),i[0]=s*f+l*d,i[1]=c*f+u*d,i[2]=s*-d+l*f,i[3]=c*-d+u*f)}get rotationMatrix(){return this._rotationMatrix}get pitchInRadians(){return this._pitchInRadians}get pitch(){return this._pitchInRadians/Math.PI*180}setPitch(e){let n=t.al(e,this.minPitch,this.maxPitch)/180*Math.PI;this._pitchInRadians!==n&&(this._unmodified=!1,this._pitchInRadians=n,this._calcMatrices())}get rollInRadians(){return this._rollInRadians}get roll(){return this._rollInRadians/Math.PI*180}setRoll(e){let t=e/180*Math.PI;this._rollInRadians!==t&&(this._unmodified=!1,this._rollInRadians=t,this._calcMatrices())}get fovInRadians(){return this._fovInRadians}get fov(){return t.aX(this._fovInRadians)}setFov(e){e=t.al(e,.1,150),this.fov!==e&&(this._unmodified=!1,this._fovInRadians=t.an(e),this._calcMatrices())}get zoom(){return this._zoom}setZoom(e){let n=this.applyConstrain(this._center,e).zoom;this._zoom!==n&&(this._unmodified=!1,this._zoom=n,this._tileZoom=Math.max(0,Math.floor(n)),this._scale=t.ao(n),this.constrainInternal(),this._calcMatrices())}get center(){return this._center}setCenter(e){e.lat===this._center.lat&&e.lng===this._center.lng||(this._unmodified=!1,this._center=e,this.constrainInternal(),this._calcMatrices())}get elevation(){return this._elevation}setElevation(e){e!==this._elevation&&(this._elevation=e,this.constrainInternal(),this._calcMatrices())}get padding(){return this._edgeInsets.toJSON()}setPadding(e){this._edgeInsets.equals(e)||(this._unmodified=!1,this._edgeInsets.interpolate(this._edgeInsets,e,1),this._calcMatrices())}get centerPoint(){return this._edgeInsets.getCenter(this._width,this._height)}get pixelsPerMeter(){return this._pixelPerMeter}get unmodified(){return this._unmodified}get cameraToCenterDistance(){return this._cameraToCenterDistance}get nearZ(){return this._nearZ}get farZ(){return this._farZ}get autoCalculateNearFarZ(){return this._autoCalculateNearFarZ}overrideNearFarZ(e,t){this._autoCalculateNearFarZ=!1,this._nearZ=e,this._farZ=t,this._calcMatrices()}clearNearFarZOverride(){this._autoCalculateNearFarZ=!0,this._calcMatrices()}isPaddingEqual(e){return this._edgeInsets.equals(e)}interpolatePadding(e,t,n){this._unmodified=!1,this._edgeInsets.interpolate(e,t,n),this.constrainInternal(),this._calcMatrices()}resize(e,t,n=!0){this._width=e,this._height=t,n&&this.constrainInternal(),this._calcMatrices()}getMaxBounds(){return this._latRange?.length!==2||this._lngRange?.length!==2?null:new de([this._lngRange[0],this._latRange[0]],[this._lngRange[1],this._latRange[1]])}setMaxBounds(e){e?(this._lngRange=[e.getWest(),e.getEast()],this._latRange=[e.getSouth(),e.getNorth()],this.constrainInternal()):(this._lngRange=null,this._latRange=[-t.am,t.am])}getCameraQueryGeometry(e,n){if(n.length===1)return[n[0],e];{let{minX:r,minY:i,maxX:a,maxY:o}=t.a8.fromPoints(n).extend(e);return[new t.P(r,i),new t.P(a,i),new t.P(a,o),new t.P(r,o),new t.P(r,i)]}}constrainInternal(){if(!this.center||!this._width||!this._height||this._constraining)return;this._constraining=!0;let e=this._unmodified,{center:t,zoom:n}=this.applyConstrain(this.center,this.zoom);this.setCenter(t),this.setZoom(n),this._unmodified=e,this._constraining=!1}_calcMatrices(){if(this._width&&this._height){this._pixelsToGLUnits=[2/this._width,-2/this._height];let e=t.ap(new Float64Array(16));t.S(e,e,[this._width/2,-this._height/2,1]),t.Q(e,e,[1,-1,0]),this._clipSpaceToPixelsMatrix=e,e=t.ap(new Float64Array(16)),t.S(e,e,[1,-1,1]),t.Q(e,e,[-1,-1,0]),t.S(e,e,[2/this._width,2/this._height,1]),this._pixelsToClipSpaceMatrix=e,this._cameraToCenterDistance=.5/Math.tan(this.fovInRadians/2)*this._height}this._callbacks.calcMatrices()}calculateCenterFromCameraLngLatAlt(e,n,r,i){let a=r===void 0?this.bearing:r,o=i=i===void 0?this.pitch:i,{distanceToCenter:s,clampedElevation:c}=this._distanceToCenterFromAltElevationPitch(n,this.elevation,o),{x:l,y:u}=Ve(o,a),d=t.a7.fromLngLat(e,n),f,p,m=t.aY(1,d.y),h=0;do{if(h+=1,h>10)break;p=s/m,f=new t.a7(d.x+l*p,d.y+u*p),m=1/f.meterInMercatorCoordinateUnits()}while(Math.abs(s-p*m)>1e-12);return{center:f.toLngLat(),elevation:c,zoom:t.ar(this.height/2/Math.tan(this.fovInRadians/2)/p/this.tileSize)}}recalculateZoomAndCenter(e){if(this.elevation-e==0)return;let n=1/this.worldSize,r=t.aq(1,this.center.lat)*this.worldSize,i=t.a7.fromLngLat(this.center,this.elevation),a=i.x/n,o=i.y/n,s=i.z/n,c=this.pitch,l=this.bearing,{x:u,y:d,z:f}=Ve(c,l),p=this.cameraToCenterDistance,m=a+p*-u,h=o+p*-d,g=s+p*f,{distanceToCenter:_,clampedElevation:v}=this._distanceToCenterFromAltElevationPitch(g/r,e,c),y=_*r,b=new t.a7((m+u*y)*n,(h+d*y)*n,0).toLngLat(),x=t.aq(1,b.lat),S=t.ar(this.height/2/Math.tan(this.fovInRadians/2)/_/x/this.tileSize);this._elevation=v,this._center=b,this.setZoom(S)}_distanceToCenterFromAltElevationPitch(e,n,r){let i=-Math.cos(t.an(r)),a=e-n,o,s=n;return i*a>=0||Math.abs(i)<.1?(o=1e4,s=e+o*i):o=-a/i,{distanceToCenter:o,clampedElevation:s}}getCameraPoint(){let e=Math.tan(this.pitchInRadians)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new t.P(e*Math.sin(this.rollInRadians),e*Math.cos(this.rollInRadians)))}getCameraAltitude(){return Math.cos(this.pitchInRadians)*this._cameraToCenterDistance/this._pixelPerMeter+this.elevation}getCameraLngLat(){let e=t.aq(1,this.center.lat)*this.worldSize;return Be(this.center,this.elevation,this.pitch,this.bearing,this.cameraToCenterDistance/e).toLngLat()}getMercatorTileCoordinates(e){if(!e)return[0,0,1,1];let n=e.canonical.z>=0?1<<e.canonical.z:2**e.canonical.z;return[e.canonical.x/n,e.canonical.y/n,1/n/t.a6,1/n/t.a6]}}class rn{constructor(e,n){this.min=e,this.max=n,this.center=t.aZ([],t.a_([],this.min,this.max),.5)}quadrant(e){let n=[e%2==0,e<2],r=t.a$(this.min),i=t.a$(this.max);for(let e=0;e<n.length;e++)r[e]=n[e]?this.min[e]:this.center[e],i[e]=n[e]?this.center[e]:this.max[e];return i[2]=this.max[2],new rn(r,i)}distanceX(e){return Math.max(Math.min(this.max[0],e[0]),this.min[0])-e[0]}distanceY(e){return Math.max(Math.min(this.max[1],e[1]),this.min[1])-e[1]}intersectsFrustum(e){let t=!0;for(let n of e.planes){let e=this.intersectsPlane(n);if(e===0)return 0;e===1&&(t=!1)}return t?2:e.aabb.min[0]>this.max[0]||e.aabb.min[1]>this.max[1]||e.aabb.min[2]>this.max[2]||e.aabb.max[0]<this.min[0]||e.aabb.max[1]<this.min[1]||e.aabb.max[2]<this.min[2]?0:1}intersectsPlane(e){let t=e[3],n=e[3];for(let r=0;r<3;r++)e[r]>0?(t+=e[r]*this.min[r],n+=e[r]*this.max[r]):(n+=e[r]*this.min[r],t+=e[r]*this.max[r]);return t>=0?2:n<0?0:1}}class an{distanceToTile2d(e,t,n,r){let i=r,a=i.distanceX([e,t]),o=i.distanceY([e,t]);return Math.hypot(a,o)}getWrap(e,t,n){return n}getTileBoundingVolume(e,n,r,i){let a=0,o=0;if(i?.terrain){let s=new t.a3(e.z,n,e.z,e.x,e.y),c=i.terrain.getMinMaxElevation(s);a=c.minElevation??Math.min(0,r),o=c.maxElevation??Math.max(0,r)}let s=1<<e.z;return new rn([n+e.x/s,e.y/s,a],[n+(e.x+1)/s,(e.y+1)/s,o])}allowVariableZoom(e,n){let r=e.fov*(Math.abs(Math.cos(e.rollInRadians))*e.height+Math.abs(Math.sin(e.rollInRadians))*e.width)/e.height,i=t.al(78.5-r/2,0,60);return!!n.terrain||e.pitch>i}allowWorldCopies(){return!0}prepareNextFrame(){}}class z{constructor(e,t,n){this.points=e,this.planes=t,this.aabb=n}static fromInvProjectionMatrix(e,n=1,r=0,i,a){let o=a?[[6,5,4],[0,1,2],[0,3,7],[2,1,5],[3,2,6],[0,4,5]]:[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]],s=2**r,c=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map((r=>function(e,n,r,i){let a=t.aE([],e,n),o=1/a[3]/r*i;return t.b4(a,a,[o,o,1/a[3],o])}(r,e,n,s)));i&&function(e,n,r,i){let a=i?4:0,o=i?0:4,s=0,c=[],l=[];for(let n=0;n<4;n++){let r=t.b0([],e[n+o],e[n+a]),i=t.b5(r);t.aZ(r,r,1/i),c.push(i),l.push(r)}for(let n=0;n<4;n++){let i=t.b6(e[n+a],l[n],r);s=i!==null&&i>=0?Math.max(s,i):Math.max(s,c[n])}let u=function(e,n){let r=t.b0([],e[n[0]],e[n[1]]),i=t.b0([],e[n[2]],e[n[1]]),a=[0,0,0,0];return t.b1(a,t.b2([],r,i)),a[3]=-t.b3(a,e[n[0]]),a}(e,n),d=function(e,n){let r=t.b7(e),i=t.b8([],e,1/r),a=t.b0([],n,t.aZ([],i,t.b3(n,i))),o=t.b7(a);if(o>0){let e=Math.sqrt(1-i[3]*i[3]),r=t.aZ([],i,-i[3]),s=t.a_([],r,t.aZ([],a,e/o));return t.b9(n,s)}return null}(r,u);if(d!==null){let e=d/t.b3(l[0],u);s=Math.min(s,e)}for(let t=0;t<4;t++){let n=Math.min(s,c[t]);e[t+o]=[e[t+a][0]+l[t][0]*n,e[t+a][1]+l[t][1]*n,e[t+a][2]+l[t][2]*n,1]}}(c,o[0],i,a);let l=o.map((e=>{let n=t.b0([],c[e[0]],c[e[1]]),r=t.b0([],c[e[2]],c[e[1]]),i=t.b1([],t.b2([],n,r)),a=-t.b3(i,c[e[1]]);return i.concat(a)})),u=[1/0,1/0,1/0],d=[-1/0,-1/0,-1/0];for(let e of c)for(let t=0;t<3;t++)u[t]=Math.min(u[t],e[t]),d[t]=Math.max(d[t],e[t]);return new z(c,l,new rn(u,d))}}class on{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e)}setMaxZoom(e){this._helper.setMaxZoom(e)}setMinPitch(e){this._helper.setMinPitch(e)}setMaxPitch(e){this._helper.setMaxPitch(e)}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e)}setBearing(e){this._helper.setBearing(e)}setPitch(e){this._helper.setPitch(e)}setRoll(e){this._helper.setRoll(e)}setFov(e){this._helper.setFov(e)}setZoom(e){this._helper.setZoom(e)}setCenter(e){this._helper.setCenter(e)}setElevation(e){this._helper.setElevation(e)}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e)}setPadding(e){this._helper.setPadding(e)}interpolatePadding(e,t,n){this._helper.interpolatePadding(e,t,n)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t,n=!0){this._helper.resize(e,t,n)}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e)}setConstrainOverride(e){this._helper.setConstrainOverride(e)}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t)}clearNearFarZOverride(){this._helper.clearNearFarZOverride()}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get constrainOverride(){return this._helper.constrainOverride}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}setTransitionState(e,t){}constructor(e){this._posMatrixCache=new Map,this._alignedPosMatrixCache=new Map,this._fogMatrixCacheF32=new Map,this.defaultConstrain=(e,n)=>{n=t.al(+n,this.minZoom,this.maxZoom);let r={center:new t.W(e.lng,e.lat),zoom:n},i=this._helper._lngRange;!this._helper._renderWorldCopies&&i===null&&(i=[-179.9999999999,179.9999999999]);let a=this.tileSize*t.ao(r.zoom),o=0,s=a,c=0,l=a,u=0,d=0,{x:f,y:p}=this.size;if(this._helper._latRange){let e=this._helper._latRange;o=t.Y(e[1])*a,s=t.Y(e[0])*a,s-o<p&&(u=p/(s-o))}i&&(c=t.X(t.Z(i[0])*a,0,a),l=t.X(t.Z(i[1])*a,0,a),l<c&&(l+=a),l-c<f&&(d=f/(l-c)));let{x:m,y:h}=Le(a,e),g,_,v=Math.max(d||0,u||0);if(v)return r.center=Re(a,new t.P(d?(l+c)/2:m,u?(s+o)/2:h)).wrap(),r.zoom+=t.ar(v),r;if(this._helper._latRange){let e=p/2;h-e<o&&(_=o+e),h+e>s&&(_=s-e)}if(i){let e=(c+l)/2,n=m;this._helper._renderWorldCopies&&(n=t.X(m,e-a/2,e+a/2));let r=f/2;n-r<c&&(g=c+r),n+r>l&&(g=l-r)}return(g!==void 0||_!==void 0)&&(r.center=Re(a,new t.P(g??m,_??h)).wrap()),r},this.applyConstrain=(e,t)=>this._helper.applyConstrain(e,t),this._helper=new nn({calcMatrices:()=>this._calcMatrices(),defaultConstrain:(e,t)=>this.defaultConstrain(e,t)},e),this._coveringTilesDetailsProvider=new an}clone(){let e=new on;return e.apply(this,!1),e}apply(e,t,n){this._helper.apply(e,t,n)}get cameraPosition(){return this._cameraPosition}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._viewProjMatrix}get inverseProjectionMatrix(){return this._invProjMatrix}get mercatorMatrix(){return this._mercatorMatrix}getVisibleUnwrappedCoordinates(e){let n=[new t.ba(0,e)];if(this._helper._renderWorldCopies){let r=this.screenPointToMercatorCoordinate(new t.P(0,0)),i=this.screenPointToMercatorCoordinate(new t.P(this._helper._width,0)),a=this.screenPointToMercatorCoordinate(new t.P(this._helper._width,this._helper._height)),o=this.screenPointToMercatorCoordinate(new t.P(0,this._helper._height)),s=Math.floor(Math.min(r.x,i.x,a.x,o.x)),c=Math.floor(Math.max(r.x,i.x,a.x,o.x));for(let r=s-1;r<=c+1;r++)r!==0&&n.push(new t.ba(r,e))}return n}getCameraFrustum(){return z.fromInvProjectionMatrix(this._invViewProjMatrix,this.worldSize)}getClippingPlane(){return null}getCoveringTilesDetailsProvider(){return this._coveringTilesDetailsProvider}recalculateZoomAndCenter(e){let t=this.screenPointToLocation(this.centerPoint,e),n=e?e.getElevationForLngLatZoom(t,this._helper._tileZoom):0;this._helper.recalculateZoomAndCenter(n)}setLocationAtPoint(e,n){let r=t.aq(this.elevation,this.center.lat),i=this.screenPointToMercatorCoordinateAtZ(n,r),a=this.screenPointToMercatorCoordinateAtZ(this.centerPoint,r),o=t.a7.fromLngLat(e),s=new t.a7(o.x-(i.x-a.x),o.y-(i.y-a.y));this.setCenter(s?.toLngLat()),this._helper._renderWorldCopies&&this.setCenter(this.center.wrap())}locationToScreenPoint(e,n){return n?this.coordinatePoint(t.a7.fromLngLat(e),n.getElevationForLngLat(e,this),this._pixelMatrix3D):this.coordinatePoint(t.a7.fromLngLat(e))}screenPointToLocation(e,t){return this.screenPointToMercatorCoordinate(e,t)?.toLngLat()}screenPointToMercatorCoordinate(e,t){if(t){let n=t.pointCoordinate(e);if(n!=null)return n}return this.screenPointToMercatorCoordinateAtZ(e)}screenPointToMercatorCoordinateAtZ(e,n){let r=n||0,i=[e.x,e.y,0,1],a=[e.x,e.y,1,1];t.aE(i,i,this._pixelMatrixInverse),t.aE(a,a,this._pixelMatrixInverse);let o=i[3],s=a[3],c=i[1]/o,l=a[1]/s,u=i[2]/o,d=a[2]/s,f=u===d?0:(r-u)/(d-u);return new t.a7(t.H.number(i[0]/o,a[0]/s,f)/this.worldSize,t.H.number(c,l,f)/this.worldSize,r)}coordinatePoint(e,n=0,r=this._pixelMatrix){let i=[e.x*this.worldSize,e.y*this.worldSize,n,1];return t.aE(i,i,r),new t.P(i[0]/i[3],i[1]/i[3])}getBounds(){let e=Math.max(0,this._helper._height/2-ze(this));return new de().extend(this.screenPointToLocation(new t.P(0,e))).extend(this.screenPointToLocation(new t.P(this._helper._width,e))).extend(this.screenPointToLocation(new t.P(this._helper._width,this._helper._height))).extend(this.screenPointToLocation(new t.P(0,this._helper._height)))}isPointOnMapSurface(e,t){return t?t.pointCoordinate(e)!=null:e.y>this.height/2-ze(this)}calculatePosMatrix(e,n=!1,r){let i=e.key??t.bb(e.wrap,e.canonical.z,e.canonical.z,e.canonical.x,e.canonical.y),a=n?this._alignedPosMatrixCache:this._posMatrixCache;if(a.has(i)){let e=a.get(i);return r?e.f32:e.f64}let o=j(e,this.worldSize);t.U(o,n?this._alignedProjMatrix:this._viewProjMatrix,o);let s={f64:o,f32:new Float32Array(o)};return a.set(i,s),r?s.f32:s.f64}calculateFogMatrix(e){let n=e.key,r=this._fogMatrixCacheF32;if(r.has(n))return r.get(n);let i=j(e,this.worldSize);return t.U(i,this._fogMatrix,i),r.set(n,new Float32Array(i)),r.get(n)}calculateCenterFromCameraLngLatAlt(e,t,n,r){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,n,r)}_calculateNearFarZIfNeeded(e,n,r){if(!this._helper.autoCalculateNearFarZ)return;let i=Math.min(this.elevation,this.minElevationForCurrentTile,this.getCameraAltitude()-100),a=e-i*this._helper._pixelPerMeter/Math.cos(n),o=i<0?a:e,s=Math.PI/2+this.pitchInRadians,c=t.an(this.fov)*(Math.abs(Math.cos(t.an(this.roll)))*this.height+Math.abs(Math.sin(t.an(this.roll)))*this.width)/this.height*(.5+r.y/this.height),l=Math.sin(c)*o/Math.sin(t.al(Math.PI-s-c,.01,Math.PI-.01)),u=ze(this),d=Math.atan(u/this._helper.cameraToCenterDistance),f=t.an(.75),p=d>f?2*d*(.5+r.y/(2*u)):f,m=Math.sin(p)*o/Math.sin(t.al(Math.PI-s-p,.01,Math.PI-.01)),h=Math.min(l,m);this._helper._farZ=1.01*(Math.cos(Math.PI/2-n)*h+o),this._helper._nearZ=this._helper._height/50}_calcMatrices(){if(!this._helper._height)return;let e=this.centerOffset,n=Le(this.worldSize,this.center),r=n.x,i=n.y;this._helper._pixelPerMeter=t.aq(1,this.center.lat)*this.worldSize;let a=t.an(Math.min(this.pitch,Ie)),o=Math.max(this._helper.cameraToCenterDistance/2,this._helper.cameraToCenterDistance+this._helper._elevation*this._helper._pixelPerMeter/Math.cos(a)),s;var c,l;this._calculateNearFarZIfNeeded(o,a,e),s=new Float64Array(16),t.bc(s,this.fovInRadians,this._helper._width/this._helper._height,this._helper._nearZ,this._helper._farZ),this._invProjMatrix=new Float64Array(16),(c=this._invProjMatrix)[0]=1/(l=s)[0],c[1]=0,c[2]=0,c[3]=0,c[4]=0,c[5]=1/l[5],c[6]=0,c[7]=0,c[8]=0,c[9]=0,c[10]=0,c[11]=1/l[14],c[12]=0,c[13]=0,c[14]=-1,c[15]=l[10]/l[14],s[8]=2*-e.x/this._helper._width,s[9]=2*e.y/this._helper._height,this._projectionMatrix=t.bd(s),t.S(s,s,[1,-1,1]),t.Q(s,s,[0,0,-this._helper.cameraToCenterDistance]),t.be(s,s,-this.rollInRadians),t.bf(s,s,this.pitchInRadians),t.be(s,s,-this.bearingInRadians),t.Q(s,s,[-r,-i,0]),this._mercatorMatrix=t.S([],s,[this.worldSize,this.worldSize,this.worldSize]),t.S(s,s,[1,1,this._helper._pixelPerMeter]),this._pixelMatrix=t.U(new Float64Array(16),this.clipSpaceToPixelsMatrix,s),t.Q(s,s,[0,0,-this.elevation]),this._viewProjMatrix=s,this._invViewProjMatrix=t.bg([],s);let u=[0,0,-1,1];t.aE(u,u,this._invViewProjMatrix),this._cameraPosition=[u[0]/u[3],u[1]/u[3],u[2]/u[3]],this._fogMatrix=new Float64Array(16),t.bc(this._fogMatrix,this.fovInRadians,this.width/this.height,o,this._helper._farZ),this._fogMatrix[8]=2*-e.x/this.width,this._fogMatrix[9]=2*e.y/this.height,t.S(this._fogMatrix,this._fogMatrix,[1,-1,1]),t.Q(this._fogMatrix,this._fogMatrix,[0,0,-this.cameraToCenterDistance]),t.be(this._fogMatrix,this._fogMatrix,-this.rollInRadians),t.bf(this._fogMatrix,this._fogMatrix,this.pitchInRadians),t.be(this._fogMatrix,this._fogMatrix,-this.bearingInRadians),t.Q(this._fogMatrix,this._fogMatrix,[-r,-i,0]),t.S(this._fogMatrix,this._fogMatrix,[1,1,this._helper._pixelPerMeter]),t.Q(this._fogMatrix,this._fogMatrix,[0,0,-this.elevation]),this._pixelMatrix3D=t.U(new Float64Array(16),this.clipSpaceToPixelsMatrix,s);let d=this._helper._width%2/2,f=this._helper._height%2/2,p=Math.cos(this.bearingInRadians),m=Math.sin(-this.bearingInRadians),h=r-Math.round(r)+p*d+m*f,g=i-Math.round(i)+p*f+m*d,_=new Float64Array(s);if(t.Q(_,_,[h>.5?h-1:h,g>.5?g-1:g,0]),this._alignedProjMatrix=_,s=t.bg(new Float64Array(16),this._pixelMatrix),!s)throw Error(`failed to invert matrix`);this._pixelMatrixInverse=s,this._clearMatrixCaches()}_clearMatrixCaches(){this._posMatrixCache.clear(),this._alignedPosMatrixCache.clear(),this._fogMatrixCacheF32.clear()}maxPitchScaleFactor(){if(!this._pixelMatrixInverse)return 1;let e=this.screenPointToMercatorCoordinate(new t.P(0,0)),n=[e.x*this.worldSize,e.y*this.worldSize,0,1];return t.aE(n,n,this._pixelMatrix)[3]/this._helper.cameraToCenterDistance}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){let e=t.aq(1,this.center.lat)*this.worldSize;return Be(this.center,this.elevation,this.pitch,this.bearing,this._helper.cameraToCenterDistance/e).toLngLat()}lngLatToCameraDepth(e,n){let r=t.a7.fromLngLat(e),i=[r.x*this.worldSize,r.y*this.worldSize,n,1];return t.aE(i,i,this._viewProjMatrix),i[2]/i[3]}getProjectionData(e){let{overscaledTileID:n,aligned:r,applyTerrainMatrix:i}=e,a=this._helper.getMercatorTileCoordinates(n),o=n?this.calculatePosMatrix(n,r,!0):null,s;return s=n?.terrainRttPosMatrix32f&&i?n.terrainRttPosMatrix32f:o||t.bh(),{mainMatrix:s,tileMercatorCoords:a,clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:s}}isLocationOccluded(e){return!1}getPixelScale(){return 1}getCircleRadiusCorrection(){return 1}getPitchedTextCorrection(e,t,n){return 1}transformLightDirection(e){return t.a$(e)}getRayDirectionFromPixel(e){throw Error(`Not implemented.`)}projectTileCoordinates(e,n,r,i){let a=this.calculatePosMatrix(r),o;i?(o=[e,n,i(e,n),1],t.aE(o,o,a)):(o=[e,n,0,1],Ct(o,o,a));let s=o[3];return{point:new t.P(o[0]/s,o[1]/s),signedDistanceFromCamera:s,isOccluded:!1}}populateCache(e){for(let t of e)this.calculatePosMatrix(t)}getMatrixForModel(e,n){let r=t.a7.fromLngLat(e,n),i=r.meterInMercatorCoordinateUnits(),a=t.bi();return t.Q(a,a,[r.x,r.y,r.z]),t.be(a,a,Math.PI),t.bf(a,a,Math.PI/2),t.S(a,a,[-i,i,i]),a}getProjectionDataForCustomLayer(e=!0){let n=new t.a3(0,0,0,0,0),r=this.getProjectionData({overscaledTileID:n,applyGlobeMatrix:e}),i=j(n,this.worldSize);t.U(i,this._viewProjMatrix,i),r.tileMercatorCoords=[0,0,1,1];let a=[t.a6,t.a6,this.worldSize/this._helper.pixelsPerMeter],o=t.bj();return t.S(o,i,a),r.fallbackMatrix=o,r.mainMatrix=o,r}getFastPathSimpleProjectionMatrix(e){return this.calculatePosMatrix(e)}}function B(){t.w(`Map cannot fit within canvas with the given bounds, padding, and/or offset.`)}function sn(e){if(e.useSlerp)if(e.k<1){let n=t.bk(e.startEulerAngles.roll,e.startEulerAngles.pitch,e.startEulerAngles.bearing),r=t.bk(e.endEulerAngles.roll,e.endEulerAngles.pitch,e.endEulerAngles.bearing),i=new Float64Array(4);t.bl(i,n,r,e.k);let a=t.bm(i);e.tr.setRoll(a.roll),e.tr.setPitch(a.pitch),e.tr.setBearing(a.bearing)}else e.tr.setRoll(e.endEulerAngles.roll),e.tr.setPitch(e.endEulerAngles.pitch),e.tr.setBearing(e.endEulerAngles.bearing);else e.tr.setRoll(t.H.number(e.startEulerAngles.roll,e.endEulerAngles.roll,e.k)),e.tr.setPitch(t.H.number(e.startEulerAngles.pitch,e.endEulerAngles.pitch,e.k)),e.tr.setBearing(t.H.number(e.startEulerAngles.bearing,e.endEulerAngles.bearing,e.k))}function cn(e,n,r,i,a){let o=a.padding,s=Le(a.worldSize,r.getNorthWest()),c=Le(a.worldSize,r.getNorthEast()),l=Le(a.worldSize,r.getSouthEast()),u=Le(a.worldSize,r.getSouthWest()),d=t.an(-i),f=s.rotate(d),p=c.rotate(d),m=l.rotate(d),h=u.rotate(d),g=new t.P(Math.max(f.x,p.x,h.x,m.x),Math.max(f.y,p.y,h.y,m.y)),_=new t.P(Math.min(f.x,p.x,h.x,m.x),Math.min(f.y,p.y,h.y,m.y)),v=g.sub(_),y=(a.width-(o.left+o.right+n.left+n.right))/v.x,b=(a.height-(o.top+o.bottom+n.top+n.bottom))/v.y;if(b<0||y<0)return void B();let x=Math.min(t.ar(a.scale*Math.min(y,b)),e.maxZoom),S=t.P.convert(e.offset),C=new t.P((n.left-n.right)/2,(n.top-n.bottom)/2).rotate(t.an(i)),w=S.add(C).mult(a.scale/t.ao(x));return{center:Re(a.worldSize,s.add(l).div(2).sub(w)),zoom:x,bearing:i}}class ln{get useGlobeControls(){return!1}handlePanInertia(e,t){let n=e.mag(),r=Math.abs(ze(t));return{easingOffset:e.mult(Math.min(.75*r/n,1)),easingCenter:t.center}}handleMapControlsRollPitchBearingZoom(e,t){e.bearingDelta&&t.setBearing(t.bearing+e.bearingDelta),e.pitchDelta&&t.setPitch(t.pitch+e.pitchDelta),e.rollDelta&&t.setRoll(t.roll+e.rollDelta),e.zoomDelta&&t.setZoom(t.zoom+e.zoomDelta)}handleMapControlsPan(e,t,n){e.around.distSqr(t.centerPoint)<.01||t.setLocationAtPoint(n,e.around)}cameraForBoxAndBearing(e,t,n,r,i){return cn(e,t,n,r,i)}handleJumpToCenterZoom(e,n){e.zoom!==(n.zoom===void 0?e.zoom:+n.zoom)&&e.setZoom(+n.zoom),n.center!==void 0&&e.setCenter(t.W.convert(n.center))}handleEaseTo(e,n){let r=e.zoom,i=e.padding,a={roll:e.roll,pitch:e.pitch,bearing:e.bearing},o={roll:n.roll===void 0?e.roll:n.roll,pitch:n.pitch===void 0?e.pitch:n.pitch,bearing:n.bearing===void 0?e.bearing:n.bearing},s=n.zoom!==void 0,c=!e.isPaddingEqual(n.padding),l=!1,u=s?+n.zoom:e.zoom,d=e.centerPoint.add(n.offsetAsPoint),f=e.screenPointToLocation(d),{center:p,zoom:m}=e.applyConstrain(t.W.convert(n.center||f),u??r);en(e,p);let h=Le(e.worldSize,f),g=Le(e.worldSize,p).sub(h),_=t.ao(m-r);return l=m!==r,{easeFunc:s=>{if(l&&e.setZoom(t.H.number(r,m,s)),t.bn(a,o)||sn({startEulerAngles:a,endEulerAngles:o,tr:e,k:s,useSlerp:a.roll!=o.roll}),c&&(e.interpolatePadding(i,n.padding,s),d=e.centerPoint.add(n.offsetAsPoint)),n.around)e.setLocationAtPoint(n.around,n.aroundPoint);else{let n=t.ao(e.zoom-r),i=(m>r?Math.min(2,_):Math.max(.5,_))**(1-s),a=Re(e.worldSize,h.add(g.mult(s*i)).mult(n));e.setLocationAtPoint(e.renderWorldCopies?a.wrap():a,d)}},isZooming:l,elevationCenter:p}}handleFlyTo(e,n){let r=n.zoom!==void 0,i=e.zoom,a=e.applyConstrain(t.W.convert(n.center||n.locationAtOffset),r?+n.zoom:i),o=a.center,s=a.zoom;en(e,o);let c=Le(e.worldSize,n.locationAtOffset),l=Le(e.worldSize,o).sub(c),u=l.mag(),d=t.ao(s-i),f;if(n.minZoom!==void 0){let r=Math.min(+n.minZoom,i,s),a=e.applyConstrain(o,r).zoom;f=t.ao(a-i)}return{easeFunc:(n,r,a,u)=>{e.setZoom(n===1?s:i+t.ar(r));let d=n===1?o:Re(e.worldSize,c.add(l.mult(a)).mult(r));e.setLocationAtPoint(e.renderWorldCopies?d.wrap():d,u)},scaleOfZoom:d,targetCenter:o,scaleOfMinZoom:f,pixelPathLength:u}}}class un{constructor(e,t,n){this.blendFunction=e,this.blendColor=t,this.mask=n}}un.Replace=[1,0],un.disabled=new un(un.Replace,t.bo.transparent,[!1,!1,!1,!1]),un.unblended=new un(un.Replace,t.bo.transparent,[!0,!0,!0,!0]),un.alphaBlended=new un([1,771],t.bo.transparent,[!0,!0,!0,!0]);let dn=2305;class fn{constructor(e,t,n){this.enable=e,this.mode=t,this.frontFace=n}}fn.disabled=new fn(!1,1029,dn),fn.backCCW=new fn(!0,1029,dn),fn.frontCCW=new fn(!0,1028,dn);class pn{constructor(e,t,n){this.func=e,this.mask=t,this.range=n}}pn.ReadOnly=!1,pn.ReadWrite=!0,pn.disabled=new pn(519,pn.ReadOnly,[0,1]);let mn=7680;class hn{constructor(e,t,n,r,i,a){this.test=e,this.ref=t,this.mask=n,this.fail=r,this.depthFail=i,this.pass=a}}function gn(e){return typeof WebGL2RenderingContext<`u`&&e instanceof WebGL2RenderingContext}hn.disabled=new hn({func:519,mask:0},0,0,mn,mn,mn);class _n{get awaitingQuery(){return!!this._readbackQueue}constructor(e){this._readbackWaitFrames=4,this._measureWaitFrames=6,this._texWidth=1,this._texHeight=1,this._measuredError=0,this._updateCount=0,this._lastReadbackFrame=-1e3,this._readbackQueue=null,this._cachedRenderContext=e;let n=e.context,r=n.gl;this._texFormat=r.RGBA,this._texType=r.UNSIGNED_BYTE;let i=new t.aU;i.emplaceBack(-1,-1),i.emplaceBack(2,-1),i.emplaceBack(-1,2);let a=new t.aW;a.emplaceBack(0,1,2),this._fullscreenTriangle=new Jt(n.createVertexBuffer(i,Yt.members),n.createIndexBuffer(a),t.aV.simpleSegment(0,0,i.length,a.length)),this._resultBuffer=new Uint8Array(4),n.activeTexture.set(r.TEXTURE1);let o=r.createTexture();r.bindTexture(r.TEXTURE_2D,o),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST),r.texImage2D(r.TEXTURE_2D,0,this._texFormat,this._texWidth,this._texHeight,0,this._texFormat,this._texType,null),this._fbo=n.createFramebuffer(this._texWidth,this._texHeight,!1,!1),this._fbo.colorAttachment.set(o),gn(r)&&(this._pbo=r.createBuffer(),r.bindBuffer(r.PIXEL_PACK_BUFFER,this._pbo),r.bufferData(r.PIXEL_PACK_BUFFER,4,r.STREAM_READ),r.bindBuffer(r.PIXEL_PACK_BUFFER,null))}destroy(){let e=this._cachedRenderContext.context.gl;this._fullscreenTriangle.destroy(),this._fbo.destroy(),e.deleteBuffer(this._pbo),this._fullscreenTriangle=null,this._fbo=null,this._pbo=null,this._resultBuffer=null}updateErrorLoop(e,t){let n=this._updateCount;return this._readbackQueue?n>=this._readbackQueue.frameNumberIssued+this._readbackWaitFrames&&this._tryReadback():n>=this._lastReadbackFrame+this._measureWaitFrames&&this._renderErrorTexture(e,t),this._updateCount++,this._measuredError}_bindFramebuffer(){let e=this._cachedRenderContext.context,t=e.gl;e.activeTexture.set(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this._fbo.colorAttachment.get()),e.bindFramebuffer.set(this._fbo.framebuffer)}_renderErrorTexture(e,n){let r=this._cachedRenderContext.context,i=r.gl;if(this._bindFramebuffer(),r.viewport.set([0,0,this._texWidth,this._texHeight]),r.clear({color:t.bo.transparent}),this._cachedRenderContext.useProgram(`projectionErrorMeasurement`).draw(r,i.TRIANGLES,pn.disabled,hn.disabled,un.unblended,fn.disabled,((e,t)=>({u_input:e,u_output_expected:t}))(e,n),null,null,`$clipping`,this._fullscreenTriangle.vertexBuffer,this._fullscreenTriangle.indexBuffer,this._fullscreenTriangle.segments),this._pbo&&gn(i)){i.bindBuffer(i.PIXEL_PACK_BUFFER,this._pbo),i.readBuffer(i.COLOR_ATTACHMENT0),i.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,0),i.bindBuffer(i.PIXEL_PACK_BUFFER,null);let e=i.fenceSync(i.SYNC_GPU_COMMANDS_COMPLETE,0);i.flush(),this._readbackQueue={frameNumberIssued:this._updateCount,sync:e}}else this._readbackQueue={frameNumberIssued:this._updateCount,sync:null}}_tryReadback(){let e=this._cachedRenderContext.context.gl;if(this._pbo&&this._readbackQueue&&gn(e)){let n=e.clientWaitSync(this._readbackQueue.sync,0,0);if(n===e.WAIT_FAILED)return t.w(`WebGL2 clientWaitSync failed.`),this._readbackQueue=null,void(this._lastReadbackFrame=this._updateCount);if(n===e.TIMEOUT_EXPIRED)return;e.bindBuffer(e.PIXEL_PACK_BUFFER,this._pbo),e.getBufferSubData(e.PIXEL_PACK_BUFFER,0,this._resultBuffer,0,4),e.bindBuffer(e.PIXEL_PACK_BUFFER,null)}else this._bindFramebuffer(),e.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,this._resultBuffer);this._readbackQueue=null,this._measuredError=_n._parseRGBA8float(this._resultBuffer),this._lastReadbackFrame=this._updateCount}static _parseRGBA8float(e){let t=0;return t+=e[0]/256,t+=e[1]/65536,t+=e[2]/16777216,e[3]<127&&(t=-t),t/128}}let vn=t.a6/128;function yn(e,n){let r=e.granularity===void 0?1:Math.max(e.granularity,1),i=r+(e.generateBorders?2:0),a=r+(e.extendToNorthPole||e.generateBorders?1:0)+(e.extendToSouthPole||e.generateBorders?1:0),o=i+1,s=a+1,c=e.generateBorders?-1:0,l=e.generateBorders||e.extendToNorthPole?-1:0,u=r+ +!!e.generateBorders,d=r+(e.generateBorders||e.extendToSouthPole?1:0),f=o*s,p=i*a*6,m=o*s>65536;if(m&&n===`16bit`)throw Error(`Granularity is too large and meshes would not fit inside 16 bit vertex indices.`);let h=m||n===`32bit`,g=new Int16Array(2*f),_=0;for(let n=l;n<=d;n++)for(let i=c;i<=u;i++){let a=i/r*t.a6;i===-1&&(a=-vn),i===r+1&&(a=t.a6+vn);let o=n/r*t.a6;n===-1&&(o=e.extendToNorthPole?t.bq:-vn),n===r+1&&(o=e.extendToSouthPole?t.br:t.a6+vn),g[_++]=a,g[_++]=o}let v=h?new Uint32Array(p):new Uint16Array(p),y=0;for(let e=0;e<a;e++)for(let t=0;t<i;t++){let n=t+1+e*o,r=t+(e+1)*o,i=t+1+(e+1)*o;v[y++]=t+e*o,v[y++]=r,v[y++]=n,v[y++]=n,v[y++]=r,v[y++]=i}return{vertices:g.buffer.slice(0),indices:v.buffer.slice(0),uses32bitIndices:h}}let bn=new t.aT({fill:new t.bs(128,2),line:new t.bs(512,0),tile:new t.bs(128,32),stencil:new t.bs(128,1),circle:3});class xn{constructor(){this._tileMeshCache={},this._errorCorrectionUsable=0,this._errorMeasurementLastValue=0,this._errorCorrectionPreviousValue=0,this._errorMeasurementLastChangeTime=-1e3}get name(){return`vertical-perspective`}get transitionState(){return 1}get useSubdivision(){return!0}get shaderVariantName(){return`globe`}get shaderDefine(){return`#define GLOBE`}get shaderPreludeCode(){return Kt.projectionGlobe}get vertexShaderPreludeCode(){return Kt.projectionMercator.vertexSource}get subdivisionGranularity(){return bn}get useGlobeControls(){return!0}get latitudeErrorCorrectionRadians(){return this._errorCorrectionUsable}destroy(){this._errorMeasurement&&this._errorMeasurement.destroy()}updateGPUdependent(e){this._errorMeasurement||=new _n(e);let n=t.Y(this._errorQueryLatitudeDegrees),r=2*Math.atan(Math.exp(Math.PI-n*Math.PI*2))-.5*Math.PI,i=this._errorMeasurement.updateErrorLoop(n,r),a=l();i!==this._errorMeasurementLastValue&&(this._errorCorrectionPreviousValue=this._errorCorrectionUsable,this._errorMeasurementLastValue=i,this._errorMeasurementLastChangeTime=a);let o=Math.min(Math.max((a-this._errorMeasurementLastChangeTime)/1e3/.5,0),1);this._errorCorrectionUsable=t.bt(this._errorCorrectionPreviousValue,-this._errorMeasurementLastValue,t.bu(o))}_getMeshKey(e){return`${e.granularity.toString(36)}_${e.generateBorders?`b`:``}${e.extendToNorthPole?`n`:``}${e.extendToSouthPole?`s`:``}`}getMeshFromTileID(e,t,n,r,i){let a=(i===`stencil`?bn.stencil:bn.tile).getGranularityForZoomLevel(t.z);return this._getMesh(e,{granularity:a,generateBorders:n,extendToNorthPole:t.y===0&&r,extendToSouthPole:t.y===(1<<t.z)-1&&r})}_getMesh(e,n){let r=this._getMeshKey(n);if(r in this._tileMeshCache)return this._tileMeshCache[r];let i=function(e,n){let r=yn(n,`16bit`),i=t.aU.deserialize({arrayBuffer:r.vertices,length:r.vertices.byteLength/2/2}),a=t.aW.deserialize({arrayBuffer:r.indices,length:r.indices.byteLength/2/3});return new Jt(e.createVertexBuffer(i,Yt.members),e.createIndexBuffer(a),t.aV.simpleSegment(0,0,i.length,a.length))}(e,n);return this._tileMeshCache[r]=i,i}recalculate(e){}hasTransition(){let e=l(),t=!1;return t||=(e-this._errorMeasurementLastChangeTime)/1e3<.7,t||=this._errorMeasurement?.awaitingQuery,t}setErrorQueryLatitudeDegrees(e){this._errorQueryLatitudeDegrees=e}}let V=new t.u({type:new t.D(t.x.projection.type)});class Sn extends t.E{constructor(e){super(),this._transitionable=new t.y(V,void 0),this.setProjection(e),this._transitioning=this._transitionable.untransitioned(),this.recalculate(new t.J(0)),this._mercatorProjection=new Qt,this._verticalPerspectiveProjection=new xn}get transitionState(){let e=this.properties.get(`type`);if(typeof e==`string`&&e===`mercator`)return 0;if(typeof e==`string`&&e===`vertical-perspective`)return 1;if(e instanceof t.bv){if(e.from===`vertical-perspective`&&e.to===`mercator`)return 1-e.transition;if(e.from===`mercator`&&e.to===`vertical-perspective`)return e.transition}return 1}get useGlobeRendering(){return this.transitionState>0}get latitudeErrorCorrectionRadians(){return this._verticalPerspectiveProjection.latitudeErrorCorrectionRadians}get currentProjection(){return this.useGlobeRendering?this._verticalPerspectiveProjection:this._mercatorProjection}get name(){return`globe`}get useSubdivision(){return this.currentProjection.useSubdivision}get shaderVariantName(){return this.currentProjection.shaderVariantName}get shaderDefine(){return this.currentProjection.shaderDefine}get shaderPreludeCode(){return this.currentProjection.shaderPreludeCode}get vertexShaderPreludeCode(){return this.currentProjection.vertexShaderPreludeCode}get subdivisionGranularity(){return this.currentProjection.subdivisionGranularity}get useGlobeControls(){return this.transitionState>0}destroy(){this._mercatorProjection.destroy(),this._verticalPerspectiveProjection.destroy()}updateGPUdependent(e){this._mercatorProjection.updateGPUdependent(e),this._verticalPerspectiveProjection.updateGPUdependent(e)}getMeshFromTileID(e,t,n,r,i){return this.currentProjection.getMeshFromTileID(e,t,n,r,i)}setProjection(e){this._transitionable.setValue(`type`,e?.type||`mercator`)}updateTransitions(e){this._transitioning=this._transitionable.transitioned(e,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()||this.currentProjection.hasTransition()}recalculate(e){this.properties=this._transitioning.possiblyEvaluate(e)}setErrorQueryLatitudeDegrees(e){this._verticalPerspectiveProjection.setErrorQueryLatitudeDegrees(e),this._mercatorProjection.setErrorQueryLatitudeDegrees(e)}}function H(e){let t=Tn(e.worldSize,e.center.lat);return 2*Math.PI*t}function Cn(e,n,r,i,a){let o=1/(1<<a),s=n/t.a6*o+i*o,c=t.by((e/t.a6*o+r*o)*Math.PI*2+Math.PI,2*Math.PI),l=2*Math.atan(Math.exp(Math.PI-s*Math.PI*2))-.5*Math.PI,u=Math.cos(l),d=new Float64Array(3);return d[0]=Math.sin(c)*u,d[1]=Math.sin(l),d[2]=Math.cos(c)*u,d}function wn(e){return function(e,t){let n=Math.cos(t),r=new Float64Array(3);return r[0]=Math.sin(e)*n,r[1]=Math.sin(t),r[2]=Math.cos(e)*n,r}(e.lng*Math.PI/180,e.lat*Math.PI/180)}function Tn(e,t){return e/(2*Math.PI)/Math.cos(t*Math.PI/180)}function En(e){let n=Math.asin(e[1])/Math.PI*180,r=Math.sqrt(e[0]*e[0]+e[2]*e[2]);if(r>1e-6){let i=e[0]/r,a=Math.acos(e[2]/r),o=(i>0?a:-a)/Math.PI*180;return new t.W(t.X(o,-180,180),n)}return new t.W(0,n)}function Dn(e){return Math.cos(e*Math.PI/180)}function On(e,n){let r=Dn(e),i=Dn(n);return t.ar(i/r)}function kn(e,n){let r=e.rotate(n.bearingInRadians),i=n.zoom+On(n.center.lat,0),a=t.bt(1/Dn(n.center.lat),1/Dn(Math.min(Math.abs(n.center.lat),60)),t.bw(i,7,3,0,1)),o=360/H({worldSize:n.worldSize,center:{lat:n.center.lat}});return new t.W(n.center.lng-r.x*o*a,t.al(n.center.lat+r.y*o,-t.am,t.am))}function An(e){let t=.5*e,n=Math.sin(t),r=Math.cos(t);return Math.log(n+r)-Math.log(r-n)}function jn(e,n,r,i){let a=e.lat+r*i;if(Math.abs(r)>1){let o=(Math.sign(e.lat+r)===Math.sign(e.lat)?Math.abs(e.lat):-Math.abs(e.lat))*Math.PI/180,s=Math.abs(e.lat+r)*Math.PI/180,c=An(o+i*(s-o)),l=An(o),u=An(s);return new t.W(e.lng+n*((c-l)/(u-l)),a)}return new t.W(e.lng+n*i,a)}class Mn{constructor(e){this._cachePrevious=new Map,this._cache=new Map,this._hadAnyChanges=!1,this._boundingVolumeFactory=e}swapBuffers(){if(!this._hadAnyChanges)return;let e=this._cachePrevious;this._cachePrevious=this._cache,this._cache=e,this._cache.clear(),this._hadAnyChanges=!1}getTileBoundingVolume(e,t,n,r){let i=`${e.z}_${e.x}_${e.y}_${r?.terrain?`t`:``}`,a=this._cache.get(i);if(a)return a;let o=this._cachePrevious.get(i);if(o)return this._cache.set(i,o),o;let s=this._boundingVolumeFactory(e,t,n,r);return this._cache.set(i,s),this._hadAnyChanges=!0,s}}class Nn{constructor(e,t,n,r){this.min=n,this.max=r,this.points=e,this.planes=t}static fromAabb(e,t){let n=[];for(let r=0;r<8;r++)n.push([1&~r?e[0]:t[0],(r>>1&1)==1?t[1]:e[1],(r>>2&1)==1?t[2]:e[2]]);return new Nn(n,[[-1,0,0,t[0]],[1,0,0,-e[0]],[0,-1,0,t[1]],[0,1,0,-e[1]],[0,0,-1,t[2]],[0,0,1,-e[2]]],e,t)}static fromCenterSizeAngles(e,n,r){let i=t.bA([],r[0],r[1],r[2]),a=t.bB([],[n[0],0,0],i),o=t.bB([],[0,n[1],0],i),s=t.bB([],[0,0,n[2]],i),c=[...e],l=[...e];for(let t=0;t<8;t++)for(let n=0;n<3;n++){let r=e[n]+a[n]*(1&~t?-1:1)+o[n]*((t>>1&1)==1?1:-1)+s[n]*((t>>2&1)==1?1:-1);c[n]=Math.min(c[n],r),l[n]=Math.max(l[n],r)}let u=[];for(let n=0;n<8;n++){let r=[...e];t.a_(r,r,t.aZ([],a,1&~n?-1:1)),t.a_(r,r,t.aZ([],o,(n>>1&1)==1?1:-1)),t.a_(r,r,t.aZ([],s,(n>>2&1)==1?1:-1)),u.push(r)}return new Nn(u,[[...a,-t.b3(a,u[0])],[...o,-t.b3(o,u[0])],[...s,-t.b3(s,u[0])],[-a[0],-a[1],-a[2],-t.b3(a,u[7])],[-o[0],-o[1],-o[2],-t.b3(o,u[7])],[-s[0],-s[1],-s[2],-t.b3(s,u[7])]],c,l)}intersectsFrustum(e){let t=!0,n=this.points.length,r=this.planes.length,i=e.planes.length,a=e.points.length;for(let r=0;r<i;r++){let i=e.planes[r],a=0;for(let e=0;e<n;e++){let t=this.points[e];i[0]*t[0]+i[1]*t[1]+i[2]*t[2]+i[3]>=0&&a++}if(a===0)return 0;a<n&&(t=!1)}if(t)return 2;for(let t=0;t<r;t++){let n=this.planes[t],r=0;for(let t=0;t<a;t++){let i=e.points[t];n[0]*i[0]+n[1]*i[1]+n[2]*i[2]+n[3]>=0&&r++}if(r===0)return 0}return 1}intersectsPlane(e){let t=this.points.length,n=0;for(let r=0;r<t;r++){let t=this.points[r];e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]>=0&&n++}return n===t?2:n===0?0:1}}function Pn(e,t,n){let r=e-t;return r<0?-r:Math.max(0,r-n)}function Fn(e,t,n,r,i){let a=e-n,o;return o=a<0?Math.min(-a,1+a-i):a>i?Math.min(Math.max(a-i,0),1-a):0,Math.max(o,Pn(t,r,i))}class In{constructor(){this._boundingVolumeCache=new Mn(this._computeTileBoundingVolume)}prepareNextFrame(){this._boundingVolumeCache.swapBuffers()}distanceToTile2d(e,t,n,r){let i=1<<n.z,a=1/i,o=n.x/i,s=n.y/i,c=2;return c=Math.min(c,Fn(e,t,o,s,a)),c=Math.min(c,Fn(e,t,o+.5,-s-a,a)),c=Math.min(c,Fn(e,t,o+.5,2-s-a,a)),c}getWrap(e,t,n){let r=1<<t.z,i=1/r,a=t.x/r,o=Pn(e.x,a,i),s=Pn(e.x,a-1,i),c=Pn(e.x,a+1,i),l=Math.min(o,s,c);return l===c?1:l===s?-1:0}allowVariableZoom(e,t){return Ue(e,t)>4}allowWorldCopies(){return!1}getTileBoundingVolume(e,t,n,r){return this._boundingVolumeCache.getTileBoundingVolume(e,t,n,r)}_computeTileBoundingVolume(e,n,r,i){let a=0,o=0;if(i?.terrain){let s=new t.a3(e.z,n,e.z,e.x,e.y),c=i.terrain.getMinMaxElevation(s);a=c.minElevation??Math.min(0,r),o=c.maxElevation??Math.max(0,r)}if(a/=t.bD,o/=t.bD,a+=1,o+=1,e.z<=0)return Nn.fromAabb([-o,-o,-o],[o,o,o]);if(e.z===1)return Nn.fromAabb([e.x===0?-o:0,e.y===0?0:-o,-o],[e.x===0?0:o,e.y===0?o:0,o]);{let n=[Cn(0,0,e.x,e.y,e.z),Cn(t.a6,0,e.x,e.y,e.z),Cn(t.a6,t.a6,e.x,e.y,e.z),Cn(0,t.a6,e.x,e.y,e.z)],r=[];for(let e of n)r.push(t.aZ([],e,o));if(o!==a)for(let e of n)r.push(t.aZ([],e,a));e.y===0&&r.push([0,1,0]),e.y===(1<<e.z)-1&&r.push([0,-1,0]);let i=[1,1,1],s=[-1,-1,-1];for(let e of r)for(let t=0;t<3;t++)i[t]=Math.min(i[t],e[t]),s[t]=Math.max(s[t],e[t]);let c=Cn(t.a6/2,t.a6/2,e.x,e.y,e.z),l=t.b2([],[0,1,0],c);t.b1(l,l);let u=t.b2([],c,l);t.b1(u,u);let d=t.b2([],n[2],n[1]);t.b1(d,d);let f=t.b2([],n[0],n[3]);t.b1(f,f),r.push(t.aZ([],c,o)),e.y>=(1<<e.z)/2&&r.push(t.aZ([],Cn(t.a6/2,0,e.x,e.y,e.z),o)),e.y<(1<<e.z)/2&&r.push(t.aZ([],Cn(t.a6/2,t.a6,e.x,e.y,e.z),o));let p=Ln(c,r),m=Ln(u,r),h=[-c[0],-c[1],-c[2],p.max],g=[c[0],c[1],c[2],-p.min],_=[-u[0],-u[1],-u[2],m.max],v=[u[0],u[1],u[2],-m.min],y=[...d,0],b=[...f,0],x=[];return e.y===0?x.push(t.bC(b,y,h),t.bC(b,y,g)):x.push(t.bC(_,y,h),t.bC(_,y,g),t.bC(_,b,h),t.bC(_,b,g)),e.y===(1<<e.z)-1?x.push(t.bC(b,y,h),t.bC(b,y,g)):x.push(t.bC(v,y,h),t.bC(v,y,g),t.bC(v,b,h),t.bC(v,b,g)),new Nn(x,[h,g,_,v,y,b],i,s)}}}function Ln(e,n){let r=1/0,i=-1/0;for(let a of n){let n=t.b3(e,a);r=Math.min(r,n),i=Math.max(i,n)}return{min:r,max:i}}class Rn{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e)}setMaxZoom(e){this._helper.setMaxZoom(e)}setMinPitch(e){this._helper.setMinPitch(e)}setMaxPitch(e){this._helper.setMaxPitch(e)}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e)}setBearing(e){this._helper.setBearing(e)}setPitch(e){this._helper.setPitch(e)}setRoll(e){this._helper.setRoll(e)}setFov(e){this._helper.setFov(e)}setZoom(e){this._helper.setZoom(e)}setCenter(e){this._helper.setCenter(e)}setElevation(e){this._helper.setElevation(e)}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e)}setPadding(e){this._helper.setPadding(e)}interpolatePadding(e,t,n){this._helper.interpolatePadding(e,t,n)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t){this._helper.resize(e,t)}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e)}setConstrainOverride(e){this._helper.setConstrainOverride(e)}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t)}clearNearFarZOverride(){this._helper.clearNearFarZOverride()}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get constrainOverride(){return this._helper.constrainOverride}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}setTransitionState(e){}constructor(e){this._cachedClippingPlane=t.bE(),this._projectionMatrix=t.bi(),this._globeViewProjMatrix32f=t.bh(),this._globeViewProjMatrixNoCorrection=t.bi(),this._globeViewProjMatrixNoCorrectionInverted=t.bi(),this._globeProjMatrixInverted=t.bi(),this._cameraPosition=t.bz(),this._globeLatitudeErrorCorrectionRadians=0,this.defaultConstrain=(e,n)=>{let r=t.al(e.lat,-t.am,t.am),i=t.al(+n,this.minZoom+On(0,r),this.maxZoom);return{center:new t.W(e.lng,r),zoom:i}},this.applyConstrain=(e,t)=>this._helper.applyConstrain(e,t),this._helper=new nn({calcMatrices:()=>this._calcMatrices(),defaultConstrain:(e,t)=>this.defaultConstrain(e,t)},e),this._coveringTilesDetailsProvider=new In}clone(){let e=new Rn;return e.apply(this,!1),e}apply(e,t,n){this._globeLatitudeErrorCorrectionRadians=n||0,this._helper.apply(e,t)}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._globeViewProjMatrixNoCorrection}get inverseProjectionMatrix(){return this._globeProjMatrixInverted}get cameraPosition(){let e=t.bz();return e[0]=this._cameraPosition[0],e[1]=this._cameraPosition[1],e[2]=this._cameraPosition[2],e}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}getProjectionData(e){let{overscaledTileID:t,applyGlobeMatrix:n}=e,r=this._helper.getMercatorTileCoordinates(t);return{mainMatrix:this._globeViewProjMatrix32f,tileMercatorCoords:r,clippingPlane:this._cachedClippingPlane,projectionTransition:+!!n,fallbackMatrix:this._globeViewProjMatrix32f}}_computeClippingPlane(e){let n=this.pitchInRadians,r=this.cameraToCenterDistance/e,i=Math.sin(n)*r,a=Math.cos(n)*r+1,o=1/Math.sqrt(i*i+a*a)*1,s=-i,c=a,l=Math.sqrt(s*s+c*c);s/=l,c/=l;let u=[0,s,c];t.bF(u,u,[0,0,0],-this.bearingInRadians),t.bG(u,u,[0,0,0],-1*this.center.lat*Math.PI/180),t.bH(u,u,[0,0,0],this.center.lng*Math.PI/180);let d=1/t.b5(u);return t.aZ(u,u,d),[...u,-o*d]}isLocationOccluded(e){return!this.isSurfacePointVisible(wn(e))}transformLightDirection(e){let n=this._helper._center.lng*Math.PI/180,r=this._helper._center.lat*Math.PI/180,i=Math.cos(r),a=[Math.sin(n)*i,Math.sin(r),Math.cos(n)*i],o=[a[2],0,-a[0]],s=[0,0,0];t.b2(s,o,a),t.b1(o,o),t.b1(s,s);let c=[0,0,0];return t.b1(c,[o[0]*e[0]+s[0]*e[1]+a[0]*e[2],o[1]*e[0]+s[1]*e[1]+a[1]*e[2],o[2]*e[0]+s[2]*e[1]+a[2]*e[2]]),c}getPixelScale(){return 1/Math.cos(this._helper._center.lat*Math.PI/180)}getCircleRadiusCorrection(){return Math.cos(this._helper._center.lat*Math.PI/180)}getPitchedTextCorrection(e,n,r){let i=function(e,n,r){let i=1/(1<<r.z);return new t.a7(e/t.a6*i+r.x*i,n/t.a6*i+r.y*i)}(e,n,r.canonical),a=(o=i.y,[t.by(i.x*Math.PI*2+Math.PI,2*Math.PI),2*Math.atan(Math.exp(Math.PI-o*Math.PI*2))-.5*Math.PI]);var o;return this.getCircleRadiusCorrection()/Math.cos(a[1])}projectTileCoordinates(e,n,r,i){let a=r.canonical,o=Cn(e,n,a.x,a.y,a.z),s=1+(i?i(e,n):0)/t.bD,c=[o[0]*s,o[1]*s,o[2]*s,1];t.aE(c,c,this._globeViewProjMatrixNoCorrection);let l=this._cachedClippingPlane,u=l[0]*o[0]+l[1]*o[1]+l[2]*o[2]+l[3]<0;return{point:new t.P(c[0]/c[3],c[1]/c[3]),signedDistanceFromCamera:c[3],isOccluded:u}}_calcMatrices(){if(!this._helper._width||!this._helper._height)return;let e=Tn(this.worldSize,this.center.lat),n=t.bj(),r=t.bj();this._helper.autoCalculateNearFarZ&&(this._helper._nearZ=.5,this._helper._farZ=this.cameraToCenterDistance+2*e),t.bc(n,this.fovInRadians,this.width/this.height,this._helper._nearZ,this._helper._farZ);let i=this.centerOffset;n[8]=2*-i.x/this._helper._width,n[9]=2*i.y/this._helper._height,this._projectionMatrix=t.bd(n),this._globeProjMatrixInverted=t.bj(),t.bg(this._globeProjMatrixInverted,n),t.Q(n,n,[0,0,-this.cameraToCenterDistance]),t.be(n,n,this.rollInRadians),t.bf(n,n,-this.pitchInRadians),t.be(n,n,this.bearingInRadians),t.Q(n,n,[0,0,-e]);let a=t.bz();a[0]=e,a[1]=e,a[2]=e,t.bf(r,n,this.center.lat*Math.PI/180),t.bI(r,r,-this.center.lng*Math.PI/180),t.S(r,r,a),this._globeViewProjMatrixNoCorrection=r,t.bf(n,n,this.center.lat*Math.PI/180-this._globeLatitudeErrorCorrectionRadians),t.bI(n,n,-this.center.lng*Math.PI/180),t.S(n,n,a),this._globeViewProjMatrix32f=new Float32Array(n),this._globeViewProjMatrixNoCorrectionInverted=t.bj(),t.bg(this._globeViewProjMatrixNoCorrectionInverted,r);let o=t.bz();this._cameraPosition=t.bz(),this._cameraPosition[2]=this.cameraToCenterDistance/e,t.bF(this._cameraPosition,this._cameraPosition,o,-this.rollInRadians),t.bG(this._cameraPosition,this._cameraPosition,o,this.pitchInRadians),t.bF(this._cameraPosition,this._cameraPosition,o,-this.bearingInRadians),t.a_(this._cameraPosition,this._cameraPosition,[0,0,1]),t.bG(this._cameraPosition,this._cameraPosition,o,-this.center.lat*Math.PI/180),t.bH(this._cameraPosition,this._cameraPosition,o,this.center.lng*Math.PI/180),this._cachedClippingPlane=this._computeClippingPlane(e);let s=t.bd(this._globeViewProjMatrixNoCorrectionInverted);t.S(s,s,[1,1,-1]),this._cachedFrustum=z.fromInvProjectionMatrix(s,1,0,this._cachedClippingPlane,!0)}calculateFogMatrix(e){t.w(`calculateFogMatrix is not supported on globe projection.`);let n=t.bj();return t.ap(n),n}getVisibleUnwrappedCoordinates(e){return[new t.ba(0,e)]}getCameraFrustum(){return this._cachedFrustum}getClippingPlane(){return this._cachedClippingPlane}getCoveringTilesDetailsProvider(){return this._coveringTilesDetailsProvider}recalculateZoomAndCenter(e){e&&t.w(`terrain is not fully supported on vertical perspective projection.`),this._helper.recalculateZoomAndCenter(0)}maxPitchScaleFactor(){return 1}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){return this._helper.getCameraLngLat()}lngLatToCameraDepth(e,n){if(!this._globeViewProjMatrixNoCorrection)return 1;let r=wn(e);t.aZ(r,r,1+n/t.bD);let i=t.bE();return t.aE(i,[r[0],r[1],r[2],1],this._globeViewProjMatrixNoCorrection),i[2]/i[3]}populateCache(e){}getBounds(){let e=.5*this.width,n=.5*this.height,r=[new t.P(0,0),new t.P(e,0),new t.P(this.width,0),new t.P(this.width,n),new t.P(this.width,this.height),new t.P(e,this.height),new t.P(0,this.height),new t.P(0,n)],i=[];for(let e of r)i.push(this.unprojectScreenPoint(e));let a=0,o=0,s=0,c=0,l=this.center;for(let e of i){let n=t.bJ(l.lng,e.lng),r=t.bJ(l.lat,e.lat);n<o&&(o=n),n>a&&(a=n),r<c&&(c=r),r>s&&(s=r)}let u=[l.lng+o,l.lat+c,l.lng+a,l.lat+s];return this.isSurfacePointOnScreen([0,1,0])&&(u[3]=90,u[0]=-180,u[2]=180),this.isSurfacePointOnScreen([0,-1,0])&&(u[1]=-90,u[0]=-180,u[2]=180),new de(u)}calculateCenterFromCameraLngLatAlt(e,t,n,r){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,n,r)}setLocationAtPoint(e,n){let r=wn(this.unprojectScreenPoint(n)),i=wn(e),a=t.bz();t.bK(a);let o=t.bz();t.bH(o,r,a,-this.center.lng*Math.PI/180),t.bG(o,o,a,this.center.lat*Math.PI/180);let s=i[0]*i[0]+i[2]*i[2],c=o[0]*o[0];if(s<c)return;let l=Math.sqrt(s-c),u=-l,d=t.bL(i[0],i[2],o[0],l),f=t.bL(i[0],i[2],o[0],u),p=t.bz();t.bH(p,i,a,-d);let m=t.bL(p[1],p[2],o[1],o[2]),h=t.bz();t.bH(h,i,a,-f);let g=t.bL(h[1],h[2],o[1],o[2]),_=.5*Math.PI,v=m>=-_&&m<=_,y=g>=-_&&g<=_,b,x;if(v&&y){let e=this.center.lng*Math.PI/180,n=this.center.lat*Math.PI/180;t.bM(d,e)+t.bM(m,n)<t.bM(f,e)+t.bM(g,n)?(b=d,x=m):(b=f,x=g)}else if(v)b=d,x=m;else{if(!y)return;b=f,x=g}let S=b/Math.PI*180,C=x/Math.PI*180,w=this.center.lat;this.setCenter(new t.W(S,t.al(C,-90,90))),this.setZoom(this.zoom+On(w,this.center.lat))}locationToScreenPoint(e,n){let r=wn(e);if(n){let i=n.getElevationForLngLatZoom(e,this._helper._tileZoom);t.aZ(r,r,1+i/t.bD)}return this._projectSurfacePointToScreen(r)}_projectSurfacePointToScreen(e){let n=t.bE();return t.aE(n,[...e,1],this._globeViewProjMatrixNoCorrection),n[0]/=n[3],n[1]/=n[3],new t.P((.5*n[0]+.5)*this.width,(.5*-n[1]+.5)*this.height)}screenPointToMercatorCoordinate(e,n){if(n){let t=n.pointCoordinate(e);if(t)return t}return t.a7.fromLngLat(this.unprojectScreenPoint(e))}screenPointToLocation(e,t){return this.screenPointToMercatorCoordinate(e,t)?.toLngLat()}isPointOnMapSurface(e,t){let n=this._cameraPosition,r=this.getRayDirectionFromPixel(e);return!!this.rayPlanetIntersection(n,r)}getRayDirectionFromPixel(e){let n=t.bE();n[0]=e.x/this.width*2-1,n[1]=-1*(e.y/this.height*2-1),n[2]=1,n[3]=1,t.aE(n,n,this._globeViewProjMatrixNoCorrectionInverted),n[0]/=n[3],n[1]/=n[3],n[2]/=n[3];let r=t.bz();r[0]=n[0]-this._cameraPosition[0],r[1]=n[1]-this._cameraPosition[1],r[2]=n[2]-this._cameraPosition[2];let i=t.bz();return t.b1(i,r),i}isSurfacePointVisible(e){let t=this._cachedClippingPlane;return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]>=0}isSurfacePointOnScreen(e){if(!this.isSurfacePointVisible(e))return!1;let n=t.bE();return t.aE(n,[...e,1],this._globeViewProjMatrixNoCorrection),n[0]/=n[3],n[1]/=n[3],n[2]/=n[3],n[0]>-1&&n[0]<1&&n[1]>-1&&n[1]<1&&n[2]>-1&&n[2]<1}rayPlanetIntersection(e,n){let r=t.b3(e,n),i=t.bz(),a=t.bz();t.aZ(a,n,r),t.b0(i,e,a);let o=1-t.b3(i,i);if(o<0)return null;let s=t.b3(e,e)-1,c=-r+(r<0?1:-1)*Math.sqrt(o),l=s/c,u=c;return{tMin:Math.min(l,u),tMax:Math.max(l,u)}}unprojectScreenPoint(e){let n=this._cameraPosition,r=this.getRayDirectionFromPixel(e),i=this.rayPlanetIntersection(n,r);if(i){let e=t.bz();t.a_(e,n,[r[0]*i.tMin,r[1]*i.tMin,r[2]*i.tMin]);let a=t.bz();return t.b1(a,e),En(a)}let a=this._cachedClippingPlane,o=a[0]*r[0]+a[1]*r[1]+a[2]*r[2],s=-t.b9(a,n)/o,c=t.bz();if(s>0)t.a_(c,n,[r[0]*s,r[1]*s,r[2]*s]);else{let e=t.bz();t.a_(e,n,[2*r[0],2*r[1],2*r[2]]);let i=t.b9(this._cachedClippingPlane,e);t.b0(c,e,[this._cachedClippingPlane[0]*i,this._cachedClippingPlane[1]*i,this._cachedClippingPlane[2]*i])}let l=function(e){let n=t.bz();return n[0]=e[0]*-e[3],n[1]=e[1]*-e[3],n[2]=e[2]*-e[3],{center:n,radius:Math.sqrt(1-e[3]*e[3])}}(a);return En(function(e,n,r){let i=t.bz();t.b0(i,r,e);let a=t.bz();return t.bx(a,e,i,n/t.b7(i)),a}(l.center,l.radius,c))}getMatrixForModel(e,n){let r=t.W.convert(e),i=1/t.bD,a=t.bi();return t.bI(a,a,r.lng/180*Math.PI),t.bf(a,a,-r.lat/180*Math.PI),t.Q(a,a,[0,0,1+n/t.bD]),t.bf(a,a,.5*Math.PI),t.S(a,a,[i,i,i]),a}getProjectionDataForCustomLayer(e=!0){let n=this.getProjectionData({overscaledTileID:new t.a3(0,0,0,0,0),applyGlobeMatrix:e});return n.tileMercatorCoords=[0,0,1,1],n}getFastPathSimpleProjectionMatrix(e){}}class zn{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e)}setMaxZoom(e){this._helper.setMaxZoom(e)}setMinPitch(e){this._helper.setMinPitch(e)}setMaxPitch(e){this._helper.setMaxPitch(e)}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e)}setBearing(e){this._helper.setBearing(e)}setPitch(e){this._helper.setPitch(e)}setRoll(e){this._helper.setRoll(e)}setFov(e){this._helper.setFov(e)}setZoom(e){this._helper.setZoom(e)}setCenter(e){this._helper.setCenter(e)}setElevation(e){this._helper.setElevation(e)}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e)}setPadding(e){this._helper.setPadding(e)}interpolatePadding(e,t,n){this._helper.interpolatePadding(e,t,n)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t,n=!0){this._helper.resize(e,t,n)}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e)}setConstrainOverride(e){this._helper.setConstrainOverride(e)}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t)}clearNearFarZOverride(){this._helper.clearNearFarZOverride()}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get constrainOverride(){return this._helper.constrainOverride}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}get isGlobeRendering(){return this._globeness>0}setTransitionState(e,t){this._globeness=e,this._globeLatitudeErrorCorrectionRadians=t,this._calcMatrices(),this._verticalPerspectiveTransform.getCoveringTilesDetailsProvider().prepareNextFrame(),this._mercatorTransform.getCoveringTilesDetailsProvider().prepareNextFrame()}get currentTransform(){return this.isGlobeRendering?this._verticalPerspectiveTransform:this._mercatorTransform}constructor(e){this._globeLatitudeErrorCorrectionRadians=0,this._globeness=1,this.defaultConstrain=(e,t)=>this.currentTransform.defaultConstrain(e,t),this.applyConstrain=(e,t)=>this._helper.applyConstrain(e,t),this._helper=new nn({calcMatrices:()=>this._calcMatrices(),defaultConstrain:(e,t)=>this.defaultConstrain(e,t)},e),this._globeness=1,this._mercatorTransform=new on,this._verticalPerspectiveTransform=new Rn}clone(){let e=new zn;return e._globeness=this._globeness,e._globeLatitudeErrorCorrectionRadians=this._globeLatitudeErrorCorrectionRadians,e.apply(this,!1),e}apply(e,t){this._helper.apply(e,t),this._mercatorTransform.apply(this,!1),this._verticalPerspectiveTransform.apply(this,!1,this._globeLatitudeErrorCorrectionRadians)}get projectionMatrix(){return this.currentTransform.projectionMatrix}get modelViewProjectionMatrix(){return this.currentTransform.modelViewProjectionMatrix}get inverseProjectionMatrix(){return this.currentTransform.inverseProjectionMatrix}get cameraPosition(){return this.currentTransform.cameraPosition}getProjectionData(e){let t=this._mercatorTransform.getProjectionData(e),n=this._verticalPerspectiveTransform.getProjectionData(e);return{mainMatrix:this.isGlobeRendering?n.mainMatrix:t.mainMatrix,clippingPlane:n.clippingPlane,tileMercatorCoords:n.tileMercatorCoords,projectionTransition:e.applyGlobeMatrix?this._globeness:0,fallbackMatrix:t.fallbackMatrix}}isLocationOccluded(e){return this.currentTransform.isLocationOccluded(e)}transformLightDirection(e){return this.currentTransform.transformLightDirection(e)}getPixelScale(){return t.bt(this._mercatorTransform.getPixelScale(),this._verticalPerspectiveTransform.getPixelScale(),this._globeness)}getCircleRadiusCorrection(){return t.bt(this._mercatorTransform.getCircleRadiusCorrection(),this._verticalPerspectiveTransform.getCircleRadiusCorrection(),this._globeness)}getPitchedTextCorrection(e,n,r){let i=this._mercatorTransform.getPitchedTextCorrection(e,n,r),a=this._verticalPerspectiveTransform.getPitchedTextCorrection(e,n,r);return t.bt(i,a,this._globeness)}projectTileCoordinates(e,t,n,r){return this.currentTransform.projectTileCoordinates(e,t,n,r)}_calcMatrices(){this._helper._width&&this._helper._height&&(this._verticalPerspectiveTransform.apply(this,!1,this._globeLatitudeErrorCorrectionRadians),this._helper._nearZ=this._verticalPerspectiveTransform.nearZ,this._helper._farZ=this._verticalPerspectiveTransform.farZ,this._mercatorTransform.apply(this,!0,this.isGlobeRendering),this._helper._nearZ=this._mercatorTransform.nearZ,this._helper._farZ=this._mercatorTransform.farZ)}calculateFogMatrix(e){return this.currentTransform.calculateFogMatrix(e)}getVisibleUnwrappedCoordinates(e){return this.currentTransform.getVisibleUnwrappedCoordinates(e)}getCameraFrustum(){return this.currentTransform.getCameraFrustum()}getClippingPlane(){return this.currentTransform.getClippingPlane()}getCoveringTilesDetailsProvider(){return this.currentTransform.getCoveringTilesDetailsProvider()}recalculateZoomAndCenter(e){this._mercatorTransform.recalculateZoomAndCenter(e),this._verticalPerspectiveTransform.recalculateZoomAndCenter(e)}maxPitchScaleFactor(){return this._mercatorTransform.maxPitchScaleFactor()}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){return this._helper.getCameraLngLat()}lngLatToCameraDepth(e,t){return this.currentTransform.lngLatToCameraDepth(e,t)}populateCache(e){this._mercatorTransform.populateCache(e),this._verticalPerspectiveTransform.populateCache(e)}getBounds(){return this.currentTransform.getBounds()}calculateCenterFromCameraLngLatAlt(e,t,n,r){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,n,r)}setLocationAtPoint(e,t){if(!this.isGlobeRendering)return this._mercatorTransform.setLocationAtPoint(e,t),void this.apply(this._mercatorTransform,!1);this._verticalPerspectiveTransform.setLocationAtPoint(e,t),this.apply(this._verticalPerspectiveTransform,!1)}locationToScreenPoint(e,t){return this.currentTransform.locationToScreenPoint(e,t)}screenPointToMercatorCoordinate(e,t){return this.currentTransform.screenPointToMercatorCoordinate(e,t)}screenPointToLocation(e,t){return this.currentTransform.screenPointToLocation(e,t)}isPointOnMapSurface(e,t){return this.currentTransform.isPointOnMapSurface(e,t)}getRayDirectionFromPixel(e){return this._verticalPerspectiveTransform.getRayDirectionFromPixel(e)}getMatrixForModel(e,t){return this.currentTransform.getMatrixForModel(e,t)}getProjectionDataForCustomLayer(e=!0){let t=this._mercatorTransform.getProjectionDataForCustomLayer(e);if(!this.isGlobeRendering)return t;let n=this._verticalPerspectiveTransform.getProjectionDataForCustomLayer(e);return n.fallbackMatrix=t.mainMatrix,n}getFastPathSimpleProjectionMatrix(e){return this.currentTransform.getFastPathSimpleProjectionMatrix(e)}}class Bn{get useGlobeControls(){return!0}handlePanInertia(e,n){let r=kn(e,n);return Math.abs(r.lng-n.center.lng)>180&&(r.lng=n.center.lng+179.5*Math.sign(r.lng-n.center.lng)),{easingCenter:r,easingOffset:new t.P(0,0)}}handleMapControlsRollPitchBearingZoom(e,n){let r=e.around,i=n.screenPointToLocation(r);e.bearingDelta&&n.setBearing(n.bearing+e.bearingDelta),e.pitchDelta&&n.setPitch(n.pitch+e.pitchDelta),e.rollDelta&&n.setRoll(n.roll+e.rollDelta);let a=n.zoom;e.zoomDelta&&n.setZoom(n.zoom+e.zoomDelta);let o=n.zoom-a;if(o===0)return;let s=t.bJ(n.center.lng,i.lng),c=s/(Math.abs(s/180)+1),l=t.bJ(n.center.lat,i.lat),u=n.getRayDirectionFromPixel(r),d=n.cameraPosition,f=-1*t.b3(d,u),p=t.bz();t.a_(p,d,[u[0]*f,u[1]*f,u[2]*f]);let m=t.b5(p)-1,h=Math.exp(.5*-Math.max(m-.3,0)),g=Tn(n.worldSize,n.center.lat)/Math.min(n.width,n.height),_=t.bw(g,.9,.5,1,.25),v=(1-t.ao(-o))*Math.min(h,_),y=n.center.lat,b=n.zoom,x=new t.W(n.center.lng+c*v,t.al(n.center.lat+l*v,-t.am,t.am));n.setLocationAtPoint(i,r);let S=n.center,C=t.bw(Math.abs(s),45,85,0,1),w=t.bw(g,.75,.35,0,1),T=Math.max(C,w)**.25,E=t.bJ(S.lng,x.lng),D=t.bJ(S.lat,x.lat);n.setCenter(new t.W(S.lng+E*T,S.lat+D*T).wrap()),n.setZoom(b+On(y,n.center.lat))}handleMapControlsPan(e,t,n){if(!e.panDelta)return;let r=t.center.lat,i=t.zoom;t.setCenter(kn(e.panDelta,t).wrap()),t.setZoom(i+On(r,t.center.lat))}cameraForBoxAndBearing(e,n,r,i,a){let o=cn(e,n,r,i,a),s=n.left/a.width*2-1,c=(a.width-n.right)/a.width*2-1,l=n.top/a.height*-2+1,u=(a.height-n.bottom)/a.height*-2+1,d=t.bJ(r.getWest(),r.getEast())<0,f=d?r.getEast():r.getWest(),p=d?r.getWest():r.getEast(),m=Math.max(r.getNorth(),r.getSouth()),h=Math.min(r.getNorth(),r.getSouth()),g=f+.5*t.bJ(f,p),_=m+.5*t.bJ(m,h),v=a.clone();v.setCenter(o.center),v.setBearing(o.bearing),v.setPitch(0),v.setRoll(0),v.setZoom(o.zoom);let y=v.modelViewProjectionMatrix,b=[wn(r.getNorthWest()),wn(r.getNorthEast()),wn(r.getSouthWest()),wn(r.getSouthEast()),wn(new t.W(p,_)),wn(new t.W(f,_)),wn(new t.W(g,m)),wn(new t.W(g,h))],x=wn(o.center),S=1/0;for(let e of b)s<0&&(S=Bn.getLesserNonNegativeNonNull(S,Bn.solveVectorScale(e,x,y,`x`,s))),c>0&&(S=Bn.getLesserNonNegativeNonNull(S,Bn.solveVectorScale(e,x,y,`x`,c))),l>0&&(S=Bn.getLesserNonNegativeNonNull(S,Bn.solveVectorScale(e,x,y,`y`,l))),u<0&&(S=Bn.getLesserNonNegativeNonNull(S,Bn.solveVectorScale(e,x,y,`y`,u)));if(Number.isFinite(S)&&S!==0)return o.zoom=Math.min(v.zoom+t.ar(S),e.maxZoom),o;B()}handleJumpToCenterZoom(e,n){let r=e.center.lat,i=e.applyConstrain(n.center?t.W.convert(n.center):e.center,e.zoom).center;e.setCenter(i.wrap());let a=n.zoom===void 0?e.zoom+On(r,i.lat):+n.zoom;e.zoom!==a&&e.setZoom(a)}handleEaseTo(e,n){let r=e.zoom,i=e.center,a=e.padding,o={roll:e.roll,pitch:e.pitch,bearing:e.bearing},s={roll:n.roll===void 0?e.roll:n.roll,pitch:n.pitch===void 0?e.pitch:n.pitch,bearing:n.bearing===void 0?e.bearing:n.bearing},c=n.zoom!==void 0,l=!e.isPaddingEqual(n.padding),u=!1,d=n.center?t.W.convert(n.center):i,f=e.applyConstrain(d,r).center;en(e,f);let p=e.clone();p.setCenter(f),p.setZoom(c?+n.zoom:r+On(i.lat,d.lat)),p.setBearing(n.bearing);let m=new t.P(t.al(e.centerPoint.x+n.offsetAsPoint.x,0,e.width),t.al(e.centerPoint.y+n.offsetAsPoint.y,0,e.height));p.setLocationAtPoint(f,m);let h=(n.offset&&n.offsetAsPoint.mag())>0?p.center:f,g=c?+n.zoom:r+On(i.lat,h.lat),_=r+On(i.lat,0),v=g+On(h.lat,0),y=t.bJ(i.lng,h.lng),b=t.bJ(i.lat,h.lat),x=t.ao(v-_);return u=g!==r,{easeFunc:r=>{if(t.bn(o,s)||sn({startEulerAngles:o,endEulerAngles:s,tr:e,k:r,useSlerp:o.roll!=s.roll}),l&&e.interpolatePadding(a,n.padding,r),n.around)t.w(`Easing around a point is not supported under globe projection.`),e.setLocationAtPoint(n.around,n.aroundPoint);else{let t=jn(i,y,b,r*(v>_?Math.min(2,x):Math.max(.5,x))**(1-r));e.setCenter(t.wrap())}if(u){let n=t.H.number(_,v,r)+On(0,e.center.lat);e.setZoom(n)}},isZooming:u,elevationCenter:h}}handleFlyTo(e,n){let r=n.zoom!==void 0,i=e.center,a=e.zoom,o=e.padding,s=!e.isPaddingEqual(n.padding),c=e.applyConstrain(t.W.convert(n.center||n.locationAtOffset),a).center,l=r?+n.zoom:e.zoom+On(e.center.lat,c.lat),u=e.clone();u.setCenter(c),u.setZoom(l),u.setBearing(n.bearing);let d=new t.P(t.al(e.centerPoint.x+n.offsetAsPoint.x,0,e.width),t.al(e.centerPoint.y+n.offsetAsPoint.y,0,e.height));u.setLocationAtPoint(c,d);let f=u.center;en(e,f);let p=function(e,n,r){let i=wn(n),a=wn(r),o=t.b3(i,a),s=Math.acos(o),c=H(e);return s/(2*Math.PI)*c}(e,i,f),m=a+On(i.lat,0),h=l+On(f.lat,0),g=t.ao(h-m),_;if(typeof n.minZoom==`number`){let r=+n.minZoom+On(f.lat,0),i=Math.min(r,m,h)+On(0,f.lat),a=e.applyConstrain(f,i).zoom+On(f.lat,0);_=t.ao(a-m)}let v=t.bJ(i.lng,f.lng),y=t.bJ(i.lat,f.lat);return{easeFunc:(r,a,c,u)=>{let d=jn(i,v,y,c);s&&e.interpolatePadding(o,n.padding,r);let p=r===1?f:d;e.setCenter(p.wrap());let h=m+t.ar(a);e.setZoom(r===1?l:h+On(0,p.lat))},scaleOfZoom:g,targetCenter:f,scaleOfMinZoom:_,pixelPathLength:p}}static solveVectorScale(e,t,n,r,i){let a=r===`x`?[n[0],n[4],n[8],n[12]]:[n[1],n[5],n[9],n[13]],o=[n[3],n[7],n[11],n[15]],s=e[0]*a[0]+e[1]*a[1]+e[2]*a[2],c=e[0]*o[0]+e[1]*o[1]+e[2]*o[2],l=t[0]*a[0]+t[1]*a[1]+t[2]*a[2],u=t[0]*o[0]+t[1]*o[1]+t[2]*o[2];return l+i*c===s+i*u||o[3]*(s-l)+a[3]*(u-c)+s*u==l*c?null:(l+a[3]-i*u-i*o[3])/(l-s-i*u+i*c)}static getLesserNonNegativeNonNull(e,t){return t!==null&&t>=0&&t<e?t:e}}class Vn{constructor(e){this._globe=e,this._mercatorCameraHelper=new ln,this._verticalPerspectiveCameraHelper=new Bn}get useGlobeControls(){return this._globe.useGlobeRendering}get currentHelper(){return this.useGlobeControls?this._verticalPerspectiveCameraHelper:this._mercatorCameraHelper}handlePanInertia(e,t){return this.currentHelper.handlePanInertia(e,t)}handleMapControlsRollPitchBearingZoom(e,t){this.currentHelper.handleMapControlsRollPitchBearingZoom(e,t)}handleMapControlsPan(e,t,n){this.currentHelper.handleMapControlsPan(e,t,n)}cameraForBoxAndBearing(e,t,n,r,i){return this.currentHelper.cameraForBoxAndBearing(e,t,n,r,i)}handleJumpToCenterZoom(e,t){this.currentHelper.handleJumpToCenterZoom(e,t)}handleEaseTo(e,t){return this.currentHelper.handleEaseTo(e,t)}handleFlyTo(e,t){return this.currentHelper.handleFlyTo(e,t)}}let Hn=(e,n)=>t.C(e,n?.filter((e=>e.identifier!==`source.canvas`))),U=t.bN();class Un extends t.E{constructor(e,n={}){super(),this._rtlPluginLoaded=()=>{for(let e in this.tileManagers){let t=this.tileManagers[e].getSource().type;t!==`vector`&&t!==`geojson`||this.tileManagers[e].reload()}},this.map=e,this.dispatcher=new ie(re(),e._getMapId()),this.dispatcher.registerMessageHandler(`GG`,((e,t)=>this.getGlyphs(e,t))),this.dispatcher.registerMessageHandler(`GI`,((e,t)=>this.getImages(e,t))),this.dispatcher.registerMessageHandler(`GDA`,((e,t)=>this.getDashes(e,t))),this.imageManager=new g,this.imageManager.setEventedParent(this);let r=e._container?.lang||typeof document<`u`&&document.documentElement?.lang||void 0;this.glyphManager=new S(e._requestManager,n.localIdeographFontFamily,r),this.lineAtlas=new O(256,512),this.crossTileSymbolIndex=new Wt,this._setInitialValues(),this._resetUpdates(),this.dispatcher.broadcast(`SR`,t.bO()),je().on(Oe,this._rtlPluginLoaded),this.on(`data`,(e=>{if(e.dataType!==`source`||e.sourceDataType!==`metadata`)return;let t=this.tileManagers[e.sourceId];if(!t)return;let n=t.getSource();if(n?.vectorLayerIds)for(let e in this._layers){let t=this._layers[e];t.source===n.id&&this._validateLayer(t)}}))}_setInitialValues(){this._spritesImagesIds={},this._layers={},this._order=[],this.tileManagers={},this.zoomHistory=new t.bP,this._availableImages=[],this._globalState={},this._serializedLayers={},this.stylesheet=null,this.light=null,this.sky=null,this.projection&&(this.projection.destroy(),delete this.projection),this._loaded=!1,this._changed=!1,this._updatedLayers={},this._updatedSources={},this._changedImages={},this._glyphsDidChange=!1,this._updatedPaintProps={},this._layerOrderChanged=!1,this.crossTileSymbolIndex=new(this.crossTileSymbolIndex?.constructor||Object),this.pauseablePlacement=void 0,this.placement=void 0,this.z=0}setGlobalStateProperty(e,n){this._checkLoaded();let r=n===null?this.stylesheet.state?.[e]?.default??null:n;if(t.bQ(r,this._globalState[e]))return this;this._globalState[e]=r,this._applyGlobalStateChanges([e])}getGlobalState(){return this._globalState}setGlobalState(e){this._checkLoaded();let n=[];for(let r in e)!t.bQ(this._globalState[r],e[r].default)&&(n.push(r),this._globalState[r]=e[r].default);this._applyGlobalStateChanges(n)}_applyGlobalStateChanges(e){if(e.length===0)return;let t=new Set,n={};for(let r of e){n[r]=this._globalState[r];for(let e in this._layers){let n=this._layers[e],i=n.getLayoutAffectingGlobalStateRefs(),a=n.getPaintAffectingGlobalStateRefs(),o=n.getVisibilityAffectingGlobalStateRefs();if(i.has(r)&&t.add(n.source),a.has(r))for(let{name:e,value:t}of a.get(r))this._updatePaintProperty(n,e,t);o!=null&&o.has(r)&&(n.recalculateVisibility(),this._updateLayer(n))}}this.dispatcher.broadcast(`UGS`,n);for(let e in this.tileManagers)t.has(e)&&(this._reloadSource(e),this._changed=!0)}loadURL(e){return t._(this,arguments,void 0,(function*(e,n={},r){this.fire(new t.n(`dataloading`,{dataType:`style`})),n.validate=typeof n.validate!=`boolean`||n.validate,this._loadStyleRequest=new AbortController;let i=this._loadStyleRequest;try{let a=yield this.map._requestManager.transformRequest(e,`Style`);t.bR(i.signal);let o=yield t.k(a,i);this._loadStyleRequest===i&&(this._loadStyleRequest=null),this._load(o.data,n,r)}catch(e){this._loadStyleRequest===i&&(this._loadStyleRequest=null),e&&!i.signal.aborted&&this.fire(new t.l(t.d(e)))}}))}loadJSON(e,n={},r){this.fire(new t.n(`dataloading`,{dataType:`style`})),this._frameRequest=new AbortController,s.frameAsync(this._frameRequest,this.map._ownerWindow).then((()=>{this._frameRequest=null,n.validate=!1!==n.validate,this._load(e,n,r)})).catch((()=>{}))}loadEmpty(){this.fire(new t.n(`dataloading`,{dataType:`style`})),this._load(U,{validate:!1})}_load(e,n,r){let i=n.transformStyle?n.transformStyle(r,e):e;if(!n.validate||!Hn(this,t.F(i))){i=Object.assign({},i),this._loaded=!0,this.stylesheet=i;for(let e in i.sources)this.addSource(e,i.sources[e],{validate:!1});i.sprite?this._loadSprite(i.sprite):this.imageManager.setLoaded(!0),this.glyphManager.setURL(i.glyphs),this._createLayers(),this.light=new T(this.stylesheet.light),this._setProjectionInternal(this.stylesheet.projection?.type||`mercator`),this.sky=new D(this.stylesheet.sky),this.map.setTerrain(this.stylesheet.terrain??null),this.fire(new t.n(`data`,{dataType:`style`})),this.fire(new t.n(`style.load`))}}_createLayers(){let e=t.bS(this.stylesheet.layers);this.setGlobalState(this.stylesheet.state??null),this.dispatcher.broadcast(`SL`,e),this._order=e.map((e=>e.id)),this._layers={},this._serializedLayers=null;for(let n of e){let e=t.bT(n,this._globalState);if(e.setEventedParent(this,{layer:{id:n.id}}),this._layers[n.id]=e,t.bU(e)&&this.tileManagers[e.source]){let t=n.paint?.[`raster-fade-duration`]??e.paint.get(`raster-fade-duration`);this.tileManagers[e.source].setRasterFadeDuration(t)}}}_loadSprite(e,n=!1,r=void 0){this.imageManager.setLoaded(!1);let i=new AbortController,a;this._spriteRequest=i,function(e,n,r,i){return t._(this,void 0,void 0,(function*(){let a=p(e),o=r>1?`@2x`:``,c={},l={};for(let{id:e,url:r}of a){let a=yield n.transformRequest(m(r,o,`.json`),`SpriteJSON`);c[e]=t.k(a,i);let s=yield n.transformRequest(m(r,o,`.png`),`SpriteImage`);l[e]=u.getImage(s,i)}return yield Promise.all([...Object.values(c),...Object.values(l)]),function(e,n){return t._(this,void 0,void 0,(function*(){let t={};for(let r in e){t[r]={};let i=s.getImageCanvasContext((yield n[r]).data),a=(yield e[r]).data;for(let e in a){let{width:n,height:o,x:s,y:c,sdf:l,pixelRatio:u,stretchX:d,stretchY:f,content:p,textFitWidth:m,textFitHeight:h}=a[e];t[r][e]={data:null,pixelRatio:u,sdf:l,stretchX:d,stretchY:f,content:p,textFitWidth:m,textFitHeight:h,spriteData:{width:n,height:o,x:s,y:c,context:i}}}}return t}))}(c,l)}))}(e,this.map._requestManager,this.map.getPixelRatio(),this._spriteRequest).then((e=>{if(this._spriteRequest=null,e)for(let t in e){this._spritesImagesIds[t]=[];let r=this._spritesImagesIds[t]?this._spritesImagesIds[t].filter((t=>!(t in e))):[];for(let e of r)this.imageManager.removeImage(e),this._changedImages[e]=!0;for(let r in e[t]){let i=t==="default"?r:`${t}:${r}`;this._spritesImagesIds[t].push(i),i in this.imageManager.images?this.imageManager.updateImage(i,e[t][r],!1):this.imageManager.addImage(i,e[t][r]),n&&(this._changedImages[i]=!0)}}})).catch((e=>{this._spriteRequest=null,a=e,i.signal.aborted||this.fire(new t.l(a))})).finally((()=>{this.imageManager.setLoaded(!0),this._availableImages=this.imageManager.listImages(),n&&(this._changed=!0),this.dispatcher.broadcast(`SI`,this._availableImages),this.fire(new t.n(`data`,{dataType:`style`})),r&&r(a)}))}_unloadSprite(){for(let e of Object.values(this._spritesImagesIds).flat())this.imageManager.removeImage(e),this._changedImages[e]=!0;this._spritesImagesIds={},this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast(`SI`,this._availableImages),this.fire(new t.n(`data`,{dataType:`style`}))}_validateLayer(e){let n=this.tileManagers[e.source];if(!n)return;let r=e.sourceLayer;if(!r)return;let i=n.getSource();(i.type===`geojson`||i.vectorLayerIds&&!i.vectorLayerIds.includes(r))&&this.fire(new t.l(Error(`Source layer "${r}" does not exist on source "${i.id}" as specified by style layer "${e.id}".`)))}loaded(){if(!this._loaded||Object.keys(this._updatedSources).length)return!1;for(let e in this.tileManagers)if(!this.tileManagers[e].loaded())return!1;return this.imageManager.isLoaded()}_serializeByIds(e,n=!1){let r=this._serializedAllLayers();if(!e||e.length===0)return Object.values(n?t.bV(r):r);let i=[];for(let a of e)if(r[a]){let e=n?t.bV(r[a]):r[a];i.push(e)}return i}_serializedAllLayers(){let e=this._serializedLayers;if(e)return e;e=this._serializedLayers={};let t=Object.keys(this._layers);for(let n of t){let t=this._layers[n];t.type!==`custom`&&(e[n]=t.serialize())}return e}hasTransitions(){if(this.light?.hasTransition()||this.sky?.hasTransition()||this.projection?.hasTransition())return!0;for(let e in this.tileManagers)if(this.tileManagers[e].hasTransition())return!0;for(let e in this._layers)if(this._layers[e].hasTransition())return!0;return!1}_checkLoaded(){if(!this._loaded)throw Error(`Style is not done loading.`)}update(e){if(!this._loaded)return;let n=this._changed;if(n){let t=Object.keys(this._updatedLayers),n=Object.keys(this._removedLayers);(t.length||n.length)&&this._updateWorkerLayers(t,n);for(let e in this._updatedSources){let t=this._updatedSources[e];if(t===`reload`)this._reloadSource(e);else{if(t!==`clear`)throw Error(`Invalid action ${t}`);this._clearSource(e)}}this._updateTilesForChangedImages(),this._updateTilesForChangedGlyphs();for(let t in this._updatedPaintProps)this._layers[t].updateTransitions(e);this.light.updateTransitions(e),this.sky.updateTransitions(e),this._resetUpdates()}let r={};for(let e in this.tileManagers){let t=this.tileManagers[e];r[e]=t.used,t.used=!1}for(let t of this._order){let n=this._layers[t];n.recalculate(e,this._availableImages),!n.isHidden(e.zoom)&&n.source&&(this.tileManagers[n.source].used=!0)}for(let e in r){let n=this.tileManagers[e];!!r[e]!=!!n.used&&n.fire(new t.n(`data`,{sourceDataType:`visibility`,dataType:`source`,sourceId:e}))}this.light.recalculate(e),this.sky.recalculate(e),this.projection.recalculate(e),this.z=e.zoom,n&&this.fire(new t.n(`data`,{dataType:`style`}))}_updateTilesForChangedImages(){let e=Object.keys(this._changedImages);if(e.length){for(let t in this.tileManagers)this.tileManagers[t].reloadTilesForDependencies([`icons`,`patterns`],e);this._changedImages={}}}_updateTilesForChangedGlyphs(){if(this._glyphsDidChange){for(let e in this.tileManagers)this.tileManagers[e].reloadTilesForDependencies([`glyphs`],[``]);this._glyphsDidChange=!1}}_updateWorkerLayers(e,t){this.dispatcher.broadcast(`UL`,{layers:this._serializeByIds(e,!1),removedIds:t})}_resetUpdates(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSources={},this._updatedPaintProps={},this._changedImages={},this._glyphsDidChange=!1}setState(e,n={}){var r;this._checkLoaded();let i=this.serialize();if(e=n.transformStyle?n.transformStyle(i,e):e,((r=n.validate)==null||r)&&Hn(this,t.F(e)))return!1;(e=t.bV(e)).layers=t.bS(e.layers);let a=t.bW(i,e),o=this._getOperationsToPerform(a);if(o.unimplemented.length>0)throw Error(`Unimplemented: ${o.unimplemented.join(`, `)}.`);if(o.operations.length===0)return!1;for(let e of o.operations)e();return this.stylesheet=e,this._serializedLayers=null,this.fire(new t.n(`style.load`,{style:this})),!0}_getOperationsToPerform(e){let t=[],n=[];for(let r of e)switch(r.command){case`setCenter`:case`setZoom`:case`setBearing`:case`setPitch`:case`setRoll`:continue;case`addLayer`:t.push((()=>this.addLayer.apply(this,r.args)));break;case`removeLayer`:t.push((()=>this.removeLayer.apply(this,r.args)));break;case`setPaintProperty`:t.push((()=>this.setPaintProperty.apply(this,r.args)));break;case`setLayoutProperty`:t.push((()=>this.setLayoutProperty.apply(this,r.args)));break;case`setFilter`:t.push((()=>this.setFilter.apply(this,r.args)));break;case`addSource`:t.push((()=>this.addSource.apply(this,r.args)));break;case`removeSource`:t.push((()=>this.removeSource.apply(this,r.args)));break;case`setLayerZoomRange`:t.push((()=>this.setLayerZoomRange.apply(this,r.args)));break;case`setLight`:t.push((()=>this.setLight.apply(this,r.args)));break;case`setGeoJSONSourceData`:t.push((()=>this.setGeoJSONSourceData.apply(this,r.args)));break;case`setGlyphs`:t.push((()=>this.setGlyphs.apply(this,r.args)));break;case`setSprite`:t.push((()=>this.setSprite.apply(this,r.args)));break;case`setTerrain`:t.push((()=>this.map.setTerrain.apply(this,r.args)));break;case`setSky`:t.push((()=>this.setSky.apply(this,r.args)));break;case`setProjection`:this.setProjection.apply(this,r.args);break;case`setGlobalState`:t.push((()=>this.setGlobalState.apply(this,r.args)));break;case`setTransition`:t.push((()=>{}));break;default:n.push(r.command)}return{operations:t,unimplemented:n}}addImage(e,n){if(this.getImage(e))return this.fire(new t.l(Error(`An image named "${e}" already exists.`)));this.imageManager.addImage(e,n),this._afterImageUpdated(e)}updateImage(e,t){this.imageManager.updateImage(e,t)}getImage(e){return this.imageManager.getImage(e)}removeImage(e){if(!this.getImage(e))return this.fire(new t.l(Error(`An image named "${e}" does not exist.`)));this.imageManager.removeImage(e),this._afterImageUpdated(e)}_afterImageUpdated(e){this._availableImages=this.imageManager.listImages(),this._changedImages[e]=!0,this._changed=!0,this.dispatcher.broadcast(`SI`,this._availableImages),this.fire(new t.n(`data`,{dataType:`style`}))}listImages(){return this._checkLoaded(),this.imageManager.listImages()}addSource(e,n,r={}){var i;if(this._checkLoaded(),this.tileManagers[e]!==void 0)throw Error(`Source "${e}" already exists.`);if(!n.type)throw Error(`The type property must be defined, but only the following properties were given: ${Object.keys(n).join(`, `)}.`);if([`vector`,`raster`,`geojson`,`video`,`image`].includes(n.type)&&this._validate(t.F.source,`sources.${e}`,n,null,r))return;(i=this.map)!=null&&i._collectResourceTiming&&(n.collectResourceTiming=!0);let a=this.tileManagers[e]=new Qe(e,n,this.dispatcher);a.style=this,a.setEventedParent(this,(()=>({isSourceLoaded:a.loaded(),source:a.serialize(),sourceId:e}))),a.onAdd(this.map),this._changed=!0}removeSource(e){if(this._checkLoaded(),this.tileManagers[e]===void 0)throw Error(`There is no source with this ID=${e}`);for(let n in this._layers)if(this._layers[n].source===e)return this.fire(new t.l(Error(`Source "${e}" cannot be removed while layer "${n}" is using it.`)));let n=this.tileManagers[e];delete this.tileManagers[e],delete this._updatedSources[e],n.fire(new t.n(`data`,{sourceDataType:`metadata`,dataType:`source`,sourceId:e})),n.setEventedParent(null),n.onRemove(this.map),this._changed=!0}setGeoJSONSourceData(e,t){if(this._checkLoaded(),this.tileManagers[e]===void 0)throw Error(`There is no source with this ID=${e}`);let n=this.tileManagers[e].getSource();if(n.type!==`geojson`)throw Error(`geojsonSource.type is ${n.type}, which is !== 'geojson`);n.setData(t),this._changed=!0}getSource(e){return this.tileManagers[e]?.getSource()}addLayer(e,n,r={}){this._checkLoaded();let i=e.id;if(this.getLayer(i))return void this.fire(new t.l(Error(`Layer "${i}" already exists on this map.`)));let a;if(e.type===`custom`){if(Hn(this,t.bX(e)))return;a=t.bT(e,this._globalState)}else{if(`source`in e&&typeof e.source==`object`&&(this.addSource(i,e.source),e=t.bV(e),e=t.e(e,{source:i})),this._validate(t.F.layer,`layers.${i}`,e,{arrayIndex:-1},r))return;a=t.bT(e,this._globalState),this._validateLayer(a),a.setEventedParent(this,{layer:{id:i}})}let o=n?this._order.indexOf(n):this._order.length;if(n&&o===-1)this.fire(new t.l(Error(`Cannot add layer "${i}" before non-existing layer "${n}".`)));else{if(this._order.splice(o,0,i),this._layerOrderChanged=!0,this._layers[i]=a,this._removedLayers[i]&&a.source&&a.type!==`custom`){let e=this._removedLayers[i];delete this._removedLayers[i],e.type===a.type?(this._updatedSources[a.source]=`reload`,this.tileManagers[a.source].pause()):this._updatedSources[a.source]=`clear`}this._updateLayer(a),a.onAdd&&a.onAdd(this.map)}}moveLayer(e,n){if(this._checkLoaded(),this._changed=!0,!this._layers[e])return void this.fire(new t.l(Error(`The layer '${e}' does not exist in the map's style and cannot be moved.`)));if(e===n)return;let r=this._order.indexOf(e);this._order.splice(r,1);let i=n?this._order.indexOf(n):this._order.length;n&&i===-1?this.fire(new t.l(Error(`Cannot move layer "${e}" before non-existing layer "${n}".`))):(this._order.splice(i,0,e),this._layerOrderChanged=!0)}removeLayer(e){this._checkLoaded();let n=this._layers[e];if(!n)return void this.fire(new t.l(Error(`Cannot remove non-existing layer "${e}".`)));n.setEventedParent(null);let r=this._order.indexOf(e);this._order.splice(r,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[e]=n,delete this._layers[e],this._serializedLayers&&delete this._serializedLayers[e],delete this._updatedLayers[e],delete this._updatedPaintProps[e],n.onRemove&&n.onRemove(this.map)}getLayer(e){return this._layers[e]}getLayersOrder(){return[...this._order]}hasLayer(e){return e in this._layers}setLayerZoomRange(e,n,r){this._checkLoaded();let i=this.getLayer(e);i?i.minzoom===n&&i.maxzoom===r||(n!=null&&(i.minzoom=n),r!=null&&(i.maxzoom=r),this._updateLayer(i)):this.fire(new t.l(Error(`Cannot set the zoom range of non-existing layer "${e}".`)))}setFilter(e,n,r={}){this._checkLoaded();let i=this.getLayer(e);if(i){if(!t.bQ(i.filter,n))return n==null?(i.setFilter(void 0),void this._updateLayer(i)):void(this._validate(t.F.filter,`layers.${i.id}.filter`,n,null,r)||(i.setFilter(t.bV(n)),this._updateLayer(i)))}else this.fire(new t.l(Error(`Cannot filter non-existing layer "${e}".`)))}getFilter(e){return t.bV(this.getLayer(e).filter)}setLayoutProperty(e,n,r,i={}){this._checkLoaded();let a=this.getLayer(e);a?t.bQ(a.getLayoutProperty(n),r)||(a.setLayoutProperty(n,r,i),this._updateLayer(a)):this.fire(new t.l(Error(`Cannot style non-existing layer "${e}".`)))}getLayoutProperty(e,n){let r=this.getLayer(e);if(r)return r.getLayoutProperty(n);this.fire(new t.l(Error(`Cannot get style of non-existing layer "${e}".`)))}setPaintProperty(e,n,r,i={}){this._checkLoaded();let a=this.getLayer(e);a?t.bQ(a.getPaintProperty(n),r)||this._updatePaintProperty(a,n,r,i):this.fire(new t.l(Error(`Cannot style non-existing layer "${e}".`)))}_updatePaintProperty(e,n,r,i={}){e.setPaintProperty(n,r,i)&&this._updateLayer(e),t.bU(e)&&n===`raster-fade-duration`&&this.tileManagers[e.source].setRasterFadeDuration(r),this._changed=!0,this._updatedPaintProps[e.id]=!0,this._serializedLayers=null}getPaintProperty(e,t){return this.getLayer(e).getPaintProperty(t)}setFeatureState(e,n){this._checkLoaded();let r=e.source,i=e.sourceLayer,a=this.tileManagers[r];if(a===void 0)return void this.fire(new t.l(Error(`The source '${r}' does not exist in the map's style.`)));let o=a.getSource().type;o===`geojson`&&i?this.fire(new t.l(Error(`GeoJSON sources cannot have a sourceLayer parameter.`))):o!==`vector`||i?(e.id===void 0&&this.fire(new t.l(Error(`The feature id parameter must be provided.`))),a.setFeatureState(i,e.id,n)):this.fire(new t.l(Error(`The sourceLayer parameter must be provided for vector source types.`)))}removeFeatureState(e,n){this._checkLoaded();let r=e.source,i=this.tileManagers[r];if(i===void 0)return void this.fire(new t.l(Error(`The source '${r}' does not exist in the map's style.`)));let a=i.getSource().type,o=a===`vector`?e.sourceLayer:void 0;a!==`vector`||o?n&&typeof e.id!=`string`&&typeof e.id!=`number`?this.fire(new t.l(Error(`A feature id is required to remove its specific state property.`))):i.removeFeatureState(o,e.id,n):this.fire(new t.l(Error(`The sourceLayer parameter must be provided for vector source types.`)))}getFeatureState(e){this._checkLoaded();let n=e.source,r=e.sourceLayer,i=this.tileManagers[n];if(i!==void 0)return i.getSource().type!==`vector`||r?(e.id===void 0&&this.fire(new t.l(Error(`The feature id parameter must be provided.`))),i.getFeatureState(r,e.id)):void this.fire(new t.l(Error(`The sourceLayer parameter must be provided for vector source types.`)));this.fire(new t.l(Error(`The source '${n}' does not exist in the map's style.`)))}getTransition(){return t.e({duration:300,delay:0},this.stylesheet?.transition)}serialize(){if(!this._loaded)return;let e=t.bY(this.tileManagers,(e=>e.serialize())),n=this._serializeByIds(this._order,!0),r=this.map.getTerrain()||void 0,i=this.stylesheet;return t.bZ({version:i.version,name:i.name,metadata:i.metadata,light:i.light,sky:i.sky,center:i.center,zoom:i.zoom,bearing:i.bearing,pitch:i.pitch,sprite:i.sprite,glyphs:i.glyphs,transition:i.transition,projection:i.projection,sources:e,layers:n,terrain:r},(e=>e!==void 0))}_updateLayer(e){this._updatedLayers[e.id]=!0,e.source&&!this._updatedSources[e.source]&&this.tileManagers[e.source].getSource().type!==`raster`&&(this._updatedSources[e.source]=`reload`,this.tileManagers[e.source].pause()),this._serializedLayers=null,this._changed=!0}_flattenAndSortRenderedFeatures(e){let t=e=>this._layers[e].type===`fill-extrusion`,n={},r=[];for(let i=this._order.length-1;i>=0;i--){let a=this._order[i];if(t(a)){n[a]=i;for(let t of e){let e=t[a];if(e)for(let t of e)r.push(t)}}}r.sort(((e,t)=>t.intersectionZ-e.intersectionZ));let i=[];for(let a=this._order.length-1;a>=0;a--){let o=this._order[a];if(t(o))for(let e=r.length-1;e>=0;e--){let t=r[e].feature;if(n[t.layer.id]<a)break;i.push(t),r.pop()}else for(let t of e){let e=t[o];if(e)for(let t of e)i.push(t.feature)}}return i}queryRenderedFeatures(e,n,r){n!=null&&n.filter&&this._validate(t.F.filter,`queryRenderedFeatures.filter`,n.filter,null,n);let i={};if(n?.layers){if(!(Array.isArray(n.layers)||n.layers instanceof Set))return this.fire(new t.l(Error(`parameters.layers must be an Array or a Set of strings`))),[];for(let e of n.layers){let n=this._layers[e];if(!n)return this.fire(new t.l(Error(`The layer '${e}' does not exist in the map's style and cannot be queried for features.`))),[];i[n.source]=!0}}let a=[];n.availableImages=this._availableImages;let o=this._serializedAllLayers(),s=n.layers instanceof Set?n.layers:Array.isArray(n.layers)?new Set(n.layers):null,c=Object.assign(Object.assign({},n),{layers:s,globalState:this._globalState});for(let t in this.tileManagers)n.layers&&!i[t]||a.push(se(this.tileManagers[t],this._layers,o,e,c,r,this.map.terrain?(e,t,n)=>this.map.terrain.getElevation(e,t,n):void 0));return this.placement&&a.push(function(e,t,n,r,i,a,o){let s={},c=a.queryRenderedSymbols(r),l=[];for(let e of Object.keys(c).map(Number))l.push(o[e]);l.sort(ce);for(let n of l){let r=n.featureIndex.lookupSymbolFeatures(c[n.bucketInstanceId],t,n.bucketIndex,n.sourceLayerIndex,{filterSpec:i.filter,globalState:i.globalState},i.layers,i.availableImages,e);for(let e in r){s[e]||(s[e]=[]);let t=r[e];t.sort(((e,t)=>{let r=n.featureSortOrder;if(r){let n=r.indexOf(e.featureIndex);return r.indexOf(t.featureIndex)-n}return t.featureIndex-e.featureIndex}));for(let n of t)s[e].push(n)}}return function(e,t,n){for(let r in e)for(let i of e[r])le(i,n[t[r].source]);return e}(s,e,n)}(this._layers,o,this.tileManagers,e,c,this.placement.collisionIndex,this.placement.retainedQueryData)),this._flattenAndSortRenderedFeatures(a)}querySourceFeatures(e,n){n!=null&&n.filter&&this._validate(t.F.filter,`querySourceFeatures.filter`,n.filter,null,n);let r=this.tileManagers[e];return r?function(e,t){let n=e.getRenderableIds().map((t=>e.getTileByID(t))),r=[],i={};for(let e of n){let n=e.tileID.canonical.key;i[n]||(i[n]=!0,e.querySourceFeatures(r,t))}return r}(r,n?Object.assign(Object.assign({},n),{globalState:this._globalState}):{globalState:this._globalState}):[]}getLight(){return this.light.getLight()}setLight(e,n={}){this._checkLoaded();let r=this.light.getLight(),i=!1;for(let n in e)if(!t.bQ(e[n],r[n])){i=!0;break}if(!i)return;let a={now:l(),transition:t.e({duration:300,delay:0},this.stylesheet.transition)};this.light.setLight(e,n),this.light.updateTransitions(a)}getProjection(){return this.stylesheet?.projection}setProjection(e){this._checkLoaded();let t=e??{type:`mercator`};if(this.stylesheet.projection=e,this.projection){if(this.projection.name===t.type)return;this.projection.destroy(),delete this.projection}this._setProjectionInternal(t.type)}getSky(){return this.stylesheet?.sky}setSky(e,n={}){this._checkLoaded();let r=this.getSky(),i=!1;if(!e&&!r)return;if(e&&!r)i=!0;else if(!e&&r)i=!0;else for(let n in e)if(!t.bQ(e[n],r[n])){i=!0;break}if(!i)return;let a={now:l(),transition:t.e({duration:300,delay:0},this.stylesheet.transition)};this.stylesheet.sky=e,this.sky.setSky(e,n),this.sky.updateTransitions(a)}_setProjectionInternal(e){let n=function(e,n){let r={constrainOverride:n};if(Array.isArray(e)){let t=new Sn({type:e});return{projection:t,transform:new zn(r),cameraHelper:new Vn(t)}}switch(e){case`mercator`:return{projection:new Qt,transform:new on(r),cameraHelper:new ln};case`globe`:{let e=new Sn({type:[`interpolate`,[`linear`],[`zoom`],11,`vertical-perspective`,12,`mercator`]});return{projection:e,transform:new zn(r),cameraHelper:new Vn(e)}}case`vertical-perspective`:return{projection:new xn,transform:new Rn(r),cameraHelper:new Bn};default:return t.w(`Unknown projection name: ${e}. Falling back to mercator projection.`),{projection:new Qt,transform:new on(r),cameraHelper:new ln}}}(e,this.map.transformConstrain);this.projection=n.projection,this.map.migrateProjection(n.transform,n.cameraHelper);for(let e in this.tileManagers)this.tileManagers[e].reload()}_validate(e,n,r,i,a={}){return!1!==a?.validate&&Hn(this,e.call(t.F,t.e({key:n,style:this.serialize(),value:r,styleSpec:t.x},i)))}_remove(e=!0){this._frameRequest&&=(this._frameRequest.abort(),null),this._loadStyleRequest&&=(this._loadStyleRequest.abort(),null),this._spriteRequest&&=(this._spriteRequest.abort(),null),je().off(Oe,this._rtlPluginLoaded);for(let e in this._layers)this._layers[e].setEventedParent(null);for(let e in this.tileManagers){let t=this.tileManagers[e];t.setEventedParent(null),t.onRemove(this.map)}this.imageManager.setEventedParent(null),this.setEventedParent(null),e&&this.dispatcher.broadcast(`RM`,void 0),this.dispatcher.remove(e)}_clearSource(e){this.tileManagers[e].clearTiles()}_reloadSource(e){this.tileManagers[e].resume(),this.tileManagers[e].reload()}_updateSources(e){for(let t in this.tileManagers)this.tileManagers[t].update(e,this.map.terrain)}_generateCollisionBoxes(){for(let e in this.tileManagers)this._reloadSource(e)}_updatePlacement(e,t,n,r,i=!1){let a=!1,o=!1,s={};for(let t of this._order){let n=this._layers[t];if(n.type!==`symbol`)continue;if(!s[n.source]){let e=this.tileManagers[n.source];s[n.source]=e.getRenderableIds(!0).map((t=>e.getTileByID(t))).sort(((e,t)=>t.tileID.overscaledZ-e.tileID.overscaledZ||(e.tileID.isLessThan(t.tileID)?-1:1)))}let r=this.crossTileSymbolIndex.addLayer(n,s[n.source],e.center.lng);a||=r}if(this.crossTileSymbolIndex.pruneUnusedLayers(this._order),i||=this._layerOrderChanged||n===0,(i||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent(l(),e.zoom))&&(this.pauseablePlacement=new zt(e,this.map.terrain,this._order,i,t,n,r,this.placement),this._layerOrderChanged=!1),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._order,this._layers,s),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(l()),o=!0),a&&this.pauseablePlacement.placement.setStale()),o||a)for(let e of this._order){let t=this._layers[e];t.type===`symbol`&&this.placement.updateLayerOpacities(t,s[t.source])}return!this.pauseablePlacement.isDone()||this.placement.hasTransitions(l())}_releaseSymbolFadeTiles(){for(let e in this.tileManagers)this.tileManagers[e].releaseSymbolFadeTiles()}getImages(e,n){return t._(this,void 0,void 0,(function*(){let e=yield this.imageManager.getImages(n.icons);this._updateTilesForChangedImages();let t=this.tileManagers[n.source];return t&&t.setDependencies(n.tileID.key,n.type,n.icons),e}))}getGlyphs(e,n){return t._(this,void 0,void 0,(function*(){let e=yield this.glyphManager.getGlyphs(n.stacks),t=this.tileManagers[n.source];return t&&t.setDependencies(n.tileID.key,n.type,[``]),e}))}getGlyphsUrl(){return this.stylesheet.glyphs||null}setGlyphs(e,n={}){this._checkLoaded(),e&&this._validate(t.F.glyphs,`glyphs`,e,null,n)||(this._glyphsDidChange=!0,this.stylesheet.glyphs=e,this.glyphManager.entries={},this.glyphManager.setURL(e))}getDashes(e,n){return t._(this,void 0,void 0,(function*(){let e={};for(let[t,r]of Object.entries(n.dashes))e[t]=this.lineAtlas.getDash(r.dasharray,r.round);return e}))}addSprite(e,n,r={},i){this._checkLoaded();let a=[{id:e,url:n}],o=[...p(this.stylesheet.sprite),...a];this._validate(t.F.sprite,`sprite`,o,null,r)||(this.stylesheet.sprite=o,this._loadSprite(a,!0,i))}removeSprite(e){this._checkLoaded();let n=p(this.stylesheet.sprite);if(n.find((t=>t.id===e))){if(this._spritesImagesIds[e])for(let t of this._spritesImagesIds[e])this.imageManager.removeImage(t),this._changedImages[t]=!0;n.splice(n.findIndex((t=>t.id===e)),1),this.stylesheet.sprite=n.length>0?n:void 0,delete this._spritesImagesIds[e],this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast(`SI`,this._availableImages),this.fire(new t.n(`data`,{dataType:`style`}))}else this.fire(new t.l(Error(`Sprite "${e}" doesn't exists on this map.`)))}getSprite(){return p(this.stylesheet.sprite)}setSprite(e,n={},r){this._checkLoaded(),e&&this._validate(t.F.sprite,`sprite`,e,null,n)||(this.stylesheet.sprite=e,e?this._loadSprite(e,!0,r):(this._unloadSprite(),r&&r(null)))}destroy(){this._frameRequest&&=(this._frameRequest.abort(),null),this._loadStyleRequest&&=(this._loadStyleRequest.abort(),null),this._spriteRequest&&=(this._spriteRequest.abort(),null);for(let e in this.tileManagers){let t=this.tileManagers[e];t.setEventedParent(null),t.onRemove(this.map)}this.tileManagers={},this.imageManager&&(this.imageManager.setEventedParent(null),this.imageManager.destroy(),this._availableImages=[],this._spritesImagesIds={}),this.glyphManager&&this.glyphManager.destroy();for(let e in this._layers){let t=this._layers[e];t.setEventedParent(null),t.onRemove&&t.onRemove(this.map)}this._setInitialValues(),this.setEventedParent(null),this.dispatcher.unregisterMessageHandler(`GG`),this.dispatcher.unregisterMessageHandler(`GI`),this.dispatcher.unregisterMessageHandler(`GDA`),this.dispatcher.remove(!0),this._listeners={},this._oneTimeListeners={}}}var Wn=t.aS([{name:`a_pos`,type:`Int16`,components:2},{name:`a_texture_pos`,type:`Int16`,components:2}]);class Gn{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffer=null,this.vao=null}bind(e,t,n,r,i,a,o,s,c){this.context=e;let l=this.boundPaintVertexBuffers.length!==r.length;for(let e=0;!l&&e<r.length;e++)this.boundPaintVertexBuffers[e]!==r[e]&&(l=!0);!this.vao||this.boundProgram!==t||this.boundLayoutVertexBuffer!==n||l||this.boundIndexBuffer!==i||this.boundVertexOffset!==a||this.boundDynamicVertexBuffer!==o||this.boundDynamicVertexBuffer2!==s||this.boundDynamicVertexBuffer3!==c?this.freshBind(t,n,r,i,a,o,s,c):(e.bindVertexArray.set(this.vao),o&&o.bind(),i!=null&&i.dynamicDraw&&i.bind(),s&&s.bind(),c&&c.bind())}freshBind(e,t,n,r,i,a,o,s){let c=e.numAttributes,l=this.context,u=l.gl;this.vao&&this.destroy(),this.vao=l.createVertexArray(),l.bindVertexArray.set(this.vao),this.boundProgram=e,this.boundLayoutVertexBuffer=t,this.boundPaintVertexBuffers=n,this.boundIndexBuffer=r,this.boundVertexOffset=i,this.boundDynamicVertexBuffer=a,this.boundDynamicVertexBuffer2=o,this.boundDynamicVertexBuffer3=s,t.enableAttributes(u,e);for(let t of n)t.enableAttributes(u,e);a&&a.enableAttributes(u,e),o&&o.enableAttributes(u,e),s&&s.enableAttributes(u,e),t.bind(),t.setVertexAttribPointers(u,e,i);for(let t of n)t.bind(),t.setVertexAttribPointers(u,e,i);a&&(a.bind(),a.setVertexAttribPointers(u,e,i)),r&&r.bind(),o&&(o.bind(),o.setVertexAttribPointers(u,e,i)),s&&(s.bind(),s.setVertexAttribPointers(u,e,i)),l.currentNumAttributes=c}destroy(){this.vao&&=(this.context.deleteVertexArray(this.vao),null)}}let Kn=(e,n,r,i,a)=>({u_texture:0,u_ele_delta:e,u_fog_matrix:n,u_fog_color:r?r.properties.get(`fog-color`):t.bo.white,u_fog_ground_blend:r?r.properties.get(`fog-ground-blend`):1,u_fog_ground_blend_opacity:a?0:r?r.calculateFogBlendOpacity(i):0,u_horizon_color:r?r.properties.get(`horizon-color`):t.bo.white,u_horizon_fog_blend:r?r.properties.get(`horizon-fog-blend`):1,u_is_globe_mode:+!!a}),qn={mainMatrix:`u_projection_matrix`,tileMercatorCoords:`u_projection_tile_mercator_coords`,clippingPlane:`u_projection_clipping_plane`,projectionTransition:`u_projection_transition`,fallbackMatrix:`u_projection_fallback_matrix`};function Jn(e){let t=[];for(let n of e){if(n===null)continue;let e=n.split(` `);t.push(e.pop())}return t}class Yn{constructor(e,n,r,i,a,o,s,c,l=[]){let u=e.gl;this.program=u.createProgram();let d=Jn(n.staticAttributes),f=r?r.getBinderAttributes():[],p=d.concat(f),m=Kt.prelude.staticUniforms?Jn(Kt.prelude.staticUniforms):[],h=s.staticUniforms?Jn(s.staticUniforms):[],g=n.staticUniforms?Jn(n.staticUniforms):[],_=r?r.getBinderUniforms():[],v=m.concat(h).concat(g).concat(_),y=[];for(let e of v)y.includes(e)||y.push(e);let b=r?r.defines():[];gn(u)&&b.unshift(`#version 300 es`),a&&b.push(`#define OVERDRAW_INSPECTOR;`),o&&b.push(`#define TERRAIN3D;`),c&&b.push(c),l&&b.push(...l);let x=b.concat(Kt.prelude.fragmentSource,s.fragmentSource,n.fragmentSource).join(`
748
748
  `),S=b.concat(Kt.prelude.vertexSource,s.vertexSource,n.vertexSource).join(`
749
- `);gn(u)||(x=function(e){return e.replace(/\bin\s/g,`varying `).replace(`out highp vec4 fragColor;`,``).replace(/fragColor/g,`gl_FragColor`).replace(/texture\(/g,`texture2D(`)}(x),S=function(e){return e.replace(/\bin\s/g,`attribute `).replace(/\bout\s/g,`varying `).replace(/texture\(/g,`texture2D(`)}(S));let C=u.createShader(u.FRAGMENT_SHADER);if(u.isContextLost())return void(this.failedToCreate=!0);if(u.shaderSource(C,x),u.compileShader(C),!u.getShaderParameter(C,u.COMPILE_STATUS))throw Error(`Could not compile fragment shader: ${u.getShaderInfoLog(C)}`);u.attachShader(this.program,C);let w=u.createShader(u.VERTEX_SHADER);if(u.isContextLost())return void(this.failedToCreate=!0);if(u.shaderSource(w,S),u.compileShader(w),!u.getShaderParameter(w,u.COMPILE_STATUS))throw Error(`Could not compile vertex shader: ${u.getShaderInfoLog(w)}`);u.attachShader(this.program,w),this.attributes={};let T={};this.numAttributes=p.length;for(let e=0;e<this.numAttributes;e++)p[e]&&(u.bindAttribLocation(this.program,e,p[e]),this.attributes[p[e]]=e);if(u.linkProgram(this.program),!u.getProgramParameter(this.program,u.LINK_STATUS))throw Error(`Program failed to link: ${u.getProgramInfoLog(this.program)}`);u.deleteShader(w),u.deleteShader(C);for(let e of y)if(e&&!T[e]){let t=u.getUniformLocation(this.program,e);t&&(T[e]=t)}this.fixedUniforms=i(e,T),this.terrainUniforms=((e,n)=>({u_depth:new t.b_(e,n.u_depth),u_terrain:new t.b_(e,n.u_terrain),u_terrain_dim:new t.bp(e,n.u_terrain_dim),u_terrain_matrix:new t.c0(e,n.u_terrain_matrix),u_terrain_unpack:new t.c1(e,n.u_terrain_unpack),u_terrain_exaggeration:new t.bp(e,n.u_terrain_exaggeration)}))(e,T),this.projectionUniforms=((e,n)=>({u_projection_matrix:new t.c0(e,n.u_projection_matrix),u_projection_tile_mercator_coords:new t.c1(e,n.u_projection_tile_mercator_coords),u_projection_clipping_plane:new t.c1(e,n.u_projection_clipping_plane),u_projection_transition:new t.bp(e,n.u_projection_transition),u_projection_fallback_matrix:new t.c0(e,n.u_projection_fallback_matrix)}))(e,T),this.binderUniforms=r?r.getUniforms(e,T):[]}draw(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v){var y;let b=e.gl;if(this.failedToCreate)return;if(e.program.set(this.program),e.setDepthMode(n),e.setStencilMode(r),e.setColorMode(i),e.setCullFace(a),s){e.activeTexture.set(b.TEXTURE2),b.bindTexture(b.TEXTURE_2D,s.depthTexture),e.activeTexture.set(b.TEXTURE3),b.bindTexture(b.TEXTURE_2D,s.texture);for(let e in this.terrainUniforms)this.terrainUniforms[e].set(s[e])}if(c)for(let e in c)this.projectionUniforms[qn[e]].set(c[e]);if(o)for(let e in this.fixedUniforms)this.fixedUniforms[e].set(o[e]);h&&h.setUniforms(e,this.binderUniforms,p,{zoom:m});let x=0;switch(t){case b.LINES:x=2;break;case b.TRIANGLES:x=3;break;case b.LINE_STRIP:x=1}for(let n of f.get())n.vaos||={},(y=n.vaos)[l]||(y[l]=new Gn),n.vaos[l].bind(e,this,u,h?h.getPaintVertexBuffers():[],d,n.vertexOffset,g,_,v),b.drawElements(t,n.primitiveLength*x,b.UNSIGNED_SHORT,n.primitiveOffset*x*2)}}function Xn(e,n,r){let i=1/t.aK(r,1,n.transform.tileZoom),a=2**r.tileID.overscaledZ,o=r.tileSize*2**n.transform.tileZoom/a,s=o*(r.tileID.canonical.x+r.tileID.wrap*a),c=o*r.tileID.canonical.y;return{u_image:0,u_texsize:r.imageAtlasTexture.size,u_scale:[i,e.fromScale,e.toScale],u_fade:e.t,u_pixel_coord_upper:[s>>16,c>>16],u_pixel_coord_lower:[65535&s,65535&c]}}let Zn=(e,n,r,i)=>{let a=e.style.light,o=a.properties.get(`position`),s=[o.x,o.y,o.z],c=t.c4();a.properties.get(`anchor`)===`viewport`&&t.c5(c,e.transform.bearingInRadians),t.c6(s,s,c);let l=e.transform.transformLightDirection(s),u=a.properties.get(`color`);return{u_lightpos:s,u_lightpos_globe:l,u_lightintensity:a.properties.get(`intensity`),u_lightcolor:[u.r,u.g,u.b],u_vertical_gradient:+n,u_opacity:r,u_fill_translate:i}},Qn=(e,n,r,i,a,o,s)=>t.e(Zn(e,n,r,i),Xn(o,e,s),{u_height_factor:-(2**a.overscaledZ)/s.tileSize/8}),$n=(e,n,r,i)=>t.e(Xn(n,e,r),{u_fill_translate:i}),er=(e,t)=>({u_world:e,u_fill_translate:t}),tr=(e,n,r,i,a)=>t.e($n(e,n,r,a),{u_world:i}),nr=(e,n,r,i,a)=>{let o=e.transform,s,c,l=0;if(r.paint.get(`circle-pitch-alignment`)===`map`){let e=t.aK(n,1,o.zoom);s=!0,c=[e,e],l=e/(t.a6*2**n.tileID.overscaledZ)*2*Math.PI*a}else s=!1,c=o.pixelsToGLUnits;return{u_camera_to_center_distance:o.cameraToCenterDistance,u_scale_with_map:+(r.paint.get(`circle-pitch-scale`)===`map`),u_pitch_with_map:+s,u_device_pixel_ratio:e.pixelRatio,u_extrude_scale:c,u_globe_extrude_scale:l,u_translate:i}},rr=e=>({u_pixel_extrude_scale:[1/e.width,1/e.height]}),ir=e=>({u_viewport_size:[e.width,e.height]}),ar=(e,t=1)=>({u_color:e,u_overlay:0,u_overlay_scale:t}),or=(e,n,r,i)=>{let a=t.aK(e,1,n)/(t.a6*2**e.tileID.overscaledZ)*2*Math.PI*i;return{u_extrude_scale:t.aK(e,1,n),u_intensity:r,u_globe_extrude_scale:a}},sr=(e,n,r,i)=>{let a=t.O();t.c7(a,0,e.width,e.height,0,0,1);let o=e.context.gl;return{u_matrix:a,u_world:[o.drawingBufferWidth,o.drawingBufferHeight],u_image:r,u_color_ramp:i,u_opacity:n.paint.get(`heatmap-opacity`)}},cr=(e,t,n)=>{let r=n.paint.get(`hillshade-accent-color`),i;switch(n.paint.get(`hillshade-method`)){case`basic`:i=4;break;case`combined`:i=1;break;case`igor`:i=2;break;case`multidirectional`:i=3;break;default:i=0}let a=n.getIlluminationProperties();for(let t=0;t<a.directionRadians.length;t++)n.paint.get(`hillshade-illumination-anchor`)===`viewport`&&(a.directionRadians[t]+=e.transform.bearingInRadians);return{u_image:0,u_latrange:ur(0,t.tileID),u_exaggeration:n.paint.get(`hillshade-exaggeration`),u_altitudes:a.altitudeRadians,u_azimuths:a.directionRadians,u_accent:r,u_method:i,u_highlights:a.highlightColor,u_shadows:a.shadowColor}},lr=(e,n)=>{let r=n.stride,i=t.O();return t.c7(i,0,t.a6,-t.a6,0,0,1),t.Q(i,i,[0,-t.a6,0]),{u_matrix:i,u_image:1,u_dimension:[r,r],u_zoom:e.overscaledZ,u_unpack:n.getUnpackVector()}};function ur(e,n){let r=2**n.canonical.z,i=n.canonical.y;return[new t.a7(0,i/r).toLngLat().lat,new t.a7(0,(i+1)/r).toLngLat().lat]}let dr=(e,t,n=0)=>({u_image:0,u_unpack:t.getUnpackVector(),u_dimension:[t.stride,t.stride],u_elevation_stops:1,u_color_stops:4,u_color_ramp_size:n,u_opacity:e.paint.get(`color-relief-opacity`)}),fr=(e,n,r,i)=>{let a=e.transform;return{u_translation:vr(e,n,r),u_ratio:i/t.aK(n,1,a.zoom),u_device_pixel_ratio:e.pixelRatio,u_units_to_pixels:[1/a.pixelsToGLUnits[0],1/a.pixelsToGLUnits[1]]}},pr=(e,n,r,i,a)=>t.e(fr(e,n,r,i),{u_image:0,u_image_height:a}),mr=(e,n,r,i,a)=>{let o=e.transform,s=_r(n,o);return{u_translation:vr(e,n,r),u_texsize:n.imageAtlasTexture.size,u_ratio:i/t.aK(n,1,o.zoom),u_device_pixel_ratio:e.pixelRatio,u_image:0,u_scale:[s,a.fromScale,a.toScale],u_fade:a.t,u_units_to_pixels:[1/o.pixelsToGLUnits[0],1/o.pixelsToGLUnits[1]]}},hr=(e,n,r,i,a)=>{let o=_r(n,e.transform);return t.e(fr(e,n,r,i),{u_tileratio:o,u_crossfade_from:a.fromScale,u_crossfade_to:a.toScale,u_image:0,u_mix:a.t,u_lineatlas_width:e.lineAtlas.width,u_lineatlas_height:e.lineAtlas.height})},gr=(e,n,r,i,a,o)=>{let s=_r(n,e.transform);return t.e(fr(e,n,r,i),{u_image:0,u_image_height:o,u_tileratio:s,u_crossfade_from:a.fromScale,u_crossfade_to:a.toScale,u_image_dash:1,u_mix:a.t,u_lineatlas_width:e.lineAtlas.width,u_lineatlas_height:e.lineAtlas.height})};function _r(e,n){return 1/t.aK(e,1,n.tileZoom)}function vr(e,n,r){return t.aL(e.transform,n,r.paint.get(`line-translate`),r.paint.get(`line-translate-anchor`))}let yr=(e,t,n,r,i)=>{return{u_tl_parent:e,u_scale_parent:t,u_buffer_scale:1,u_fade_t:n.mix,u_opacity:n.opacity*r.paint.get(`raster-opacity`),u_image0:0,u_image1:1,u_brightness_low:r.paint.get(`raster-brightness-min`),u_brightness_high:r.paint.get(`raster-brightness-max`),u_saturation_factor:(o=r.paint.get(`raster-saturation`),o>0?1-1/(1.001-o):-o),u_contrast_factor:(a=r.paint.get(`raster-contrast`),a>0?1/(1-a):1+a),u_spin_weights:br(r.paint.get(`raster-hue-rotate`)),u_coords_top:[i[0].x,i[0].y,i[1].x,i[1].y],u_coords_bottom:[i[3].x,i[3].y,i[2].x,i[2].y]};var a,o};function br(e){e*=Math.PI/180;let t=Math.sin(e),n=Math.cos(e);return[(2*n+1)/3,(-Math.sqrt(3)*t-n+1)/3,(Math.sqrt(3)*t-n+1)/3]}let xr=(e,t,n,r,i,a,o,s,c,l,u,d,f)=>{let p=o.transform;return{u_is_size_zoom_constant:+(e===`constant`||e===`source`),u_is_size_feature_constant:+(e===`constant`||e===`camera`),u_size_t:t?t.uSizeT:0,u_size:t?t.uSize:0,u_camera_to_center_distance:p.cameraToCenterDistance,u_pitch:p.pitch/360*2*Math.PI,u_rotate_symbol:+n,u_aspect_ratio:p.width/p.height,u_fade_change:o.options.fadeDuration?o.symbolFadeChange:1,u_label_plane_matrix:s,u_coord_matrix:c,u_is_text:+u,u_pitch_with_map:+r,u_is_along_line:i,u_is_variable_anchor:a,u_texsize:d,u_texture:0,u_translation:l,u_pitched_scale:f}},Sr=(e,n,r,i,a,o,s,c,l,u,d,f,p,m)=>{let h=s.transform;return t.e(xr(e,n,r,i,a,o,s,c,l,u,d,f,m),{u_gamma_scale:i?Math.cos(h.pitch*Math.PI/180)*h.cameraToCenterDistance:1,u_device_pixel_ratio:s.pixelRatio,u_is_halo:+!!p,u_is_plain:1})},Cr=(e,n,r,i,a,o,s,c,l,u,d,f,p)=>t.e(Sr(e,n,r,i,a,o,s,c,l,u,!0,d,!0,p),{u_texsize_icon:f,u_texture_icon:1}),wr=(e,t)=>({u_opacity:e,u_color:t}),Tr=(e,n,r,i,a)=>t.e(function(e,n,r,i){let a=r.imageManager.getPattern(e.from.toString()),o=r.imageManager.getPattern(e.to.toString()),{width:s,height:c}=r.imageManager.getPixelSize(),l=2**i.tileID.overscaledZ,u=i.tileSize*2**r.transform.tileZoom/l,d=u*(i.tileID.canonical.x+i.tileID.wrap*l),f=u*i.tileID.canonical.y;return{u_image:0,u_pattern_tl_a:a.tl,u_pattern_br_a:a.br,u_pattern_tl_b:o.tl,u_pattern_br_b:o.br,u_texsize:[s,c],u_mix:n.t,u_pattern_size_a:a.displaySize,u_pattern_size_b:o.displaySize,u_scale_a:n.fromScale,u_scale_b:n.toScale,u_tile_units_to_pixels:1/t.aK(i,1,r.transform.tileZoom),u_pixel_coord_upper:[d>>16,f>>16],u_pixel_coord_lower:[65535&d,65535&f]}}(r,a,n,i),{u_opacity:e}),Er=(e,t)=>{},Dr={fillExtrusion:(e,n)=>({u_lightpos:new t.c2(e,n.u_lightpos),u_lightpos_globe:new t.c2(e,n.u_lightpos_globe),u_lightintensity:new t.bp(e,n.u_lightintensity),u_lightcolor:new t.c2(e,n.u_lightcolor),u_vertical_gradient:new t.bp(e,n.u_vertical_gradient),u_opacity:new t.bp(e,n.u_opacity),u_fill_translate:new t.c3(e,n.u_fill_translate)}),fillExtrusionPattern:(e,n)=>({u_lightpos:new t.c2(e,n.u_lightpos),u_lightpos_globe:new t.c2(e,n.u_lightpos_globe),u_lightintensity:new t.bp(e,n.u_lightintensity),u_lightcolor:new t.c2(e,n.u_lightcolor),u_vertical_gradient:new t.bp(e,n.u_vertical_gradient),u_height_factor:new t.bp(e,n.u_height_factor),u_opacity:new t.bp(e,n.u_opacity),u_fill_translate:new t.c3(e,n.u_fill_translate),u_image:new t.b_(e,n.u_image),u_texsize:new t.c3(e,n.u_texsize),u_pixel_coord_upper:new t.c3(e,n.u_pixel_coord_upper),u_pixel_coord_lower:new t.c3(e,n.u_pixel_coord_lower),u_scale:new t.c2(e,n.u_scale),u_fade:new t.bp(e,n.u_fade)}),fill:(e,n)=>({u_fill_translate:new t.c3(e,n.u_fill_translate)}),fillPattern:(e,n)=>({u_image:new t.b_(e,n.u_image),u_texsize:new t.c3(e,n.u_texsize),u_pixel_coord_upper:new t.c3(e,n.u_pixel_coord_upper),u_pixel_coord_lower:new t.c3(e,n.u_pixel_coord_lower),u_scale:new t.c2(e,n.u_scale),u_fade:new t.bp(e,n.u_fade),u_fill_translate:new t.c3(e,n.u_fill_translate)}),fillOutline:(e,n)=>({u_world:new t.c3(e,n.u_world),u_fill_translate:new t.c3(e,n.u_fill_translate)}),fillOutlinePattern:(e,n)=>({u_world:new t.c3(e,n.u_world),u_image:new t.b_(e,n.u_image),u_texsize:new t.c3(e,n.u_texsize),u_pixel_coord_upper:new t.c3(e,n.u_pixel_coord_upper),u_pixel_coord_lower:new t.c3(e,n.u_pixel_coord_lower),u_scale:new t.c2(e,n.u_scale),u_fade:new t.bp(e,n.u_fade),u_fill_translate:new t.c3(e,n.u_fill_translate)}),circle:(e,n)=>({u_camera_to_center_distance:new t.bp(e,n.u_camera_to_center_distance),u_scale_with_map:new t.b_(e,n.u_scale_with_map),u_pitch_with_map:new t.b_(e,n.u_pitch_with_map),u_extrude_scale:new t.c3(e,n.u_extrude_scale),u_device_pixel_ratio:new t.bp(e,n.u_device_pixel_ratio),u_globe_extrude_scale:new t.bp(e,n.u_globe_extrude_scale),u_translate:new t.c3(e,n.u_translate)}),collisionBox:(e,n)=>({u_pixel_extrude_scale:new t.c3(e,n.u_pixel_extrude_scale)}),collisionCircle:(e,n)=>({u_viewport_size:new t.c3(e,n.u_viewport_size)}),debug:(e,n)=>({u_color:new t.b$(e,n.u_color),u_overlay:new t.b_(e,n.u_overlay),u_overlay_scale:new t.bp(e,n.u_overlay_scale)}),depth:Er,clippingMask:Er,heatmap:(e,n)=>({u_extrude_scale:new t.bp(e,n.u_extrude_scale),u_intensity:new t.bp(e,n.u_intensity),u_globe_extrude_scale:new t.bp(e,n.u_globe_extrude_scale)}),heatmapTexture:(e,n)=>({u_matrix:new t.c0(e,n.u_matrix),u_world:new t.c3(e,n.u_world),u_image:new t.b_(e,n.u_image),u_color_ramp:new t.b_(e,n.u_color_ramp),u_opacity:new t.bp(e,n.u_opacity)}),hillshade:(e,n)=>({u_image:new t.b_(e,n.u_image),u_latrange:new t.c3(e,n.u_latrange),u_exaggeration:new t.bp(e,n.u_exaggeration),u_altitudes:new t.c9(e,n.u_altitudes),u_azimuths:new t.c9(e,n.u_azimuths),u_accent:new t.b$(e,n.u_accent),u_method:new t.b_(e,n.u_method),u_shadows:new t.c8(e,n.u_shadows),u_highlights:new t.c8(e,n.u_highlights)}),hillshadePrepare:(e,n)=>({u_matrix:new t.c0(e,n.u_matrix),u_image:new t.b_(e,n.u_image),u_dimension:new t.c3(e,n.u_dimension),u_zoom:new t.bp(e,n.u_zoom),u_unpack:new t.c1(e,n.u_unpack)}),colorRelief:(e,n)=>({u_image:new t.b_(e,n.u_image),u_unpack:new t.c1(e,n.u_unpack),u_dimension:new t.c3(e,n.u_dimension),u_elevation_stops:new t.b_(e,n.u_elevation_stops),u_color_stops:new t.b_(e,n.u_color_stops),u_color_ramp_size:new t.b_(e,n.u_color_ramp_size),u_opacity:new t.bp(e,n.u_opacity)}),line:(e,n)=>({u_translation:new t.c3(e,n.u_translation),u_ratio:new t.bp(e,n.u_ratio),u_device_pixel_ratio:new t.bp(e,n.u_device_pixel_ratio),u_units_to_pixels:new t.c3(e,n.u_units_to_pixels)}),lineGradient:(e,n)=>({u_translation:new t.c3(e,n.u_translation),u_ratio:new t.bp(e,n.u_ratio),u_device_pixel_ratio:new t.bp(e,n.u_device_pixel_ratio),u_units_to_pixels:new t.c3(e,n.u_units_to_pixels),u_image:new t.b_(e,n.u_image),u_image_height:new t.bp(e,n.u_image_height)}),linePattern:(e,n)=>({u_translation:new t.c3(e,n.u_translation),u_texsize:new t.c3(e,n.u_texsize),u_ratio:new t.bp(e,n.u_ratio),u_device_pixel_ratio:new t.bp(e,n.u_device_pixel_ratio),u_image:new t.b_(e,n.u_image),u_units_to_pixels:new t.c3(e,n.u_units_to_pixels),u_scale:new t.c2(e,n.u_scale),u_fade:new t.bp(e,n.u_fade)}),lineSDF:(e,n)=>({u_translation:new t.c3(e,n.u_translation),u_ratio:new t.bp(e,n.u_ratio),u_device_pixel_ratio:new t.bp(e,n.u_device_pixel_ratio),u_units_to_pixels:new t.c3(e,n.u_units_to_pixels),u_image:new t.b_(e,n.u_image),u_mix:new t.bp(e,n.u_mix),u_tileratio:new t.bp(e,n.u_tileratio),u_crossfade_from:new t.bp(e,n.u_crossfade_from),u_crossfade_to:new t.bp(e,n.u_crossfade_to),u_lineatlas_width:new t.bp(e,n.u_lineatlas_width),u_lineatlas_height:new t.bp(e,n.u_lineatlas_height)}),lineGradientSDF:(e,n)=>({u_translation:new t.c3(e,n.u_translation),u_ratio:new t.bp(e,n.u_ratio),u_device_pixel_ratio:new t.bp(e,n.u_device_pixel_ratio),u_units_to_pixels:new t.c3(e,n.u_units_to_pixels),u_image:new t.b_(e,n.u_image),u_image_height:new t.bp(e,n.u_image_height),u_tileratio:new t.bp(e,n.u_tileratio),u_crossfade_from:new t.bp(e,n.u_crossfade_from),u_crossfade_to:new t.bp(e,n.u_crossfade_to),u_image_dash:new t.b_(e,n.u_image_dash),u_mix:new t.bp(e,n.u_mix),u_lineatlas_width:new t.bp(e,n.u_lineatlas_width),u_lineatlas_height:new t.bp(e,n.u_lineatlas_height)}),raster:(e,n)=>({u_tl_parent:new t.c3(e,n.u_tl_parent),u_scale_parent:new t.bp(e,n.u_scale_parent),u_buffer_scale:new t.bp(e,n.u_buffer_scale),u_fade_t:new t.bp(e,n.u_fade_t),u_opacity:new t.bp(e,n.u_opacity),u_image0:new t.b_(e,n.u_image0),u_image1:new t.b_(e,n.u_image1),u_brightness_low:new t.bp(e,n.u_brightness_low),u_brightness_high:new t.bp(e,n.u_brightness_high),u_saturation_factor:new t.bp(e,n.u_saturation_factor),u_contrast_factor:new t.bp(e,n.u_contrast_factor),u_spin_weights:new t.c2(e,n.u_spin_weights),u_coords_top:new t.c1(e,n.u_coords_top),u_coords_bottom:new t.c1(e,n.u_coords_bottom)}),symbolIcon:(e,n)=>({u_is_size_zoom_constant:new t.b_(e,n.u_is_size_zoom_constant),u_is_size_feature_constant:new t.b_(e,n.u_is_size_feature_constant),u_size_t:new t.bp(e,n.u_size_t),u_size:new t.bp(e,n.u_size),u_camera_to_center_distance:new t.bp(e,n.u_camera_to_center_distance),u_pitch:new t.bp(e,n.u_pitch),u_rotate_symbol:new t.b_(e,n.u_rotate_symbol),u_aspect_ratio:new t.bp(e,n.u_aspect_ratio),u_fade_change:new t.bp(e,n.u_fade_change),u_label_plane_matrix:new t.c0(e,n.u_label_plane_matrix),u_coord_matrix:new t.c0(e,n.u_coord_matrix),u_is_text:new t.b_(e,n.u_is_text),u_pitch_with_map:new t.b_(e,n.u_pitch_with_map),u_is_along_line:new t.b_(e,n.u_is_along_line),u_is_variable_anchor:new t.b_(e,n.u_is_variable_anchor),u_texsize:new t.c3(e,n.u_texsize),u_texture:new t.b_(e,n.u_texture),u_translation:new t.c3(e,n.u_translation),u_pitched_scale:new t.bp(e,n.u_pitched_scale)}),symbolSDF:(e,n)=>({u_is_size_zoom_constant:new t.b_(e,n.u_is_size_zoom_constant),u_is_size_feature_constant:new t.b_(e,n.u_is_size_feature_constant),u_size_t:new t.bp(e,n.u_size_t),u_size:new t.bp(e,n.u_size),u_camera_to_center_distance:new t.bp(e,n.u_camera_to_center_distance),u_pitch:new t.bp(e,n.u_pitch),u_rotate_symbol:new t.b_(e,n.u_rotate_symbol),u_aspect_ratio:new t.bp(e,n.u_aspect_ratio),u_fade_change:new t.bp(e,n.u_fade_change),u_label_plane_matrix:new t.c0(e,n.u_label_plane_matrix),u_coord_matrix:new t.c0(e,n.u_coord_matrix),u_is_text:new t.b_(e,n.u_is_text),u_pitch_with_map:new t.b_(e,n.u_pitch_with_map),u_is_along_line:new t.b_(e,n.u_is_along_line),u_is_variable_anchor:new t.b_(e,n.u_is_variable_anchor),u_texsize:new t.c3(e,n.u_texsize),u_texture:new t.b_(e,n.u_texture),u_gamma_scale:new t.bp(e,n.u_gamma_scale),u_device_pixel_ratio:new t.bp(e,n.u_device_pixel_ratio),u_is_halo:new t.b_(e,n.u_is_halo),u_is_plain:new t.b_(e,n.u_is_plain),u_translation:new t.c3(e,n.u_translation),u_pitched_scale:new t.bp(e,n.u_pitched_scale)}),symbolTextAndIcon:(e,n)=>({u_is_size_zoom_constant:new t.b_(e,n.u_is_size_zoom_constant),u_is_size_feature_constant:new t.b_(e,n.u_is_size_feature_constant),u_size_t:new t.bp(e,n.u_size_t),u_size:new t.bp(e,n.u_size),u_camera_to_center_distance:new t.bp(e,n.u_camera_to_center_distance),u_pitch:new t.bp(e,n.u_pitch),u_rotate_symbol:new t.b_(e,n.u_rotate_symbol),u_aspect_ratio:new t.bp(e,n.u_aspect_ratio),u_fade_change:new t.bp(e,n.u_fade_change),u_label_plane_matrix:new t.c0(e,n.u_label_plane_matrix),u_coord_matrix:new t.c0(e,n.u_coord_matrix),u_is_text:new t.b_(e,n.u_is_text),u_pitch_with_map:new t.b_(e,n.u_pitch_with_map),u_is_along_line:new t.b_(e,n.u_is_along_line),u_is_variable_anchor:new t.b_(e,n.u_is_variable_anchor),u_texsize:new t.c3(e,n.u_texsize),u_texsize_icon:new t.c3(e,n.u_texsize_icon),u_texture:new t.b_(e,n.u_texture),u_texture_icon:new t.b_(e,n.u_texture_icon),u_gamma_scale:new t.bp(e,n.u_gamma_scale),u_device_pixel_ratio:new t.bp(e,n.u_device_pixel_ratio),u_is_halo:new t.b_(e,n.u_is_halo),u_translation:new t.c3(e,n.u_translation),u_pitched_scale:new t.bp(e,n.u_pitched_scale)}),background:(e,n)=>({u_opacity:new t.bp(e,n.u_opacity),u_color:new t.b$(e,n.u_color)}),backgroundPattern:(e,n)=>({u_opacity:new t.bp(e,n.u_opacity),u_image:new t.b_(e,n.u_image),u_pattern_tl_a:new t.c3(e,n.u_pattern_tl_a),u_pattern_br_a:new t.c3(e,n.u_pattern_br_a),u_pattern_tl_b:new t.c3(e,n.u_pattern_tl_b),u_pattern_br_b:new t.c3(e,n.u_pattern_br_b),u_texsize:new t.c3(e,n.u_texsize),u_mix:new t.bp(e,n.u_mix),u_pattern_size_a:new t.c3(e,n.u_pattern_size_a),u_pattern_size_b:new t.c3(e,n.u_pattern_size_b),u_scale_a:new t.bp(e,n.u_scale_a),u_scale_b:new t.bp(e,n.u_scale_b),u_pixel_coord_upper:new t.c3(e,n.u_pixel_coord_upper),u_pixel_coord_lower:new t.c3(e,n.u_pixel_coord_lower),u_tile_units_to_pixels:new t.bp(e,n.u_tile_units_to_pixels)}),terrain:(e,n)=>({u_texture:new t.b_(e,n.u_texture),u_ele_delta:new t.bp(e,n.u_ele_delta),u_fog_matrix:new t.c0(e,n.u_fog_matrix),u_fog_color:new t.b$(e,n.u_fog_color),u_fog_ground_blend:new t.bp(e,n.u_fog_ground_blend),u_fog_ground_blend_opacity:new t.bp(e,n.u_fog_ground_blend_opacity),u_horizon_color:new t.b$(e,n.u_horizon_color),u_horizon_fog_blend:new t.bp(e,n.u_horizon_fog_blend),u_is_globe_mode:new t.bp(e,n.u_is_globe_mode)}),terrainDepth:(e,n)=>({u_ele_delta:new t.bp(e,n.u_ele_delta)}),terrainCoords:(e,n)=>({u_texture:new t.b_(e,n.u_texture),u_terrain_coords_id:new t.bp(e,n.u_terrain_coords_id),u_ele_delta:new t.bp(e,n.u_ele_delta)}),projectionErrorMeasurement:(e,n)=>({u_input:new t.bp(e,n.u_input),u_output_expected:new t.bp(e,n.u_output_expected)}),atmosphere:(e,n)=>({u_sun_pos:new t.c2(e,n.u_sun_pos),u_atmosphere_blend:new t.bp(e,n.u_atmosphere_blend),u_globe_position:new t.c2(e,n.u_globe_position),u_globe_radius:new t.bp(e,n.u_globe_radius),u_inv_proj_matrix:new t.c0(e,n.u_inv_proj_matrix)}),sky:(e,n)=>({u_sky_color:new t.b$(e,n.u_sky_color),u_horizon_color:new t.b$(e,n.u_horizon_color),u_horizon:new t.c3(e,n.u_horizon),u_horizon_normal:new t.c3(e,n.u_horizon_normal),u_sky_horizon_blend:new t.bp(e,n.u_sky_horizon_blend),u_sky_blend:new t.bp(e,n.u_sky_blend)})};class Or{constructor(e,t,n){this.context=e;let r=e.gl;this.buffer=r.createBuffer(),this.dynamicDraw=!!n,this.context.unbindVAO(),e.bindElementBuffer.set(this.buffer),r.bufferData(r.ELEMENT_ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?r.DYNAMIC_DRAW:r.STATIC_DRAW),this.dynamicDraw||t.freeBufferAfterUpload()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(e){let t=this.context.gl;if(!this.dynamicDraw)throw Error(`Attempted to update data while not in dynamic mode.`);this.context.unbindVAO(),this.bind(),t.bufferSubData(t.ELEMENT_ARRAY_BUFFER,0,e.arrayBuffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}let kr={Int8:`BYTE`,Uint8:`UNSIGNED_BYTE`,Int16:`SHORT`,Uint16:`UNSIGNED_SHORT`,Int32:`INT`,Uint32:`UNSIGNED_INT`,Float32:`FLOAT`};class W{constructor(e,t,n,r){this.length=t.length,this.attributes=n,this.itemSize=t.bytesPerElement,this.dynamicDraw=r,this.context=e;let i=e.gl;this.buffer=i.createBuffer(),e.bindVertexBuffer.set(this.buffer),i.bufferData(i.ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?i.DYNAMIC_DRAW:i.STATIC_DRAW),this.dynamicDraw||t.freeBufferAfterUpload()}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(e){if(e.length!==this.length)throw Error(`Length of new data is ${e.length}, which doesn't match current length of ${this.length}`);let t=this.context.gl;this.bind(),t.bufferSubData(t.ARRAY_BUFFER,0,e.arrayBuffer)}enableAttributes(e,t){for(let n of this.attributes){let r=t.attributes[n.name];r!==void 0&&e.enableVertexAttribArray(r)}}setVertexAttribPointers(e,t,n){for(let r of this.attributes){let i=t.attributes[r.name];i!==void 0&&e.vertexAttribPointer(i,r.components,e[kr[r.type]],!1,this.itemSize,r.offset+this.itemSize*(n||0))}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class Ar{constructor(e){this.gl=e.gl,this.default=this.getDefault(),this.current=this.default,this.dirty=!1}get(){return this.current}set(e){}getDefault(){return this.default}setDefault(){this.set(this.default)}}class jr extends Ar{getDefault(){return t.bo.transparent}set(e){let t=this.current;(e.r!==t.r||e.g!==t.g||e.b!==t.b||e.a!==t.a||this.dirty)&&(this.gl.clearColor(e.r,e.g,e.b,e.a),this.current=e,this.dirty=!1)}}class Mr extends Ar{getDefault(){return 1}set(e){(e!==this.current||this.dirty)&&(this.gl.clearDepth(e),this.current=e,this.dirty=!1)}}class Nr extends Ar{getDefault(){return 0}set(e){(e!==this.current||this.dirty)&&(this.gl.clearStencil(e),this.current=e,this.dirty=!1)}}class Pr extends Ar{getDefault(){return[!0,!0,!0,!0]}set(e){let t=this.current;(e[0]!==t[0]||e[1]!==t[1]||e[2]!==t[2]||e[3]!==t[3]||this.dirty)&&(this.gl.colorMask(e[0],e[1],e[2],e[3]),this.current=e,this.dirty=!1)}}class Fr extends Ar{getDefault(){return!0}set(e){(e!==this.current||this.dirty)&&(this.gl.depthMask(e),this.current=e,this.dirty=!1)}}class Ir extends Ar{getDefault(){return 255}set(e){(e!==this.current||this.dirty)&&(this.gl.stencilMask(e),this.current=e,this.dirty=!1)}}class Lr extends Ar{getDefault(){return{func:this.gl.ALWAYS,ref:0,mask:255}}set(e){let t=this.current;(e.func!==t.func||e.ref!==t.ref||e.mask!==t.mask||this.dirty)&&(this.gl.stencilFunc(e.func,e.ref,e.mask),this.current=e,this.dirty=!1)}}class Rr extends Ar{getDefault(){let e=this.gl;return[e.KEEP,e.KEEP,e.KEEP]}set(e){let t=this.current;(e[0]!==t[0]||e[1]!==t[1]||e[2]!==t[2]||this.dirty)&&(this.gl.stencilOp(e[0],e[1],e[2]),this.current=e,this.dirty=!1)}}class zr extends Ar{getDefault(){return!1}set(e){if(e===this.current&&!this.dirty)return;let t=this.gl;e?t.enable(t.STENCIL_TEST):t.disable(t.STENCIL_TEST),this.current=e,this.dirty=!1}}class Br extends Ar{getDefault(){return[0,1]}set(e){let t=this.current;(e[0]!==t[0]||e[1]!==t[1]||this.dirty)&&(this.gl.depthRange(e[0],e[1]),this.current=e,this.dirty=!1)}}class Vr extends Ar{getDefault(){return!1}set(e){if(e===this.current&&!this.dirty)return;let t=this.gl;e?t.enable(t.DEPTH_TEST):t.disable(t.DEPTH_TEST),this.current=e,this.dirty=!1}}class Hr extends Ar{getDefault(){return this.gl.LESS}set(e){(e!==this.current||this.dirty)&&(this.gl.depthFunc(e),this.current=e,this.dirty=!1)}}class Ur extends Ar{getDefault(){return!1}set(e){if(e===this.current&&!this.dirty)return;let t=this.gl;e?t.enable(t.BLEND):t.disable(t.BLEND),this.current=e,this.dirty=!1}}class Wr extends Ar{getDefault(){let e=this.gl;return[e.ONE,e.ZERO]}set(e){let t=this.current;(e[0]!==t[0]||e[1]!==t[1]||this.dirty)&&(this.gl.blendFunc(e[0],e[1]),this.current=e,this.dirty=!1)}}class Gr extends Ar{getDefault(){return t.bo.transparent}set(e){let t=this.current;(e.r!==t.r||e.g!==t.g||e.b!==t.b||e.a!==t.a||this.dirty)&&(this.gl.blendColor(e.r,e.g,e.b,e.a),this.current=e,this.dirty=!1)}}class Kr extends Ar{getDefault(){return this.gl.FUNC_ADD}set(e){(e!==this.current||this.dirty)&&(this.gl.blendEquation(e),this.current=e,this.dirty=!1)}}class qr extends Ar{getDefault(){return!1}set(e){if(e===this.current&&!this.dirty)return;let t=this.gl;e?t.enable(t.CULL_FACE):t.disable(t.CULL_FACE),this.current=e,this.dirty=!1}}class Jr extends Ar{getDefault(){return this.gl.BACK}set(e){(e!==this.current||this.dirty)&&(this.gl.cullFace(e),this.current=e,this.dirty=!1)}}class Yr extends Ar{getDefault(){return this.gl.CCW}set(e){(e!==this.current||this.dirty)&&(this.gl.frontFace(e),this.current=e,this.dirty=!1)}}class G extends Ar{getDefault(){return null}set(e){(e!==this.current||this.dirty)&&(this.gl.useProgram(e),this.current=e,this.dirty=!1)}}class Xr extends Ar{getDefault(){return this.gl.TEXTURE0}set(e){(e!==this.current||this.dirty)&&(this.gl.activeTexture(e),this.current=e,this.dirty=!1)}}class Zr extends Ar{getDefault(){let e=this.gl;return[0,0,e.drawingBufferWidth,e.drawingBufferHeight]}set(e){let t=this.current;(e[0]!==t[0]||e[1]!==t[1]||e[2]!==t[2]||e[3]!==t[3]||this.dirty)&&(this.gl.viewport(e[0],e[1],e[2],e[3]),this.current=e,this.dirty=!1)}}class Qr extends Ar{getDefault(){return null}set(e){if(e===this.current&&!this.dirty)return;let t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,e),this.current=e,this.dirty=!1}}class $r extends Ar{getDefault(){return null}set(e){if(e===this.current&&!this.dirty)return;let t=this.gl;t.bindRenderbuffer(t.RENDERBUFFER,e),this.current=e,this.dirty=!1}}class ei extends Ar{getDefault(){return null}set(e){if(e===this.current&&!this.dirty)return;let t=this.gl;t.bindTexture(t.TEXTURE_2D,e),this.current=e,this.dirty=!1}}class ti extends Ar{getDefault(){return null}set(e){if(e===this.current&&!this.dirty)return;let t=this.gl;t.bindBuffer(t.ARRAY_BUFFER,e),this.current=e,this.dirty=!1}}class ni extends Ar{getDefault(){return null}set(e){let t=this.gl;t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,e),this.current=e,this.dirty=!1}}class K extends Ar{getDefault(){return null}set(e){var t;if(e===this.current&&!this.dirty)return;let n=this.gl;gn(n)?n.bindVertexArray(e):(t=n.getExtension(`OES_vertex_array_object`))==null||t.bindVertexArrayOES(e),this.current=e,this.dirty=!1}}class ri extends Ar{getDefault(){return 4}set(e){if(e===this.current&&!this.dirty)return;let t=this.gl;t.pixelStorei(t.UNPACK_ALIGNMENT,e),this.current=e,this.dirty=!1}}class ii extends Ar{getDefault(){return!1}set(e){if(e===this.current&&!this.dirty)return;let t=this.gl;t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e),this.current=e,this.dirty=!1}}class ai extends Ar{getDefault(){return!1}set(e){if(e===this.current&&!this.dirty)return;let t=this.gl;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,e),this.current=e,this.dirty=!1}}class oi extends Ar{constructor(e,t){super(e),this.context=e,this.parent=t}getDefault(){return null}}class q extends oi{setDirty(){this.dirty=!0}set(e){if(e===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);let t=this.gl;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),this.current=e,this.dirty=!1}}class J extends oi{set(e){if(e===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);let t=this.gl;t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.RENDERBUFFER,e),this.current=e,this.dirty=!1}}class si extends oi{set(e){if(e===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);let t=this.gl;t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,e),this.current=e,this.dirty=!1}}let ci=`Framebuffer is not complete`;class li{constructor(e,t,n,r,i){this.context=e,this.width=t,this.height=n;let a=e.gl,o=this.framebuffer=a.createFramebuffer();if(this.colorAttachment=new q(e,o),r)this.depthAttachment=i?new si(e,o):new J(e,o);else if(i)throw Error(`Stencil cannot be set without depth`);if(a.checkFramebufferStatus(a.FRAMEBUFFER)!==a.FRAMEBUFFER_COMPLETE)throw Error(ci)}destroy(){let e=this.context.gl,t=this.colorAttachment.get();if(t&&e.deleteTexture(t),this.depthAttachment){let t=this.depthAttachment.get();t&&e.deleteRenderbuffer(t)}e.deleteFramebuffer(this.framebuffer)}}class ui{constructor(e){if(this.gl=e,this.clearColor=new jr(this),this.clearDepth=new Mr(this),this.clearStencil=new Nr(this),this.colorMask=new Pr(this),this.depthMask=new Fr(this),this.stencilMask=new Ir(this),this.stencilFunc=new Lr(this),this.stencilOp=new Rr(this),this.stencilTest=new zr(this),this.depthRange=new Br(this),this.depthTest=new Vr(this),this.depthFunc=new Hr(this),this.blend=new Ur(this),this.blendFunc=new Wr(this),this.blendColor=new Gr(this),this.blendEquation=new Kr(this),this.cullFace=new qr(this),this.cullFaceSide=new Jr(this),this.frontFace=new Yr(this),this.program=new G(this),this.activeTexture=new Xr(this),this.viewport=new Zr(this),this.bindFramebuffer=new Qr(this),this.bindRenderbuffer=new $r(this),this.bindTexture=new ei(this),this.bindVertexBuffer=new ti(this),this.bindElementBuffer=new ni(this),this.bindVertexArray=new K(this),this.pixelStoreUnpack=new ri(this),this.pixelStoreUnpackPremultiplyAlpha=new ii(this),this.pixelStoreUnpackFlipY=new ai(this),this.extTextureFilterAnisotropic=e.getExtension(`EXT_texture_filter_anisotropic`),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=e.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT)),this.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE),gn(e)){this.HALF_FLOAT=e.HALF_FLOAT;let t=e.getExtension(`EXT_color_buffer_half_float`);this.RGBA16F=e.RGBA16F??t?.RGBA16F_EXT,this.RGB16F=e.RGB16F??t?.RGB16F_EXT,e.getExtension(`EXT_color_buffer_float`)}else{e.getExtension(`EXT_color_buffer_half_float`),e.getExtension(`OES_texture_half_float_linear`);let t=e.getExtension(`OES_texture_half_float`);this.HALF_FLOAT=t?.HALF_FLOAT_OES}}setDefault(){this.unbindVAO(),this.clearColor.setDefault(),this.clearDepth.setDefault(),this.clearStencil.setDefault(),this.colorMask.setDefault(),this.depthMask.setDefault(),this.stencilMask.setDefault(),this.stencilFunc.setDefault(),this.stencilOp.setDefault(),this.stencilTest.setDefault(),this.depthRange.setDefault(),this.depthTest.setDefault(),this.depthFunc.setDefault(),this.blend.setDefault(),this.blendFunc.setDefault(),this.blendColor.setDefault(),this.blendEquation.setDefault(),this.cullFace.setDefault(),this.cullFaceSide.setDefault(),this.frontFace.setDefault(),this.program.setDefault(),this.activeTexture.setDefault(),this.bindFramebuffer.setDefault(),this.pixelStoreUnpack.setDefault(),this.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.pixelStoreUnpackFlipY.setDefault()}setDirty(){this.clearColor.dirty=!0,this.clearDepth.dirty=!0,this.clearStencil.dirty=!0,this.colorMask.dirty=!0,this.depthMask.dirty=!0,this.stencilMask.dirty=!0,this.stencilFunc.dirty=!0,this.stencilOp.dirty=!0,this.stencilTest.dirty=!0,this.depthRange.dirty=!0,this.depthTest.dirty=!0,this.depthFunc.dirty=!0,this.blend.dirty=!0,this.blendFunc.dirty=!0,this.blendColor.dirty=!0,this.blendEquation.dirty=!0,this.cullFace.dirty=!0,this.cullFaceSide.dirty=!0,this.frontFace.dirty=!0,this.program.dirty=!0,this.activeTexture.dirty=!0,this.viewport.dirty=!0,this.bindFramebuffer.dirty=!0,this.bindRenderbuffer.dirty=!0,this.bindTexture.dirty=!0,this.bindVertexBuffer.dirty=!0,this.bindElementBuffer.dirty=!0,this.bindVertexArray.dirty=!0,this.pixelStoreUnpack.dirty=!0,this.pixelStoreUnpackPremultiplyAlpha.dirty=!0,this.pixelStoreUnpackFlipY.dirty=!0}createIndexBuffer(e,t){return new Or(this,e,t)}createVertexBuffer(e,t,n){return new W(this,e,t,n)}createRenderbuffer(e,t,n){let r=this.gl,i=r.createRenderbuffer();return this.bindRenderbuffer.set(i),r.renderbufferStorage(r.RENDERBUFFER,e,t,n),this.bindRenderbuffer.set(null),i}createFramebuffer(e,t,n,r){return new li(this,e,t,n,r)}clear({color:e,depth:t,stencil:n}){let r=this.gl,i=0;e&&(i|=r.COLOR_BUFFER_BIT,this.clearColor.set(e),this.colorMask.set([!0,!0,!0,!0])),t!==void 0&&(i|=r.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(t),this.depthMask.set(!0)),n!==void 0&&(i|=r.STENCIL_BUFFER_BIT,this.clearStencil.set(n),this.stencilMask.set(255)),r.clear(i)}setCullFace(e){!1===e.enable?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(e.mode),this.frontFace.set(e.frontFace))}setDepthMode(e){e.func!==this.gl.ALWAYS||e.mask?(this.depthTest.set(!0),this.depthFunc.set(e.func),this.depthMask.set(e.mask),this.depthRange.set(e.range)):this.depthTest.set(!1)}setStencilMode(e){e.test.func!==this.gl.ALWAYS||e.mask?(this.stencilTest.set(!0),this.stencilMask.set(e.mask),this.stencilOp.set([e.fail,e.depthFail,e.pass]),this.stencilFunc.set({func:e.test.func,ref:e.ref,mask:e.test.mask})):this.stencilTest.set(!1)}setColorMode(e){t.bQ(e.blendFunction,un.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(e.blendFunction),this.blendColor.set(e.blendColor)),this.colorMask.set(e.mask)}createVertexArray(){return gn(this.gl)?this.gl.createVertexArray():this.gl.getExtension(`OES_vertex_array_object`)?.createVertexArrayOES()}deleteVertexArray(e){var t;gn(this.gl)?this.gl.deleteVertexArray(e):(t=this.gl.getExtension(`OES_vertex_array_object`))==null||t.deleteVertexArrayOES(e)}unbindVAO(){this.bindVertexArray.set(null)}}let di;function Y(e,n,r,i,a){let o=e.context,s=e.transform,c=o.gl,l=e.useProgram(`collisionBox`),u=[],d=0,f=0;for(let t of i){let i=n.getTile(t).getBucket(r);if(!i)continue;let p=a?i.textCollisionBox:i.iconCollisionBox,m=i.collisionCircleArray;m.length>0&&(u.push({circleArray:m,circleOffset:f,coord:t}),d+=m.length/4,f=d),p&&l.draw(o,c.LINES,pn.disabled,hn.disabled,e.colorModeForRenderPass(),fn.disabled,rr(e.transform),e.style.map.terrain?.getTerrainData(t),s.getProjectionData({overscaledTileID:t,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),r.id,p.layoutVertexBuffer,p.indexBuffer,p.segments,null,e.transform.zoom,null,null,p.collisionVertexBuffer)}if(!a||!u.length)return;let p=e.useProgram(`collisionCircle`),m=new t.ca;m.resize(4*d),m._trim();let h=0;for(let e of u)for(let t=0;t<e.circleArray.length/4;t++){let n=4*t,r=e.circleArray[n+0],i=e.circleArray[n+1],a=e.circleArray[n+2],o=e.circleArray[n+3];m.emplace(h++,r,i,a,o,0),m.emplace(h++,r,i,a,o,1),m.emplace(h++,r,i,a,o,2),m.emplace(h++,r,i,a,o,3)}(!di||di.length<2*d)&&(di=function(e){let n=2*e,r=new t.cc;r.resize(n),r._trim();for(let e=0;e<n;e++){let t=6*e;r.uint16[t+0]=4*e+0,r.uint16[t+1]=4*e+1,r.uint16[t+2]=4*e+2,r.uint16[t+3]=4*e+2,r.uint16[t+4]=4*e+3,r.uint16[t+5]=4*e+0}return r}(d));let g=o.createIndexBuffer(di,!0),_=o.createVertexBuffer(m,t.cb.members,!0);for(let n of u){let i=ir(e.transform);p.draw(o,c.TRIANGLES,pn.disabled,hn.disabled,e.colorModeForRenderPass(),fn.disabled,i,e.style.map.terrain?.getTerrainData(n.coord),null,r.id,_,g,t.aV.simpleSegment(0,2*n.circleOffset,n.circleArray.length,n.circleArray.length/2),null,e.transform.zoom,null,null,null)}_.destroy(),g.destroy()}let fi=t.ap(new Float32Array(16));function pi(e,n,r,i,a,o){let{horizontalAlign:s,verticalAlign:c}=t.aP(e);return new t.P((-(s-.5)*n/a+i[0])*o,(-(c-.5)*r/a+i[1])*o)}function mi(e,n,r,i,a,o){let s=n.tileAnchorPoint.add(new t.P(n.translation[0],n.translation[1]));if(n.pitchWithMap){let e=i.mult(o);r||(e=e.rotate(-a));let t=s.add(e);return ot(t.x,t.y,n.pitchedLabelPlaneMatrix,n.getElevation).point}if(r){let t=ht(n.tileAnchorPoint.x+1,n.tileAnchorPoint.y,n).point.sub(e),r=Math.atan(t.y/t.x)+(t.x<0?Math.PI:0);return e.add(i.rotate(r))}return e.add(i)}function hi(e,n,r,i,a,o,s,c,l,u,d,f){let p=e.text.placedSymbolArray,m=e.text.dynamicLayoutVertexArray,h=e.icon.dynamicLayoutVertexArray,g={};m.clear();for(let h=0;h<p.length;h++){let _=p.get(h),v=_.hidden||!_.crossTileID||e.allowVerticalPlacement&&!_.placedOrientation?null:i[_.crossTileID];if(v){let i=new t.P(_.anchorX,_.anchorY),p={getElevation:f,width:a.width,height:a.height,pitchedLabelPlaneMatrix:o,pitchWithMap:r,transform:a,tileAnchorPoint:i,translation:u,unwrappedTileID:d},h=r?_t(i.x,i.y,p):ht(i.x,i.y,p),y=st(a.cameraToCenterDistance,h.signedDistanceFromCamera),b=t.ay(e.textSizeData,c,_)*y/t.aJ;r&&(b*=e.tilePixelRatio/s);let{width:x,height:S,anchor:C,textOffset:w,textBoxScale:T}=v,E=pi(C,x,S,w,T,b),D=a.getPitchedTextCorrection(i.x+u[0],i.y+u[1],d),O=mi(h.point,p,n,E,-a.bearingInRadians,D),k=e.allowVerticalPlacement&&_.placedOrientation===t.ax.vertical?Math.PI/2:0;for(let e=0;e<_.numGlyphs;e++)t.aD(m,O,k);l&&_.associatedIconIndex>=0&&(g[_.associatedIconIndex]={shiftedAnchor:O,angle:k})}else St(_.numGlyphs,m)}if(l){h.clear();let n=e.icon.placedSymbolArray;for(let e=0;e<n.length;e++){let r=n.get(e);if(r.hidden)St(r.numGlyphs,h);else{let n=g[e];if(n)for(let e=0;e<r.numGlyphs;e++)t.aD(h,n.shiftedAnchor,n.angle);else St(r.numGlyphs,h)}}e.icon.dynamicLayoutVertexBuffer.updateData(h)}e.text.dynamicLayoutVertexBuffer.updateData(m)}function gi(e,t,n){return n.iconsInText&&t?`symbolTextAndIcon`:e?`symbolSDF`:`symbolIcon`}function _i(e,n,r,i,a,o,s,c,l,u,d,f,p){let m=e.context,h=m.gl,g=e.transform,_=c===`map`,v=l===`map`,y=c!==`viewport`&&r.layout.get(`symbol-placement`)!==`point`,b=_&&!v&&!y,x=!r.layout.get(`symbol-sort-key`).isConstant(),S=!1,C=e.getDepthModeForSublayer(0,pn.ReadOnly),w=r._unevaluatedLayout.hasValue(`text-variable-anchor`)||r._unevaluatedLayout.hasValue(`text-variable-anchor-offset`),T=[],E=g.getCircleRadiusCorrection();for(let c of i){let i=n.getTile(c),l=i.getBucket(r);if(!l)continue;let d=a?l.text:l.icon;if(!d?.segments.get().length||!d.hasVisibleVertices)continue;let f=d.programConfigurations.get(r.id),m=a||l.sdfIcons,C=a?l.textSizeData:l.iconSizeData,D=v||g.pitch!==0,O=e.useProgram(gi(m,a,l),f),k=t.aw(C,g.zoom),A=e.style.map.terrain?.getTerrainData(c),ee,te,ne,re,ie=[0,0],ae=null;if(a)te=i.glyphAtlasTexture,ne=h.LINEAR,ee=i.glyphAtlasTexture.size,l.iconsInText&&(ie=i.imageAtlasTexture.size,ae=i.imageAtlasTexture,re=D||e.options.rotating||e.options.zooming||C.kind===`composite`||C.kind===`camera`?h.LINEAR:h.NEAREST);else{let t=r.layout.get(`icon-size`).constantOr(0)!==1||l.iconsNeedLinear;te=i.imageAtlasTexture,ne=m||e.options.rotating||e.options.zooming||t||D?h.LINEAR:h.NEAREST,ee=i.imageAtlasTexture.size}let oe=t.aK(i,1,e.transform.zoom),se=rt(_,e.transform,oe),ce=it(v,_,e.transform,oe),le=t.aL(g,i,o,s),ue=g.getProjectionData({overscaledTileID:c,applyGlobeMatrix:!p,applyTerrainMatrix:!0}),de=w&&l.hasTextData(),fe=r.layout.get(`icon-text-fit`)!==`none`&&de&&l.hasIconData();if(y){let n=t.O();tt(n,se);let i=e.style.map.terrain?(t,n)=>e.style.map.terrain.getElevation(c,t,n):null;lt(l,e,a,se,n,v,u,r.layout.get(`text-rotation-alignment`)===`map`,c.toUnwrapped(),g.width,g.height,le,i)}let pe=a&&w||fe,me=y||pe?fi:v?se:e.transform.clipSpaceToPixelsMatrix,he=m&&r.paint.get(a?`text-halo-width`:`icon-halo-width`).constantOr(1)!==0,ge;ge=m?l.iconsInText?Cr(C.kind,k,b,v,y,pe,e,me,ce,le,ee,ie,E):Sr(C.kind,k,b,v,y,pe,e,me,ce,le,a,ee,he,E):xr(C.kind,k,b,v,y,pe,e,me,ce,le,a,ee,E);let _e={program:O,buffers:d,uniformValues:ge,projectionData:ue,atlasTexture:te,atlasTextureIcon:ae,atlasInterpolation:ne,atlasInterpolationIcon:re,isSDF:m,hasHalo:he};if(x&&l.canOverlap){S=!0;let e=d.segments.get();for(let n of e)T.push({segments:new t.aV([n]),sortKey:n.sortKey,state:_e,terrainData:A})}else T.push({segments:d.segments,sortKey:0,state:_e,terrainData:A})}S&&T.sort(((e,t)=>e.sortKey-t.sortKey));let D=r.paint.get(a?`text-halo-width`:`icon-halo-width`).constantOr(null)??1/0,O=r.layout.get(`text-letter-spacing`).constantOr(0)*t.aJ<0||D>1;for(let t of T){let n=t.state;m.activeTexture.set(h.TEXTURE0),n.atlasTexture.bind(n.atlasInterpolation,h.CLAMP_TO_EDGE),n.atlasTextureIcon&&(m.activeTexture.set(h.TEXTURE1),n.atlasTextureIcon&&n.atlasTextureIcon.bind(n.atlasInterpolationIcon,h.CLAMP_TO_EDGE));let i=n.isSDF&&n.hasHalo;if(i){let i=n.uniformValues;i.u_is_halo=1,O&&(i.u_is_plain=0,vi(n.buffers,t.segments,r,e,n.program,C,d,f,i,n.projectionData,t.terrainData),i.u_is_halo=0,i.u_is_plain=1)}vi(n.buffers,t.segments,r,e,n.program,C,d,f,n.uniformValues,n.projectionData,t.terrainData),i&&!O&&(n.uniformValues.u_is_halo=0)}}function vi(e,t,n,r,i,a,o,s,c,l,u){let d=r.context;i.draw(d,d.gl.TRIANGLES,a,o,s,fn.backCCW,c,u,l,n.id,e.layoutVertexBuffer,e.indexBuffer,t,n.paint,r.transform.zoom,e.programConfigurations.get(n.id),e.dynamicLayoutVertexBuffer,e.opacityVertexBuffer)}function yi(e,n,r,i,a){let o=e.context,s=o.gl,c=hn.disabled,l=new un([s.ONE,s.ONE],t.bo.transparent,[!0,!0,!0,!0]),u=n.getBucket(r);if(!u)return;let d=i.key,f=r.heatmapFbos.get(d);f||(f=xi(o,n.tileSize,n.tileSize),r.heatmapFbos.set(d,f)),o.bindFramebuffer.set(f.framebuffer),o.viewport.set([0,0,n.tileSize,n.tileSize]),o.clear({color:t.bo.transparent});let p=u.programConfigurations.get(r.id),m=e.useProgram(`heatmap`,p,!a),h=e.transform.getProjectionData({overscaledTileID:n.tileID,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),g=e.style.map.terrain.getTerrainData(i);m.draw(o,s.TRIANGLES,pn.disabled,c,l,fn.disabled,or(n,e.transform.zoom,r.paint.get(`heatmap-intensity`),1),g,h,r.id,u.layoutVertexBuffer,u.indexBuffer,u.segments,r.paint,e.transform.zoom,p)}function bi(e,t,n,r,i){let a=e.context,o=a.gl,s=e.transform;a.setColorMode(e.colorModeForRenderPass());let c=Si(a,t),l=n.key,u=t.heatmapFbos.get(l);if(!u)return;a.activeTexture.set(o.TEXTURE0),o.bindTexture(o.TEXTURE_2D,u.colorAttachment.get()),a.activeTexture.set(o.TEXTURE1),c.bind(o.LINEAR,o.CLAMP_TO_EDGE);let d=s.getProjectionData({overscaledTileID:n,applyTerrainMatrix:i,applyGlobeMatrix:!r});e.useProgram(`heatmapTexture`).draw(a,o.TRIANGLES,pn.disabled,hn.disabled,e.colorModeForRenderPass(),fn.disabled,sr(e,t,0,1),null,d,t.id,e.rasterBoundsBuffer,e.quadTriangleIndexBuffer,e.rasterBoundsSegments,t.paint,s.zoom),u.destroy(),t.heatmapFbos.delete(l)}function xi(e,t,n){let r=e.gl,i=r.createTexture();r.bindTexture(r.TEXTURE_2D,i),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR);let a=e.HALF_FLOAT??r.UNSIGNED_BYTE,o=e.RGBA16F??r.RGBA;r.texImage2D(r.TEXTURE_2D,0,o,t,n,0,r.RGBA,a,null);let s=e.createFramebuffer(t,n,!1,!1);return s.colorAttachment.set(i),s}function Si(e,n){return n.colorRampTexture||=new t.T(e,n.colorRamp,e.gl.RGBA),n.colorRampTexture}function Ci(e,n,r,i,a,o,s,c){let l=256;if(a.stepInterpolant){let i=n.getSource().maxzoom,a=s.canonical.z===i?Math.ceil(1<<e.transform.maxZoom-s.canonical.z):1;l=t.al(t.ce(o.maxLineLength/t.a6*1024*a),256,r.maxTextureSize)}return c.gradient=t.cf({expression:a.gradientExpression(),evaluationKey:`lineProgress`,resolution:l,image:c.gradient||void 0,clips:o.lineClipsArray}),c.texture?c.texture.update(c.gradient):c.texture=new t.T(r,c.gradient,i.RGBA),c.version=a.gradientVersion,c.texture}function wi(e,t,n,r,i){e.activeTexture.set(t.TEXTURE0),n.imageAtlasTexture.bind(t.LINEAR,t.CLAMP_TO_EDGE),r.updatePaintBuffers(i)}function Ti(e,t,n,r,i,a){(i||e.lineAtlas.dirty)&&(t.activeTexture.set(n.TEXTURE0),e.lineAtlas.bind(t)),r.updatePaintBuffers(a)}function Ei(e,t,n,r,i,a,o){let s=a.gradients[i.id],c=s.texture;i.gradientVersion!==s.version&&(c=Ci(e,t,n,r,i,a,o,s)),n.activeTexture.set(r.TEXTURE0),c.bind(i.stepInterpolant?r.NEAREST:r.LINEAR,r.CLAMP_TO_EDGE)}function Di(e,t,n,r,i,a,o,s,c){let l=a.gradients[i.id],u=l.texture;i.gradientVersion!==l.version&&(u=Ci(e,t,n,r,i,a,o,l)),n.activeTexture.set(r.TEXTURE0),u.bind(i.stepInterpolant?r.NEAREST:r.LINEAR,r.CLAMP_TO_EDGE),n.activeTexture.set(r.TEXTURE1),e.lineAtlas.bind(n),s.updatePaintBuffers(c)}function Oi(e,t,n,r,i){if(!n||!r?.imageAtlas)return;let a=r.imageAtlas.patternPositions,o=a[n.to.toString()],s=a[n.from.toString()];if(!o&&s&&(o=s),!s&&o&&(s=o),!o||!s){let e=i.getPaintProperty(t);o=a[e],s=a[e]}o&&s&&e.setConstantPatternPositions(o,s)}function ki(e,n,r,i,a,o,s,c){let l=e.context.gl,u=`fill-pattern`,d=r.paint.get(u),f=d?.constantOr(1),p=r.getCrossfadeParameters(),m,h,g,_,v,y=e.transform,b=r.paint.get(`fill-translate`),x=r.paint.get(`fill-translate-anchor`);s?(h=f&&!r.getPaintProperty(`fill-outline-color`)?`fillOutlinePattern`:`fillOutline`,m=l.LINES):(h=f?`fillPattern`:`fill`,m=l.TRIANGLES);let S=d.constantOr(null);for(let d of i){let i=n.getTile(d);if(f&&!i.patternsLoaded())continue;let C=i.getBucket(r);if(!C)continue;let w=C.programConfigurations.get(r.id),T=e.useProgram(h,w),E=e.style.map.terrain?.getTerrainData(d);f&&(e.context.activeTexture.set(l.TEXTURE0),i.imageAtlasTexture.bind(l.LINEAR,l.CLAMP_TO_EDGE),w.updatePaintBuffers(p)),Oi(w,u,S,i,r);let D=y.getProjectionData({overscaledTileID:d,applyGlobeMatrix:!c,applyTerrainMatrix:!0}),O=t.aL(y,i,b,x);if(s){_=C.indexBuffer2,v=C.segments2;let t=[l.drawingBufferWidth,l.drawingBufferHeight];g=h===`fillOutlinePattern`&&f?tr(e,p,i,t,O):er(t,O)}else _=C.indexBuffer,v=C.segments,g=f?$n(e,p,i,O):{u_fill_translate:O};let k=e.stencilModeForClipping(d);T.draw(e.context,m,a,k,o,fn.backCCW,g,E,D,r.id,C.layoutVertexBuffer,_,v,r.paint,e.transform.zoom,w)}}function Ai(e,n,r,i,a,o,s,c){let l=e.context,u=l.gl,d=`fill-extrusion-pattern`,f=r.paint.get(d),p=f.constantOr(1),m=r.getCrossfadeParameters(),h=r.paint.get(`fill-extrusion-opacity`),g=f.constantOr(null),_=e.transform;for(let f of i){let i=n.getTile(f),v=i.getBucket(r);if(!v)continue;let y=e.style.map.terrain?.getTerrainData(f),b=v.programConfigurations.get(r.id),x=e.useProgram(p?`fillExtrusionPattern`:`fillExtrusion`,b);p&&(e.context.activeTexture.set(u.TEXTURE0),i.imageAtlasTexture.bind(u.LINEAR,u.CLAMP_TO_EDGE),b.updatePaintBuffers(m));let S=_.getProjectionData({overscaledTileID:f,applyGlobeMatrix:!c,applyTerrainMatrix:!0});Oi(b,d,g,i,r);let C=t.aL(_,i,r.paint.get(`fill-extrusion-translate`),r.paint.get(`fill-extrusion-translate-anchor`)),w=r.paint.get(`fill-extrusion-vertical-gradient`),T=p?Qn(e,w,h,C,f,m,i):Zn(e,w,h,C);x.draw(l,l.gl.TRIANGLES,a,o,s,fn.backCCW,T,y,S,r.id,v.layoutVertexBuffer,v.indexBuffer,v.segments,r.paint,e.transform.zoom,b,e.style.map.terrain&&v.centroidVertexBuffer)}}function ji(e,t,n,r,i,a,o,s,c){let l=e.style.projection,u=e.context,d=e.transform,f=u.gl,p=[`#define NUM_ILLUMINATION_SOURCES ${n.paint.get(`hillshade-highlight-color`).values.length}`],m=e.useProgram(`hillshade`,null,!1,p),h=!e.options.moving;for(let p of r){let r=t.getTile(p),g=r.fbo;if(!g)continue;let _=l.getMeshFromTileID(u,p.canonical,s,!0,`raster`),v=e.style.map.terrain?.getTerrainData(p);u.activeTexture.set(f.TEXTURE0),f.bindTexture(f.TEXTURE_2D,g.colorAttachment.get());let y=d.getProjectionData({overscaledTileID:p,aligned:h,applyGlobeMatrix:!c,applyTerrainMatrix:!0});m.draw(u,f.TRIANGLES,a,i[p.overscaledZ],o,fn.backCCW,cr(e,r,n),v,y,n.id,_.vertexBuffer,_.indexBuffer,_.segments)}}let Mi=0;function Ni(e,n,r,i,a,o,s,c,l){let u=e.style.projection,d=e.context,f=e.transform,p=d.gl,m=e.useProgram(`colorRelief`),h=!e.options.moving,g=r.paint.get(`resampling`)===`nearest`?p.NEAREST:p.LINEAR,_=!0,v=0;for(let y of i){let i=n.getTile(y),b=i.dem;if(_){Mi||=p.getParameter(p.MAX_TEXTURE_SIZE);let e=Mi,{elevationTexture:t,colorTexture:n}=r.getColorRampTextures(d,e,b.getUnpackVector());d.activeTexture.set(p.TEXTURE1),t.bind(p.NEAREST,p.CLAMP_TO_EDGE),d.activeTexture.set(p.TEXTURE4),n.bind(p.LINEAR,p.CLAMP_TO_EDGE),_=!1,v=t.size[0]}if(!b?.data)continue;let x=b.stride,S=b.getPixels();if(d.activeTexture.set(p.TEXTURE0),d.pixelStoreUnpackPremultiplyAlpha.set(!1),i.demTexture||=e.getTileTexture(x),i.demTexture){let e=i.demTexture;e.update(S,{premultiply:!1}),e.bind(g,p.CLAMP_TO_EDGE)}else i.demTexture=new t.T(d,S,p.RGBA,{premultiply:!1}),i.demTexture.bind(g,p.CLAMP_TO_EDGE);let C=u.getMeshFromTileID(d,y.canonical,c,!0,`raster`),w=e.style.map.terrain?.getTerrainData(y),T=f.getProjectionData({overscaledTileID:y,aligned:h,applyGlobeMatrix:!l,applyTerrainMatrix:!0});m.draw(d,p.TRIANGLES,o,a[y.overscaledZ],s,fn.backCCW,dr(r,i.dem,v),w,T,r.id,C.vertexBuffer,C.indexBuffer,C.segments)}}let Pi=[new t.P(0,0),new t.P(t.a6,0),new t.P(t.a6,t.a6),new t.P(0,t.a6)];function Fi(e,t,n,r,i,a,o,s,c=!1,l=!1){let u=r[r.length-1].overscaledZ,d=e.context,f=d.gl,p=e.useProgram(`raster`),m=e.transform,h=e.style.projection,g=e.colorModeForRenderPass(),_=!e.options.moving,v=n.paint.get(`raster-opacity`),y=n.paint.get(`resampling`)===`nearest`||n.paint.get(`raster-resampling`)===`nearest`?f.NEAREST:f.LINEAR,b=n.paint.get(`raster-fade-duration`),x=!!e.style.map.terrain;for(let S of r){let r=e.getDepthModeForSublayer(S.overscaledZ-u,v===1?pn.ReadWrite:pn.ReadOnly,f.LESS),C=t.getTile(S);d.activeTexture.set(f.TEXTURE0),C.texture.bind(y,f.CLAMP_TO_EDGE,f.LINEAR_MIPMAP_NEAREST),d.activeTexture.set(f.TEXTURE1);let{parentTile:w,parentScaleBy:T,parentTopLeft:E,fadeValues:D}=Ii(C,t,b,x);C.fadeOpacity=D.tileOpacity,w?(w.fadeOpacity=D.parentTileOpacity,w.texture.bind(y,f.CLAMP_TO_EDGE,f.LINEAR_MIPMAP_NEAREST)):C.texture.bind(y,f.CLAMP_TO_EDGE,f.LINEAR_MIPMAP_NEAREST),C.texture.useMipmap&&d.extTextureFilterAnisotropic&&e.transform.pitch>e.options.anisotropicFilterPitch&&f.texParameterf(f.TEXTURE_2D,d.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,d.extTextureFilterAnisotropicMax);let O=e.style.map.terrain?.getTerrainData(S),k=m.getProjectionData({overscaledTileID:S,aligned:_,applyGlobeMatrix:!l,applyTerrainMatrix:!0}),A=yr(E,T,D.fadeMix,n,s),ee=h.getMeshFromTileID(d,S.canonical,a,o,`raster`);p.draw(d,f.TRIANGLES,r,i?i[S.overscaledZ]:hn.disabled,g,c?fn.frontCCW:fn.backCCW,A,O,k,n.id,ee.vertexBuffer,ee.indexBuffer,ee.segments)}}function Ii(e,n,r,i){let a={parentTile:null,parentScaleBy:1,parentTopLeft:[0,0],fadeValues:{tileOpacity:1,parentTileOpacity:1,fadeMix:{opacity:1,mix:0}}};if(r===0||i)return a;if(e.fadingParentID){let i=n.getLoadedTile(e.fadingParentID);if(!i)return a;let o=2**(i.tileID.overscaledZ-e.tileID.overscaledZ);return{parentTile:i,parentScaleBy:o,parentTopLeft:[e.tileID.canonical.x*o%1,e.tileID.canonical.y*o%1],fadeValues:function(e,n,r){let i=l(),a=(i-n.timeAdded)/r,o=e.fadingDirection===Ne.Incoming,s=t.al((i-e.timeAdded)/r,0,1),c=t.al(1-a,0,1),u=o?s:c;return{tileOpacity:u,parentTileOpacity:o?c:s,fadeMix:{opacity:1,mix:1-u}}}(e,i,r)}}return e.selfFading?{parentTile:null,parentScaleBy:1,parentTopLeft:[0,0],fadeValues:function(e,n){let r=(l()-e.timeAdded)/n,i=t.al(r,0,1);return{tileOpacity:i,fadeMix:{opacity:i,mix:0}}}(e,r)}:a}let Li=new t.bo(1,0,0,1),Ri=new t.bo(0,1,0,1),zi=new t.bo(0,0,1,1),Bi=new t.bo(1,0,1,1),Vi=new t.bo(0,1,1,1);function Hi(e,t,n,r){Wi(e,0,t+n/2,e.transform.width,n,r)}function Ui(e,t,n,r){Wi(e,t-n/2,0,n,e.transform.height,r)}function Wi(e,t,n,r,i,a){let o=e.context,s=o.gl;s.enable(s.SCISSOR_TEST),s.scissor(t*e.pixelRatio,n*e.pixelRatio,r*e.pixelRatio,i*e.pixelRatio),o.clear({color:a}),s.disable(s.SCISSOR_TEST)}function Gi(e,n,r){let i=e.context,a=i.gl,o=e.useProgram(`debug`),s=pn.disabled,c=hn.disabled,l=e.colorModeForRenderPass(),u=`$debug`,d=e.style.map.terrain?.getTerrainData(r);i.activeTexture.set(a.TEXTURE0);let f=n.getTileByID(r.key).latestRawTileData,p=Math.floor((f?.byteLength||0)/1024),m=n.getTile(r).tileSize,h=512/Math.min(m,512)*(r.overscaledZ/e.transform.zoom)*.5,g=r.canonical.toString();r.overscaledZ!==r.canonical.z&&(g+=` => ${r.overscaledZ}`),function(e,t){e.initDebugOverlayCanvas();let n=e.debugOverlayCanvas,r=e.context.gl,i=e.debugOverlayCanvas.getContext(`2d`);i.clearRect(0,0,n.width,n.height),i.shadowColor=`white`,i.shadowBlur=2,i.lineWidth=1.5,i.strokeStyle=`white`,i.textBaseline=`top`,i.font=`bold 36px Open Sans, sans-serif`,i.fillText(t,5,5),i.strokeText(t,5,5),e.debugOverlayTexture.update(n),e.debugOverlayTexture.bind(r.LINEAR,r.CLAMP_TO_EDGE)}(e,`${g} ${p}kB`);let _=e.transform.getProjectionData({overscaledTileID:r,applyGlobeMatrix:!0,applyTerrainMatrix:!0});o.draw(i,a.TRIANGLES,s,c,un.alphaBlended,fn.disabled,ar(t.bo.transparent,h),null,_,u,e.debugBuffer,e.quadTriangleIndexBuffer,e.debugSegments),o.draw(i,a.LINE_STRIP,s,c,l,fn.disabled,ar(t.bo.red),d,_,u,e.debugBuffer,e.tileBorderIndexBuffer,e.debugSegments)}function Ki(e,t,n,r){let{isRenderingGlobe:i}=r,a=e.context,o=a.gl,s=e.transform,c=e.colorModeForRenderPass(),l=e.getDepthModeFor3D(),u=e.useProgram(`terrain`);a.bindFramebuffer.set(null),a.viewport.set([0,0,e.width,e.height]);for(let r of n){let n=t.getTerrainMesh(r.tileID),d=e.renderToTexture.getTexture(r),f=t.getTerrainData(r.tileID);a.activeTexture.set(o.TEXTURE0),o.bindTexture(o.TEXTURE_2D,d.texture);let p=Kn(t.getMeshFrameDelta(s.zoom),s.calculateFogMatrix(r.tileID.toUnwrapped()),e.style.sky,s.pitch,i),m=s.getProjectionData({overscaledTileID:r.tileID,applyTerrainMatrix:!1,applyGlobeMatrix:!0});u.draw(a,o.TRIANGLES,l,hn.disabled,c,fn.backCCW,p,f,m,`terrain`,n.vertexBuffer,n.indexBuffer,n.segments)}}function qi(e,n){if(!n.mesh){let r=new t.aU;r.emplaceBack(-1,-1),r.emplaceBack(1,-1),r.emplaceBack(1,1),r.emplaceBack(-1,1);let i=new t.aW;i.emplaceBack(0,1,2),i.emplaceBack(0,2,3),n.mesh=new Jt(e.createVertexBuffer(r,Yt.members),e.createIndexBuffer(i),t.aV.simpleSegment(0,0,r.length,i.length))}return n.mesh}let Ji={symbol:function(e,n,r,i,a,o){if(e.renderPass!==`translucent`)return;let{isRenderingToTexture:s}=o,c=hn.disabled,l=e.colorModeForRenderPass();(r._unevaluatedLayout.hasValue(`text-variable-anchor`)||r._unevaluatedLayout.hasValue(`text-variable-anchor-offset`))&&function(e,n,r,i,a,o,s,c,l){let u=n.transform,d=n.style.map.terrain,f=a===`map`,p=o===`map`;for(let a of e){let e=i.getTile(a),o=e.getBucket(r);if(!(o?.text)?.segments.get().length)continue;let m=t.aw(o.textSizeData,u.zoom),h=t.aK(e,1,n.transform.zoom),g=rt(f,n.transform,h),_=r.layout.get(`icon-text-fit`)!==`none`&&o.hasIconData();if(m){let n=2**(u.zoom-e.tileID.overscaledZ),r=d?(e,t)=>d.getElevation(a,e,t):null;hi(o,f,p,l,u,g,n,m,_,t.aL(u,e,s,c),a.toUnwrapped(),r)}}}(i,e,r,n,r.layout.get(`text-rotation-alignment`),r.layout.get(`text-pitch-alignment`),r.paint.get(`text-translate`),r.paint.get(`text-translate-anchor`),a),r.paint.get(`icon-opacity`).constantOr(1)!==0&&_i(e,n,r,i,!1,r.paint.get(`icon-translate`),r.paint.get(`icon-translate-anchor`),r.layout.get(`icon-rotation-alignment`),r.layout.get(`icon-pitch-alignment`),r.layout.get(`icon-keep-upright`),c,l,s),r.paint.get(`text-opacity`).constantOr(1)!==0&&_i(e,n,r,i,!0,r.paint.get(`text-translate`),r.paint.get(`text-translate-anchor`),r.layout.get(`text-rotation-alignment`),r.layout.get(`text-pitch-alignment`),r.layout.get(`text-keep-upright`),c,l,s),n.map.showCollisionBoxes&&(Y(e,n,r,i,!0),Y(e,n,r,i,!1))},circle:function(e,n,r,i,a){if(e.renderPass!==`translucent`)return;let{isRenderingToTexture:o}=a,s=r.paint.get(`circle-opacity`),c=r.paint.get(`circle-stroke-width`),l=r.paint.get(`circle-stroke-opacity`),u=!r.layout.get(`circle-sort-key`).isConstant();if(s.constantOr(1)===0&&(c.constantOr(1)===0||l.constantOr(1)===0))return;let d=e.context,f=d.gl,p=e.transform,m=e.getDepthModeForSublayer(0,pn.ReadOnly),h=hn.disabled,g=e.colorModeForRenderPass(),_=[],v=p.getCircleRadiusCorrection();for(let a of i){let i=n.getTile(a),s=i.getBucket(r);if(!s)continue;let c=r.paint.get(`circle-translate`),l=r.paint.get(`circle-translate-anchor`),d=t.aL(p,i,c,l),f=s.programConfigurations.get(r.id),m=e.useProgram(`circle`,f),h=s.layoutVertexBuffer,g=s.indexBuffer,y=e.style.map.terrain?.getTerrainData(a),b={programConfiguration:f,program:m,layoutVertexBuffer:h,indexBuffer:g,uniformValues:nr(e,i,r,d,v),terrainData:y,projectionData:p.getProjectionData({overscaledTileID:a,applyGlobeMatrix:!o,applyTerrainMatrix:!0})};if(u){let e=s.segments.get();for(let n of e)_.push({segments:new t.aV([n]),sortKey:n.sortKey,state:b})}else _.push({segments:s.segments,sortKey:0,state:b})}u&&_.sort(((e,t)=>e.sortKey-t.sortKey));for(let t of _){let{programConfiguration:n,program:i,layoutVertexBuffer:a,indexBuffer:o,uniformValues:s,terrainData:c,projectionData:l}=t.state;i.draw(d,f.TRIANGLES,m,h,g,fn.backCCW,s,c,l,r.id,a,o,t.segments,r.paint,e.transform.zoom,n)}},heatmap:function(e,n,r,i,a){if(r.paint.get(`heatmap-opacity`)===0)return;let o=e.context,{isRenderingToTexture:s,isRenderingGlobe:c}=a;if(e.style.map.terrain){for(let t of i){let i=n.getTile(t);n.hasRenderableParent(t)||(e.renderPass===`offscreen`?yi(e,i,r,t,c):e.renderPass===`translucent`&&bi(e,r,t,s,c))}o.viewport.set([0,0,e.width,e.height])}else e.renderPass===`offscreen`?function(e,n,r,i){let a=e.context,o=a.gl,s=e.transform,c=hn.disabled,l=new un([o.ONE,o.ONE],t.bo.transparent,[!0,!0,!0,!0]);(function(e,n,r){let i=e.gl;e.activeTexture.set(i.TEXTURE1),e.viewport.set([0,0,n.width/4,n.height/4]);let a=r.heatmapFbos.get(t.cd);a?(i.bindTexture(i.TEXTURE_2D,a.colorAttachment.get()),e.bindFramebuffer.set(a.framebuffer)):(a=xi(e,n.width/4,n.height/4),r.heatmapFbos.set(t.cd,a))})(a,e,r),a.clear({color:t.bo.transparent});for(let t of i){if(n.hasRenderableParent(t))continue;let i=n.getTile(t),u=i.getBucket(r);if(!u)continue;let d=u.programConfigurations.get(r.id),f=e.useProgram(`heatmap`,d),p=s.getProjectionData({overscaledTileID:t,applyGlobeMatrix:!0,applyTerrainMatrix:!1}),m=s.getCircleRadiusCorrection();f.draw(a,o.TRIANGLES,pn.disabled,c,l,fn.backCCW,or(i,s.zoom,r.paint.get(`heatmap-intensity`),m),null,p,r.id,u.layoutVertexBuffer,u.indexBuffer,u.segments,r.paint,s.zoom,d)}a.viewport.set([0,0,e.width,e.height])}(e,n,r,i):e.renderPass===`translucent`&&function(e,n){let r=e.context,i=r.gl;r.setColorMode(e.colorModeForRenderPass());let a=n.heatmapFbos.get(t.cd);a&&(r.activeTexture.set(i.TEXTURE0),i.bindTexture(i.TEXTURE_2D,a.colorAttachment.get()),r.activeTexture.set(i.TEXTURE1),Si(r,n).bind(i.LINEAR,i.CLAMP_TO_EDGE),e.useProgram(`heatmapTexture`).draw(r,i.TRIANGLES,pn.disabled,hn.disabled,e.colorModeForRenderPass(),fn.disabled,sr(e,n,0,1),null,null,n.id,e.viewportBuffer,e.quadTriangleIndexBuffer,e.viewportSegments,n.paint,e.transform.zoom))}(e,r)},line:function(e,t,n,r,i){if(e.renderPass!==`translucent`)return;let{isRenderingToTexture:a}=i,o=n.paint.get(`line-opacity`),s=n.paint.get(`line-width`);if(o.constantOr(1)===0||s.constantOr(1)===0)return;let c=e.getDepthModeForSublayer(0,pn.ReadOnly),l=e.colorModeForRenderPass(),u=n.paint.get(`line-dasharray`),d=u.constantOr(1),f=n.paint.get(`line-pattern`),p=f.constantOr(1),m=n.paint.get(`line-gradient`),h=n.getCrossfadeParameters(),g;g=p?`linePattern`:d&&m?`lineGradientSDF`:d?`lineSDF`:m?`lineGradient`:`line`;let _=e.context,v=_.gl,y=e.transform,b=!0;for(let i of r){let r=t.getTile(i);if(p&&!r.patternsLoaded())continue;let o=r.getBucket(n);if(!o)continue;let s=o.programConfigurations.get(n.id),x=e.context.program.get(),S=e.useProgram(g,s),C=b||S.program!==x,w=e.style.map.terrain?.getTerrainData(i),T=f.constantOr(null),E=u?.constantOr(null);if(T&&r.imageAtlas){let e=r.imageAtlas,t=e.patternPositions[T.to.toString()],n=e.patternPositions[T.from.toString()];t&&n&&s.setConstantPatternPositions(t,n)}else if(E){let t=n.layout.get(`line-cap`).constantOr(null)===`round`,r=e.lineAtlas.getDash(E.to,t),i=e.lineAtlas.getDash(E.from,t);s.setConstantDashPositions(r,i)}let D=y.getProjectionData({overscaledTileID:i,applyGlobeMatrix:!a,applyTerrainMatrix:!0}),O=y.getPixelScale(),k;p?(k=mr(e,r,n,O,h),wi(_,v,r,s,h)):d&&m?(k=gr(e,r,n,O,h,o.lineClipsArray.length),Di(e,t,_,v,n,o,i,s,h)):d?(k=hr(e,r,n,O,h),Ti(e,_,v,s,C,h)):m?(k=pr(e,r,n,O,o.lineClipsArray.length),Ei(e,t,_,v,n,o,i)):k=fr(e,r,n,O);let A=e.stencilModeForClipping(i);S.draw(_,v.TRIANGLES,c,A,l,fn.disabled,k,w,D,n.id,o.layoutVertexBuffer,o.indexBuffer,o.segments,n.paint,e.transform.zoom,s,o.layoutVertexBuffer2),b=!1}},fill:function(e,n,r,i,a){let o=r.paint.get(`fill-color`),s=r.paint.get(`fill-opacity`);if(s.constantOr(1)===0)return;let{isRenderingToTexture:c}=a,l=e.colorModeForRenderPass(),u=r.paint.get(`fill-pattern`),d=e.opaquePassEnabledForLayer()&&!u.constantOr(1)&&o.constantOr(t.bo.transparent).a===1&&s.constantOr(0)===1?`opaque`:`translucent`;e.renderPass===d&&ki(e,n,r,i,e.getDepthModeForSublayer(1,e.renderPass===`opaque`?pn.ReadWrite:pn.ReadOnly),l,!1,c),e.renderPass===`translucent`&&r.paint.get(`fill-antialias`)&&ki(e,n,r,i,e.getDepthModeForSublayer(r.getPaintProperty(`fill-outline-color`)?2:0,pn.ReadOnly),l,!0,c)},fillExtrusion:function(e,t,n,r,i){let a=n.paint.get(`fill-extrusion-opacity`);if(a===0)return;let{isRenderingToTexture:o}=i;if(e.renderPass===`translucent`){let i=new pn(e.context.gl.LEQUAL,pn.ReadWrite,e.depthRangeFor3D);if(a!==1||n.paint.get(`fill-extrusion-pattern`).constantOr(1))Ai(e,t,n,r,i,hn.disabled,un.disabled,o),Ai(e,t,n,r,i,e.stencilModeFor3D(),e.colorModeForRenderPass(),o);else{let a=e.colorModeForRenderPass();Ai(e,t,n,r,i,hn.disabled,a,o)}}},hillshade:function(e,n,r,i,a){if(e.renderPass!==`offscreen`&&e.renderPass!==`translucent`)return;let{isRenderingToTexture:o}=a,s=e.context,c=e.style.projection.useSubdivision,l=e.getDepthModeForSublayer(0,pn.ReadOnly),u=e.colorModeForRenderPass();if(e.renderPass===`offscreen`)(function(e,n,r,i,a,o,s){let c=e.context,l=c.gl,u=i.paint.get(`resampling`)===`nearest`?l.NEAREST:l.LINEAR;for(let d of r){let r=n.getTile(d),f=r.dem;if(!f?.data||!r.needsHillshadePrepare)continue;let p=f.dim,m=f.stride,h=f.getPixels();if(c.activeTexture.set(l.TEXTURE1),c.pixelStoreUnpackPremultiplyAlpha.set(!1),r.demTexture||=e.getTileTexture(m),r.demTexture){let e=r.demTexture;e.update(h,{premultiply:!1}),e.bind(l.NEAREST,l.CLAMP_TO_EDGE)}else r.demTexture=new t.T(c,h,l.RGBA,{premultiply:!1}),r.demTexture.bind(l.NEAREST,l.CLAMP_TO_EDGE);c.activeTexture.set(l.TEXTURE0);let g=r.fbo;if(!g){let e=new t.T(c,{width:p,height:p,data:null},l.RGBA);e.bind(u,l.CLAMP_TO_EDGE),g=r.fbo=c.createFramebuffer(p,p,!0,!1),g.colorAttachment.set(e.texture)}c.bindFramebuffer.set(g.framebuffer),c.viewport.set([0,0,p,p]),e.useProgram(`hillshadePrepare`).draw(c,l.TRIANGLES,a,o,s,fn.disabled,lr(r.tileID,f),null,null,i.id,e.rasterBoundsBuffer,e.quadTriangleIndexBuffer,e.rasterBoundsSegments),r.needsHillshadePrepare=!1}})(e,n,i,r,l,hn.disabled,u),s.viewport.set([0,0,e.width,e.height]);else if(e.renderPass===`translucent`)if(c){let[t,a,s]=e.stencilConfigForOverlapTwoPass(i);ji(e,n,r,s,t,l,u,!1,o),ji(e,n,r,s,a,l,u,!0,o)}else{let[t,a]=e.getStencilConfigForOverlapAndUpdateStencilID(i);ji(e,n,r,a,t,l,u,!1,o)}},colorRelief:function(e,t,n,r,i){if(e.renderPass!==`translucent`||!r.length)return;let{isRenderingToTexture:a}=i,o=e.style.projection.useSubdivision,s=e.getDepthModeForSublayer(0,pn.ReadOnly),c=e.colorModeForRenderPass();if(o){let[i,o,l]=e.stencilConfigForOverlapTwoPass(r);Ni(e,t,n,l,i,s,c,!1,a),Ni(e,t,n,l,o,s,c,!0,a)}else{let[i,o]=e.getStencilConfigForOverlapAndUpdateStencilID(r);Ni(e,t,n,o,i,s,c,!1,a)}},raster:function(e,t,n,r,i){if(e.renderPass!==`translucent`||n.paint.get(`raster-opacity`)===0||!r.length)return;let{isRenderingToTexture:a}=i,o=t.getSource(),s=e.style.projection.useSubdivision;if(o instanceof Ce)Fi(e,t,n,r,null,!1,!1,o.tileCoords,o.flippedWindingOrder,a);else if(s){let[i,o,s]=e.stencilConfigForOverlapTwoPass(r);Fi(e,t,n,s,i,!1,!0,Pi,!1,a),Fi(e,t,n,s,o,!0,!0,Pi,!1,a)}else{let[i,o]=e.getStencilConfigForOverlapAndUpdateStencilID(r);Fi(e,t,n,o,i,!1,!0,Pi,!1,a)}},background:function(e,t,n,r,i){let a=n.paint.get(`background-color`),o=n.paint.get(`background-opacity`);if(o===0)return;let{isRenderingToTexture:s}=i,c=e.context,l=c.gl,u=e.style.projection,d=e.transform,f=d.tileSize,p=n.paint.get(`background-pattern`);if(e.isPatternMissing(p))return;let m=!p&&a.a===1&&o===1&&e.opaquePassEnabledForLayer()?`opaque`:`translucent`;if(e.renderPass!==m)return;let h=hn.disabled,g=e.getDepthModeForSublayer(0,m===`opaque`?pn.ReadWrite:pn.ReadOnly),_=e.colorModeForRenderPass(),v=e.useProgram(p?`backgroundPattern`:`background`),y=r||We(d,{tileSize:f,terrain:e.style.map.terrain});p&&(c.activeTexture.set(l.TEXTURE0),e.imageManager.bind(e.context));let b=n.getCrossfadeParameters();for(let t of y){let r=d.getProjectionData({overscaledTileID:t,applyGlobeMatrix:!s,applyTerrainMatrix:!0}),i=p?Tr(o,e,p,{tileID:t,tileSize:f},b):wr(o,a),m=e.style.map.terrain?.getTerrainData(t),y=u.getMeshFromTileID(c,t.canonical,!1,!0,`raster`);v.draw(c,l.TRIANGLES,g,h,_,fn.backCCW,i,m,r,n.id,y.vertexBuffer,y.indexBuffer,y.segments)}},sky:function(e,t){let n=e.context,r=n.gl,i=((e,t,n)=>{let r=Math.cos(t.rollInRadians),i=Math.sin(t.rollInRadians),a=ze(t),o=t.getProjectionData({overscaledTileID:null,applyGlobeMatrix:!0,applyTerrainMatrix:!0}).projectionTransition;return{u_sky_color:e.properties.get(`sky-color`),u_horizon_color:e.properties.get(`horizon-color`),u_horizon:[(t.width/2-a*i)*n,(t.height/2+a*r)*n],u_horizon_normal:[-i,r],u_sky_horizon_blend:e.properties.get(`sky-horizon-blend`)*t.height/2*n,u_sky_blend:o}})(t,e.style.map.transform,e.pixelRatio),a=new pn(r.LEQUAL,pn.ReadWrite,[0,1]),o=hn.disabled,s=e.colorModeForRenderPass(),c=e.useProgram(`sky`),l=qi(n,t);c.draw(n,r.TRIANGLES,a,o,s,fn.disabled,i,null,void 0,`sky`,l.vertexBuffer,l.indexBuffer,l.segments)},atmosphere:function(e,n,r){let i=e.context,a=i.gl,o=e.useProgram(`atmosphere`),s=new pn(a.LEQUAL,pn.ReadOnly,[0,1]),c=e.transform,l=function(e,n){let r=e.properties.get(`position`),i=[-r.x,-r.y,-r.z],a=t.ap(new Float64Array(16));return e.properties.get(`anchor`)===`map`&&(t.be(a,a,n.rollInRadians),t.bf(a,a,-n.pitchInRadians),t.be(a,a,n.bearingInRadians),t.bf(a,a,n.center.lat*Math.PI/180),t.bI(a,a,-n.center.lng*Math.PI/180)),t.cg(i,i,a),i}(r,e.transform),u=c.getProjectionData({overscaledTileID:null,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),d=n.properties.get(`atmosphere-blend`)*u.projectionTransition;if(d===0)return;let f=Tn(c.worldSize,c.center.lat),p=c.inverseProjectionMatrix,m=new Float64Array(4);m[3]=1,t.aE(m,m,c.modelViewProjectionMatrix),m[0]/=m[3],m[1]/=m[3],m[2]/=m[3],m[3]=1,t.aE(m,m,p),m[0]/=m[3],m[1]/=m[3],m[2]/=m[3],m[3]=1;let h=((e,t,n,r,i)=>({u_sun_pos:e,u_atmosphere_blend:t,u_globe_position:n,u_globe_radius:r,u_inv_proj_matrix:i}))(l,d,[m[0],m[1],m[2]],f,p),g=qi(i,n);o.draw(i,a.TRIANGLES,s,hn.disabled,un.alphaBlended,fn.disabled,h,null,null,`atmosphere`,g.vertexBuffer,g.indexBuffer,g.segments)},custom:function(e,t,n,r){let{isRenderingGlobe:i}=r,a=e.context,o=n.implementation,s=e.style.projection,c=e.transform,l=c.getProjectionDataForCustomLayer(i),u={farZ:c.farZ,nearZ:c.nearZ,fov:c.fov*Math.PI/180,modelViewProjectionMatrix:c.modelViewProjectionMatrix,projectionMatrix:c.projectionMatrix,shaderData:{variantName:s.shaderVariantName,vertexShaderPrelude:`const float PI = 3.141592653589793;\nuniform mat4 u_projection_matrix;\n${s.shaderPreludeCode.vertexSource}`,define:s.shaderDefine},defaultProjectionData:l},d=o.renderingMode?o.renderingMode:`2d`;if(e.renderPass===`offscreen`){let t=o.prerender;t&&(e.setCustomLayerDefaults(),a.setColorMode(e.colorModeForRenderPass()),t.call(o,a.gl,u),a.setDirty(),e.setBaseState())}else if(e.renderPass===`translucent`){e.setCustomLayerDefaults(),a.setColorMode(e.colorModeForRenderPass()),a.setStencilMode(hn.disabled);let t=d===`3d`?e.getDepthModeFor3D():e.getDepthModeForSublayer(0,pn.ReadOnly);a.setDepthMode(t),o.render(a.gl,u),a.setDirty(),e.setBaseState(),a.bindFramebuffer.set(null)}},debug:function(e,t,n){for(let r of n)Gi(e,t,r)},debugPadding:function(e){let t=e.transform.padding;Hi(e,e.transform.height-(t.top||0),3,Li),Hi(e,t.bottom||0,3,Ri),Ui(e,t.left||0,3,zi),Ui(e,e.transform.width-(t.right||0),3,Bi);let n=e.transform.centerPoint;(function(e,t,n,r){Wi(e,t-1,n-10,2,20,r),Wi(e,t-10,n-1,20,2,r)})(e,n.x,e.transform.height-n.y,Vi)},terrainDepth:function(e,n){let r=e.context,i=r.gl,a=e.transform,o=un.unblended,s=new pn(i.LEQUAL,pn.ReadWrite,[0,1]),c=n.tileManager.getRenderableTiles(),l=e.useProgram(`terrainDepth`);r.bindFramebuffer.set(n.getFramebuffer(`depth`).framebuffer),r.viewport.set([0,0,e.width/devicePixelRatio,e.height/devicePixelRatio]),r.clear({color:t.bo.transparent,depth:1});for(let e of c){let t=n.getTerrainMesh(e.tileID),c=n.getTerrainData(e.tileID),u=a.getProjectionData({overscaledTileID:e.tileID,applyTerrainMatrix:!1,applyGlobeMatrix:!0}),d={u_ele_delta:n.getMeshFrameDelta(a.zoom)};l.draw(r,i.TRIANGLES,s,hn.disabled,o,fn.backCCW,d,c,u,`terrain`,t.vertexBuffer,t.indexBuffer,t.segments)}r.bindFramebuffer.set(null),r.viewport.set([0,0,e.width,e.height])},terrainCoords:function(e,n){let r=e.context,i=r.gl,a=e.transform,o=un.unblended,s=new pn(i.LEQUAL,pn.ReadWrite,[0,1]),c=n.getCoordsTexture(),l=n.tileManager.getRenderableTiles(),u=e.useProgram(`terrainCoords`);r.bindFramebuffer.set(n.getFramebuffer(`coords`).framebuffer),r.viewport.set([0,0,e.width/devicePixelRatio,e.height/devicePixelRatio]),r.clear({color:t.bo.transparent,depth:1}),n.coordsIndex=[];for(let e of l){let t=n.getTerrainMesh(e.tileID),l=n.getTerrainData(e.tileID);r.activeTexture.set(i.TEXTURE0),i.bindTexture(i.TEXTURE_2D,c.texture);let d={u_terrain_coords_id:(255-n.coordsIndex.length)/255,u_texture:0,u_ele_delta:n.getMeshFrameDelta(a.zoom)},f=a.getProjectionData({overscaledTileID:e.tileID,applyTerrainMatrix:!1,applyGlobeMatrix:!0});u.draw(r,i.TRIANGLES,s,hn.disabled,o,fn.backCCW,d,l,f,`terrain`,t.vertexBuffer,t.indexBuffer,t.segments),n.coordsIndex.push(e.tileID.key)}r.bindFramebuffer.set(null),r.viewport.set([0,0,e.width,e.height])}};class Yi{constructor(e,n){this.drawFunctions=Ji,this.context=new ui(e),this.transform=n,this._tileTextures={},this.terrainFacilitator={depthDirty:!0,coordsDirty:!1,matrix:t.ap(new Float64Array(16)),renderTime:0},this.setup(),this.numSublayers=Qe.maxOverzooming+Qe.maxUnderzooming+1,this.depthEpsilon=1/2**16,this.crossTileSymbolIndex=new Wt}resize(e,t,n){if(this.width=Math.floor(e*n),this.height=Math.floor(t*n),this.pixelRatio=n,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(let e of this.style._order)this.style._layers[e].resize()}setup(){let e=this.context,n=new t.aU;n.emplaceBack(0,0),n.emplaceBack(t.a6,0),n.emplaceBack(0,t.a6),n.emplaceBack(t.a6,t.a6),this.tileExtentBuffer=e.createVertexBuffer(n,Yt.members),this.tileExtentSegments=t.aV.simpleSegment(0,0,4,2);let r=new t.aU;r.emplaceBack(0,0),r.emplaceBack(t.a6,0),r.emplaceBack(0,t.a6),r.emplaceBack(t.a6,t.a6),this.debugBuffer=e.createVertexBuffer(r,Yt.members),this.debugSegments=t.aV.simpleSegment(0,0,4,5);let i=new t.ch;i.emplaceBack(0,0,0,0),i.emplaceBack(t.a6,0,t.a6,0),i.emplaceBack(0,t.a6,0,t.a6),i.emplaceBack(t.a6,t.a6,t.a6,t.a6),this.rasterBoundsBuffer=e.createVertexBuffer(i,Wn.members),this.rasterBoundsSegments=t.aV.simpleSegment(0,0,4,2);let a=new t.aU;a.emplaceBack(0,0),a.emplaceBack(t.a6,0),a.emplaceBack(0,t.a6),a.emplaceBack(t.a6,t.a6),this.rasterBoundsBufferPosOnly=e.createVertexBuffer(a,Yt.members),this.rasterBoundsSegmentsPosOnly=t.aV.simpleSegment(0,0,4,5);let o=new t.aU;o.emplaceBack(0,0),o.emplaceBack(1,0),o.emplaceBack(0,1),o.emplaceBack(1,1),this.viewportBuffer=e.createVertexBuffer(o,Yt.members),this.viewportSegments=t.aV.simpleSegment(0,0,4,2);let s=new t.ci;s.emplaceBack(0),s.emplaceBack(1),s.emplaceBack(3),s.emplaceBack(2),s.emplaceBack(0),this.tileBorderIndexBuffer=e.createIndexBuffer(s);let c=new t.aW;c.emplaceBack(1,0,2),c.emplaceBack(1,2,3),this.quadTriangleIndexBuffer=e.createIndexBuffer(c);let l=this.context.gl;this.stencilClearMode=new hn({func:l.ALWAYS,mask:0},0,255,l.ZERO,l.ZERO,l.ZERO),this.tileExtentMesh=new Jt(this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments)}clearStencil(){let e=this.context,n=e.gl;this.nextStencilID=1,this.currentStencilSource=void 0;let r=t.O();t.c7(r,0,this.width,this.height,0,0,1),t.S(r,r,[n.drawingBufferWidth,n.drawingBufferHeight,0]);let i={mainMatrix:r,tileMercatorCoords:[0,0,1,1],clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:r};this.useProgram(`clippingMask`,null,!0).draw(e,n.TRIANGLES,pn.disabled,this.stencilClearMode,un.disabled,fn.disabled,null,null,i,`$clipping`,this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}_renderTileClippingMasks(e,t,n){if(this.currentStencilSource===e.source||!e.isTileClipped()||!t?.length)return;this.currentStencilSource=e.source,this.nextStencilID+t.length>256&&this.clearStencil();let r=this.context;r.setColorMode(un.disabled),r.setDepthMode(pn.disabled);let i={};for(let e of t)i[e.key]=this.nextStencilID++;this._renderTileMasks(i,t,n,!0),this._renderTileMasks(i,t,n,!1),this._tileClippingMaskIDs=i}_renderTileMasks(e,t,n,r){let i=this.context,a=i.gl,o=this.style.projection,s=this.transform,c=this.useProgram(`clippingMask`);for(let l of t){let t=e[l.key],u=this.style.map.terrain?.getTerrainData(l),d=o.getMeshFromTileID(this.context,l.canonical,r,!0,`stencil`),f=s.getProjectionData({overscaledTileID:l,applyGlobeMatrix:!n,applyTerrainMatrix:!0});c.draw(i,a.TRIANGLES,pn.disabled,new hn({func:a.ALWAYS,mask:0},t,255,a.KEEP,a.KEEP,a.REPLACE),un.disabled,n?fn.disabled:fn.backCCW,null,u,f,`$clipping`,d.vertexBuffer,d.indexBuffer,d.segments)}}_renderTilesDepthBuffer(){let e=this.context,t=e.gl,n=this.style.projection,r=this.transform,i=this.useProgram(`depth`),a=this.getDepthModeFor3D(),o=We(r,{tileSize:r.tileSize});for(let s of o){let o=this.style.map.terrain?.getTerrainData(s),c=n.getMeshFromTileID(this.context,s.canonical,!0,!0,`raster`),l=r.getProjectionData({overscaledTileID:s,applyGlobeMatrix:!0,applyTerrainMatrix:!0});i.draw(e,t.TRIANGLES,a,hn.disabled,un.disabled,fn.backCCW,null,o,l,`$clipping`,c.vertexBuffer,c.indexBuffer,c.segments)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();let e=this.nextStencilID++,t=this.context.gl;return new hn({func:t.NOTEQUAL,mask:255},e,255,t.KEEP,t.KEEP,t.REPLACE)}stencilModeForClipping(e){let t=this.context.gl;return new hn({func:t.EQUAL,mask:255},this._tileClippingMaskIDs[e.key],0,t.KEEP,t.KEEP,t.REPLACE)}getStencilConfigForOverlapAndUpdateStencilID(e){let t=this.context.gl,n=e.sort(((e,t)=>t.overscaledZ-e.overscaledZ)),r=n[n.length-1].overscaledZ,i=n[0].overscaledZ-r+1;if(i>1){this.currentStencilSource=void 0,this.nextStencilID+i>256&&this.clearStencil();let e={};for(let n=0;n<i;n++)e[n+r]=new hn({func:t.GEQUAL,mask:255},n+this.nextStencilID,255,t.KEEP,t.KEEP,t.REPLACE);return this.nextStencilID+=i,[e,n]}return[{[r]:hn.disabled},n]}stencilConfigForOverlapTwoPass(e){let t=this.context.gl,n=e.sort(((e,t)=>t.overscaledZ-e.overscaledZ)),r=n[n.length-1].overscaledZ,i=n[0].overscaledZ-r+1;if(this.clearStencil(),i>1){let e={},a={};for(let n=0;n<i;n++)e[n+r]=new hn({func:t.GREATER,mask:255},i+1+n,255,t.KEEP,t.KEEP,t.REPLACE),a[n+r]=new hn({func:t.GREATER,mask:255},1+n,255,t.KEEP,t.KEEP,t.REPLACE);return this.nextStencilID=2*i+1,[e,a,n]}return this.nextStencilID=3,[{[r]:new hn({func:t.GREATER,mask:255},2,255,t.KEEP,t.KEEP,t.REPLACE)},{[r]:new hn({func:t.GREATER,mask:255},1,255,t.KEEP,t.KEEP,t.REPLACE)},n]}colorModeForRenderPass(){let e=this.context.gl;if(this._showOverdrawInspector){let n=1/8;return new un([e.CONSTANT_COLOR,e.ONE],new t.bo(n,n,n,0),[!0,!0,!0,!0])}return this.renderPass===`opaque`?un.unblended:un.alphaBlended}getDepthModeForSublayer(e,t,n){if(!this.opaquePassEnabledForLayer())return pn.disabled;let r=1-((1+this.currentLayer)*this.numSublayers+e)*this.depthEpsilon;return new pn(n||this.context.gl.LEQUAL,t,[r,r])}getDepthModeFor3D(){return new pn(this.context.gl.LEQUAL,pn.ReadWrite,this.depthRangeFor3D)}opaquePassEnabledForLayer(){return this.currentLayer<this.opaquePassCutoff}render(e,n){var r;this.style=e,this.options=n,this.lineAtlas=e.lineAtlas,this.imageManager=e.imageManager,this.glyphManager=e.glyphManager,this.symbolFadeChange=e.placement.symbolFadeChange(l()),this.imageManager.beginFrame();let i=this.style._order,a=this.style.tileManagers,o={},s={},c={},u={isRenderingToTexture:!1,isRenderingGlobe:e.projection?.transitionState>0};for(let e in a){let t=a[e];t.used&&t.prepare(this.context),o[e]=t.getVisibleCoordinates(!1),s[e]=o[e].slice().reverse(),c[e]=t.getVisibleCoordinates(!0).reverse()}this.opaquePassCutoff=1/0;for(let e=0;e<i.length;e++)if(this.style._layers[i[e]].is3D()){this.opaquePassCutoff=e;break}this.maybeDrawDepth(!1),this.renderToTexture&&(this.renderToTexture.prepareForRender(this.style,this.transform.zoom),this.opaquePassCutoff=0),this.renderPass=`offscreen`;for(let e of i){let t=this.style._layers[e];if(!t.hasOffscreenPass()||t.isHidden(this.transform.zoom))continue;let n=s[t.source];(t.type===`custom`||n.length)&&this.renderLayer(this,a[t.source],t,n,u)}if((r=this.style.projection)==null||r.updateGPUdependent({context:this.context,useProgram:e=>this.useProgram(e)}),this.context.viewport.set([0,0,this.width,this.height]),this.context.bindFramebuffer.set(null),this.context.clear({color:n.showOverdrawInspector?t.bo.black:t.bo.transparent,depth:1}),this.clearStencil(),this.style.sky&&this.drawFunctions.sky(this,this.style.sky),this._showOverdrawInspector=n.showOverdrawInspector,this.depthRangeFor3D=[0,1-(e._order.length+2)*this.numSublayers*this.depthEpsilon],!this.renderToTexture)for(this.renderPass=`opaque`,this.currentLayer=i.length-1;this.currentLayer>=0;this.currentLayer--){let e=this.style._layers[i[this.currentLayer]],t=a[e.source],n=o[e.source];this._renderTileClippingMasks(e,n,!1),this.renderLayer(this,t,e,n,u)}this.renderPass=`translucent`;let d=!1;for(this.currentLayer=0;this.currentLayer<i.length;this.currentLayer++){let e=this.style._layers[i[this.currentLayer]],t=a[e.source];if(this.renderToTexture?.renderLayer(e,u))continue;this.opaquePassEnabledForLayer()||d||(d=!0,u.isRenderingGlobe&&!this.style.map.terrain&&this._renderTilesDepthBuffer());let n=(e.type===`symbol`?c:s)[e.source];this._renderTileClippingMasks(e,o[e.source],!!this.renderToTexture),this.renderLayer(this,t,e,n,u)}if(u.isRenderingGlobe&&this.drawFunctions.atmosphere(this,this.style.sky,this.style.light),this.options.showTileBoundaries){let e=function(e,t){let n=null,r=Object.values(e._layers).flatMap((n=>n.source&&!n.isHidden(t)?[e.tileManagers[n.source]]:[])),i=r.filter((e=>e.getSource().type===`vector`)),a=r.filter((e=>e.getSource().type!==`vector`)),o=e=>{(!n||n.getSource().maxzoom<e.getSource().maxzoom)&&(n=e)};for(let e of i)o(e);if(!n)for(let e of a)o(e);return n}(this.style,this.transform.zoom);e&&this.drawFunctions.debug(this,e,e.getVisibleCoordinates())}this.options.showPadding&&this.drawFunctions.debugPadding(this),this.context.setDefault()}maybeDrawDepth(e){if(!this.style?.map?.terrain)return;let n=this.terrainFacilitator.matrix,r=this.transform.modelViewProjectionMatrix,i=this.terrainFacilitator.depthDirty;i||=e?!t.cj(n,r):!t.ck(n,r),i||=this.style.map.terrain.tileManager.anyTilesAfterTime(this.terrainFacilitator.renderTime),i&&(t.cl(n,r),this.terrainFacilitator.renderTime=Date.now(),this.terrainFacilitator.depthDirty=!1,this.terrainFacilitator.coordsDirty=!0,this.drawFunctions.terrainDepth(this,this.style.map.terrain))}maybeDrawCoords(){var e;(e=this.style?.map)!=null&&e.terrain&&this.terrainFacilitator.coordsDirty&&(this.terrainFacilitator.coordsDirty=!1,this.drawFunctions.terrainCoords(this,this.style.map.terrain))}renderLayer(e,n,r,i,a){if(r.isHidden(this.transform.zoom)||r.type!==`background`&&r.type!==`custom`&&!(i||[]).length)return;this.id=r.id;let o=this.drawFunctions;t.aQ(r)?o.symbol(e,n,r,i,this.style.placement.variableOffsets,a):t.cm(r)?o.circle(e,n,r,i,a):t.cn(r)?o.heatmap(e,n,r,i,a):t.co(r)?o.line(e,n,r,i,a):t.cp(r)?o.fill(e,n,r,i,a):t.cq(r)?o.fillExtrusion(e,n,r,i,a):t.cr(r)?o.hillshade(e,n,r,i,a):t.cs(r)?o.colorRelief(e,n,r,i,a):t.bU(r)?o.raster(e,n,r,i,a):t.ct(r)?o.background(e,n,r,i,a):t.cu(r)&&o.custom(e,n,r,a)}saveTileTexture(e){let t=this._tileTextures[e.size[0]];t?t.length<Yi.MAX_TEXTURE_POOL_SIZE_PER_BUCKET?t.push(e):e.destroy():this._tileTextures[e.size[0]]=[e]}getTileTexture(e){let t=this._tileTextures[e];return t&&t.length>0?t.pop():null}isPatternMissing(e){if(!e)return!1;if(!e.from||!e.to)return!0;let t=this.imageManager.getPattern(e.from.toString()),n=this.imageManager.getPattern(e.to.toString());return!t||!n}useProgram(e,t,n=!1,r=[]){var i;this.cache||={};let a=!!this.style.map.terrain,o=this.style.projection,s=n?Kt.projectionMercator:o.shaderPreludeCode,c=n?Xt:o.shaderDefine,l=e+(t?t.cacheKey:``)+`/${n?Zt:o.shaderVariantName}`+(this._showOverdrawInspector?`/overdraw`:``)+(a?`/terrain`:``)+(r?`/${r.join(`/`)}`:``);return(i=this.cache)[l]||(i[l]=new Yn(this.context,Kt[e],t,Dr[e],this._showOverdrawInspector,a,s,c,r)),this.cache[l]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault()}setBaseState(){let e=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(e.FUNC_ADD)}initDebugOverlayCanvas(){this.debugOverlayCanvas??(this.debugOverlayCanvas=document.createElement(`canvas`),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new t.T(this.context,this.debugOverlayCanvas,this.context.gl.RGBA))}destroy(){var e,t;if(this._tileTextures){for(let e in this._tileTextures){let t=this._tileTextures[e];if(t)for(let e of t)e.destroy()}this._tileTextures={}}if(this.tileExtentBuffer&&this.tileExtentBuffer.destroy(),this.debugBuffer&&this.debugBuffer.destroy(),this.rasterBoundsBuffer&&this.rasterBoundsBuffer.destroy(),this.rasterBoundsBufferPosOnly&&this.rasterBoundsBufferPosOnly.destroy(),this.viewportBuffer&&this.viewportBuffer.destroy(),this.tileBorderIndexBuffer&&this.tileBorderIndexBuffer.destroy(),this.quadTriangleIndexBuffer&&this.quadTriangleIndexBuffer.destroy(),this.tileExtentMesh&&((e=this.tileExtentMesh.vertexBuffer)==null||e.destroy()),this.tileExtentMesh&&((t=this.tileExtentMesh.indexBuffer)==null||t.destroy()),this.debugOverlayTexture&&this.debugOverlayTexture.destroy(),this.cache){for(let e in this.cache){let t=this.cache[e];t!=null&&t.program&&this.context.gl.deleteProgram(t.program)}this.cache={}}this.context&&this.context.setDefault()}overLimit(){let{drawingBufferWidth:e,drawingBufferHeight:t}=this.context.gl;return this.width!==e||this.height!==t}}function Xi(e,t){let n,r=!1,i=null,a=()=>{i=null,r&&=(e(...n),i=setTimeout(a,t),!1)};return(...e)=>(r=!0,n=e,i||a(),i)}Yi.MAX_TEXTURE_POOL_SIZE_PER_BUCKET=50;class Zi{constructor(e){this._getCurrentHash=()=>{let e=window.location.hash.replace(`#`,``);if(this._hashName){let t,n=e.split(`&`).map((e=>e.split(`=`)));for(let e of n)e[0]===this._hashName&&(t=e);return(t&&t[1]||``).split(`/`)}return e.split(`/`)},this._onHashChange=()=>{let e=this._getCurrentHash();if(!this._isValidHash(e))return!1;let t=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(e[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+e[2],+e[1]],zoom:+e[0],bearing:t,pitch:+(e[4]||0)}),!0},this._updateHashUnthrottled=()=>{let e=window.location.href.replace(/(#.*)?$/,this.getHashString());window.history.replaceState(window.history.state,null,e)},this._removeHash=()=>{let e=this._getCurrentHash();if(e.length===0)return;let t=e.join(`/`),n=t;n.split(`&`).length>0&&(n=n.split(`&`)[0]),this._hashName&&(n=`${this._hashName}=${t}`);let r=window.location.hash.replace(n,``);r.startsWith(`#&`)?r=r.slice(0,1)+r.slice(2):r===`#`&&(r=``);let i=window.location.href.replace(/(#.+)?$/,r);i=i.replace(`&&`,`&`),window.history.replaceState(window.history.state,null,i)},this._updateHash=Xi(this._updateHashUnthrottled,300),this._hashName=e&&encodeURIComponent(e)}addTo(e){return this._map=e,addEventListener(`hashchange`,this._onHashChange,!1),this._map.on(`moveend`,this._updateHash),this}remove(){return removeEventListener(`hashchange`,this._onHashChange,!1),this._map.off(`moveend`,this._updateHash),clearTimeout(this._updateHash()),this._removeHash(),delete this._map,this}getHashString(e){let t=this._map.getCenter(),n=Math.round(100*this._map.getZoom())/100,r=10**Math.ceil((n*Math.LN2+Math.log(512/360/.5))/Math.LN10),i=Math.round(t.lng*r)/r,a=Math.round(t.lat*r)/r,o=this._map.getBearing(),s=this._map.getPitch(),c=``;if(c+=e?`/${i}/${a}/${n}`:`${n}/${a}/${i}`,(o||s)&&(c+=`/`+Math.round(10*o)/10),s&&(c+=`/${Math.round(s)}`),this._hashName){let e=this._hashName,t=!1,n=window.location.hash.slice(1).split(`&`).map((n=>{let r=n.split(`=`)[0];return r===e?(t=!0,`${r}=${c}`):n})).filter((e=>e));return t||n.push(`${e}=${c}`),`#${n.join(`&`)}`}return`#${c}`}_isValidHash(e){if(e.length<3||e.some(isNaN))return!1;try{new t.W(+e[2],+e[1])}catch{return!1}let n=+e[0],r=+(e[3]||0),i=+(e[4]||0);return n>=this._map.getMinZoom()&&n<=this._map.getMaxZoom()&&r>=-180&&r<=180&&i>=this._map.getMinPitch()&&i<=this._map.getMaxPitch()}}let Qi={linearity:.3,easing:t.cv(0,0,.3,1)},$i=t.e({deceleration:2500,maxSpeed:1400},Qi),ea=t.e({deceleration:20,maxSpeed:1400},Qi),ta=t.e({deceleration:1e3,maxSpeed:360},Qi),X=t.e({deceleration:1e3,maxSpeed:90},Qi),na=t.e({deceleration:1e3,maxSpeed:360},Qi);class ra{constructor(e){this._map=e,this.clear()}clear(){this._inertiaBuffer=[]}record(e){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:l(),settings:e})}_drainInertiaBuffer(){let e=this._inertiaBuffer,t=l();for(;e.length>0&&t-e[0].time>160;)e.shift()}_onMoveEnd(e){if(this._drainInertiaBuffer(),this._inertiaBuffer.length<2)return;let n={zoom:0,bearing:0,pitch:0,roll:0,pan:new t.P(0,0),pinchAround:void 0,around:void 0};for(let{settings:e}of this._inertiaBuffer)n.zoom+=e.zoomDelta||0,n.bearing+=e.bearingDelta||0,n.pitch+=e.pitchDelta||0,n.roll+=e.rollDelta||0,e.panDelta&&n.pan._add(e.panDelta),e.around&&(n.around=e.around),e.pinchAround&&(n.pinchAround=e.pinchAround);let r=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,i={};if(n.pan.mag()){let a=aa(n.pan.mag(),r,t.e({},$i,e||{})),o=n.pan.mult(a.amount/n.pan.mag()),s=this._map.cameraHelper.handlePanInertia(o,this._map.transform);i.center=s.easingCenter,i.offset=s.easingOffset,ia(i,a)}if(n.zoom){let e=aa(n.zoom,r,ea);i.zoom=t.cw(this._map.transform.zoom+e.amount,this._map.getZoomSnap(),e.amount),ia(i,e)}if(n.bearing){let e=aa(n.bearing,r,ta);i.bearing=this._map.transform.bearing+t.al(e.amount,-179,179),ia(i,e)}if(n.pitch){let e=aa(n.pitch,r,X);i.pitch=this._map.transform.pitch+e.amount,ia(i,e)}if(n.roll){let e=aa(n.roll,r,na);i.roll=this._map.transform.roll+t.al(e.amount,-179,179),ia(i,e)}if(i.zoom||i.bearing){let e=n.pinchAround===void 0?n.around:n.pinchAround;i.around=e?this._map.unproject(e):this._map.getCenter()}return this.clear(),t.e(i,{noMoveStart:!0})}}function ia(e,t){(!e.duration||e.duration<t.duration)&&(e.duration=t.duration,e.easing=t.easing)}function aa(e,n,r){let{maxSpeed:i,linearity:a,deceleration:o}=r,s=t.al(e*a/(n/1e3),-i,i),c=Math.abs(s)/(o*a);return{easing:r.easing,duration:1e3*c,amount:c/2*s}}class oa extends t.n{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(e,n,r,i={}){r=r instanceof MouseEvent?r:new MouseEvent(e,r);let a=d.mousePos(n.getCanvas(),r),o=n.unproject(a);super(e,t.e({point:a,lngLat:o,originalEvent:r},i)),this._defaultPrevented=!1,this.target=n}}class sa extends t.n{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(e,n,r){let i=e===`touchend`?r.changedTouches:r.touches,a=d.touchPos(n.getCanvasContainer(),i),o=a.map((e=>n.unproject(e))),s=a.reduce(((e,t,n,r)=>e.add(t.div(r.length))),new t.P(0,0));super(e,{points:a,point:s,lngLats:o,lngLat:n.unproject(s),originalEvent:r}),this._defaultPrevented=!1}}class ca extends t.n{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(e,t,n){super(e,{originalEvent:n}),this._defaultPrevented=!1}}class la{constructor(e,t){this._map=e,this._clickTolerance=t.clickTolerance}reset(){delete this._mousedownPos}wheel(e){return this._firePreventable(new ca(e.type,this._map,e))}mousedown(e,t){return this._mousedownPos=t,this._firePreventable(new oa(e.type,this._map,e))}mouseup(e){this._map.fire(new oa(e.type,this._map,e))}click(e,t){this._mousedownPos&&this._mousedownPos.dist(t)>=this._clickTolerance||this._map.fire(new oa(e.type,this._map,e))}dblclick(e){return this._firePreventable(new oa(e.type,this._map,e))}mouseover(e){this._map.fire(new oa(e.type,this._map,e))}mouseout(e){this._map.fire(new oa(e.type,this._map,e))}touchstart(e){return this._firePreventable(new sa(e.type,this._map,e))}touchmove(e){this._map.fire(new sa(e.type,this._map,e))}touchend(e){this._map.fire(new sa(e.type,this._map,e))}touchcancel(e){this._map.fire(new sa(e.type,this._map,e))}_firePreventable(e){if(this._map.fire(e),e.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class ua{constructor(e){this._map=e}reset(){this._delayContextMenu=!1,this._ignoreContextMenu=!0,delete this._contextMenuEvent}mousemove(e){this._map.fire(new oa(e.type,this._map,e))}mousedown(){this._delayContextMenu=!0,this._ignoreContextMenu=!1}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new oa(`contextmenu`,this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(e){this._delayContextMenu?this._contextMenuEvent=e:this._ignoreContextMenu||this._map.fire(new oa(e.type,this._map,e)),this._map.listens(`contextmenu`)&&e.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class da{constructor(e){this._map=e}get transform(){return this._map._requestedCameraState||this._map.transform}get center(){return{lng:this.transform.center.lng,lat:this.transform.center.lat}}get zoom(){return this.transform.zoom}get pitch(){return this.transform.pitch}get bearing(){return this.transform.bearing}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this._map.terrain)}}class fa{constructor(e,t){this._map=e,this._tr=new da(e),this._el=e.getCanvasContainer(),this._container=e.getContainer(),this._clickTolerance=t.clickTolerance||1,t.boxZoom&&typeof t.boxZoom==`object`&&(this._boxZoomEnd=t.boxZoom.boxZoomEnd)}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){this.isEnabled()||(this._enabled=!0)}disable(){this.isEnabled()&&(this._enabled=!1)}mousedown(e,t){this.isEnabled()&&e.shiftKey&&e.button===0&&(d.disableDrag(),this._startPos=this._lastPos=t,this._active=!0)}mousemoveWindow(e,t){if(!this._active)return;let n=t;if(this._lastPos.equals(n)||!this._box&&n.dist(this._startPos)<this._clickTolerance)return;let r=this._startPos;this._lastPos=n,this._box||(this._box=d.create(`div`,`maplibregl-boxzoom`,this._container),this._container.classList.add(`maplibregl-crosshair`),this._fireEvent(`boxzoomstart`,e));let i=Math.min(r.x,n.x),a=Math.max(r.x,n.x),o=Math.min(r.y,n.y),s=Math.max(r.y,n.y);this._box.style.transform=`translate(${i}px,${o}px)`,this._box.style.width=a-i+`px`,this._box.style.height=s-o+`px`}mouseupWindow(e,n){if(!this._active||e.button!==0)return;let r=this._startPos,i=n;if(this.reset(),d.suppressClick(),r.x!==i.x||r.y!==i.y)return this._map.fire(new t.n(`boxzoomend`,{originalEvent:e})),this._boxZoomEnd?void this._boxZoomEnd(this._map,r,i,e):{cameraAnimation:e=>e.fitScreenCoordinates(r,i,this._tr.bearing,{linear:!0})};this._fireEvent(`boxzoomcancel`,e)}keydown(e){this._active&&e.keyCode===27&&(this.reset(),this._fireEvent(`boxzoomcancel`,e))}reset(){this._active=!1,this._container.classList.remove(`maplibregl-crosshair`),this._box&&=(this._box.remove(),null),d.enableDrag(),delete this._startPos,delete this._lastPos}_fireEvent(e,n){return this._map.fire(new t.n(e,{originalEvent:n}))}}function pa(e,t){if(e.length!==t.length)throw Error(`The number of touches and points are not equal - touches ${e.length}, points ${t.length}`);let n={};for(let r=0;r<e.length;r++)n[e[r].identifier]=t[r];return n}class ma{constructor(e){this.reset(),this.numTouches=e.numTouches}reset(){delete this.centroid,delete this.startTime,delete this.touches,this.aborted=!1}touchstart(e,n,r){(this.centroid||r.length>this.numTouches)&&(this.aborted=!0),this.aborted||(this.startTime===void 0&&(this.startTime=e.timeStamp),r.length===this.numTouches&&(this.centroid=function(e){let n=new t.P(0,0);for(let t of e)n._add(t);return n.div(e.length)}(n),this.touches=pa(r,n)))}touchmove(e,t,n){if(this.aborted||!this.centroid)return;let r=pa(n,t);for(let e in this.touches){let t=r[e];(!t||t.dist(this.touches[e])>30)&&(this.aborted=!0)}}touchend(e,t,n){if((!this.centroid||e.timeStamp-this.startTime>500)&&(this.aborted=!0),n.length===0){let e=!this.aborted&&this.centroid;if(this.reset(),e)return e}}}class Z{constructor(e){this.singleTap=new ma(e),this.numTaps=e.numTaps,this.reset()}reset(){this.lastTime=1/0,delete this.lastTap,this.count=0,this.singleTap.reset()}touchstart(e,t,n){this.singleTap.touchstart(e,t,n)}touchmove(e,t,n){this.singleTap.touchmove(e,t,n)}touchend(e,t,n){let r=this.singleTap.touchend(e,t,n);if(r){let t=e.timeStamp-this.lastTime<500,n=!this.lastTap||this.lastTap.dist(r)<30;if(t&&n||this.reset(),this.count++,this.lastTime=e.timeStamp,this.lastTap=r,this.count===this.numTaps)return this.reset(),r}}}class ha{constructor(e){this._tr=new da(e),this._zoomIn=new Z({numTouches:1,numTaps:2}),this._zoomOut=new Z({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(e,t,n){this._zoomIn.touchstart(e,t,n),this._zoomOut.touchstart(e,t,n)}touchmove(e,t,n){this._zoomIn.touchmove(e,t,n),this._zoomOut.touchmove(e,t,n)}touchend(e,n,r){let i=this._zoomIn.touchend(e,n,r),a=this._zoomOut.touchend(e,n,r),o=this._tr;return i?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:n=>n.easeTo({duration:300,zoom:t.cw(o.zoom+1,n.getZoomSnap()),around:o.unproject(i)},{originalEvent:e})}):a?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:n=>n.easeTo({duration:300,zoom:t.cw(o.zoom-1,n.getZoomSnap()),around:o.unproject(a)},{originalEvent:e})}):void 0}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class ga{constructor(e){this._enabled=!!e.enable,this._moveStateManager=e.moveStateManager,this._clickTolerance=e.clickTolerance||1,this._moveFunction=e.move,this._activateOnStart=!!e.activateOnStart,e.assignEvents(this),this.reset()}reset(e){this._active=!1,this._moved=!1,delete this._lastPoint,this._moveStateManager.endMove(e)}_move(...e){let t=this._moveFunction(...e);if(t.bearingDelta||t.pitchDelta||t.rollDelta||t.around||t.panDelta)return this._active=!0,t}dragStart(e,t){this.isEnabled()&&!this._lastPoint&&this._moveStateManager.isValidStartEvent(e)&&(this._moveStateManager.startMove(e),this._lastPoint=Array.isArray(t)?t[0]:t,this._activateOnStart&&this._lastPoint&&(this._active=!0))}dragMove(e,t){if(!this.isEnabled())return;let n=this._lastPoint;if(!n)return;if(e.preventDefault(),!this._moveStateManager.isValidMoveEvent(e))return void this.reset(e);let r=Array.isArray(t)?t[0]:t;return!this._moved&&r.dist(n)<this._clickTolerance?void 0:(this._moved=!0,this._lastPoint=r,this._move(n,r))}dragEnd(e){this.isEnabled()&&this._lastPoint&&this._moveStateManager.isValidEndEvent(e)&&(this._moved&&d.suppressClick(),this.reset(e))}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}getClickTolerance(){return this._clickTolerance}}let _a={0:1,2:2};class va{constructor(e){this._correctEvent=e.checkCorrectEvent}startMove(e){this._eventButton=e.button}endMove(e){delete this._eventButton}isValidStartEvent(e){return this._correctEvent(e)}isValidMoveEvent(e){return!function(e,t){let n=_a[t];return e.buttons===void 0||(e.buttons&n)!==n}(e,this._eventButton)}isValidEndEvent(e){return e.button===this._eventButton}}class ya{constructor(){this._firstTouch=void 0}_isOneFingerTouch(e){return e.targetTouches.length===1}_isSameTouchEvent(e){return e.targetTouches[0].identifier===this._firstTouch}startMove(e){this._firstTouch=e.targetTouches[0].identifier}endMove(e){delete this._firstTouch}isValidStartEvent(e){return this._isOneFingerTouch(e)}isValidMoveEvent(e){return this._isOneFingerTouch(e)&&this._isSameTouchEvent(e)}isValidEndEvent(e){return this._isOneFingerTouch(e)&&this._isSameTouchEvent(e)}}class ba{constructor(e=new va({checkCorrectEvent:()=>!0}),t=new ya){this.mouseMoveStateManager=e,this.oneFingerTouchMoveStateManager=t}_executeRelevantHandler(e,t,n){return e instanceof MouseEvent?t(e):typeof TouchEvent<`u`&&e instanceof TouchEvent?n(e):void 0}startMove(e){this._executeRelevantHandler(e,(e=>{this.mouseMoveStateManager.startMove(e)}),(e=>{this.oneFingerTouchMoveStateManager.startMove(e)}))}endMove(e){this._executeRelevantHandler(e,(e=>{this.mouseMoveStateManager.endMove(e)}),(e=>{this.oneFingerTouchMoveStateManager.endMove(e)}))}isValidStartEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidStartEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidStartEvent(e)))}isValidMoveEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidMoveEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidMoveEvent(e)))}isValidEndEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidEndEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidEndEvent(e)))}}let xa=e=>{e.mousedown=e.dragStart,e.mousemoveWindow=e.dragMove,e.mouseup=e.dragEnd,e.contextmenu=e=>{e.preventDefault()}};class Sa{constructor(e,t){this._clickTolerance=e.clickTolerance||1,this._map=t,this.reset()}reset(){this._active=!1,this._touches={},this._sum=new t.P(0,0)}_shouldBePrevented(e){return e<(this._map.cooperativeGestures.isEnabled()?2:1)}touchstart(e,t,n){return this._calculateTransform(e,t,n)}touchmove(e,t,n){if(this._active){if(!this._shouldBePrevented(n.length))return e.preventDefault(),this._calculateTransform(e,t,n);this._map.cooperativeGestures.notifyGestureBlocked(`touch_pan`,e)}}touchend(e,t,n){this._calculateTransform(e,t,n),this._active&&this._shouldBePrevented(n.length)&&this.reset()}touchcancel(){this.reset()}_calculateTransform(e,n,r){r.length>0&&(this._active=!0);let i=pa(r,n),a=new t.P(0,0),o=new t.P(0,0),s=0;for(let e in i){let t=i[e],n=this._touches[e];n&&(a._add(t),o._add(t.sub(n)),s++,i[e]=t)}if(this._touches=i,this._shouldBePrevented(s)||!o.mag())return;let c=o.div(s);return this._sum._add(c),this._sum.mag()<this._clickTolerance?void 0:{around:a.div(s),panDelta:c}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class Ca{constructor(){this.reset()}reset(){this._active=!1,delete this._firstTwoTouches}touchstart(e,t,n){this._firstTwoTouches||n.length<2||(this._firstTwoTouches=[n[0].identifier,n[1].identifier],this._start([t[0],t[1]]))}touchmove(e,t,n){if(!this._firstTwoTouches)return;e.preventDefault();let[r,i]=this._firstTwoTouches,a=wa(n,t,r),o=wa(n,t,i);if(!a||!o)return;let s=this._aroundCenter?null:a.add(o).div(2);return this._move([a,o],s,e)}touchend(e,t,n){if(!this._firstTwoTouches)return;let[r,i]=this._firstTwoTouches,a=wa(n,t,r),o=wa(n,t,i);a&&o||(this._active&&d.suppressClick(),this.reset())}touchcancel(){this.reset()}enable(e){this._enabled=!0,this._aroundCenter=!!e&&e.around===`center`}disable(){this._enabled=!1,this.reset()}isEnabled(){return!!this._enabled}isActive(){return!!this._active}}function wa(e,t,n){for(let r=0;r<e.length;r++)if(e[r].identifier===n)return t[r]}function Ta(e,t){return Math.log(e/t)/Math.LN2}class Ea extends Ca{constructor(){super(),this._zoomRate=1,this._zoomThreshold=.1}setZoomRate(e){this._zoomRate=e??1}setZoomThreshold(e){this._zoomThreshold=e??.1}reset(){super.reset(),delete this._distance,delete this._startDistance}_start(e){this._startDistance=this._distance=e[0].dist(e[1])}_move(e,t){let n=this._distance;if(this._distance=e[0].dist(e[1]),this._active||!(Math.abs(Ta(this._distance,this._startDistance))<this._zoomThreshold))return this._active=!0,{zoomDelta:Ta(this._distance,n)*this._zoomRate,pinchAround:t}}}function Da(e,t){return 180*e.angleWith(t)/Math.PI}class Oa extends Ca{reset(){super.reset(),delete this._minDiameter,delete this._startVector,delete this._vector}_start(e){this._startVector=this._vector=e[0].sub(e[1]),this._minDiameter=e[0].dist(e[1])}_move(e,t,n){let r=this._vector;if(this._vector=e[0].sub(e[1]),this._active||!this._isBelowThreshold(this._vector))return this._active=!0,{bearingDelta:Da(this._vector,r),pinchAround:t}}_isBelowThreshold(e){this._minDiameter=Math.min(this._minDiameter,e.mag());let t=25/(Math.PI*this._minDiameter)*360,n=Da(e,this._startVector);return Math.abs(n)<t}}function ka(e){return Math.abs(e.y)>Math.abs(e.x)}class Aa extends Ca{constructor(e){super(),this._currentTouchCount=0,this._map=e}reset(){super.reset(),this._valid=void 0,delete this._firstMove,delete this._lastPoints}touchstart(e,t,n){super.touchstart(e,t,n),this._currentTouchCount=n.length}_start(e){this._lastPoints=e,ka(e[0].sub(e[1]))&&(this._valid=!1)}_move(e,t,n){if(this._map.cooperativeGestures.isEnabled()&&this._currentTouchCount<3)return;let r=e[0].sub(this._lastPoints[0]),i=e[1].sub(this._lastPoints[1]);return this._valid=this.gestureBeginsVertically(r,i,n.timeStamp),this._valid?(this._lastPoints=e,this._active=!0,{pitchDelta:(r.y+i.y)/2*-.5}):void 0}gestureBeginsVertically(e,t,n){if(this._valid!==void 0)return this._valid;let r=e.mag()>=2,i=t.mag()>=2;if(!r&&!i)return;if(!r||!i)return this._firstMove===void 0&&(this._firstMove=n),n-this._firstMove<100&&void 0;let a=e.y>0==t.y>0;return ka(e)&&ka(t)&&a}}let ja={panStep:100,bearingStep:15,pitchStep:10};class Ma{constructor(e){this._tr=new da(e);let t=ja;this._panStep=t.panStep,this._bearingStep=t.bearingStep,this._pitchStep=t.pitchStep,this._rotationDisabled=!1}reset(){this._active=!1}keydown(e){if(e.altKey||e.ctrlKey||e.metaKey)return;let n=0,r=0,i=0,a=0,o=0;switch(e.keyCode){case 61:case 107:case 171:case 187:n=1;break;case 189:case 109:case 173:n=-1;break;case 37:e.shiftKey?r=-1:(e.preventDefault(),a=-1);break;case 39:e.shiftKey?r=1:(e.preventDefault(),a=1);break;case 38:e.shiftKey?i=1:(e.preventDefault(),o=-1);break;case 40:e.shiftKey?i=-1:(e.preventDefault(),o=1);break;default:return}return this._rotationDisabled&&(r=0,i=0),{cameraAnimation:s=>{let c=this._tr;s.easeTo({duration:300,easeId:`keyboardHandler`,easing:Na,zoom:n?t.cw(c.zoom+n*(e.shiftKey?2:1),s.getZoomSnap()):c.zoom,bearing:c.bearing+r*this._bearingStep,pitch:c.pitch+i*this._pitchStep,offset:[-a*this._panStep,-o*this._panStep],center:c.center},{originalEvent:e})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0}enableRotation(){this._rotationDisabled=!1}}function Na(e){return e*(2-e)}let Pa=4.000244140625;class Fa{constructor(e,t){this._onTimeout=e=>{this._type=`wheel`,this._delta-=this._lastValue,this._active||this._start(e)},this._map=e,this._tr=new da(e),this._triggerRenderFrame=t,this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=.0022222222222222222}setZoomRate(e){this._defaultZoomRate=e}setWheelZoomRate(e){this._wheelZoomRate=e}isEnabled(){return!!this._enabled}isActive(){return!!this._active||this._finishTimeout!==void 0}isZooming(){return!!this._zooming}enable(e){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!e&&e.around===`center`)}disable(){this.isEnabled()&&(this._enabled=!1)}_shouldBePrevented(e){return!!this._map.cooperativeGestures.isEnabled()&&!(e.ctrlKey||this._map.cooperativeGestures.isBypassed(e))}wheel(e){if(!this.isEnabled())return;if(this._shouldBePrevented(e))return void this._map.cooperativeGestures.notifyGestureBlocked(`wheel_zoom`,e);let t=e.deltaMode===WheelEvent.DOM_DELTA_LINE?40*e.deltaY:e.deltaY,n=l(),r=n-(this._lastWheelEventTime||0);this._lastWheelEventTime=n,t!==0&&t%Pa==0?this._type=`wheel`:t!==0&&Math.abs(t)<4?this._type=`trackpad`:r>400?(this._type=null,this._lastValue=t,this._timeout=setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(r*t)<200?`trackpad`:`wheel`,this._timeout&&(clearTimeout(this._timeout),this._timeout=null,t+=this._lastValue)),e.shiftKey&&t&&(t/=4),this._type&&(this._lastWheelEvent=e,this._delta-=t,this._active||this._start(e)),e.preventDefault()}_start(e){if(!this._delta)return;this._needsRerender=!1,this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);let n=d.mousePos(this._map.getCanvas(),e),r=this._tr;this._aroundPoint=this._aroundCenter?r.transform.locationToScreenPoint(t.W.convert(r.center)):n,this._needsRerender||(this._needsRerender=!0,this._triggerRenderFrame())}renderFrame(){if(!this._needsRerender||(this._needsRerender=!1,!this.isActive()))return;let e=this._tr.transform;if(typeof this._lastExpectedZoom==`number`){let t=e.zoom-this._lastExpectedZoom;typeof this._startZoom==`number`&&(this._startZoom+=t),typeof this._targetZoom==`number`&&(this._targetZoom+=t)}if(this._delta!==0){let n=this._type===`wheel`&&Math.abs(this._delta)>Pa?this._wheelZoomRate:this._defaultZoomRate,r=2/(1+Math.exp(-Math.abs(this._delta*n)));this._delta<0&&r!==0&&(r=1/r);let i=typeof this._targetZoom==`number`?t.ao(this._targetZoom):e.scale,a=e.applyConstrain(e.getCameraLngLat(),t.ar(i*r)).zoom,o=this._map.getZoomSnap();if(this._type===`wheel`&&o>0){let n=t.cw(e.zoom,o);this._targetZoom=t.cw(a,o,a-n)}else this._targetZoom=a;this._type===`wheel`&&(this._startZoom=e.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0}let n=typeof this._targetZoom==`number`?this._targetZoom:e.zoom,r=this._startZoom,i=this._easing,a,o=!1;if(this._type===`wheel`&&r&&i){let e=l()-this._lastWheelEventTime,s=Math.min((e+5)/200,1),c=i(s);a=t.H.number(r,n,c),s<1?this._needsRerender=!0:o=!0}else a=n,o=!0;return this._active=!0,o&&(this._active=!1,this._finishTimeout=setTimeout((()=>{this._zooming=!1,this._triggerRenderFrame(),delete this._targetZoom,delete this._lastExpectedZoom,delete this._finishTimeout}),200)),this._lastExpectedZoom=a,{noInertia:!0,needsRenderFrame:!o,zoomDelta:a-e.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}_smoothOutEasing(e){let n=t.cy;if(this._prevEase){let e=this._prevEase,r=(l()-e.start)/e.duration,i=e.easing(r+.01)-e.easing(r),a=.27/Math.sqrt(i*i+1e-4)*.01,o=Math.sqrt(.0729-a*a);n=t.cv(a,o,.25,1)}return this._prevEase={start:l(),duration:e,easing:n},n}reset(){this._active=!1,this._zooming=!1,delete this._targetZoom,delete this._lastExpectedZoom,this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout)}}class Ia{constructor(e,t){this._clickZoom=e,this._tapZoom=t}enable(){this._clickZoom.enable(),this._tapZoom.enable()}disable(){this._clickZoom.disable(),this._tapZoom.disable()}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class La{constructor(e){this._tr=new da(e),this.reset()}reset(){this._active=!1}dblclick(e,n){return e.preventDefault(),{cameraAnimation:r=>{r.easeTo({duration:300,zoom:t.cw(this._tr.zoom+(e.shiftKey?-1:1),r.getZoomSnap()),around:this._tr.unproject(n)},{originalEvent:e})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class Ra{constructor(){this._tap=new Z({numTouches:1,numTaps:1}),this._zoomRate=1,this.reset()}setZoomRate(e){this._zoomRate=e??1}reset(){this._active=!1,delete this._swipePoint,delete this._swipeTouch,delete this._tapTime,delete this._tapPoint,this._tap.reset()}touchstart(e,t,n){if(!this._swipePoint)if(this._tapTime){let r=t[0],i=e.timeStamp-this._tapTime<500,a=this._tapPoint.dist(r)<30;i&&a?n.length>0&&(this._swipePoint=r,this._swipeTouch=n[0].identifier):this.reset()}else this._tap.touchstart(e,t,n)}touchmove(e,t,n){if(this._tapTime){if(this._swipePoint){if(n[0].identifier!==this._swipeTouch)return;let r=t[0],i=r.y-this._swipePoint.y;return this._swipePoint=r,e.preventDefault(),this._active=!0,{zoomDelta:i/128*this._zoomRate}}}else this._tap.touchmove(e,t,n)}touchend(e,t,n){if(this._tapTime)this._swipePoint&&n.length===0&&this.reset();else{let r=this._tap.touchend(e,t,n);r&&(this._tapTime=e.timeStamp,this._tapPoint=r)}}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class za{constructor(e,t,n){this._el=e,this._mousePan=t,this._touchPan=n}enable(e){this._inertiaOptions=e||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add(`maplibregl-touch-drag-pan`)}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove(`maplibregl-touch-drag-pan`)}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class Ba{constructor(e,t,n,r){this._pitchWithRotate=e.pitchWithRotate,this._rollEnabled=e.rollEnabled,this._mouseRotate=t,this._mousePitch=n,this._mouseRoll=r}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable(),this._rollEnabled&&this._mouseRoll.enable()}disable(){this._mouseRotate.disable(),this._mousePitch.disable(),this._mouseRoll.disable()}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())&&(!this._rollEnabled||this._mouseRoll.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()||this._mouseRoll.isActive()}}class Va{constructor(e,t,n,r){this._el=e,this._touchZoom=t,this._touchRotate=n,this._tapDragZoom=r,this._rotationDisabled=!1,this._enabled=!0}enable(e){this._touchZoom.enable(e),this._rotationDisabled||this._touchRotate.enable(e),this._tapDragZoom.enable(),this._el.classList.add(`maplibregl-touch-zoom-rotate`)}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove(`maplibregl-touch-zoom-rotate`)}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}setZoomRate(e){this._touchZoom.setZoomRate(e),this._tapDragZoom.setZoomRate(e)}setZoomThreshold(e){this._touchZoom.setZoomThreshold(e)}disableRotation(){this._rotationDisabled=!0,this._touchRotate.disable()}enableRotation(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable()}}class Ha{constructor(e,t){this._bypassKey=navigator.userAgent.includes(`Mac`)?`metaKey`:`ctrlKey`,this._map=e,this._options=t,this._enabled=!1}isActive(){return!1}reset(){}_setupUI(){if(this._container)return;let e=this._map.getCanvasContainer();e.classList.add(`maplibregl-cooperative-gestures`),this._container=d.create(`div`,`maplibregl-cooperative-gesture-screen`,e);let t=this._map._getUIString(`CooperativeGesturesHandler.WindowsHelpText`);this._bypassKey===`metaKey`&&(t=this._map._getUIString(`CooperativeGesturesHandler.MacHelpText`));let n=this._map._getUIString(`CooperativeGesturesHandler.MobileHelpText`),r=document.createElement(`div`);r.className=`maplibregl-desktop-message`,r.textContent=t,this._container.appendChild(r);let i=document.createElement(`div`);i.className=`maplibregl-mobile-message`,i.textContent=n,this._container.appendChild(i),this._container.setAttribute(`aria-hidden`,`true`)}_destroyUI(){this._container&&(this._container.remove(),this._map.getCanvasContainer().classList.remove(`maplibregl-cooperative-gestures`)),delete this._container}enable(){this._setupUI(),this._enabled=!0}disable(){this._enabled=!1,this._destroyUI()}isEnabled(){return this._enabled}isBypassed(e){return e[this._bypassKey]}notifyGestureBlocked(e,n){this._enabled&&(this._map.fire(new t.n(`cooperativegestureprevented`,{gestureType:e,originalEvent:n})),this._container.classList.add(`maplibregl-show`),setTimeout((()=>{this._container.classList.remove(`maplibregl-show`)}),100))}}let Ua=e=>e.zoom||e.drag||e.roll||e.pitch||e.rotate;class Wa extends t.n{}function Ga(e){return e.panDelta?.mag()||e.zoomDelta||e.bearingDelta||e.pitchDelta||e.rollDelta}class Q{get _ownerDocument(){return this._el?.ownerDocument||document}get _ownerWindow(){return this._el?.ownerDocument?.defaultView||window}constructor(e,n){this.handleWindowEvent=e=>{this.handleEvent(e,`${e.type}Window`)},this.handleEvent=(e,n)=>{if(e.type===`blur`)return void this.stop(!0);this._updatingCamera=!0;let r=e.type===`renderFrame`?void 0:e,i={needsRenderFrame:!1},a={},o={};for(let{handlerName:s,handler:c,allowed:l}of this._handlers){if(!c.isEnabled())continue;let u;if(this._blockedByActive(o,l,s))c.reset();else if(c[n||e.type]){if(t.cz(e,n||e.type)){let t=d.mousePos(this._map.getCanvas(),e);u=c[n||e.type](e,t)}else if(t.cA(e,n||e.type)){let t=this._getMapTouches(e.touches),r=d.touchPos(this._map.getCanvas(),t);u=c[n||e.type](e,r,t)}else t.cB(n||e.type)||(u=c[n||e.type](e));this.mergeHandlerResult(i,a,u,s,r),u!=null&&u.needsRenderFrame&&this._triggerRenderFrame()}(u||c.isActive())&&(o[s]=c)}let s={};for(let e in this._previousActiveHandlers)o[e]||(s[e]=r);this._previousActiveHandlers=o,(Object.keys(s).length||Ga(i))&&(this._changes.push([i,a,s]),this._triggerRenderFrame()),(Object.keys(o).length||Ga(i))&&this._map._stop(!0),this._updatingCamera=!1;let{cameraAnimation:c}=i;c&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],c(this._map))},this._map=e,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new ra(e),this._bearingSnap=n.bearingSnap,this._previousActiveHandlers={},this._eventsInProgress={},this._addDefaultHandlers(n);let r=this._el;this._listeners=[[r,`touchstart`,{passive:!0}],[r,`touchmove`,{passive:!1}],[r,`touchend`,void 0],[r,`touchcancel`,void 0],[r,`mousedown`,void 0],[r,`mousemove`,void 0],[r,`mouseup`,void 0],[this._ownerDocument,`mousemove`,{capture:!0}],[this._ownerDocument,`mouseup`,void 0],[r,`mouseover`,void 0],[r,`mouseout`,void 0],[r,`dblclick`,void 0],[r,`click`,void 0],[r,`keydown`,{capture:!1}],[r,`keyup`,void 0],[r,`wheel`,{passive:!1}],[r,`contextmenu`,void 0],[this._ownerWindow,`blur`,void 0]];for(let[e,t,n]of this._listeners)e.addEventListener(t,e===this._ownerDocument?this.handleWindowEvent:this.handleEvent,n)}destroy(){for(let[e,t,n]of this._listeners)e.removeEventListener(t,e===this._ownerDocument?this.handleWindowEvent:this.handleEvent,n)}_addDefaultHandlers(e){let n=this._map,r=n.getCanvasContainer();this._add(`mapEvent`,new la(n,e));let i=n.boxZoom=new fa(n,e);this._add(`boxZoom`,i),e.interactive&&e.boxZoom&&i.enable();let a=n.cooperativeGestures=new Ha(n,e.cooperativeGestures);this._add(`cooperativeGestures`,a),e.cooperativeGestures&&a.enable();let o=new ha(n),s=new La(n);n.doubleClickZoom=new Ia(s,o),this._add(`tapZoom`,o),this._add(`clickZoom`,s),e.interactive&&e.doubleClickZoom&&n.doubleClickZoom.enable();let c=new Ra;this._add(`tapDragZoom`,c);let l=n.touchPitch=new Aa(n);this._add(`touchPitch`,l),e.interactive&&e.touchPitch&&n.touchPitch.enable(e.touchPitch);let u=()=>n.project(n.getCenter()),d=function({enable:e,clickTolerance:n,aroundCenter:r=!0,minPixelCenterThreshold:i=100,rotateDegreesPerPixelMoved:a=.8},o){return new ga({clickTolerance:n,move:(e,n)=>{let s=o();if(r&&Math.abs(s.y-e.y)>i)return{bearingDelta:t.cx(new t.P(e.x,n.y),n,s)};let c=(n.x-e.x)*a;return r&&n.y<s.y&&(c=-c),{bearingDelta:c}},moveStateManager:new va({checkCorrectEvent:e=>e.button===0&&e.ctrlKey||e.button===2&&!e.ctrlKey}),enable:e,assignEvents:xa})}(e,u),f=function({enable:e,clickTolerance:t,pitchDegreesPerPixelMoved:n=-.5}){return new ga({clickTolerance:t,move:(e,t)=>({pitchDelta:(t.y-e.y)*n}),moveStateManager:new va({checkCorrectEvent:e=>e.button===0&&e.ctrlKey||e.button===2}),enable:e,assignEvents:xa})}(e),p=function({enable:e,clickTolerance:t,rollDegreesPerPixelMoved:n=.3},r){return new ga({clickTolerance:t,move:(e,t)=>{let i=r(),a=(t.x-e.x)*n;return t.y<i.y&&(a=-a),{rollDelta:a}},moveStateManager:new va({checkCorrectEvent:e=>e.button===2&&e.ctrlKey}),enable:e,assignEvents:xa})}(e,u);n.dragRotate=new Ba(e,d,f,p),this._add(`mouseRotate`,d,[`mousePitch`]),this._add(`mousePitch`,f,[`mouseRotate`,`mouseRoll`]),this._add(`mouseRoll`,p,[`mousePitch`]),e.interactive&&e.dragRotate&&n.dragRotate.enable();let m=function({enable:e,clickTolerance:t}){return new ga({clickTolerance:t,move:(e,t)=>({around:t,panDelta:t.sub(e)}),activateOnStart:!0,moveStateManager:new va({checkCorrectEvent:e=>e.button===0&&!e.ctrlKey}),enable:e,assignEvents:xa})}(e),h=new Sa(e,n);n.dragPan=new za(r,m,h),this._add(`mousePan`,m),this._add(`touchPan`,h,[`touchZoom`,`touchRotate`]),e.interactive&&e.dragPan&&n.dragPan.enable(e.dragPan);let g=new Oa,_=new Ea;n.touchZoomRotate=new Va(r,_,g,c),this._add(`touchRotate`,g,[`touchPan`,`touchZoom`]),this._add(`touchZoom`,_,[`touchPan`,`touchRotate`]),e.interactive&&e.touchZoomRotate&&n.touchZoomRotate.enable(e.touchZoomRotate),this._add(`blockableMapEvent`,new ua(n));let v=n.scrollZoom=new Fa(n,(()=>this._triggerRenderFrame()));this._add(`scrollZoom`,v,[`mousePan`]),e.interactive&&e.scrollZoom&&n.scrollZoom.enable(e.scrollZoom);let y=n.keyboard=new Ma(n);this._add(`keyboard`,y),e.interactive&&e.keyboard&&n.keyboard.enable()}_add(e,t,n){this._handlers.push({handlerName:e,handler:t,allowed:n}),this._handlersById[e]=t}stop(e){if(!this._updatingCamera){for(let{handler:e}of this._handlers)e.reset();this._inertia.clear(),this._fireEvents({},{},e),this._changes=[]}}isActive(){for(let{handler:e}of this._handlers)if(e.isActive())return!0;return!1}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return!!Ua(this._eventsInProgress)||this.isZooming()}_blockedByActive(e,t,n){for(let r in e)if(r!==n&&!t?.includes(r))return!0;return!1}_getMapTouches(e){let t=[];for(let n of e)this._el.contains(n.target)&&t.push(n);return t}mergeHandlerResult(e,n,r,i,a){if(!r)return;t.e(e,r);let o={handlerName:i,originalEvent:r.originalEvent||a};r.zoomDelta!==void 0&&(n.zoom=o),r.panDelta!==void 0&&(n.drag=o),r.rollDelta!==void 0&&(n.roll=o),r.pitchDelta!==void 0&&(n.pitch=o),r.bearingDelta!==void 0&&(n.rotate=o)}_applyChanges(){let e={},n={},r={};for(let[i,a,o]of this._changes)i.panDelta&&(e.panDelta=(e.panDelta||new t.P(0,0))._add(i.panDelta)),i.zoomDelta&&(e.zoomDelta=(e.zoomDelta||0)+i.zoomDelta),i.bearingDelta&&(e.bearingDelta=(e.bearingDelta||0)+i.bearingDelta),i.pitchDelta&&(e.pitchDelta=(e.pitchDelta||0)+i.pitchDelta),i.rollDelta&&(e.rollDelta=(e.rollDelta||0)+i.rollDelta),i.around!==void 0&&(e.around=i.around),i.pinchAround!==void 0&&(e.pinchAround=i.pinchAround),i.noInertia&&(e.noInertia=i.noInertia),t.e(n,a),t.e(r,o);this._updateMapTransform(e,n,r),this._changes=[]}_updateMapTransform(e,t,n){let r=this._map,i=r._getTransformForUpdate(),a=r.terrain;if(!(Ga(e)||a&&this._terrainMovement))return void this._fireEvents(t,n,!0);r._stop(!0);let{panDelta:o,zoomDelta:s,bearingDelta:c,pitchDelta:l,rollDelta:u,around:d,pinchAround:f}=e;f!==void 0&&(d=f),d||=r.transform.centerPoint,a&&!i.isPointOnMapSurface(d)&&(d=i.centerPoint);let p={panDelta:o,zoomDelta:s,rollDelta:u,pitchDelta:l,bearingDelta:c,around:d};this._map.cameraHelper.useGlobeControls&&!i.isPointOnMapSurface(d)&&(d=i.centerPoint);let m=d.distSqr(i.centerPoint)<.01?i.center:i.screenPointToLocation(o?d.sub(o):d);this._handleMapControls({terrain:a,tr:i,deltasForHelper:p,preZoomAroundLoc:m,combinedEventsInProgress:t,panDelta:o}),r._applyUpdatedTransform(i),this._map._update(),e.noInertia||this._inertia.record(e),this._fireEvents(t,n,!0)}_handleMapControls({terrain:e,tr:t,deltasForHelper:n,preZoomAroundLoc:r,combinedEventsInProgress:i,panDelta:a}){let o=this._map.cameraHelper;if(o.handleMapControlsRollPitchBearingZoom(n,t),e)return o.useGlobeControls?(this._terrainMovement||!i.drag&&!i.zoom||(this._terrainMovement=!0,this._map._elevationFreeze=!0),void o.handleMapControlsPan(n,t,r)):this._terrainMovement||!i.drag&&!i.zoom?void(i.drag&&this._terrainMovement&&a?t.setCenter(t.screenPointToLocation(t.centerPoint.sub(a))):o.handleMapControlsPan(n,t,r)):(this._terrainMovement=!0,this._map._elevationFreeze=!0,void o.handleMapControlsPan(n,t,r));o.handleMapControlsPan(n,t,r)}_fireEvents(e,n,r){let i=Ua(this._eventsInProgress),a=Ua(e),o={};for(let t in e){let{originalEvent:n}=e[t];this._eventsInProgress[t]||(o[`${t}start`]=n),this._eventsInProgress[t]=e[t]}!i&&a&&this._fireEvent(`movestart`,a.originalEvent);for(let e in o)this._fireEvent(e,o[e]);a&&this._fireEvent(`move`,a.originalEvent);for(let t in e){let{originalEvent:n}=e[t];this._fireEvent(t,n)}let c={},l;for(let e in this._eventsInProgress){let{handlerName:t,originalEvent:r}=this._eventsInProgress[e];this._handlersById[t].isActive()||(delete this._eventsInProgress[e],l=n[t]||r,c[`${e}end`]=l)}for(let e in c)this._fireEvent(e,c[e]);let u=Ua(this._eventsInProgress),d=(i||a)&&!u;if(d&&this._terrainMovement){this._map._elevationFreeze=!1,this._terrainMovement=!1;let e=this._map._getTransformForUpdate();this._map.getCenterClampedToGround()&&e.recalculateZoomAndCenter(this._map.terrain),this._map._applyUpdatedTransform(e)}if(r&&d){this._updatingCamera=!0;let e=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),n=e=>e!==0&&-this._bearingSnap<e&&e<this._bearingSnap;!e||!e.essential&&s.prefersReducedMotion?(this._map.fire(new t.n(`moveend`,{originalEvent:l})),n(this._map.getBearing())&&this._map.resetNorth()):(n(e.bearing||this._map.getBearing())&&(e.bearing=0),e.freezeElevation=!0,this._map.easeTo(e,{originalEvent:l})),this._updatingCamera=!1}}_fireEvent(e,n){this._map.fire(new t.n(e,n?{originalEvent:n}:{}))}_requestFrame(){return this._map.triggerRepaint(),this._map._renderTaskQueue.add((e=>{delete this._frameId,this.handleEvent(new Wa(`renderFrame`,{timeStamp:e})),this._applyChanges()}))}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}class $ extends t.E{constructor(e,t,n){super(),this._renderFrameCallback=()=>{let e=Math.min((l()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(e)),e<1&&this._easeFrameId?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()},this._moving=!1,this._zooming=!1,this.transform=e,this._bearingSnap=n.bearingSnap,this._zoomSnap=n.zoomSnap,this.cameraHelper=t,this.on(`moveend`,(()=>{delete this._requestedCameraState}))}migrateProjection(e,t){e.apply(this.transform,!0),this.transform=e,this.cameraHelper=t}getCenter(){return new t.W(this.transform.center.lng,this.transform.center.lat)}setCenter(e,t){return this.jumpTo({center:e},t)}getCenterElevation(){return this.transform.elevation}setCenterElevation(e,t){return this.jumpTo({elevation:e},t),this}getCenterClampedToGround(){return this._centerClampedToGround}setCenterClampedToGround(e){this._centerClampedToGround=e}panBy(e,n,r){return e=t.P.convert(e).mult(-1),this.panTo(this.transform.center,t.e({offset:e},n),r)}panTo(e,n,r){return this.easeTo(t.e({center:e},n),r)}getZoom(){return this.transform.zoom}setZoom(e,t){return this.jumpTo({zoom:e},t),this}zoomTo(e,n,r){return this.easeTo(t.e({zoom:e},n),r)}zoomIn(e,n){return this.zoomTo(t.cw(this.getZoom()+1,this._zoomSnap),e,n),this}zoomOut(e,n){return this.zoomTo(t.cw(this.getZoom()-1,this._zoomSnap),e,n),this}getVerticalFieldOfView(){return this.transform.fov}setVerticalFieldOfView(e,n){return e!=this.transform.fov&&(this.transform.setFov(e),this.fire(new t.n(`movestart`,n)).fire(new t.n(`move`,n)).fire(new t.n(`moveend`,n))),this}getBearing(){return this.transform.bearing}setZoomSnap(e){return this._zoomSnap=e,this}getZoomSnap(){return this._zoomSnap}setBearing(e,t){return this.jumpTo({bearing:e},t),this}getPadding(){return this.transform.padding}setPadding(e,t){return this.jumpTo({padding:e},t),this}rotateTo(e,n,r){return this.easeTo(t.e({bearing:e},n),r)}resetNorth(e,n){return this.rotateTo(0,t.e({duration:1e3},e),n),this}resetNorthPitch(e,n){return this.easeTo(t.e({bearing:0,pitch:0,roll:0,duration:1e3},e),n),this}snapToNorth(e,t){return Math.abs(this.getBearing())<this._bearingSnap?this.resetNorth(e,t):this}getPitch(){return this.transform.pitch}setPitch(e,t){return this.jumpTo({pitch:e},t),this}getRoll(){return this.transform.roll}setRoll(e,t){return this.jumpTo({roll:e},t),this}cameraForBounds(e,t){e=de.convert(e).adjustAntiMeridian();let n=t?.bearing||0;return this._cameraForBoxAndBearing(e.getNorthWest(),e.getSouthEast(),n,t)}_cameraForBoxAndBearing(e,n,r,i){let a={top:0,bottom:0,right:0,left:0};if(typeof(i=t.e({padding:a,offset:[0,0],maxZoom:this.transform.maxZoom},i)).padding==`number`){let e=i.padding;i.padding={top:e,bottom:e,right:e,left:e}}let o=t.e(a,i.padding);i.padding=o;let s=this.transform,c=new de(e,n),l=this.cameraHelper.cameraForBoxAndBearing(i,o,c,r,s);return l&&this._zoomSnap&&(l.zoom=t.cw(l.zoom,this._zoomSnap,-1)),l}fitBounds(e,t,n){return this._fitInternal(this.cameraForBounds(e,t),t,n)}fitScreenCoordinates(e,n,r,i,a){return this._fitInternal(this._cameraForBoxAndBearing(this.transform.screenPointToLocation(t.P.convert(e)),this.transform.screenPointToLocation(t.P.convert(n)),r,i),i,a)}_fitInternal(e,n,r){return e?(delete(n=t.e(e,n)).padding,n.linear?this.easeTo(n,r):this.flyTo(n,r)):this}jumpTo(e,n){this.stop(),`zoom`in e&&this._zoomSnap&&(e.zoom=t.cw(e.zoom,this._zoomSnap));let r=this._getTransformForUpdate(),i=!1,a=!1,o=!1,s=r.zoom;this.terrain&&r.setElevation(this.terrain.getElevationForLngLatZoom(e.center?t.W.convert(e.center):r.center,e.zoom||r.tileZoom)),this.cameraHelper.handleJumpToCenterZoom(r,e);let c=r.zoom!==s;return`elevation`in e&&r.elevation!==+e.elevation&&r.setElevation(+e.elevation),`bearing`in e&&r.bearing!==+e.bearing&&(i=!0,r.setBearing(+e.bearing)),`pitch`in e&&r.pitch!==+e.pitch&&(a=!0,r.setPitch(+e.pitch)),`roll`in e&&r.roll!==+e.roll&&(o=!0,r.setRoll(+e.roll)),e.padding==null||r.isPaddingEqual(e.padding)||r.setPadding(e.padding),this._applyUpdatedTransform(r),this.fire(new t.n(`movestart`,n)).fire(new t.n(`move`,n)),c&&this.fire(new t.n(`zoomstart`,n)).fire(new t.n(`zoom`,n)).fire(new t.n(`zoomend`,n)),i&&this.fire(new t.n(`rotatestart`,n)).fire(new t.n(`rotate`,n)).fire(new t.n(`rotateend`,n)),a&&this.fire(new t.n(`pitchstart`,n)).fire(new t.n(`pitch`,n)).fire(new t.n(`pitchend`,n)),o&&this.fire(new t.n(`rollstart`,n)).fire(new t.n(`roll`,n)).fire(new t.n(`rollend`,n)),this.fire(new t.n(`moveend`,n))}calculateCameraOptionsFromTo(e,n,r,i=0){let a=t.a7.fromLngLat(e,n),o=t.a7.fromLngLat(r,i),s=o.x-a.x,c=o.y-a.y,l=o.z-a.z,u=Math.hypot(s,c,l);if(u===0)throw Error(`Can't calculate camera options with same From and To`);let d=Math.hypot(s,c),f=t.ar(this.transform.cameraToCenterDistance/u/this.transform.tileSize),p=180*Math.atan2(s,-c)/Math.PI,m=180*Math.acos(d/u)/Math.PI;return m=l<0?90-m:90+m,{center:o.toLngLat(),elevation:i,zoom:f,pitch:m,bearing:p}}calculateCameraOptionsFromCameraLngLatAltRotation(e,t,n,r,i){let a=this.transform.calculateCenterFromCameraLngLatAlt(e,t,n,r);return{center:a.center,elevation:a.elevation,zoom:a.zoom,bearing:n,pitch:r,roll:i}}easeTo(e,n){this._stop(!1,e.easeId),`zoom`in(e=t.e({offset:[0,0],duration:500,easing:t.cy},e))&&this._zoomSnap&&(e.zoom=t.cw(e.zoom,this._zoomSnap)),(!1===e.animate||!e.essential&&s.prefersReducedMotion)&&(e.duration=0);let r=this._getTransformForUpdate(),i=this.getBearing(),a=r.pitch,o=r.roll,c=`bearing`in e?this._normalizeBearing(e.bearing,i):i,l=`pitch`in e?+e.pitch:a,u=`roll`in e?this._normalizeBearing(e.roll,o):o,d=`padding`in e?e.padding:r.padding,f=t.P.convert(e.offset),p,m;e.around&&(p=t.W.convert(e.around),m=r.locationToScreenPoint(p));let h={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching,rolling:this._rolling},g=this.cameraHelper.handleEaseTo(r,{bearing:c,pitch:l,roll:u,padding:d,around:p,aroundPoint:m,offsetAsPoint:f,offset:e.offset,zoom:e.zoom,center:e.center});return this._rotating||=i!==c,this._pitching||=l!==a,this._rolling||=u!==o,this._padding=!r.isPaddingEqual(d),this._zooming||=g.isZooming,this._easeId=e.easeId,this._prepareEase(n,e.noMoveStart,h),this.terrain&&this._prepareElevation(g.elevationCenter),this._ease((t=>{g.easeFunc(t),this.terrain&&!e.freezeElevation&&this._updateElevation(t),this._applyUpdatedTransform(r),this._fireMoveEvents(n)}),(t=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(n,t)}),e),this}_prepareEase(e,n,r={}){this._moving=!0,n||r.moving||this.fire(new t.n(`movestart`,e)),this._zooming&&!r.zooming&&this.fire(new t.n(`zoomstart`,e)),this._rotating&&!r.rotating&&this.fire(new t.n(`rotatestart`,e)),this._pitching&&!r.pitching&&this.fire(new t.n(`pitchstart`,e)),this._rolling&&!r.rolling&&this.fire(new t.n(`rollstart`,e))}_prepareElevation(e){this._elevationCenter=e,this._elevationStart=this.transform.elevation,this._elevationTarget=this.terrain.getElevationForLngLatZoom(e,this.transform.tileZoom),this._elevationFreeze=!0}_updateElevation(e){this._elevationStart!==void 0&&this._elevationCenter!==void 0||this._prepareElevation(this.transform.center),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom));let n=this.terrain.getElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);if(e<1&&n!==this._elevationTarget){let t=this._elevationTarget-this._elevationStart;this._elevationStart+=e*(t-(n-(t*e+this._elevationStart))/(1-e)),this._elevationTarget=n}this.transform.setElevation(t.H.number(this._elevationStart,this._elevationTarget,e))}_finalizeElevation(){this._elevationFreeze=!1,this.getCenterClampedToGround()&&this.transform.recalculateZoomAndCenter(this.terrain)}_getTransformForUpdate(){return this.transformCameraUpdate||this.terrain?(this._requestedCameraState||=this.transform.clone(),this._requestedCameraState):this.transform}_elevateCameraIfInsideTerrain(e){if(!this.terrain&&e.elevation>=0&&e.pitch<=90)return{};let t=e.getCameraLngLat(),n=e.getCameraAltitude(),r=this.terrain?this.terrain.getElevationForLngLatZoom(t,e.zoom):0;if(n<r){let n=this.calculateCameraOptionsFromTo(t,r,e.center,e.elevation);return{pitch:n.pitch,zoom:n.zoom}}return{}}_applyUpdatedTransform(e){let t=[];if(t.push((e=>this._elevateCameraIfInsideTerrain(e))),this.transformCameraUpdate&&t.push((e=>this.transformCameraUpdate(e))),!t.length)return;let n=e.clone();for(let e of t){let t=n.clone(),{center:r,zoom:i,roll:a,pitch:o,bearing:s,elevation:c}=e(t);r&&t.setCenter(r),c!==void 0&&t.setElevation(c),i!==void 0&&t.setZoom(i),a!==void 0&&t.setRoll(a),o!==void 0&&t.setPitch(o),s!==void 0&&t.setBearing(s),n.apply(t,!1)}this.transform.apply(n,!1)}_fireMoveEvents(e){this.fire(new t.n(`move`,e)),this._zooming&&this.fire(new t.n(`zoom`,e)),this._rotating&&this.fire(new t.n(`rotate`,e)),this._pitching&&this.fire(new t.n(`pitch`,e)),this._rolling&&this.fire(new t.n(`roll`,e))}_afterEase(e,n){if(this._easeId&&n&&this._easeId===n)return;delete this._easeId;let r=this._zooming,i=this._rotating,a=this._pitching,o=this._rolling;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._rolling=!1,this._padding=!1,r&&this.fire(new t.n(`zoomend`,e)),i&&this.fire(new t.n(`rotateend`,e)),a&&this.fire(new t.n(`pitchend`,e)),o&&this.fire(new t.n(`rollend`,e)),this.fire(new t.n(`moveend`,e))}flyTo(e,n){if(!e.essential&&s.prefersReducedMotion){let r=t.V(e,[`center`,`zoom`,`bearing`,`pitch`,`roll`,`elevation`,`padding`]);return this.jumpTo(r,n)}this.stop(),`zoom`in(e=t.e({offset:[0,0],speed:1.2,curve:1.42,easing:t.cy},e))&&this._zoomSnap&&(e.zoom=t.cw(e.zoom,this._zoomSnap));let r=this._getTransformForUpdate(),i=r.bearing,a=r.pitch,o=r.roll,c=r.padding,l=`bearing`in e?this._normalizeBearing(e.bearing,i):i,u=`pitch`in e?+e.pitch:a,d=`roll`in e?this._normalizeBearing(e.roll,o):o,f=`padding`in e?e.padding:r.padding,p=t.P.convert(e.offset),m=r.centerPoint.add(p),h=r.screenPointToLocation(m),g=this.cameraHelper.handleFlyTo(r,{bearing:l,pitch:u,roll:d,padding:f,locationAtOffset:h,offsetAsPoint:p,center:e.center,minZoom:e.minZoom,zoom:e.zoom}),_=e.curve,v=Math.max(r.width,r.height),y=v/g.scaleOfZoom,b=g.pixelPathLength;typeof g.scaleOfMinZoom==`number`&&(_=Math.sqrt(v/g.scaleOfMinZoom/b*2));let x=_*_;function S(e){let t=(y*y-v*v+(e?-1:1)*x*x*b*b)/(2*(e?y:v)*x*b);return Math.log(Math.sqrt(t*t+1)-t)}function C(e){return(Math.exp(e)-Math.exp(-e))/2}function w(e){return(Math.exp(e)+Math.exp(-e))/2}let T=S(!1),E=function(e){return w(T)/w(T+_*e)},D=function(e){return v*((w(T)*(C(t=T+_*e)/w(t))-C(T))/x)/b;var t},O=(S(!0)-T)/_;if(Math.abs(b)<2e-6||!isFinite(O)){if(Math.abs(v-y)<1e-6)return this.easeTo(e,n);let t=y<v?-1:1;O=Math.abs(Math.log(y/v))/_,D=()=>0,E=e=>Math.exp(t*_*e)}return e.duration=`duration`in e?+e.duration:1e3*O/(`screenSpeed`in e?+e.screenSpeed/_:+e.speed),e.maxDuration&&e.duration>e.maxDuration&&(e.duration=0),this._zooming=!0,this._rotating=i!==l,this._pitching=u!==a,this._rolling=d!==o,this._padding=!r.isPaddingEqual(f),this._prepareEase(n,!1),this.terrain&&this._prepareElevation(g.targetCenter),this._ease((s=>{let h=s*O,_=1/E(h),v=D(h);this._rotating&&r.setBearing(t.H.number(i,l,s)),this._pitching&&r.setPitch(t.H.number(a,u,s)),this._rolling&&r.setRoll(t.H.number(o,d,s)),this._padding&&(r.interpolatePadding(c,f,s),m=r.centerPoint.add(p)),g.easeFunc(s,_,v,m),this.terrain&&!e.freezeElevation&&this._updateElevation(s),this._applyUpdatedTransform(r),this._fireMoveEvents(n)}),(()=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(n)}),e),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_stop(e,t){var n;if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){let e=this._onEaseEnd;delete this._onEaseEnd,e.call(this,t)}return e||(n=this.handlers)==null||n.stop(!1),this}_ease(e,t,n){!1===n.animate||n.duration===0?(e(1),t()):(this._easeStart=l(),this._easeOptions=n,this._onEaseFrame=e,this._onEaseEnd=t,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_normalizeBearing(e,n){e=t.X(e,-180,180);let r=Math.abs(e-n);return Math.abs(e-360-n)<r&&(e-=360),Math.abs(e+360-n)<r&&(e+=360),e}queryTerrainElevation(e){return this.terrain?this.terrain.getElevationForLngLat(t.W.convert(e),this.transform):null}}let Ka={compact:!0,customAttribution:`<a href="https://maplibre.org/" target="_blank">MapLibre</a>`};class qa{constructor(e=Ka){this._toggleAttribution=()=>{this._container.classList.contains(`maplibregl-compact`)&&(this._container.classList.contains(`maplibregl-compact-show`)?(this._container.setAttribute(`open`,``),this._container.classList.remove(`maplibregl-compact-show`)):(this._container.classList.add(`maplibregl-compact-show`),this._container.removeAttribute(`open`)))},this._updateData=e=>{!e||e.sourceDataType!==`metadata`&&e.sourceDataType!==`visibility`&&e.dataType!==`style`&&e.type!==`terrain`||this._updateAttributions()},this._updateCompact=()=>{this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1===this._compact?this._container.setAttribute(`open`,``):this._container.classList.contains(`maplibregl-compact`)||this._container.classList.contains(`maplibregl-attrib-empty`)||(this._container.setAttribute(`open`,``),this._container.classList.add(`maplibregl-compact`,`maplibregl-compact-show`)):(this._container.setAttribute(`open`,``),this._container.classList.contains(`maplibregl-compact`)&&this._container.classList.remove(`maplibregl-compact`,`maplibregl-compact-show`))},this._updateCompactMinimize=()=>{this._container.classList.contains(`maplibregl-compact`)&&this._container.classList.contains(`maplibregl-compact-show`)&&this._container.classList.remove(`maplibregl-compact-show`)},this.options=e}getDefaultPosition(){return`bottom-right`}onAdd(e){return this._map=e,this._compact=this.options.compact,this._container=d.create(`details`,`maplibregl-ctrl maplibregl-ctrl-attrib`),this._compactButton=d.create(`summary`,`maplibregl-ctrl-attrib-button`,this._container),this._compactButton.addEventListener(`click`,this._toggleAttribution),this._setElementTitle(this._compactButton,`ToggleAttribution`),this._innerContainer=d.create(`div`,`maplibregl-ctrl-attrib-inner`,this._container),this._updateAttributions(),this._updateCompact(),this._map.on(`styledata`,this._updateData),this._map.on(`sourcedata`,this._updateData),this._map.on(`terrain`,this._updateData),this._map.on(`resize`,this._updateCompact),this._map.on(`drag`,this._updateCompactMinimize),this._container}onRemove(){this._container.remove(),this._map.off(`styledata`,this._updateData),this._map.off(`sourcedata`,this._updateData),this._map.off(`terrain`,this._updateData),this._map.off(`resize`,this._updateCompact),this._map.off(`drag`,this._updateCompactMinimize),this._map=void 0,this._compact=void 0,this._attribHTML=void 0}_setElementTitle(e,t){let n=this._map._getUIString(`AttributionControl.${t}`);e.title=n,e.setAttribute(`aria-label`,n)}_updateAttributions(){if(!this._map.style)return;let e=[];if(this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?e=e.concat(this.options.customAttribution.map((e=>typeof e==`string`?e:``))):typeof this.options.customAttribution==`string`&&e.push(this.options.customAttribution)),this._map.style.stylesheet){let e=this._map.style.stylesheet;this.styleOwner=e.owner,this.styleId=e.id}let t=this._map.style.tileManagers;for(let n in t){let r=t[n];if(r.used||r.usedForTerrain){let t=r.getSource();t.attribution&&!e.includes(t.attribution)&&e.push(t.attribution)}}e=e.filter((e=>String(e).trim())),e.sort(((e,t)=>e.length-t.length)),e=e.filter(((t,n)=>{for(let r=n+1;r<e.length;r++)if(e[r].includes(t))return!1;return!0}));let n=e.join(` | `);n!==this._attribHTML&&(this._attribHTML=n,e.length?(this._innerContainer.innerHTML=d.sanitize(n),this._container.classList.remove(`maplibregl-attrib-empty`)):this._container.classList.add(`maplibregl-attrib-empty`),this._updateCompact(),this._editLink=null)}}class Ja{constructor(e={}){this._updateCompact=()=>{let e=this._container.children;if(e.length){let t=e[0];this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1!==this._compact&&t.classList.add(`maplibregl-compact`):t.classList.remove(`maplibregl-compact`)}},this.options=e}getDefaultPosition(){return`bottom-left`}onAdd(e){this._map=e,this._compact=this.options?.compact,this._container=d.create(`div`,`maplibregl-ctrl`);let t=d.create(`a`,`maplibregl-ctrl-logo`);return t.target=`_blank`,t.rel=`noopener nofollow`,t.href=`https://maplibre.org/`,t.setAttribute(`aria-label`,this._map._getUIString(`LogoControl.Title`)),t.setAttribute(`rel`,`noopener nofollow`),this._container.appendChild(t),this._container.style.display=`block`,this._map.on(`resize`,this._updateCompact),this._updateCompact(),this._container}onRemove(){this._container.remove(),this._map.off(`resize`,this._updateCompact),this._map=void 0,this._compact=void 0}}class Ya{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1}add(e){let t=++this._id;return this._queue.push({callback:e,id:t,cancelled:!1}),t}remove(e){let t=this._currentlyRunning,n=t?this._queue.concat(t):this._queue;for(let t of n)if(t.id===e)return void(t.cancelled=!0)}run(e=0){if(this._currentlyRunning)throw Error(`Attempting to run(), but is already running.`);let t=this._currentlyRunning=this._queue;this._queue=[];for(let n of t)if(!n.cancelled&&(n.callback(e),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]}}var Xa=t.aS([{name:`a_pos3d`,type:`Int16`,components:3}]);class Za extends t.E{constructor(e){super(),this._lastTilesetChange=l(),this.tileManager=e,this._tiles={},this._renderableTilesKeys=[],this._sourceTileCache={},this.minzoom=0,this.maxzoom=22,this.deltaZoom=1,this.tileSize=e._source.tileSize*2**this.deltaZoom,e.usedForTerrain=!0,e.tileSize=this.tileSize}destruct(){this.tileManager.usedForTerrain=!1,this.tileManager.tileSize=null}getSource(){return this.tileManager._source}update(e,n){this.tileManager.update(e,n),this._renderableTilesKeys=[];let r={};for(let i of We(e,{tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,reparseOverscaled:!1,terrain:n,calculateTileZoom:this.tileManager._source.calculateTileZoom}))r[i.key]=!0,this._renderableTilesKeys.push(i.key),this._tiles[i.key]||(i.terrainRttPosMatrix32f=new Float64Array(16),t.c7(i.terrainRttPosMatrix32f,0,t.a6,t.a6,0,0,1),this._tiles[i.key]=new Pe(i,this.tileSize),this._lastTilesetChange=l());for(let e in this._tiles)r[e]||delete this._tiles[e]}freeRtt(e){for(let t in this._tiles){let n=this._tiles[t];(!e||n.tileID.equals(e)||n.tileID.isChildOf(e)||e.isChildOf(n.tileID))&&(n.rtt=[])}}getRenderableTiles(){return this._renderableTilesKeys.map((e=>this.getTileByID(e)))}getTileByID(e){return this._tiles[e]}getTerrainCoords(e,t){return t?this._getTerrainCoordsForTileRanges(e,t):this._getTerrainCoordsForRegularTile(e)}_getTerrainCoordsForRegularTile(e){let n={};for(let r of this._renderableTilesKeys){let i=this._tiles[r].tileID,a=e.clone(),o=t.bj();if(i.canonical.equals(e.canonical))t.c7(o,0,t.a6,t.a6,0,0,1);else if(i.canonical.isChildOf(e.canonical)){let n=i.canonical.z-e.canonical.z,r=i.canonical.x-(i.canonical.x>>n<<n),a=i.canonical.y-(i.canonical.y>>n<<n),s=t.a6>>n;t.c7(o,0,s,s,0,0,1),t.Q(o,o,[-r*s,-a*s,0])}else{if(!e.canonical.isChildOf(i.canonical))continue;{let n=e.canonical.z-i.canonical.z,r=e.canonical.x-(e.canonical.x>>n<<n),a=e.canonical.y-(e.canonical.y>>n<<n),s=t.a6>>n;t.c7(o,0,t.a6,t.a6,0,0,1),t.Q(o,o,[r*s,a*s,0]),t.S(o,o,[1/2**n,1/2**n,0])}}a.terrainRttPosMatrix32f=new Float32Array(o),n[r]=a}return n}_getTerrainCoordsForTileRanges(e,n){let r={};for(let i of this._renderableTilesKeys){let a=this._tiles[i].tileID;if(!this._isWithinTileRanges(a,n))continue;let o=e.clone(),s=t.bj();if(a.canonical.z===e.canonical.z){let n=e.canonical.x-a.canonical.x+e.wrap*(1<<e.canonical.z),r=e.canonical.y-a.canonical.y;t.c7(s,0,t.a6,t.a6,0,0,1),t.Q(s,s,[n*t.a6,r*t.a6,0])}else if(a.canonical.z>e.canonical.z){let n=a.canonical.z-e.canonical.z,r=a.canonical.x-(a.canonical.x>>n<<n)+e.wrap*(1<<a.canonical.z),i=a.canonical.y-(a.canonical.y>>n<<n),o=e.canonical.x-(a.canonical.x>>n),c=e.canonical.y-(a.canonical.y>>n),l=t.a6>>n;t.c7(s,0,l,l,0,0,1),t.Q(s,s,[-r*l+o*t.a6,-i*l+c*t.a6,0])}else{let n=e.canonical.z-a.canonical.z,r=e.canonical.x-(e.canonical.x>>n<<n)+e.wrap*(1<<e.canonical.z),i=e.canonical.y-(e.canonical.y>>n<<n),o=(e.canonical.x>>n)-a.canonical.x,c=(e.canonical.y>>n)-a.canonical.y,l=t.a6<<n;t.c7(s,0,l,l,0,0,1),t.Q(s,s,[r*t.a6+o*l,i*t.a6+c*l,0])}o.terrainRttPosMatrix32f=new Float32Array(s),r[i]=o}return r}getSourceTile(e,t){var n,r;let i=this.tileManager._source,a=e.overscaledZ-this.deltaZoom;if(a>i.maxzoom&&(a=i.maxzoom),a<i.minzoom)return;(n=this._sourceTileCache)[r=e.key]||(n[r]=e.scaledTo(a).key);let o=this.findTileInCaches(this._sourceTileCache[e.key]);if(!o?.dem&&t)for(;a>=i.minzoom&&!o?.dem;)o=this.findTileInCaches(e.scaledTo(a--).key);return o}findTileInCaches(e){let t=this.tileManager.getTileByID(e);return t||(t=this.tileManager._outOfViewCache.getByKey(e),t)}anyTilesAfterTime(e=Date.now()){return this._lastTilesetChange>=e}_isWithinTileRanges(e,t){let n=t[e.canonical.z];return!!n&&(e.wrap>n.minWrap||e.wrap<n.maxWrap||e.canonical.x>=n.minTileXWrapped&&e.canonical.x<=n.maxTileXWrapped&&e.canonical.y>=n.minTileY&&e.canonical.y<=n.maxTileY)}}class Qa{constructor(e,t,n){this._meshCache={},this.painter=e,this.tileManager=new Za(t),this.options=n,this.exaggeration=typeof n.exaggeration==`number`?n.exaggeration:1,this.qualityFactor=2,this.meshSize=128,this._demMatrixCache={},this.coordsIndex=[],this._coordsTextureSize=1024}destroy(){this._fbo&&=(this._fbo.destroy(),null),this._fboCoordsTexture&&=(this._fboCoordsTexture.destroy(),null),this._fboDepthTexture&&=(this._fboDepthTexture.destroy(),null),this._emptyDemTexture&&=(this._emptyDemTexture.destroy(),null),this._emptyDepthTexture&&=(this._emptyDepthTexture.destroy(),null),this._coordsTexture&&=(this._coordsTexture.destroy(),null);for(let e in this._meshCache)this._meshCache[e].destroy();this._meshCache={},this.tileManager.destruct()}getDEMElevation(e,n,r,i=t.a6){let a=e.normalizeCoordinates(n,r,i);if(!a)return 0;let o=this.getTerrainData(a.tileID),s=o.tile?.dem;if(!s)return 0;let c=t.cC([],[a.x/i*t.a6,a.y/i*t.a6],o.u_terrain_matrix),l=[c[0]*s.dim,c[1]*s.dim],u=Math.floor(l[0]),d=Math.floor(l[1]),f=l[0]-u,p=l[1]-d;return s.get(u,d)*(1-f)*(1-p)+s.get(u+1,d)*f*(1-p)+s.get(u,d+1)*(1-f)*p+s.get(u+1,d+1)*f*p}getElevationForLngLatZoom(e,n){if(!t.cD(n,e.wrap()))return 0;let{tileID:r,mercatorX:i,mercatorY:a}=this._getOverscaledTileIDFromLngLatZoom(e,n);return this.getElevation(r,i%t.a6,a%t.a6,t.a6)}getElevationForLngLat(e,t){let n=We(t,{maxzoom:this.tileManager.maxzoom,minzoom:this.tileManager.minzoom,tileSize:512,terrain:this}),r=0;for(let e of n)e.canonical.z>r&&(r=Math.min(e.canonical.z,this.tileManager.maxzoom));return this.getElevationForLngLatZoom(e,r)}getElevation(e,n,r,i=t.a6){return this.getDEMElevation(e,n,r,i)*this.exaggeration}getTerrainData(e){if(!this._emptyDemTexture){let e=this.painter.context,n=new t.R({width:1,height:1},new Uint8Array(4));this._emptyDepthTexture=new t.T(e,n,e.gl.RGBA,{premultiply:!1}),this._emptyDemUnpack=[0,0,0,0],this._emptyDemTexture=new t.T(e,new t.R({width:1,height:1}),e.gl.RGBA,{premultiply:!1}),this._emptyDemTexture.bind(e.gl.NEAREST,e.gl.CLAMP_TO_EDGE),this._emptyDemMatrix=t.ap([])}let n=this.tileManager.getSourceTile(e,!0);if(n?.dem&&(!n.demTexture||n.needsTerrainPrepare)){let e=this.painter.context;n.demTexture=this.painter.getTileTexture(n.dem.stride),n.demTexture?n.demTexture.update(n.dem.getPixels(),{premultiply:!1}):n.demTexture=new t.T(e,n.dem.getPixels(),e.gl.RGBA,{premultiply:!1}),n.demTexture.bind(e.gl.NEAREST,e.gl.CLAMP_TO_EDGE),n.needsTerrainPrepare=!1}let r=n&&n.toString()+n.tileID.key+e.key;if(r&&!this._demMatrixCache[r]){let i=this.tileManager.getSource().maxzoom,a=e.canonical.z-n.tileID.canonical.z;e.overscaledZ>e.canonical.z&&(e.canonical.z>=i?a=e.canonical.z-i:t.w(`cannot calculate elevation if elevation maxzoom > source.maxzoom`));let o=e.canonical.x-(e.canonical.x>>a<<a),s=e.canonical.y-(e.canonical.y>>a<<a),c=t.cE(new Float64Array(16),[1/(t.a6<<a),1/(t.a6<<a),0]);t.Q(c,c,[o*t.a6,s*t.a6,0]),this._demMatrixCache[r]={matrix:c,coord:e}}return{u_depth:2,u_terrain:3,u_terrain_dim:n?.dem?.dim||1,u_terrain_matrix:r?this._demMatrixCache[r].matrix:this._emptyDemMatrix,u_terrain_unpack:(n?.dem)?.getUnpackVector()||this._emptyDemUnpack,u_terrain_exaggeration:this.exaggeration,texture:(n?.demTexture||this._emptyDemTexture).texture,depthTexture:(this._fboDepthTexture||this._emptyDepthTexture).texture,tile:n}}getFramebuffer(e){let n=this.painter,r=n.width/devicePixelRatio,i=n.height/devicePixelRatio;return!this._fbo||this._fbo.width===r&&this._fbo.height===i||(this._fbo.destroy(),this._fboCoordsTexture.destroy(),this._fboDepthTexture.destroy(),delete this._fbo,delete this._fboDepthTexture,delete this._fboCoordsTexture),this._fboCoordsTexture||(this._fboCoordsTexture=new t.T(n.context,{width:r,height:i,data:null},n.context.gl.RGBA,{premultiply:!1}),this._fboCoordsTexture.bind(n.context.gl.NEAREST,n.context.gl.CLAMP_TO_EDGE)),this._fboDepthTexture||(this._fboDepthTexture=new t.T(n.context,{width:r,height:i,data:null},n.context.gl.RGBA,{premultiply:!1}),this._fboDepthTexture.bind(n.context.gl.NEAREST,n.context.gl.CLAMP_TO_EDGE)),this._fbo||(this._fbo=n.context.createFramebuffer(r,i,!0,!1),this._fbo.depthAttachment.set(n.context.createRenderbuffer(n.context.gl.DEPTH_COMPONENT16,r,i))),this._fbo.colorAttachment.set(e===`coords`?this._fboCoordsTexture.texture:this._fboDepthTexture.texture),this._fbo}getCoordsTexture(){let e=this.painter.context;if(this._coordsTexture)return this._coordsTexture;let n=new Uint8Array(this._coordsTextureSize*this._coordsTextureSize*4);for(let e=0,t=0;e<this._coordsTextureSize;e++)for(let r=0;r<this._coordsTextureSize;r++,t+=4)n[t+0]=255&r,n[t+1]=255&e,n[t+2]=r>>8<<4|e>>8,n[t+3]=0;let r=new t.R({width:this._coordsTextureSize,height:this._coordsTextureSize},new Uint8Array(n.buffer)),i=new t.T(e,r,e.gl.RGBA,{premultiply:!1});return i.bind(e.gl.NEAREST,e.gl.CLAMP_TO_EDGE),this._coordsTexture=i,i}pointCoordinate(e){this.painter.maybeDrawDepth(!0),this.painter.maybeDrawCoords();let n=new Uint8Array(4),r=this.painter.context,i=r.gl,a=Math.round(e.x*this.painter.pixelRatio/devicePixelRatio),o=Math.round(e.y*this.painter.pixelRatio/devicePixelRatio),s=Math.round(this.painter.height/devicePixelRatio);r.bindFramebuffer.set(this.getFramebuffer(`coords`).framebuffer),i.readPixels(a,s-o-1,1,1,i.RGBA,i.UNSIGNED_BYTE,n),r.bindFramebuffer.set(null);let c=n[0]+(n[2]>>4<<8),l=n[1]+((15&n[2])<<8),u=this.coordsIndex[255-n[3]],d=u&&this.tileManager.getTileByID(u);if(!d)return null;let f=this._coordsTextureSize,p=(1<<d.tileID.canonical.z)*f;return new t.a7((d.tileID.canonical.x*f+c)/p+d.tileID.wrap,(d.tileID.canonical.y*f+l)/p,this.getElevation(d.tileID,c,l,f))}depthAtPoint(e){let t=new Uint8Array(4),n=this.painter.context,r=n.gl;return n.bindFramebuffer.set(this.getFramebuffer(`depth`).framebuffer),r.readPixels(e.x,this.painter.height/devicePixelRatio-e.y-1,1,1,r.RGBA,r.UNSIGNED_BYTE,t),n.bindFramebuffer.set(null),(t[0]/16777216+t[1]/65536+t[2]/256+t[3])/256}getTerrainMesh(e){let n=this.painter.style.projection?.transitionState>0,r=n&&e.canonical.y===0,i=n&&e.canonical.y===(1<<e.canonical.z)-1,a=`m_${r?`n`:``}_${i?`s`:``}`;if(this._meshCache[a])return this._meshCache[a];let o=this.painter.context,s=new t.cF,c=new t.aW,l=this.meshSize,u=t.a6/l,d=l*l;for(let e=0;e<=l;e++)for(let t=0;t<=l;t++)s.emplaceBack(t*u,e*u,0);for(let e=0;e<d;e+=l+1)for(let t=0;t<l;t++)c.emplaceBack(t+e,l+t+e+1,l+t+e+2),c.emplaceBack(t+e,l+t+e+2,t+e+1);let f=s.length,p=f+(l+1),m=(l+1)*l,h=r?t.bq:0,g=+!r,_=i?t.br:t.a6,v=+!i;for(let e=0;e<=l;e++)s.emplaceBack(e*u,h,g);for(let e=0;e<=l;e++)s.emplaceBack(e*u,_,v);for(let e=0;e<l;e++)c.emplaceBack(m+e,p+e,p+e+1),c.emplaceBack(m+e,p+e+1,m+e+1),c.emplaceBack(0+e,f+e+1,f+e),c.emplaceBack(0+e,0+e+1,f+e+1);let y=s.length,b=y+2*(l+1);for(let e of[0,1])for(let n=0;n<=l;n++)for(let r of[0,1])s.emplaceBack(e*t.a6,n*u,r);for(let e=0;e<2*l;e+=2)c.emplaceBack(y+e,y+e+1,y+e+3),c.emplaceBack(y+e,y+e+3,y+e+2),c.emplaceBack(b+e,b+e+3,b+e+1),c.emplaceBack(b+e,b+e+2,b+e+3);let x=new Jt(o.createVertexBuffer(s,Xa.members),o.createIndexBuffer(c),t.aV.simpleSegment(0,0,s.length,c.length));return this._meshCache[a]=x,x}getMeshFrameDelta(e){return 2*Math.PI*t.bD/2**Math.max(e,0)/5}getMinTileElevationForLngLatZoom(e,n){if(!t.cD(n,e.wrap()))return 0;let{tileID:r}=this._getOverscaledTileIDFromLngLatZoom(e,n);return this.getMinMaxElevation(r).minElevation??0}getMinMaxElevation(e){let t=this.getTerrainData(e).tile,n={minElevation:null,maxElevation:null};return t!=null&&t.dem&&(n.minElevation=t.dem.min*this.exaggeration,n.maxElevation=t.dem.max*this.exaggeration),n}_getOverscaledTileIDFromLngLatZoom(e,n){let r=t.a7.fromLngLat(e.wrap()),i=(1<<n)*t.a6,a=r.x*i,o=r.y*i,s=Math.floor(a/t.a6),c=Math.floor(o/t.a6);return{tileID:new t.a3(n,0,n,s,c),mercatorX:a,mercatorY:o}}}class $a{constructor(e,t,n){this._context=e,this._size=t,this._tileSize=n,this._objects=[],this._recentlyUsed=[],this._stamp=0}destruct(){for(let e of this._objects)e.texture.destroy(),e.fbo.destroy()}_createObject(e){let n=this._context.createFramebuffer(this._tileSize,this._tileSize,!0,!0),r=new t.T(this._context,{width:this._tileSize,height:this._tileSize,data:null},this._context.gl.RGBA);return r.bind(this._context.gl.LINEAR,this._context.gl.CLAMP_TO_EDGE),this._context.extTextureFilterAnisotropic&&this._context.gl.texParameterf(this._context.gl.TEXTURE_2D,this._context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,this._context.extTextureFilterAnisotropicMax),n.depthAttachment.set(this._context.createRenderbuffer(this._context.gl.DEPTH_STENCIL,this._tileSize,this._tileSize)),n.colorAttachment.set(r.texture),{id:e,fbo:n,texture:r,stamp:-1,inUse:!1}}getObjectForId(e){return this._objects[e]}useObject(e){e.inUse=!0,this._recentlyUsed=this._recentlyUsed.filter((t=>e.id!==t)),this._recentlyUsed.push(e.id)}stampObject(e){e.stamp=++this._stamp}getOrCreateFreeObject(){for(let e of this._recentlyUsed)if(!this._objects[e].inUse)return this._objects[e];if(this._objects.length>=this._size)throw Error(`No free RenderPool available, call freeAllObjects() required!`);let e=this._createObject(this._objects.length);return this._objects.push(e),e}freeObject(e){e.inUse=!1}freeAllObjects(){for(let e of this._objects)this.freeObject(e)}isFull(){return!(this._objects.length<this._size)&&!1===this._objects.some((e=>!e.inUse))}}let eo={background:!0,fill:!0,line:!0,raster:!0,hillshade:!0,"color-relief":!0};class to{constructor(e,t){this.painter=e,this.terrain=t,this.pool=new $a(e.context,30,t.tileManager.tileSize*t.qualityFactor)}destruct(){this.pool.destruct()}getTexture(e){return this.pool.getObjectForId(e.rtt[this._stacks.length-1].id).texture}prepareForRender(e,t){var n;this._stacks=[],this._prevType=null,this._rttTiles=[],this._renderableTiles=this.terrain.tileManager.getRenderableTiles(),this._renderableLayerIds=e._order.filter((n=>!e._layers[n].isHidden(t))),this._coordsAscending={};for(let t in e.tileManagers){this._coordsAscending[t]={};let r=e.tileManagers[t].getVisibleCoordinates(),i=e.tileManagers[t].getSource(),a=i instanceof Ce?i.terrainTileRanges:null;for(let e of r){let r=this.terrain.tileManager.getTerrainCoords(e,a);for(let e in r)(n=this._coordsAscending[t])[e]||(n[e]=[]),this._coordsAscending[t][e].push(r[e])}}this._rttFingerprints={};for(let t of e._order){let n=e._layers[t],r=n.source;if(eo[n.type]&&!this._rttFingerprints[r]){this._rttFingerprints[r]={};let t=e.tileManagers[r]?.getState().revision??0;for(let e in this._coordsAscending[r])this._rttFingerprints[r][e]=`${this._coordsAscending[r][e].map((e=>e.key)).sort().join()}#${t}`}}for(let e of this._renderableTiles)for(let t in this._rttFingerprints){let n=this._rttFingerprints[t][e.tileID.key];n&&n!==e.rttFingerprint[t]&&(e.rtt=[])}}renderLayer(e,n){if(e.isHidden(this.painter.transform.zoom))return!1;let r=Object.assign(Object.assign({},n),{isRenderingToTexture:!0}),i=e.type,a=this.painter,o=this._renderableLayerIds[this._renderableLayerIds.length-1]===e.id;if(eo[i]&&(this._prevType&&eo[this._prevType]||this._stacks.push([]),this._prevType=i,this._stacks[this._stacks.length-1].push(e.id),!o))return!0;if(eo[this._prevType]||eo[i]&&o){this._prevType=i;let e=this._stacks.length-1,n=this._stacks[e]||[];for(let i of this._renderableTiles){if(this.pool.isFull()&&(Ki(this.painter,this.terrain,this._rttTiles,r),this._rttTiles=[],this.pool.freeAllObjects()),this._rttTiles.push(i),i.rtt[e]){let t=this.pool.getObjectForId(i.rtt[e].id);if(t.stamp===i.rtt[e].stamp){this.pool.useObject(t);continue}}let o=this.pool.getOrCreateFreeObject();this.pool.useObject(o),this.pool.stampObject(o),i.rtt[e]={id:o.id,stamp:o.stamp},a.context.bindFramebuffer.set(o.fbo.framebuffer),a.context.clear({color:t.bo.transparent,stencil:0}),a.currentStencilSource=void 0;for(let e of n){let t=a.style._layers[e],n=t.source?this._coordsAscending[t.source][i.tileID.key]:[i.tileID];a.context.viewport.set([0,0,o.fbo.width,o.fbo.height]),a._renderTileClippingMasks(t,n,!0),a.renderLayer(a,a.style.tileManagers[t.source],t,n,r),t.source&&(i.rttFingerprint[t.source]=this._rttFingerprints[t.source][i.tileID.key])}}return Ki(this.painter,this.terrain,this._rttTiles,r),this._rttTiles=[],this.pool.freeAllObjects(),eo[i]}return!1}}let no={"AttributionControl.ToggleAttribution":`Toggle attribution`,"AttributionControl.MapFeedback":`Map feedback`,"FullscreenControl.Enter":`Enter fullscreen`,"FullscreenControl.Exit":`Exit fullscreen`,"GeolocateControl.FindMyLocation":`Find my location`,"GeolocateControl.LocationNotAvailable":`Location not available`,"LogoControl.Title":`MapLibre logo`,"Map.Title":`Map`,"Marker.Title":`Map marker`,"NavigationControl.ResetBearing":`Drag to rotate map, click to reset north`,"NavigationControl.ZoomIn":`Zoom in`,"NavigationControl.ZoomOut":`Zoom out`,"Popup.Close":`Close popup`,"ScaleControl.Feet":`ft`,"ScaleControl.Meters":`m`,"ScaleControl.Kilometers":`km`,"ScaleControl.Miles":`mi`,"ScaleControl.NauticalMiles":`nm`,"GlobeControl.Enable":`Enable globe`,"GlobeControl.Disable":`Disable globe`,"TerrainControl.Enable":`Enable terrain`,"TerrainControl.Disable":`Disable terrain`,"CooperativeGesturesHandler.WindowsHelpText":`Use Ctrl + scroll to zoom the map`,"CooperativeGesturesHandler.MacHelpText":`Use ⌘ + scroll to zoom the map`,"CooperativeGesturesHandler.MobileHelpText":`Use two fingers to move the map`},ro=n,io={hash:!1,interactive:!0,bearingSnap:7,zoomSnap:0,attributionControl:Ka,maplibreLogo:!1,refreshExpiredTiles:!0,canvasContextAttributes:{antialias:!1,preserveDrawingBuffer:!1,powerPreference:`high-performance`,failIfMajorPerformanceCaveat:!1,desynchronized:!1,contextType:void 0},scrollZoom:!0,minZoom:-2,maxZoom:22,minPitch:0,maxPitch:60,boxZoom:!0,dragRotate:!0,dragPan:!0,keyboard:!0,doubleClickZoom:!0,touchZoomRotate:!0,touchPitch:!0,cooperativeGestures:!1,trackResize:!0,center:[0,0],elevation:0,zoom:0,bearing:0,pitch:0,roll:0,renderWorldCopies:!0,maxTileCacheSize:null,maxTileCacheZoomLevels:t.c.MAX_TILE_CACHE_ZOOM_LEVELS,transformRequest:null,transformCameraUpdate:null,transformConstrain:null,fadeDuration:300,crossSourceCollisions:!0,clickTolerance:3,localIdeographFontFamily:`sans-serif`,pitchWithRotate:!0,rollEnabled:!1,reduceMotion:void 0,validateStyle:!0,maxCanvasSize:[4096,4096],cancelPendingTileRequestsWhileZooming:!0,centerClampedToGround:!0,experimentalZoomLevelsToOverscale:void 0,anisotropicFilterPitch:20},ao=class extends ${get _ownerWindow(){return this._container?.ownerDocument?.defaultView||window}constructor(e){var n;let r=Object.assign(Object.assign(Object.assign({},io),e),{canvasContextAttributes:Object.assign(Object.assign({},io.canvasContextAttributes),e.canvasContextAttributes)});if(r.minZoom!=null&&r.maxZoom!=null&&r.minZoom>r.maxZoom)throw Error(`maxZoom must be greater than or equal to minZoom`);if(r.minPitch!=null&&r.maxPitch!=null&&r.minPitch>r.maxPitch)throw Error(`maxPitch must be greater than or equal to minPitch`);if(r.minPitch!=null&&r.minPitch<0)throw Error(`minPitch must be greater than or equal to 0`);if(r.maxPitch!=null&&r.maxPitch>180)throw Error(`maxPitch must be less than or equal to 180`);let i=new on,a=new ln;r.minZoom!==void 0&&i.setMinZoom(r.minZoom),r.maxZoom!==void 0&&i.setMaxZoom(r.maxZoom),r.minPitch!==void 0&&i.setMinPitch(r.minPitch),r.maxPitch!==void 0&&i.setMaxPitch(r.maxPitch),r.renderWorldCopies!==void 0&&i.setRenderWorldCopies(r.renderWorldCopies),r.transformConstrain!==null&&i.setConstrainOverride(r.transformConstrain),super(i,a,{bearingSnap:r.bearingSnap,zoomSnap:r.zoomSnap}),this._idleTriggered=!1,this._crossFadingFactor=1,this._renderTaskQueue=new Ya,this._controls=[],this._mapId=t.ad(),this._lostContextStyle={style:null,images:null},this._contextLost=e=>{if(e.preventDefault(),this._frameRequest&&=(this._frameRequest.abort(),null),this.painter.destroy(),this._lostContextStyle=this._getStyleAndImages(),this.style){for(let e of Object.values(this.style._layers))if(e.type===`custom`&&console.warn(`Custom layer with id '${e.id}' cannot be restored after WebGL context loss. You will need to re-add it manually after context restoration.`),e._listeners)for(let[t]of Object.entries(e._listeners))console.warn(`Custom layer with id '${e.id}' had event listeners for event '${t}' which cannot be restored after WebGL context loss. You will need to re-add them manually after context restoration.`);this.style.destroy(),this.style=null,this.fire(new t.n(`webglcontextlost`,{originalEvent:e}))}else this.fire(new t.n(`webglcontextlost`,{originalEvent:e}))},this._contextRestored=e=>{this._lostContextStyle.style&&this.setStyle(this._lostContextStyle.style,{diff:!1}),this._lostContextStyle.images&&this.style&&(this.style.imageManager.images=this._lostContextStyle.images),this._lostContextStyle={style:null,images:null},this._setupPainter(),this.resize(),this._update(),this._resizeInternal(),this.fire(new t.n(`webglcontextrestored`,{originalEvent:e}))},this._onMapScroll=e=>{if(e.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1},this._onWindowOnline=()=>{this._update()},this._interactive=r.interactive,this._maxTileCacheSize=r.maxTileCacheSize,this._maxTileCacheZoomLevels=r.maxTileCacheZoomLevels,this._canvasContextAttributes=Object.assign({},r.canvasContextAttributes),this._trackResize=!0===r.trackResize,this._bearingSnap=r.bearingSnap,this._zoomSnap=r.zoomSnap,this._centerClampedToGround=r.centerClampedToGround,this._refreshExpiredTiles=!0===r.refreshExpiredTiles,this._fadeDuration=r.fadeDuration,this._crossSourceCollisions=!0===r.crossSourceCollisions,this._collectResourceTiming=!0===r.collectResourceTiming,this._locale=Object.assign(Object.assign({},no),r.locale),this._clickTolerance=r.clickTolerance,this._overridePixelRatio=r.pixelRatio,this._maxCanvasSize=r.maxCanvasSize,this._zoomLevelsToOverscale=r.experimentalZoomLevelsToOverscale,this.transformCameraUpdate=r.transformCameraUpdate,this.transformConstrain=r.transformConstrain,this.cancelPendingTileRequestsWhileZooming=!0===r.cancelPendingTileRequestsWhileZooming,this.setAnisotropicFilterPitch(r.anisotropicFilterPitch),r.reduceMotion!==void 0&&(s.prefersReducedMotion=r.reduceMotion),this._imageQueueHandle=u.addThrottleControl((()=>this.isMoving())),this._requestManager=new f(r.transformRequest),this._container=this._resolveContainer(r.container),r.maxBounds&&this.setMaxBounds(r.maxBounds),this._setupContainer(),this._setupPainter(),this.on(`move`,(()=>this._update(!1))),this.on(`moveend`,(()=>this._update(!1))),this.on(`zoom`,(()=>this._update(!0))),this.on(`terrain`,(()=>{this.painter.terrainFacilitator.depthDirty=!0,this._update(!0)})),this.once(`idle`,(()=>this._idleTriggered=!0)),typeof window<`u`&&(this._ownerWindow.addEventListener(`online`,this._onWindowOnline,!1),this._setupResizeObserver()),this.handlers=new Q(this,r),this._hash=r.hash?new Zi(typeof r.hash==`string`&&r.hash||void 0).addTo(this):void 0,(n=this._hash)!=null&&n._onHashChange()||(this.jumpTo({center:r.center,elevation:r.elevation,zoom:r.zoom,bearing:r.bearing,pitch:r.pitch,roll:r.roll}),r.bounds&&(this.resize(),this.fitBounds(r.bounds,t.e({},r.fitBoundsOptions,{duration:0}))));let o=typeof r.style==`string`||r.style?.projection?.type!==`globe`;this.resize(null,o),this._localIdeographFontFamily=r.localIdeographFontFamily,this._validateStyle=r.validateStyle,r.style&&this.setStyle(r.style,{localIdeographFontFamily:r.localIdeographFontFamily}),r.attributionControl&&this.addControl(new qa(typeof r.attributionControl==`boolean`?void 0:r.attributionControl)),r.maplibreLogo&&this.addControl(new Ja,r.logoPosition),this.on(`style.load`,(()=>{if(o||this._resizeTransform(),this.transform.unmodified){let e=t.V(this.style.stylesheet,[`center`,`zoom`,`bearing`,`pitch`,`roll`]);this.jumpTo(e)}})),this.on(`data`,(e=>{this._update(e.dataType===`style`),this.fire(new t.n(`${e.dataType}data`,e))})),this.on(`dataloading`,(e=>{this.fire(new t.n(`${e.dataType}dataloading`,e))})),this.on(`dataabort`,(e=>{this.fire(new t.n(`sourcedataabort`,e))}))}_getMapId(){return this._mapId}setGlobalStateProperty(e,t){return this.style.setGlobalStateProperty(e,t),this._update(!0)}getGlobalState(){return this.style.getGlobalState()}addControl(e,n){if(n===void 0&&(n=e.getDefaultPosition?e.getDefaultPosition():`top-right`),!e?.onAdd)return this.fire(new t.l(Error(`Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.`)));let r=e.onAdd(this);this._controls.push(e);let i=this._controlPositions[n];return n.includes(`bottom`)?i.insertBefore(r,i.firstChild):i.appendChild(r),this}removeControl(e){if(!e?.onRemove)return this.fire(new t.l(Error(`Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.`)));let n=this._controls.indexOf(e);return n>-1&&this._controls.splice(n,1),e.onRemove(this),this}hasControl(e){return this._controls.includes(e)}coveringTiles(e){return We(this.transform,e)}calculateCameraOptionsFromTo(e,t,n,r){return r==null&&this.terrain&&(r=this.terrain.getElevationForLngLat(n,this.transform)),super.calculateCameraOptionsFromTo(e,t,n,r)}resize(e,n=!0){if(this._lostContextStyle.style!==null)return this;this._resizeInternal(n);let r=!this._moving;return r&&(this.stop(),this.fire(new t.n(`movestart`,e)).fire(new t.n(`move`,e))),this.fire(new t.n(`resize`,e)),r&&this.fire(new t.n(`moveend`,e)),this}_resizeInternal(e=!0){let[t,n]=this._containerDimensions(),r=this._getClampedPixelRatio(t,n);if(this._resizeCanvas(t,n,r),this.painter.resize(t,n,r),this.painter.overLimit()){let e=this.painter.context.gl;this._maxCanvasSize=[e.drawingBufferWidth,e.drawingBufferHeight];let r=this._getClampedPixelRatio(t,n);this._resizeCanvas(t,n,r),this.painter.resize(t,n,r)}this._resizeTransform(e)}_resizeTransform(e=!0){var t;let[n,r]=this._containerDimensions();this.transform.resize(n,r,e),(t=this._requestedCameraState)==null||t.resize(n,r,e)}_getClampedPixelRatio(e,t){let{0:n,1:r}=this._maxCanvasSize,i=this.getPixelRatio(),a=e*i,o=t*i;return Math.min(a>n?n/a:1,o>r?r/o:1)*i}getPixelRatio(){return this._overridePixelRatio??devicePixelRatio}setPixelRatio(e){this._overridePixelRatio=e,this.resize()}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()}setMaxBounds(e){return this.transform.setMaxBounds(de.convert(e)),this._update()}setMinZoom(e){if((e??=-2)>=-2&&e<=this.transform.maxZoom){let n=this.transform.zoom,r=this._getTransformForUpdate();return r.setMinZoom(e),this._applyUpdatedTransform(r),this._update(),n!==this.transform.zoom&&this.fire(new t.n(`zoomstart`)).fire(new t.n(`zoom`)).fire(new t.n(`zoomend`)).fire(new t.n(`movestart`)).fire(new t.n(`move`)).fire(new t.n(`moveend`)),this}throw Error(`minZoom must be between -2 and the current maxZoom, inclusive`)}getMinZoom(){return this.transform.minZoom}setMaxZoom(e){if((e??=22)>=this.transform.minZoom){let n=this.transform.zoom,r=this._getTransformForUpdate();return r.setMaxZoom(e),this._applyUpdatedTransform(r),this._update(),n!==this.transform.zoom&&this.fire(new t.n(`zoomstart`)).fire(new t.n(`zoom`)).fire(new t.n(`zoomend`)).fire(new t.n(`movestart`)).fire(new t.n(`move`)).fire(new t.n(`moveend`)),this}throw Error(`maxZoom must be greater than the current minZoom`)}getMaxZoom(){return this.transform.maxZoom}setMinPitch(e){if((e??=0)<0)throw Error(`minPitch must be greater than or equal to 0`);if(e>=0&&e<=this.transform.maxPitch){let n=this.transform.pitch,r=this._getTransformForUpdate();return r.setMinPitch(e),this._applyUpdatedTransform(r),this._update(),n!==this.transform.pitch&&this.fire(new t.n(`pitchstart`)).fire(new t.n(`pitch`)).fire(new t.n(`pitchend`)).fire(new t.n(`movestart`)).fire(new t.n(`move`)).fire(new t.n(`moveend`)),this}throw Error(`minPitch must be between 0 and the current maxPitch, inclusive`)}getMinPitch(){return this.transform.minPitch}setMaxPitch(e){if((e??=60)>180)throw Error(`maxPitch must be less than or equal to 180`);if(e>=this.transform.minPitch){let n=this.transform.pitch,r=this._getTransformForUpdate();return r.setMaxPitch(e),this._applyUpdatedTransform(r),this._update(),n!==this.transform.pitch&&this.fire(new t.n(`pitchstart`)).fire(new t.n(`pitch`)).fire(new t.n(`pitchend`)).fire(new t.n(`movestart`)).fire(new t.n(`move`)).fire(new t.n(`moveend`)),this}throw Error(`maxPitch must be greater than the current minPitch`)}getMaxPitch(){return this.transform.maxPitch}getAnisotropicFilterPitch(){return this._anisotropicFilterPitch}setAnisotropicFilterPitch(e){if((e??=20)>180)throw Error(`anisotropicFilterPitch must be less than or equal to 180`);if(e<0)throw Error(`anisotropicFilterPitch must be greater than or equal to 0`);return this._anisotropicFilterPitch=e,this._update()}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(e){return this.transform.setRenderWorldCopies(e),this._update()}setTransformConstrain(e){return this.transform.setConstrainOverride(e),this._update()}project(e){return this.transform.locationToScreenPoint(t.W.convert(e),this.style&&this.terrain)}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this.terrain)}isMoving(){return this._moving||this.handlers?.isMoving()}isZooming(){return this._zooming||this.handlers?.isZooming()}isRotating(){return this._rotating||this.handlers?.isRotating()}_createDelegatedListener(e,t,n){if(e===`mouseenter`||e===`mouseover`){let r=!1;return{layers:t,listener:n,delegates:{mousemove:i=>{let a=t.filter((e=>this.getLayer(e))),o=a.length===0?[]:this.queryRenderedFeatures(i.point,{layers:a});o.length?r||(r=!0,n.call(this,new oa(e,this,i.originalEvent,{features:o}))):r=!1},mouseout:()=>{r=!1}}}}if(e===`mouseleave`||e===`mouseout`){let r=!1;return{layers:t,listener:n,delegates:{mousemove:i=>{let a=t.filter((e=>this.getLayer(e)));(a.length===0?[]:this.queryRenderedFeatures(i.point,{layers:a})).length?r=!0:r&&(r=!1,n.call(this,new oa(e,this,i.originalEvent)))},mouseout:t=>{r&&(r=!1,n.call(this,new oa(e,this,t.originalEvent)))}}}}{let r=e=>{let r=t.filter((e=>this.getLayer(e))),i=r.length===0?[]:this.queryRenderedFeatures(e.point,{layers:r});i.length&&(e.features=i,n.call(this,e),delete e.features)};return{layers:t,listener:n,delegates:{[e]:r}}}}_saveDelegatedListener(e,t){var n;this._delegatedListeners||={},(n=this._delegatedListeners)[e]||(n[e]=[]),this._delegatedListeners[e].push(t)}_removeDelegatedListener(e,t,n){if(!this._delegatedListeners?.[e])return;let r=this._delegatedListeners[e];for(let e=0;e<r.length;e++){let i=r[e];if(i.listener===n&&i.layers.length===t.length&&i.layers.every((e=>t.includes(e)))){for(let e in i.delegates)this.off(e,i.delegates[e]);r.splice(e,1);return}}}on(e,t,n){if(n===void 0)return super.on(e,t);let r=typeof t==`string`?[t]:t,i=this._createDelegatedListener(e,r,n);this._saveDelegatedListener(e,i);for(let e in i.delegates)this.on(e,i.delegates[e]);return{unsubscribe:()=>{this._removeDelegatedListener(e,r,n)}}}once(e,t,n){if(n===void 0)return super.once(e,t);let r=typeof t==`string`?[t]:t,i=this._createDelegatedListener(e,r,n);for(let t in i.delegates){let a=i.delegates[t];i.delegates[t]=(...t)=>{this._removeDelegatedListener(e,r,n),a(...t)}}this._saveDelegatedListener(e,i);for(let e in i.delegates)this.once(e,i.delegates[e]);return this}off(e,t,n){return n===void 0?super.off(e,t):(this._removeDelegatedListener(e,typeof t==`string`?[t]:t,n),this)}queryRenderedFeatures(e,n){if(!this.style)return[];let r,i=e instanceof t.P||Array.isArray(e),a=i?e:[[0,0],[this.transform.width,this.transform.height]];if(n||=(i?{}:e)||{},a instanceof t.P||typeof a[0]==`number`)r=[t.P.convert(a)];else{let e=t.P.convert(a[0]),n=t.P.convert(a[1]);r=[e,new t.P(n.x,e.y),n,new t.P(e.x,n.y),e]}return this.style.queryRenderedFeatures(r,n,this.transform)}querySourceFeatures(e,t){return this.style.querySourceFeatures(e,t)}setStyle(e,n){return!1!==(n=t.e({},{localIdeographFontFamily:this._localIdeographFontFamily,validate:this._validateStyle},n)).diff&&n.localIdeographFontFamily===this._localIdeographFontFamily&&this.style&&e?(this._diffStyle(e,n),this):(this._localIdeographFontFamily=n.localIdeographFontFamily,this._updateStyle(e,n))}setTransformRequest(e){return this._requestManager.setTransformRequest(e),this}_getUIString(e){let t=this._locale[e];if(t==null)throw Error(`Missing UI string '${e}'`);return t}_updateStyle(e,t){var n,r;if((n=this._diffStyleRequest)==null||n.abort(),this._diffStyleRequest=null,t.transformStyle&&this.style&&!this.style._loaded)return void this.style.once(`style.load`,(()=>this._updateStyle(e,t)));let i=this.style&&t.transformStyle?this.style.serialize():void 0;return this.style&&(this.style.setEventedParent(null),this.style._remove(!e)),e?(this.style=new Un(this,t||{}),this.style.setEventedParent(this,{style:this.style}),typeof e==`string`?this.style.loadURL(e,t,i):this.style.loadJSON(e,t,i),this):(this._frameRequest&&=(this._frameRequest.abort(),null),(r=this.style?.projection)==null||r.destroy(),delete this.style,this)}_lazyInitEmptyStyle(){this.style||(this.style=new Un(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty())}_diffStyle(e,n){return t._(this,void 0,void 0,(function*(){var r;if((r=this._diffStyleRequest)==null||r.abort(),typeof e==`string`){let r=e;this._diffStyleRequest=new AbortController;let i=this._diffStyleRequest;try{let e=yield this._requestManager.transformRequest(r,`Style`);if(i.signal.aborted)return void(this._diffStyleRequest=null);let a=yield t.k(e,i);this._diffStyleRequest=null,this._updateDiff(a.data,n)}catch(e){this._diffStyleRequest=null,t.$(e)||this.fire(new t.l(t.d(e)))}}else typeof e==`object`&&(this._diffStyleRequest=null,this._updateDiff(e,n))}))}_updateDiff(e,n){try{this.style.setState(e,n)&&this._update(!0)}catch(r){t.w(`Unable to perform style diff: ${t.d(r).message}. Rebuilding the style from scratch.`),this._updateStyle(e,n)}}getStyle(){if(this.style)return this.style.serialize()}_getStyleAndImages(){return this.style?{style:this.style.serialize(),images:this.style.imageManager.cloneImages()}:{style:null,images:{}}}isStyleLoaded(){if(this.style)return this.style.loaded();t.w(`There is no style added to the map.`)}addSource(e,t){return this._lazyInitEmptyStyle(),this.style.addSource(e,t),this._update(!0)}isSourceLoaded(e){let n=this.style?.tileManagers[e];if(n!==void 0)return n.loaded();this.fire(new t.l(Error(`There is no tile manager with ID '${e}'`)))}setTerrain(e){if(this.style._checkLoaded(),this._terrainDataCallback&&this.style.off(`data`,this._terrainDataCallback),e){let n=this.style.tileManagers[e.source];if(!n)throw Error(`cannot load terrain, because there exists no source with ID: ${e.source}`);this.terrain===null&&n.reload();for(let n in this.style._layers){let r=this.style._layers[n];r.type===`hillshade`&&r.source===e.source&&t.w(`You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.`),r.type===`color-relief`&&r.source===e.source&&t.w(`You are using the same source for a color-relief layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.`)}this.terrain=new Qa(this.painter,n,e),this.painter.renderToTexture=new to(this.painter,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._terrainDataCallback=t=>{t.dataType===`style`?this.terrain.tileManager.freeRtt():t.dataType===`source`&&t.tile&&(t.sourceId!==e.source||this._elevationFreeze||(this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))),t.source?.type===`image`?this.terrain.tileManager.freeRtt():this.terrain.tileManager.freeRtt(t.tile.tileID))},this.style.on(`data`,this._terrainDataCallback)}else this.terrain&&this.terrain.destroy(),this.terrain=null,this.painter.renderToTexture&&this.painter.renderToTexture.destruct(),this.painter.renderToTexture=null,this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0);return this.fire(new t.n(`terrain`,{terrain:e})),this}getTerrain(){return this.terrain?.options??null}areTilesLoaded(){let e=this.style?.tileManagers;for(let t of Object.values(e))if(!t.areTilesLoaded())return!1;return!0}removeSource(e){return this.style.removeSource(e),this._update(!0)}getSource(e){return this.style.getSource(e)}setSourceTileLodParams(e,t,n){if(n){let r=this.getSource(n);if(!r)throw Error(`There is no source with ID "${n}", cannot set LOD parameters`);r.calculateTileZoom=N(Math.max(1,e),Math.max(1,t))}else for(let n in this.style.tileManagers)this.style.tileManagers[n].getSource().calculateTileZoom=N(Math.max(1,e),Math.max(1,t));return this._update(!0),this}refreshTiles(e,n){let r=this.style.tileManagers[e];if(!r)throw Error(`There is no tile manager with ID "${e}", cannot refresh tile`);n===void 0?r.reload(!0):r.refreshTiles(n.map((e=>new t.aa(e.z,e.x,e.y))))}addImage(e,n,r={}){let{pixelRatio:i=1,sdf:a=!1,stretchX:o,stretchY:c,content:l,textFitWidth:u,textFitHeight:d}=r;if(this._lazyInitEmptyStyle(),!(n instanceof HTMLImageElement||t.b(n))){if(n.width===void 0||n.height===void 0)return this.fire(new t.l(Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));{let{width:r,height:s,data:f}=n,p=n;return this.style.addImage(e,{data:new t.R({width:r,height:s},new Uint8Array(f)),pixelRatio:i,stretchX:o,stretchY:c,content:l,textFitWidth:u,textFitHeight:d,sdf:a,version:0,userImage:p}),p.onAdd&&p.onAdd(this,e),this}}{let{width:r,height:f,data:p}=s.getImageData(n);this.style.addImage(e,{data:new t.R({width:r,height:f},p),pixelRatio:i,stretchX:o,stretchY:c,content:l,textFitWidth:u,textFitHeight:d,sdf:a,version:0})}}updateImage(e,n){let r=this.style.getImage(e);if(!r)return this.fire(new t.l(Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));let{width:i,height:a,data:o}=n instanceof HTMLImageElement||t.b(n)?s.getImageData(n):n;if(i===void 0||a===void 0)return this.fire(new t.l(Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(i!==r.data.width||a!==r.data.height)return this.fire(new t.l(Error(`The width and height of the updated image must be that same as the previous version of the image`)));let c=!(n instanceof HTMLImageElement||t.b(n));return r.data.replace(o,c),this.style.updateImage(e,r),this}getImage(e){return this.style.getImage(e)}hasImage(e){return e?!!this.style.getImage(e):(this.fire(new t.l(Error(`Missing required image id`))),!1)}removeImage(e){this.style.removeImage(e)}loadImage(e){return t._(this,void 0,void 0,(function*(){return u.getImage(yield this._requestManager.transformRequest(e,`Image`),new AbortController)}))}listImages(){return this.style.listImages()}addLayer(e,t){return this._lazyInitEmptyStyle(),this.style.addLayer(e,t),this._update(!0)}moveLayer(e,t){return this.style.moveLayer(e,t),this._update(!0)}removeLayer(e){return this.style.removeLayer(e),this._update(!0)}getLayer(e){return this.style.getLayer(e)}getLayersOrder(){return this.style.getLayersOrder()}setLayerZoomRange(e,t,n){return this.style.setLayerZoomRange(e,t,n),this._update(!0)}setFilter(e,t,n={}){return this.style.setFilter(e,t,n),this._update(!0)}getFilter(e){return this.style.getFilter(e)}setPaintProperty(e,t,n,r={}){return this.style.setPaintProperty(e,t,n,r),this._update(!0)}getPaintProperty(e,t){return this.style.getPaintProperty(e,t)}setLayoutProperty(e,t,n,r={}){return this.style.setLayoutProperty(e,t,n,r),this._update(!0)}getLayoutProperty(e,t){return this.style.getLayoutProperty(e,t)}setGlyphs(e,t={}){return this._lazyInitEmptyStyle(),this.style.setGlyphs(e,t),this._update(!0)}getGlyphs(){return this.style.getGlyphsUrl()}addSprite(e,t,n={}){return this._lazyInitEmptyStyle(),this.style.addSprite(e,t,n,(e=>{e||this._update(!0)})),this}removeSprite(e){return this._lazyInitEmptyStyle(),this.style.removeSprite(e),this._update(!0)}getSprite(){return this.style.getSprite()}setSprite(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSprite(e,t,(e=>{e||this._update(!0)})),this}setLight(e,t={}){return this._lazyInitEmptyStyle(),this.style.setLight(e,t),this._update(!0)}getLight(){return this.style.getLight()}setSky(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSky(e,t),this._update(!0)}getSky(){return this.style.getSky()}setFeatureState(e,t){return this.style.setFeatureState(e,t),this._update()}removeFeatureState(e,t){return this.style.removeFeatureState(e,t),this._update()}getFeatureState(e){return this.style.getFeatureState(e)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}_containerDimensions(){let e=0,t=0;return this._container&&(e=this._container.clientWidth||400,t=this._container.clientHeight||300),[e,t]}_setupResizeObserver(){let e=!1,t=Xi((e=>{this._trackResize&&!this._removed&&(this.resize(e),this.redraw())}),50),n=this._ownerWindow.ResizeObserver??ResizeObserver;this._resizeObserver=new n((n=>{e?t(n):e=!0})),this._resizeObserver.observe(this._container)}_resolveContainer(e){if(typeof e==`string`){let t=document.getElementById(e);if(!t)throw Error(`Container '${e}' not found.`);return t}if(e instanceof HTMLElement||e&&typeof e==`object`&&e.nodeType===1)return e;throw Error(`Invalid type: 'container' must be a String or HTMLElement.`)}_setupContainer(){let e=this._container;e.classList.add(`maplibregl-map`);let t=this._canvasContainer=d.create(`div`,`maplibregl-canvas-container`,e);this._interactive&&t.classList.add(`maplibregl-interactive`),this._canvas=d.create(`canvas`,`maplibregl-canvas`,t),this._canvas.addEventListener(`webglcontextlost`,this._contextLost,!1),this._canvas.addEventListener(`webglcontextrestored`,this._contextRestored,!1),this._canvas.setAttribute(`tabindex`,this._interactive?`0`:`-1`),this._canvas.setAttribute(`aria-label`,this._getUIString(`Map.Title`)),this._canvas.setAttribute(`role`,`region`);let n=this._containerDimensions(),r=this._getClampedPixelRatio(n[0],n[1]);this._resizeCanvas(n[0],n[1],r);let i=this._controlContainer=d.create(`div`,`maplibregl-control-container`,e),a=this._controlPositions={};for(let e of[`top-left`,`top-right`,`bottom-left`,`bottom-right`])a[e]=d.create(`div`,`maplibregl-ctrl-${e} `,i);this._container.addEventListener(`scroll`,this._onMapScroll,!1)}_resizeCanvas(e,t,n){this._canvas.width=Math.floor(n*e),this._canvas.height=Math.floor(n*t),this._canvas.style.width=`${e}px`,this._canvas.style.height=`${t}px`}_setupPainter(){let e=Object.assign(Object.assign({},this._canvasContextAttributes),{alpha:!0,depth:!0,stencil:!0,premultipliedAlpha:!0}),t=null;this._canvas.addEventListener(`webglcontextcreationerror`,(n=>{t={requestedAttributes:e},n&&(t.statusMessage=n.statusMessage,t.type=n.type)}),{once:!0});let n=null;if(n=this._canvasContextAttributes.contextType?this._canvas.getContext(this._canvasContextAttributes.contextType,e):this._canvas.getContext(`webgl2`,e)||this._canvas.getContext(`webgl`,e),!n){let e=`Failed to initialize WebGL`;throw t?(t.message=e,Error(JSON.stringify(t))):Error(e)}this.painter=new Yi(n,this.transform)}migrateProjection(e,n){super.migrateProjection(e,n),this.painter.transform=e,this.fire(new t.n(`projectiontransition`,{newProjection:this.style.projection.name}))}loaded(){return!this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}_update(e){return this.style?._loaded?(this._styleDirty||=e,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(e){return this._update(),this._renderTaskQueue.add(e)}_cancelRenderFrame(e){this._renderTaskQueue.remove(e)}_render(e){var n;let r=this._idleTriggered?this._fadeDuration:0,i=this.style.projection?.transitionState>0;if(this.painter.context.setDirty(),this.painter.setBaseState(),this._renderTaskQueue.run(e),this._removed)return;let a=!1;if(this.style&&this._styleDirty){this._styleDirty=!1;let e=this.transform.zoom,n=l();this.style.zoomHistory.update(e,n);let i=new t.J(e,{now:n,fadeDuration:r,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),o=i.crossFadingFactor();o===1&&o===this._crossFadingFactor||(a=!0,this._crossFadingFactor=o),this.style.update(i)}let o=this.style.projection?.transitionState>0!==i;(n=this.style.projection)==null||n.setErrorQueryLatitudeDegrees(this.transform.center.lat),this.transform.setTransitionState(this.style.projection?.transitionState,this.style.projection?.latitudeErrorCorrectionRadians),this.style&&(this._sourcesDirty||o)&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this.terrain?(this.terrain.tileManager.update(this.transform,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),!this._elevationFreeze&&this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))):(this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0)),this._placementDirty=this.style?._updatePlacement(this.transform,this.showCollisionBoxes,r,this._crossSourceCollisions,o),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:r,showPadding:this.showPadding,anisotropicFilterPitch:this.getAnisotropicFilterPitch()}),this.fire(new t.n(`render`)),this.loaded()&&!this._loaded&&(this._loaded=!0,this.fire(new t.n(`load`))),this.style&&(this.style.hasTransitions()||a)&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles();let s=this._sourcesDirty||this._styleDirty||this._placementDirty;return s||this._repaint?this.triggerRepaint():!this.isMoving()&&this.loaded()&&this.fire(new t.n(`idle`)),!this._loaded||this._fullyLoaded||s||(this._fullyLoaded=!0),this}redraw(){return this.style&&(this._frameRequest&&=(this._frameRequest.abort(),null),this._render(0)),this}remove(){var e,n;this._hash&&this._hash.remove();for(let e of this._controls)e.onRemove(this);this._controls=[],this._frameRequest&&=(this._frameRequest.abort(),null),this._renderTaskQueue.clear(),(e=this._diffStyleRequest)==null||e.abort(),this.painter.destroy(),this.handlers.destroy(),delete this.handlers,this.setStyle(null),typeof window<`u`&&this._ownerWindow.removeEventListener(`online`,this._onWindowOnline,!1),u.removeThrottleControl(this._imageQueueHandle),(n=this._resizeObserver)==null||n.disconnect();let r=this.painter.context.gl.getExtension(`WEBGL_lose_context`);r!=null&&r.loseContext&&r.loseContext(),this._canvas.removeEventListener(`webglcontextrestored`,this._contextRestored,!1),this._canvas.removeEventListener(`webglcontextlost`,this._contextLost,!1),this._canvasContainer.remove(),this._controlContainer.remove(),this._container.removeEventListener(`scroll`,this._onMapScroll,!1),this._container.classList.remove(`maplibregl-map`),this._removed=!0,this.fire(new t.n(`remove`))}triggerRepaint(){this.style&&!this._frameRequest&&(this._frameRequest=new AbortController,s.frame(this._frameRequest,(e=>{this._frameRequest=null;try{this._render(e)}catch(e){if(!t.$(e)&&!function(e){return e.message===ci}(e))throw e}}),(()=>{}),this._ownerWindow))}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(e){this._showTileBoundaries!==e&&(this._showTileBoundaries=e,this._update())}get showPadding(){return!!this._showPadding}set showPadding(e){this._showPadding!==e&&(this._showPadding=e,this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(e){this._showCollisionBoxes!==e&&(this._showCollisionBoxes=e,e?this.style._generateCollisionBoxes():this._update())}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(e){this._showOverdrawInspector!==e&&(this._showOverdrawInspector=e,this._update())}get repaint(){return!!this._repaint}set repaint(e){this._repaint!==e&&(this._repaint=e,this.triggerRepaint())}get vertices(){return!!this._vertices}set vertices(e){this._vertices=e,this._update()}get version(){return ro}getCameraTargetElevation(){return this.transform.elevation}getProjection(){return this.style.getProjection()}setProjection(e){return this._lazyInitEmptyStyle(),this.style.setProjection(e),this._update(!0)}},oo={showCompass:!0,showZoom:!0,visualizePitch:!1,visualizeRoll:!0};class so{constructor(e,n,r=!1){this.mousedown=e=>{this.startMove(e,d.mousePos(this.element,e)),window.addEventListener(`mousemove`,this.mousemove),window.addEventListener(`mouseup`,this.mouseup)},this.mousemove=e=>{this.move(e,d.mousePos(this.element,e))},this.mouseup=e=>{this._rotatePitchHandler.dragEnd(e),this.offTemp()},this.touchstart=e=>{e.targetTouches.length===1?(this._startPos=this._lastPos=d.touchPos(this.element,e.targetTouches)[0],this.startMove(e,this._startPos),window.addEventListener(`touchmove`,this.touchmove,{passive:!1}),window.addEventListener(`touchend`,this.touchend)):this.reset()},this.touchmove=e=>{e.targetTouches.length===1?(this._lastPos=d.touchPos(this.element,e.targetTouches)[0],this.move(e,this._lastPos)):this.reset()},this.touchend=e=>{e.targetTouches.length===0&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)<this._clickTolerance&&this.element.click(),delete this._startPos,delete this._lastPos,this.offTemp()},this.reset=()=>{this._rotatePitchHandler.reset(),delete this._startPos,delete this._lastPos,this.offTemp()},this._clickTolerance=10,this.element=n;let i=new ba;this._rotatePitchHandler=new ga({clickTolerance:3,move:(e,i)=>{let a=n.getBoundingClientRect(),o=new t.P((a.bottom-a.top)/2,(a.right-a.left)/2);return{bearingDelta:t.cx(new t.P(e.x,i.y),i,o),pitchDelta:r?-.5*(i.y-e.y):void 0}},moveStateManager:i,enable:!0,assignEvents:()=>{}}),this.map=e,n.addEventListener(`mousedown`,this.mousedown),n.addEventListener(`touchstart`,this.touchstart,{passive:!1}),n.addEventListener(`touchcancel`,this.reset)}startMove(e,t){this._rotatePitchHandler.dragStart(e,t),d.disableDrag()}move(e,t){let n=this.map,{bearingDelta:r,pitchDelta:i}=this._rotatePitchHandler.dragMove(e,t)||{};r&&n.setBearing(n.getBearing()+r),i&&n.setPitch(n.getPitch()+i)}off(){let e=this.element;e.removeEventListener(`mousedown`,this.mousedown),e.removeEventListener(`touchstart`,this.touchstart),window.removeEventListener(`touchmove`,this.touchmove),window.removeEventListener(`touchend`,this.touchend),e.removeEventListener(`touchcancel`,this.reset),this.offTemp()}offTemp(){d.enableDrag(),window.removeEventListener(`mousemove`,this.mousemove),window.removeEventListener(`mouseup`,this.mouseup),window.removeEventListener(`touchmove`,this.touchmove),window.removeEventListener(`touchend`,this.touchend)}}let co;function lo(e,n,r,i=!1){if(i||!r.getCoveringTilesDetailsProvider().allowWorldCopies())return e?.wrap();let a=new t.W(e.lng,e.lat);if(e=new t.W(e.lng,e.lat),n){let i=new t.W(e.lng-360,e.lat),a=new t.W(e.lng+360,e.lat),o=r.locationToScreenPoint(e).distSqr(n);r.locationToScreenPoint(i).distSqr(n)<o?e=i:r.locationToScreenPoint(a).distSqr(n)<o&&(e=a)}for(;Math.abs(e.lng-r.center.lng)>180;){let t=r.locationToScreenPoint(e);if(t.x>=0&&t.y>=0&&t.x<=r.width&&t.y<=r.height)break;e.lng>r.center.lng?e.lng-=360:e.lng+=360}return e.lng!==a.lng&&r.isPointOnMapSurface(r.locationToScreenPoint(e))?e:a}let uo={center:`translate(-50%,-50%)`,top:`translate(-50%,0)`,"top-left":`translate(0,0)`,"top-right":`translate(-100%,0)`,bottom:`translate(-50%,-100%)`,"bottom-left":`translate(0,-100%)`,"bottom-right":`translate(-100%,-100%)`,left:`translate(0,-50%)`,right:`translate(-100%,-50%)`};function fo(e,t,n){let r=e.classList;for(let e in uo)r.remove(`maplibregl-${n}-anchor-${e}`);r.add(`maplibregl-${n}-anchor-${t}`)}class po extends t.E{constructor(e){if(super(),this._onClick=e=>{this.fire(new t.n(`click`,{originalEvent:e}))},this._onKeyPress=e=>{e.code!==`Space`&&e.code!==`Enter`||this.togglePopup()},this._onMapClick=e=>{let t=e.originalEvent.target,n=this._element;this._popup&&(t===n||n.contains(t))&&this.togglePopup()},this._update=e=>{if(!this._map)return;let t=this._map.loaded()&&!this._map.isMoving();(e?.type===`terrain`||e?.type===`render`&&!t)&&this._map.once(`render`,this._update),this._lngLat=lo(this._lngLat,this._flatPos,this._map.transform),this._flatPos=this._pos=this._map.project(this._lngLat)._add(this._offset),this._map.terrain&&(this._flatPos=this._map.transform.locationToScreenPoint(this._lngLat)._add(this._offset));let n=``;this._rotationAlignment===`viewport`||this._rotationAlignment===`auto`?n=`rotateZ(${this._rotation}deg)`:this._rotationAlignment===`map`&&(n=`rotateZ(${this._rotation-this._map.getBearing()}deg)`);let r=``;this._pitchAlignment===`viewport`||this._pitchAlignment===`auto`?r=`rotateX(0deg)`:this._pitchAlignment===`map`&&(r=`rotateX(${this._map.getPitch()}deg)`),this._subpixelPositioning||e&&e.type!==`moveend`||(this._pos=this._pos.round()),this._element.style.transform=`${uo[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${r} ${n}`,s.frameAsync(new AbortController,this._map._ownerWindow).then((()=>{this._updateOpacity(e?.type===`moveend`)})).catch((()=>{}))},this._onMove=e=>{if(!this._isDragging){let t=this._clickTolerance||this._map._clickTolerance;this._isDragging=e.point.dist(this._pointerdownPos)>=t}this._isDragging&&(this._pos=e.point.sub(this._positionDelta),this._lngLat=this._map.unproject(this._pos),this.setLngLat(this._lngLat),this._element.style.pointerEvents=`none`,this._state===`pending`&&(this._state=`active`,this.fire(new t.n(`dragstart`))),this.fire(new t.n(`drag`)))},this._onUp=()=>{this._element.style.pointerEvents=`auto`,this._positionDelta=null,this._pointerdownPos=null,this._isDragging=!1,this._map.off(`mousemove`,this._onMove),this._map.off(`touchmove`,this._onMove),this._state===`active`&&this.fire(new t.n(`dragend`)),this._state=`inactive`},this._addDragHandler=e=>{this._element.contains(e.originalEvent.target)&&(e.preventDefault(),this._positionDelta=e.point.sub(this._pos).add(this._offset),this._pointerdownPos=e.point,this._state=`pending`,this._map.on(`mousemove`,this._onMove),this._map.on(`touchmove`,this._onMove),this._map.once(`mouseup`,this._onUp),this._map.once(`touchend`,this._onUp))},this._anchor=e?.anchor||`center`,this._color=e?.color||`#3FB1CE`,this._scale=e?.scale||1,this._draggable=e?.draggable||!1,this._clickTolerance=e?.clickTolerance||0,this._subpixelPositioning=e?.subpixelPositioning||!1,this._isDragging=!1,this._state=`inactive`,this._rotation=e?.rotation||0,this._rotationAlignment=e?.rotationAlignment||`auto`,this._pitchAlignment=e?.pitchAlignment&&e.pitchAlignment!==`auto`?e.pitchAlignment:this._rotationAlignment,this.setOpacity(e?.opacity,e?.opacityWhenCovered),e?.element)this._element=e.element,this._offset=t.P.convert(e?.offset||[0,0]);else{this._defaultMarker=!0,this._element=d.create(`div`);let n=d.createNS(`http://www.w3.org/2000/svg`,`svg`);n.setAttributeNS(null,`display`,`block`),n.setAttributeNS(null,`height`,`41px`),n.setAttributeNS(null,`width`,`27px`),n.setAttributeNS(null,`viewBox`,`0 0 27 41`);let r=d.createNS(`http://www.w3.org/2000/svg`,`g`);r.setAttributeNS(null,`stroke`,`none`),r.setAttributeNS(null,`stroke-width`,`1`),r.setAttributeNS(null,`fill`,`none`),r.setAttributeNS(null,`fill-rule`,`evenodd`);let i=d.createNS(`http://www.w3.org/2000/svg`,`g`);i.setAttributeNS(null,`fill-rule`,`nonzero`);let a=d.createNS(`http://www.w3.org/2000/svg`,`g`);a.setAttributeNS(null,`transform`,`translate(3.0, 29.0)`),a.setAttributeNS(null,`fill`,`#000000`);for(let e of[{rx:`10.5`,ry:`5.25002273`},{rx:`10.5`,ry:`5.25002273`},{rx:`9.5`,ry:`4.77275007`},{rx:`8.5`,ry:`4.29549936`},{rx:`7.5`,ry:`3.81822308`},{rx:`6.5`,ry:`3.34094679`},{rx:`5.5`,ry:`2.86367051`},{rx:`4.5`,ry:`2.38636864`}]){let t=d.createNS(`http://www.w3.org/2000/svg`,`ellipse`);t.setAttributeNS(null,`opacity`,`0.04`),t.setAttributeNS(null,`cx`,`10.5`),t.setAttributeNS(null,`cy`,`5.80029008`),t.setAttributeNS(null,`rx`,e.rx),t.setAttributeNS(null,`ry`,e.ry),a.appendChild(t)}let o=d.createNS(`http://www.w3.org/2000/svg`,`g`);o.setAttributeNS(null,`fill`,this._color);let s=d.createNS(`http://www.w3.org/2000/svg`,`path`);s.setAttributeNS(null,`d`,`M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z`),o.appendChild(s);let c=d.createNS(`http://www.w3.org/2000/svg`,`g`);c.setAttributeNS(null,`opacity`,`0.25`),c.setAttributeNS(null,`fill`,`#000000`);let l=d.createNS(`http://www.w3.org/2000/svg`,`path`);l.setAttributeNS(null,`d`,`M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z`),c.appendChild(l);let u=d.createNS(`http://www.w3.org/2000/svg`,`g`);u.setAttributeNS(null,`transform`,`translate(6.0, 7.0)`),u.setAttributeNS(null,`fill`,`#FFFFFF`);let f=d.createNS(`http://www.w3.org/2000/svg`,`g`);f.setAttributeNS(null,`transform`,`translate(8.0, 8.0)`);let p=d.createNS(`http://www.w3.org/2000/svg`,`circle`);p.setAttributeNS(null,`fill`,`#000000`),p.setAttributeNS(null,`opacity`,`0.25`),p.setAttributeNS(null,`cx`,`5.5`),p.setAttributeNS(null,`cy`,`5.5`),p.setAttributeNS(null,`r`,`5.4999962`);let m=d.createNS(`http://www.w3.org/2000/svg`,`circle`);m.setAttributeNS(null,`fill`,`#FFFFFF`),m.setAttributeNS(null,`cx`,`5.5`),m.setAttributeNS(null,`cy`,`5.5`),m.setAttributeNS(null,`r`,`5.4999962`),f.appendChild(p),f.appendChild(m),i.appendChild(a),i.appendChild(o),i.appendChild(c),i.appendChild(u),i.appendChild(f),n.appendChild(i),n.setAttributeNS(null,`height`,41*this._scale+`px`),n.setAttributeNS(null,`width`,27*this._scale+`px`),this._element.appendChild(n),this._offset=t.P.convert(e?.offset||[0,-14])}if(this._element.classList.add(`maplibregl-marker`),this._element.addEventListener(`dragstart`,(e=>{e.preventDefault()})),this._element.addEventListener(`mousedown`,(e=>{e.preventDefault()})),fo(this._element,this._anchor,`marker`),e?.className)for(let t of e.className.split(` `))this._element.classList.add(t);this._popup=null}addTo(e){return this.remove(),this._map=e,this._element.hasAttribute(`aria-label`)||this._element.setAttribute(`aria-label`,e._getUIString(`Marker.Title`)),this._element.hasAttribute(`role`)||this._element.setAttribute(`role`,`button`),e.getCanvasContainer().appendChild(this._element),e.on(`move`,this._update),e.on(`moveend`,this._update),e.on(`terrain`,this._update),e.on(`projectiontransition`,this._update),this._element.addEventListener(`click`,this._onClick),this.setDraggable(this._draggable),this._update(),this._map.on(`click`,this._onMapClick),this}remove(){return this._opacityTimeout&&(clearTimeout(this._opacityTimeout),delete this._opacityTimeout),this._map&&(this._map.off(`click`,this._onMapClick),this._map.off(`move`,this._update),this._map.off(`moveend`,this._update),this._map.off(`terrain`,this._update),this._map.off(`projectiontransition`,this._update),this._map.off(`mousedown`,this._addDragHandler),this._map.off(`touchstart`,this._addDragHandler),this._map.off(`mouseup`,this._onUp),this._map.off(`touchend`,this._onUp),this._map.off(`mousemove`,this._onMove),this._map.off(`touchmove`,this._onMove),delete this._map),this._element.removeEventListener(`click`,this._onClick),this._element.remove(),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.W.convert(e),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this}getElement(){return this._element}setPopup(e){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeEventListener(`keypress`,this._onKeyPress),this._originalTabIndex||this._element.removeAttribute(`tabindex`)),e){if(!(`offset`in e.options)){let t=38.1,n=13.5,r=13.5/Math.SQRT2;e.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[r,-1*(t-n+r)],"bottom-right":[-r,-1*(t-n+r)],left:[n,-1*(t-n)],right:[-13.5,-1*(t-n)]}:this._offset}this._popup=e,this._originalTabIndex=this._element.getAttribute(`tabindex`),this._originalTabIndex||this._element.setAttribute(`tabindex`,`0`),this._element.addEventListener(`keypress`,this._onKeyPress)}return this}setSubpixelPositioning(e){return this._subpixelPositioning=e,this}getPopup(){return this._popup}togglePopup(){let e=this._popup;return this._element.style.opacity===this._opacityWhenCovered||e&&(e.isOpen()?e.remove():(e.setLngLat(this._lngLat),e.addTo(this._map))),this}_updateOpacity(e=!1){var n;let r=this._map?.terrain,i=this._map.transform.isLocationOccluded(this._lngLat);if(!r||i){let e=i?this._opacityWhenCovered:this._opacity;this._element.style.opacity!==e&&(this._element.style.opacity=e,this._element.classList.toggle(`maplibregl-marker-covered`,i));return}if(e)this._opacityTimeout=null;else{if(this._opacityTimeout)return;this._opacityTimeout=setTimeout((()=>{this._opacityTimeout=null}),100)}let a=this._map,o=a.terrain.depthAtPoint(this._pos),s=a.terrain.getElevationForLngLat(this._lngLat,a.transform);if(a.transform.lngLatToCameraDepth(this._lngLat,s)-o<.006)return this._element.style.opacity=this._opacity,void this._element.classList.remove(`maplibregl-marker-covered`);let c=-this._offset.y/a.transform.pixelsPerMeter,l=Math.sin(a.getPitch()*Math.PI/180)*c,u=a.terrain.depthAtPoint(new t.P(this._pos.x,this._pos.y-this._offset.y)),d=a.transform.lngLatToCameraDepth(this._lngLat,s+l)-u>.006;(n=this._popup)!=null&&n.isOpen()&&d&&this._popup.remove(),this._element.style.opacity=d?this._opacityWhenCovered:this._opacity,this._element.classList.toggle(`maplibregl-marker-covered`,d)}getOffset(){return this._offset}setOffset(e){return this._offset=t.P.convert(e),this._update(),this}addClassName(e){this._element.classList.add(e)}removeClassName(e){this._element.classList.remove(e)}toggleClassName(e){return this._element.classList.toggle(e)}setDraggable(e){return this._draggable=!!e,this._map&&(e?(this._map.on(`mousedown`,this._addDragHandler),this._map.on(`touchstart`,this._addDragHandler)):(this._map.off(`mousedown`,this._addDragHandler),this._map.off(`touchstart`,this._addDragHandler))),this}isDraggable(){return this._draggable}setRotation(e){return this._rotation=e||0,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(e){return this._rotationAlignment=e||`auto`,this._update(),this}getRotationAlignment(){return this._rotationAlignment}setPitchAlignment(e){return this._pitchAlignment=e&&e!==`auto`?e:this._rotationAlignment,this._update(),this}getPitchAlignment(){return this._pitchAlignment}setOpacity(e,t){return(this._opacity===void 0||e===void 0&&t===void 0)&&(this._opacity=`1`,this._opacityWhenCovered=`0.2`),e!==void 0&&(this._opacity=String(e)),t!==void 0&&(this._opacityWhenCovered=String(t)),this._map&&this._updateOpacity(!0),this}}let mo={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0},ho=0,go=!1,_o={maxWidth:100,unit:`metric`};function vo(e,t,n){let r=n?.maxWidth||100,i=e._container.clientHeight/2,a=e._container.clientWidth/2,o=e.unproject([a-r/2,i]),s=e.unproject([a+r/2,i]),c=Math.round(e.project(s).x-e.project(o).x),l=Math.min(r,c,e._container.clientWidth),u=o.distanceTo(s);if(n?.unit===`imperial`){let n=3.2808*u;n>5280?yo(t,l,n/5280,e._getUIString(`ScaleControl.Miles`)):yo(t,l,n,e._getUIString(`ScaleControl.Feet`))}else n?.unit===`nautical`?yo(t,l,u/1852,e._getUIString(`ScaleControl.NauticalMiles`)):u>=1e3?yo(t,l,u/1e3,e._getUIString(`ScaleControl.Kilometers`)):yo(t,l,u,e._getUIString(`ScaleControl.Meters`))}function yo(e,t,n,r){let i=function(e){let t=10**(`${Math.floor(e)}`.length-1),n=e/t;return n=n>=10?10:n>=5?5:n>=3?3:n>=2?2:n>=1?1:function(e){let t=10**Math.ceil(-Math.log(e)/Math.LN10);return Math.round(e*t)/t}(n),t*n}(n);e.style.width=i/n*t+`px`,e.innerHTML=`${i}&nbsp;${r}`}let bo={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:``,maxWidth:`240px`,subpixelPositioning:!1,locationOccludedOpacity:void 0,padding:void 0},xo=[`a[href]`,`[tabindex]:not([tabindex='-1'])`,`[contenteditable]:not([contenteditable='false'])`,`button:not([disabled])`,`input:not([disabled])`,`select:not([disabled])`,`textarea:not([disabled])`].join(`, `);function So(e){if(e){if(typeof e==`number`){let n=Math.round(Math.abs(e)/Math.SQRT2);return{center:new t.P(0,0),top:new t.P(0,e),"top-left":new t.P(n,n),"top-right":new t.P(-n,n),bottom:new t.P(0,-e),"bottom-left":new t.P(n,-n),"bottom-right":new t.P(-n,-n),left:new t.P(e,0),right:new t.P(-e,0)}}if(e instanceof t.P||Array.isArray(e)){let n=t.P.convert(e);return{center:n,top:n,"top-left":n,"top-right":n,bottom:n,"bottom-left":n,"bottom-right":n,left:n,right:n}}return{center:t.P.convert(e.center||[0,0]),top:t.P.convert(e.top||[0,0]),"top-left":t.P.convert(e[`top-left`]||[0,0]),"top-right":t.P.convert(e[`top-right`]||[0,0]),bottom:t.P.convert(e.bottom||[0,0]),"bottom-left":t.P.convert(e[`bottom-left`]||[0,0]),"bottom-right":t.P.convert(e[`bottom-right`]||[0,0]),left:t.P.convert(e.left||[0,0]),right:t.P.convert(e.right||[0,0])}}return So(new t.P(0,0))}let Co=n;e.AJAXError=t.cG,e.EXTENT=t.a6,e.Event=t.n,e.Evented=t.E,e.LngLat=t.W,e.MercatorCoordinate=t.a7,e.Point=t.P,e.addProtocol=t.cH,e.config=t.c,e.removeProtocol=t.cI,e.AttributionControl=qa,e.BoxZoomHandler=fa,e.CanvasSource=Te,e.CooperativeGesturesHandler=Ha,e.DoubleClickZoomHandler=Ia,e.DragPanHandler=za,e.DragRotateHandler=Ba,e.EdgeInsets=$t,e.FullscreenControl=class extends t.E{constructor(e={}){var n;super(),this._onFullscreenChange=()=>{let e=window.document.fullscreenElement||window.document.webkitFullscreenElement;for(;e?.shadowRoot?.fullscreenElement;)e=e.shadowRoot.fullscreenElement;e===this._container!==this._fullscreen&&this._handleFullscreenChange()},this._onClickFullscreen=()=>{this._isFullscreen()?this._exitFullscreen():this._requestFullscreen()},this._fullscreen=!1,this._pseudo=(n=e.pseudo)!=null&&n,e!=null&&e.container&&(e.container instanceof HTMLElement?this._container=e.container:t.w(`Full screen control 'container' must be a DOM element.`)),`onfullscreenchange`in document?this._fullscreenchange=`fullscreenchange`:`onmozfullscreenchange`in document?this._fullscreenchange=`mozfullscreenchange`:`onwebkitfullscreenchange`in document?this._fullscreenchange=`webkitfullscreenchange`:`onmsfullscreenchange`in document&&(this._fullscreenchange=`MSFullscreenChange`)}onAdd(e){return this._map=e,this._container||=this._map.getContainer(),this._controlContainer=d.create(`div`,`maplibregl-ctrl maplibregl-ctrl-group`),this._setupUI(),this._controlContainer}onRemove(){this._controlContainer.remove(),this._map=null,window.document.removeEventListener(this._fullscreenchange,this._onFullscreenChange)}_setupUI(){let e=this._fullscreenButton=d.create(`button`,`maplibregl-ctrl-fullscreen`,this._controlContainer);d.create(`span`,`maplibregl-ctrl-icon`,e).setAttribute(`aria-hidden`,`true`),e.type=`button`,this._updateTitle(),this._fullscreenButton.addEventListener(`click`,this._onClickFullscreen),window.document.addEventListener(this._fullscreenchange,this._onFullscreenChange)}_updateTitle(){let e=this._getTitle();this._fullscreenButton.setAttribute(`aria-label`,e),this._fullscreenButton.title=e}_getTitle(){return this._map._getUIString(this._isFullscreen()?`FullscreenControl.Exit`:`FullscreenControl.Enter`)}_isFullscreen(){return this._fullscreen}_handleFullscreenChange(){this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle(`maplibregl-ctrl-shrink`),this._fullscreenButton.classList.toggle(`maplibregl-ctrl-fullscreen`),this._updateTitle(),this._fullscreen?(this.fire(new t.n(`fullscreenstart`)),this._prevCooperativeGesturesEnabled=this._map.cooperativeGestures.isEnabled(),this._map.cooperativeGestures.disable()):(this.fire(new t.n(`fullscreenend`)),this._prevCooperativeGesturesEnabled&&this._map.cooperativeGestures.enable())}_exitFullscreen(){this._pseudo?this._togglePseudoFullScreen():window.document.exitFullscreen?window.document.exitFullscreen():window.document.webkitCancelFullScreen?window.document.webkitCancelFullScreen():this._togglePseudoFullScreen()}_requestFullscreen(){this._pseudo?this._togglePseudoFullScreen():this._container.requestFullscreen?this._container.requestFullscreen():this._container.webkitRequestFullscreen?this._container.webkitRequestFullscreen():this._togglePseudoFullScreen()}_togglePseudoFullScreen(){this._container.classList.toggle(`maplibregl-pseudo-fullscreen`),this._handleFullscreenChange(),this._map.resize()}},e.GeoJSONSource=Se,e.GeolocateControl=class extends t.E{constructor(e){super(),this._onSuccess=e=>{if(this._map){if(this._isOutOfMapMaxBounds(e))return this._setErrorState(),this.fire(new t.n(`outofmaxbounds`,e)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,this._watchState){case`WAITING_ACTIVE`:case`ACTIVE_LOCK`:case`ACTIVE_ERROR`:this._watchState=`ACTIVE_LOCK`,this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-waiting`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-active-error`),this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-active`);break;case`BACKGROUND`:case`BACKGROUND_ERROR`:this._watchState=`BACKGROUND`,this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-waiting`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-background-error`),this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-background`);break;default:throw Error(`Unexpected watchState ${this._watchState}`)}this.options.showUserLocation&&this._watchState!==`OFF`&&this._updateMarker(e),this.options.trackUserLocation&&this._watchState!==`ACTIVE_LOCK`||this._updateCamera(e),this.options.showUserLocation&&this._dotElement.classList.remove(`maplibregl-user-location-dot-stale`),this.fire(new t.n(`geolocate`,e)),this._finish()}},this._updateCamera=e=>{let n=new t.W(e.coords.longitude,e.coords.latitude),r=e.coords.accuracy,i=this._map.getBearing(),a=t.e({bearing:i},this.options.fitBoundsOptions),o=de.fromLngLat(n,r);this._map.fitBounds(o,a,{geolocateSource:!0})},this._updateMarker=e=>{if(e){let n=new t.W(e.coords.longitude,e.coords.latitude);this._accuracyCircleMarker.setLngLat(n).addTo(this._map),this._userLocationDotMarker.setLngLat(n).addTo(this._map),this._accuracy=e.coords.accuracy,this._updateCircleRadiusIfNeeded()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()},this._onUpdate=()=>{this._updateCircleRadiusIfNeeded()},this._onError=e=>{if(this._map){if(e.code===1){this._watchState=`OFF`,this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-waiting`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-active`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-active-error`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-background`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-background-error`),this._geolocateButton.disabled=!0;let e=this._map._getUIString(`GeolocateControl.LocationNotAvailable`);this._geolocateButton.title=e,this._geolocateButton.setAttribute(`aria-label`,e),this._geolocationWatchID!==void 0&&this._clearWatch()}else{if(e.code===3&&go)return;this._setErrorState()}this._watchState!==`OFF`&&this.options.showUserLocation&&this._dotElement.classList.add(`maplibregl-user-location-dot-stale`),this.fire(new t.n(`error`,e)),this._finish()}},this._finish=()=>{this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0},this._onMoveStart=e=>{if(!this._map)return;let n=e?.[0]instanceof ResizeObserverEntry;e.geolocateSource||this._watchState!==`ACTIVE_LOCK`||n||this._map.isZooming()||(this._watchState=`BACKGROUND`,this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-background`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-active`),this.fire(new t.n(`trackuserlocationend`)),this.fire(new t.n(`userlocationlostfocus`)))},this._setupUI=()=>{this._map&&(this._container.addEventListener(`contextmenu`,(e=>{e.preventDefault()})),this._geolocateButton=d.create(`button`,`maplibregl-ctrl-geolocate`,this._container),d.create(`span`,`maplibregl-ctrl-icon`,this._geolocateButton).setAttribute(`aria-hidden`,`true`),this._geolocateButton.type=`button`,this._geolocateButton.disabled=!0)},this._finishSetupUI=e=>{if(this._map){if(!1===e){t.w(`Geolocation support is not available so the GeolocateControl will be disabled.`);let e=this._map._getUIString(`GeolocateControl.LocationNotAvailable`);this._geolocateButton.disabled=!0,this._geolocateButton.title=e,this._geolocateButton.setAttribute(`aria-label`,e)}else{let e=this._map._getUIString(`GeolocateControl.FindMyLocation`);this._geolocateButton.disabled=!1,this._geolocateButton.title=e,this._geolocateButton.setAttribute(`aria-label`,e)}this.options.trackUserLocation&&(this._geolocateButton.setAttribute(`aria-pressed`,`false`),this._watchState=`OFF`),this.options.showUserLocation&&(this._dotElement=d.create(`div`,`maplibregl-user-location-dot`),this._userLocationDotMarker=new po({element:this._dotElement}),this._circleElement=d.create(`div`,`maplibregl-user-location-accuracy-circle`),this._accuracyCircleMarker=new po({element:this._circleElement,pitchAlignment:`map`}),this.options.trackUserLocation&&(this._watchState=`OFF`),this._map.on(`zoom`,this._onUpdate),this._map.on(`move`,this._onUpdate),this._map.on(`rotate`,this._onUpdate),this._map.on(`pitch`,this._onUpdate)),this._geolocateButton.addEventListener(`click`,(()=>this.trigger())),this._setup=!0,this.options.trackUserLocation&&this._map.on(`movestart`,this._onMoveStart)}},this.options=t.e({},mo,e)}onAdd(e){return this._map=e,this._container=d.create(`div`,`maplibregl-ctrl maplibregl-ctrl-group`),this._setupUI(),function(){return t._(this,arguments,void 0,(function*(e=!1){if(co!==void 0&&!e)return co;if(window.navigator.permissions===void 0)return co=!!window.navigator.geolocation,co;try{co=(yield window.navigator.permissions.query({name:`geolocation`})).state!==`denied`}catch{co=!!window.navigator.geolocation}return co}))}().then((e=>this._finishSetupUI(e))),this._container}onRemove(){this._geolocationWatchID!==void 0&&(window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),this._container.remove(),this._map.off(`movestart`,this._onMoveStart),this._map.off(`zoom`,this._onUpdate),this._map.off(`move`,this._onUpdate),this._map.off(`rotate`,this._onUpdate),this._map.off(`pitch`,this._onUpdate),this._map=void 0,ho=0,go=!1}_isOutOfMapMaxBounds(e){let t=this._map.getMaxBounds(),n=e.coords;return t&&(n.longitude<t.getWest()||n.longitude>t.getEast()||n.latitude<t.getSouth()||n.latitude>t.getNorth())}_setErrorState(){switch(this._watchState){case`WAITING_ACTIVE`:this._watchState=`ACTIVE_ERROR`,this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-active`),this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-active-error`);break;case`ACTIVE_LOCK`:this._watchState=`ACTIVE_ERROR`,this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-active`),this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-active-error`),this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-waiting`);break;case`BACKGROUND`:this._watchState=`BACKGROUND_ERROR`,this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-background`),this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-background-error`),this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-waiting`);break;case`ACTIVE_ERROR`:case`BACKGROUND_ERROR`:case`OFF`:case void 0:break;default:throw Error(`Unexpected watchState ${this._watchState}`)}}_updateCircleRadiusIfNeeded(){let e=this._userLocationDotMarker.getLngLat();if(!(this.options.showUserLocation&&this.options.showAccuracyCircle&&this._accuracy&&e))return;let t=this._map.project(e),n=this._map.unproject([t.x+100,t.y]),r=e.distanceTo(n)/100,i=2*this._accuracy/r;this._circleElement.style.width=`${i.toFixed(2)}px`,this._circleElement.style.height=`${i.toFixed(2)}px`}trigger(){if(!this._setup)return t.w(`Geolocate control triggered before added to a map`),!1;if(this.options.trackUserLocation){switch(this._watchState){case`OFF`:this._watchState=`WAITING_ACTIVE`,this.fire(new t.n(`trackuserlocationstart`));break;case`WAITING_ACTIVE`:case`ACTIVE_LOCK`:case`ACTIVE_ERROR`:case`BACKGROUND_ERROR`:ho--,go=!1,this._watchState=`OFF`,this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-waiting`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-active`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-active-error`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-background`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-background-error`),this.fire(new t.n(`trackuserlocationend`));break;case`BACKGROUND`:this._watchState=`ACTIVE_LOCK`,this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-background`),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new t.n(`trackuserlocationstart`)),this.fire(new t.n(`userlocationfocus`));break;default:throw Error(`Unexpected watchState ${this._watchState}`)}switch(this._watchState){case`WAITING_ACTIVE`:this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-waiting`),this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-active`);break;case`ACTIVE_LOCK`:this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-active`);break;case`OFF`:break;default:throw Error(`Unexpected watchState ${this._watchState}`)}if(this._watchState===`OFF`&&this._geolocationWatchID!==void 0)this._clearWatch();else if(this._geolocationWatchID===void 0){let e;this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-waiting`),this._geolocateButton.setAttribute(`aria-pressed`,`true`),ho++,ho>1?(e={maximumAge:6e5,timeout:0},go=!0):(e=this.options.positionOptions,go=!1),this._geolocationWatchID=window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,e)}}else window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return!0}_clearWatch(){window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-waiting`),this._geolocateButton.setAttribute(`aria-pressed`,`false`),this.options.showUserLocation&&this._updateMarker(null)}},e.GlobeControl=class{constructor(){this._toggleProjection=()=>{let e=this._map.getProjection()?.type;this._map.setProjection(e!==`mercator`&&e?{type:`mercator`}:{type:`globe`}),this._updateGlobeIcon()},this._updateGlobeIcon=()=>{this._globeButton.classList.remove(`maplibregl-ctrl-globe`),this._globeButton.classList.remove(`maplibregl-ctrl-globe-enabled`),this._map.getProjection()?.type===`globe`?(this._globeButton.classList.add(`maplibregl-ctrl-globe-enabled`),this._globeButton.title=this._map._getUIString(`GlobeControl.Disable`)):(this._globeButton.classList.add(`maplibregl-ctrl-globe`),this._globeButton.title=this._map._getUIString(`GlobeControl.Enable`))}}onAdd(e){return this._map=e,this._container=d.create(`div`,`maplibregl-ctrl maplibregl-ctrl-group`),this._globeButton=d.create(`button`,`maplibregl-ctrl-globe`,this._container),d.create(`span`,`maplibregl-ctrl-icon`,this._globeButton).setAttribute(`aria-hidden`,`true`),this._globeButton.type=`button`,this._globeButton.addEventListener(`click`,this._toggleProjection),this._updateGlobeIcon(),this._map.on(`styledata`,this._updateGlobeIcon),this._map.on(`projectiontransition`,this._updateGlobeIcon),this._container}onRemove(){this._container.remove(),this._map.off(`styledata`,this._updateGlobeIcon),this._map.off(`projectiontransition`,this._updateGlobeIcon),this._globeButton.removeEventListener(`click`,this._toggleProjection),this._map=void 0}},e.Hash=Zi,e.ImageSource=Ce,e.KeyboardHandler=Ma,e.LngLatBounds=de,e.LogoControl=Ja,e.Map=ao,e.MapLibreMap=ao,e.MapMouseEvent=oa,e.MapTouchEvent=sa,e.MapWheelEvent=ca,e.Marker=po,e.NavigationControl=class{constructor(e){this._updateZoomButtons=()=>{let e=this._map.getZoom(),t=e===this._map.getMaxZoom(),n=e===this._map.getMinZoom();this._zoomInButton.disabled=t,this._zoomOutButton.disabled=n,this._zoomInButton.setAttribute(`aria-disabled`,t.toString()),this._zoomOutButton.setAttribute(`aria-disabled`,n.toString())},this._rotateCompassArrow=()=>{this._compassIcon.style.transform=this.options.visualizePitch&&this.options.visualizeRoll?`scale(${1/Math.cos(this._map.transform.pitchInRadians)**.5}) rotateZ(${-this._map.transform.roll}deg) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizePitch?`scale(${1/Math.cos(this._map.transform.pitchInRadians)**.5}) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizeRoll?`rotate(${-this._map.transform.bearing-this._map.transform.roll}deg)`:`rotate(${-this._map.transform.bearing}deg)`},this._setButtonTitle=(e,t)=>{let n=this._map._getUIString(`NavigationControl.${t}`);e.title=n,e.setAttribute(`aria-label`,n)},this.options=t.e({},oo,e),this._container=d.create(`div`,`maplibregl-ctrl maplibregl-ctrl-group`),this._container.addEventListener(`contextmenu`,(e=>e.preventDefault())),this.options.showZoom&&(this._zoomInButton=this._createButton(`maplibregl-ctrl-zoom-in`,(e=>this._map.zoomIn({},{originalEvent:e}))),d.create(`span`,`maplibregl-ctrl-icon`,this._zoomInButton).setAttribute(`aria-hidden`,`true`),this._zoomOutButton=this._createButton(`maplibregl-ctrl-zoom-out`,(e=>this._map.zoomOut({},{originalEvent:e}))),d.create(`span`,`maplibregl-ctrl-icon`,this._zoomOutButton).setAttribute(`aria-hidden`,`true`)),this.options.showCompass&&(this._compass=this._createButton(`maplibregl-ctrl-compass`,(e=>{this.options.visualizePitch?this._map.resetNorthPitch({},{originalEvent:e}):this._map.resetNorth({},{originalEvent:e})})),this._compassIcon=d.create(`span`,`maplibregl-ctrl-icon`,this._compass),this._compassIcon.setAttribute(`aria-hidden`,`true`))}onAdd(e){return this._map=e,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,`ZoomIn`),this._setButtonTitle(this._zoomOutButton,`ZoomOut`),this._map.on(`zoom`,this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,`ResetBearing`),this.options.visualizePitch&&this._map.on(`pitch`,this._rotateCompassArrow),this.options.visualizeRoll&&this._map.on(`roll`,this._rotateCompassArrow),this._map.on(`rotate`,this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new so(this._map,this._compass,this.options.visualizePitch)),this._container}onRemove(){this._container.remove(),this.options.showZoom&&this._map.off(`zoom`,this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&this._map.off(`pitch`,this._rotateCompassArrow),this.options.visualizeRoll&&this._map.off(`roll`,this._rotateCompassArrow),this._map.off(`rotate`,this._rotateCompassArrow),this._handler.off(),delete this._handler),delete this._map}_createButton(e,t){let n=d.create(`button`,e,this._container);return n.type=`button`,n.addEventListener(`click`,t),n}},e.Popup=class extends t.E{constructor(e){super(),this._updateOpacity=()=>{this.options.locationOccludedOpacity!==void 0&&(this._container.style.opacity=this._map.transform.isLocationOccluded(this.getLngLat())?`${this.options.locationOccludedOpacity}`:``)},this.remove=()=>(this._content&&this._content.remove(),this._container&&(this._container.remove(),delete this._container),this._map&&(this._map.off(`move`,this._update),this._map.off(`move`,this._onClose),this._map.off(`click`,this._onClose),this._map.off(`remove`,this.remove),this._map.off(`terrain`,this._update),this._map.off(`projectiontransition`,this._update),this._map.off(`mousemove`,this._update),this._map.off(`mouseup`,this._update),this._map.off(`drag`,this._update),this._map._canvasContainer.classList.remove(`maplibregl-track-pointer`),delete this._map,this.fire(new t.n(`close`))),this),this._update=e=>{if(!this._map||!this._lngLat&&!this._trackPointer||!this._content)return;if(!this._container){if(this._container=d.create(`div`,`maplibregl-popup`,this._map.getContainer()),this._tip=d.create(`div`,`maplibregl-popup-tip`,this._container),this._container.appendChild(this._content),this.options.className)for(let e of this.options.className.split(` `))this._container.classList.add(e);this._closeButton&&this._closeButton.setAttribute(`aria-label`,this._map._getUIString(`Popup.Close`)),this._trackPointer&&this._container.classList.add(`maplibregl-popup-track-pointer`)}let t;if(this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth&&(this._container.style.maxWidth=this.options.maxWidth),this._lngLat=lo(this._lngLat,this._flatPos,this._map.transform,this._trackPointer),e&&`point`in e&&e.point&&(t=e.point),this._trackPointer&&!t)return;let n=this._flatPos=this._pos=this._trackPointer&&t?t:this._map.project(this._lngLat);this._map.terrain&&(this._flatPos=this._trackPointer&&t?t:this._map.transform.locationToScreenPoint(this._lngLat));let r=this.options.anchor,i=So(this.options.offset);if(!r){let e=this._container.offsetWidth,t=this._container.offsetHeight,a=function(e){return e?{top:e.top??0,right:e.right??0,bottom:e.bottom??0,left:e.left??0}:{top:0,right:0,bottom:0,left:0}}(this.options.padding),o;o=n.y+i.bottom.y<t+a.top?[`top`]:n.y>this._map.transform.height-t-a.bottom?[`bottom`]:[],n.x<e/2+a.left?o.push(`left`):n.x>this._map.transform.width-e/2-a.right&&o.push(`right`),r=o.length===0?`bottom`:o.join(`-`)}let a=n.add(i[r]);this.options.subpixelPositioning||(a=a.round()),this._container.style.transform=`${uo[r]} translate(${a.x}px,${a.y}px)`,fo(this._container,r,`popup`),this._updateOpacity()},this._onClose=()=>{this.remove()},this.options=t.e(Object.create(bo),e)}addTo(e){return this._map&&this.remove(),this._map=e,this.options.closeOnClick&&this._map.on(`click`,this._onClose),this.options.closeOnMove&&this._map.on(`move`,this._onClose),this._map.on(`remove`,this.remove),this._map.on(`terrain`,this._update),this._map.on(`projectiontransition`,this._update),this._update(),this._focusFirstElement(),this._trackPointer?(this._map.on(`mousemove`,this._update),this._map.on(`mouseup`,this._update),this._container&&this._container.classList.add(`maplibregl-popup-track-pointer`),this._map._canvasContainer.classList.add(`maplibregl-track-pointer`)):this._map.on(`move`,this._update),this.fire(new t.n(`open`)),this}isOpen(){return!!this._map}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.W.convert(e),this._pos=null,this._flatPos=null,this._trackPointer=!1,this._update(),this._map&&(this._map.on(`move`,this._update),this._map.off(`mousemove`,this._update),this._container&&this._container.classList.remove(`maplibregl-popup-track-pointer`),this._map._canvasContainer.classList.remove(`maplibregl-track-pointer`)),this}trackPointer(){return this._trackPointer=!0,this._pos=null,this._flatPos=null,this._update(),this._map&&(this._map.off(`move`,this._update),this._map.on(`mousemove`,this._update),this._map.on(`drag`,this._update),this._container&&this._container.classList.add(`maplibregl-popup-track-pointer`),this._map._canvasContainer.classList.add(`maplibregl-track-pointer`)),this}getElement(){return this._container}setText(e){return this.setDOMContent(document.createTextNode(e))}setHTML(e){let t=document.createDocumentFragment(),n=document.createElement(`body`),r;for(n.innerHTML=e;r=n.firstChild,r;)t.appendChild(r);return this.setDOMContent(t)}getMaxWidth(){return this._container?.style.maxWidth}setMaxWidth(e){return this.options.maxWidth=e,this._update(),this}setDOMContent(e){if(this._content)for(;this._content.hasChildNodes();)this._content.firstChild&&this._content.removeChild(this._content.firstChild);else this._content=d.create(`div`,`maplibregl-popup-content`,this._container);return this._content.appendChild(e),this._createCloseButton(),this._update(),this._focusFirstElement(),this}addClassName(e){return this._container&&this._container.classList.add(e),this}removeClassName(e){return this._container&&this._container.classList.remove(e),this}setOffset(e){return this.options.offset=e,this._update(),this}toggleClassName(e){if(this._container)return this._container.classList.toggle(e)}setSubpixelPositioning(e){this.options.subpixelPositioning=e}setPadding(e){this.options.padding=e,this._update()}_createCloseButton(){this.options.closeButton&&(this._closeButton=d.create(`button`,`maplibregl-popup-close-button`,this._content),this._closeButton.type=`button`,this._closeButton.innerHTML=`&#215;`,this._closeButton.addEventListener(`click`,this._onClose))}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;let e=this._container.querySelector(xo);e&&e.focus()}},e.RasterDEMTileSource=he,e.RasterTileSource=me,e.ScaleControl=class{constructor(e){this._onMove=()=>{vo(this._map,this._container,this.options)},this.setUnit=e=>{this.options.unit=e,vo(this._map,this._container,this.options)},this.options=Object.assign(Object.assign({},_o),e)}getDefaultPosition(){return`bottom-left`}onAdd(e){return this._map=e,this._container=d.create(`div`,`maplibregl-ctrl maplibregl-ctrl-scale`,e.getContainer()),this._map.on(`move`,this._onMove),this._onMove(),this._container}onRemove(){this._container.remove(),this._map.off(`move`,this._onMove),this._map=void 0}},e.ScrollZoomHandler=Fa,e.Style=Un,e.TerrainControl=class{constructor(e){this._toggleTerrain=()=>{this._map.getTerrain()?this._map.setTerrain(null):this._map.setTerrain(this.options),this._updateTerrainIcon()},this._updateTerrainIcon=()=>{this._terrainButton.classList.remove(`maplibregl-ctrl-terrain`),this._terrainButton.classList.remove(`maplibregl-ctrl-terrain-enabled`),this._map.terrain?(this._terrainButton.classList.add(`maplibregl-ctrl-terrain-enabled`),this._terrainButton.title=this._map._getUIString(`TerrainControl.Disable`)):(this._terrainButton.classList.add(`maplibregl-ctrl-terrain`),this._terrainButton.title=this._map._getUIString(`TerrainControl.Enable`))},this.options=e}onAdd(e){return this._map=e,this._container=d.create(`div`,`maplibregl-ctrl maplibregl-ctrl-group`),this._terrainButton=d.create(`button`,`maplibregl-ctrl-terrain`,this._container),d.create(`span`,`maplibregl-ctrl-icon`,this._terrainButton).setAttribute(`aria-hidden`,`true`),this._terrainButton.type=`button`,this._terrainButton.addEventListener(`click`,this._toggleTerrain),this._updateTerrainIcon(),this._map.on(`terrain`,this._updateTerrainIcon),this._container}onRemove(){this._container.remove(),this._map.off(`terrain`,this._updateTerrainIcon),this._map=void 0}},e.TwoFingersTouchPitchHandler=Aa,e.TwoFingersTouchRotateHandler=Oa,e.TwoFingersTouchZoomHandler=Ea,e.TwoFingersTouchZoomRotateHandler=Va,e.VectorTileSource=pe,e.VideoSource=we,e.addSourceType=(e,n)=>t._(void 0,void 0,void 0,(function*(){if(De(e))throw Error(`A source type called "${e}" already exists.`);((e,t)=>{Ee[e]=t})(e,n)})),e.clearPrewarmedResources=function(){let e=te;e&&(e.isPreloaded()&&e.numActive()===1?(e.release(k),te=null):console.warn(`Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()`))},e.createTileMesh=yn,e.getGlobalDispatcher=ae,e.getMaxParallelImageRequests=function(){return t.c.MAX_PARALLEL_IMAGE_REQUESTS},e.getRTLTextPluginStatus=function(){return je().getRTLTextPluginStatus()},e.getVersion=function(){return Co},e.getWorkerCount=function(){return A.workerCount},e.getWorkerUrl=function(){return t.c.WORKER_URL},e.importScriptInWorkers=function(e){return ae().broadcast(`IS`,e)},e.isTimeFrozen=function(){return c.isFrozen()},e.now=l,e.prewarm=function(){re().acquire(k)},e.restoreNow=function(){c.restoreNow()},e.setMaxParallelImageRequests=function(e){t.c.MAX_PARALLEL_IMAGE_REQUESTS=e},e.setNow=function(e){c.setNow(e)},e.setRTLTextPlugin=function(e,t){return je().setRTLTextPlugin(e,t)},e.setWorkerCount=function(e){A.workerCount=e},e.setWorkerUrl=function(e){t.c.WORKER_URL=e}})),e}))}))(),1),jl=Uint8Array,Ml=Uint16Array,Nl=Int32Array,Pl=new jl([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]),Fl=new jl([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]),Il=new jl([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ll=function(e,t){for(var n=new Ml(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new Nl(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},Rl=Ll(Pl,2),zl=Rl.b,Bl=Rl.r;zl[28]=258,Bl[258]=28;var Vl=Ll(Fl,0),Hl=Vl.b;Vl.r;for(var Ul=new Ml(32768),Wl=0;Wl<32768;++Wl){var Gl=(Wl&43690)>>1|(Wl&21845)<<1;Gl=(Gl&52428)>>2|(Gl&13107)<<2,Gl=(Gl&61680)>>4|(Gl&3855)<<4,Ul[Wl]=((Gl&65280)>>8|(Gl&255)<<8)>>1}for(var Kl=(function(e,t,n){for(var r=e.length,i=0,a=new Ml(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new Ml(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new Ml(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[Ul[d]>>c]=l}else for(s=new Ml(r),i=0;i<r;++i)e[i]&&(s[i]=Ul[o[e[i]-1]++]>>15-e[i]);return s}),ql=new jl(288),Wl=0;Wl<144;++Wl)ql[Wl]=8;for(var Wl=144;Wl<256;++Wl)ql[Wl]=9;for(var Wl=256;Wl<280;++Wl)ql[Wl]=7;for(var Wl=280;Wl<288;++Wl)ql[Wl]=8;for(var Jl=new jl(32),Wl=0;Wl<32;++Wl)Jl[Wl]=5;var Yl=Kl(ql,9,1),Xl=Kl(Jl,5,1),Zl=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},Ql=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},$l=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},eu=function(e){return(e+7)/8|0},tu=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new jl(e.subarray(t,n))},nu=[`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`],ru=function(e,t,n){var r=Error(t||nu[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,ru),!n)throw r;return r},iu=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new jl(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new jl(i*3));var l=function(e){var t=n.length;if(e>t){var r=new jl(Math.max(t*2,e));r.set(n),n=r}},u=t.f||0,d=t.p||0,f=t.b||0,p=t.l,m=t.d,h=t.m,g=t.n,_=i*8;do{if(!p){u=Ql(e,d,1);var v=Ql(e,d+1,3);if(d+=3,!v){var y=eu(d)+4,b=e[y-4]|e[y-3]<<8,x=y+b;if(x>i){c&&ru(0);break}s&&l(f+b),n.set(e.subarray(y,x),f),t.b=f+=b,t.p=d=x*8,t.f=u;continue}else if(v==1)p=Yl,m=Xl,h=9,g=5;else if(v==2){var S=Ql(e,d,31)+257,C=Ql(e,d+10,15)+4,w=S+Ql(e,d+5,31)+1;d+=14;for(var T=new jl(w),E=new jl(19),D=0;D<C;++D)E[Il[D]]=Ql(e,d+D*3,7);d+=C*3;for(var O=Zl(E),k=(1<<O)-1,A=Kl(E,O,1),D=0;D<w;){var ee=A[Ql(e,d,k)];d+=ee&15;var y=ee>>4;if(y<16)T[D++]=y;else{var te=0,ne=0;for(y==16?(ne=3+Ql(e,d,3),d+=2,te=T[D-1]):y==17?(ne=3+Ql(e,d,7),d+=3):y==18&&(ne=11+Ql(e,d,127),d+=7);ne--;)T[D++]=te}}var re=T.subarray(0,S),ie=T.subarray(S);h=Zl(re),g=Zl(ie),p=Kl(re,h,1),m=Kl(ie,g,1)}else ru(1);if(d>_){c&&ru(0);break}}s&&l(f+131072);for(var ae=(1<<h)-1,oe=(1<<g)-1,se=d;;se=d){var te=p[$l(e,d)&ae],ce=te>>4;if(d+=te&15,d>_){c&&ru(0);break}if(te||ru(2),ce<256)n[f++]=ce;else if(ce==256){se=d,p=null;break}else{var le=ce-254;if(ce>264){var D=ce-257,ue=Pl[D];le=Ql(e,d,(1<<ue)-1)+zl[D],d+=ue}var de=m[$l(e,d)&oe],fe=de>>4;de||ru(3),d+=de&15;var ie=Hl[fe];if(fe>3){var ue=Fl[fe];ie+=$l(e,d)&(1<<ue)-1,d+=ue}if(d>_){c&&ru(0);break}s&&l(f+131072);var pe=f+le;if(f<ie){var me=a-ie,he=Math.min(ie,pe);for(me+f<0&&ru(3);f<he;++f)n[f]=r[me+f]}for(;f<pe;++f)n[f]=n[f-ie]}}t.l=p,t.p=se,t.b=f,t.f=u,p&&(u=1,t.m=h,t.d=m,t.n=g)}while(!u);return f!=n.length&&o?tu(n,0,f):n.subarray(0,f)},au=new jl(0),ou=function(e){(e[0]!=31||e[1]!=139||e[2]!=8)&&ru(6,`invalid gzip data`);var t=e[3],n=10;t&4&&(n+=(e[10]|e[11]<<8)+2);for(var r=(t>>3&1)+(t>>4&1);r>0;r-=!e[n++]);return n+(t&2)},su=function(e){var t=e.length;return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0},cu=function(e,t){return((e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31)&&ru(6,`invalid zlib data`),(e[1]>>5&1)==+!t&&ru(6,`invalid zlib data: `+(e[1]&32?`need`:`unexpected`)+` dictionary`),(e[1]>>3&4)+2};function lu(e,t){return iu(e,{i:2},t&&t.out,t&&t.dictionary)}function uu(e,t){var n=ou(e);return n+8>e.length&&ru(6,`invalid gzip data`),iu(e.subarray(n,-8),{i:2},t&&t.out||new jl(su(e)),t&&t.dictionary)}function du(e,t){return iu(e.subarray(cu(e,t&&t.dictionary),-4),{i:2},t&&t.out,t&&t.dictionary)}function fu(e,t){return e[0]==31&&e[1]==139&&e[2]==8?uu(e,t):(e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31?lu(e,t):du(e,t)}var pu=typeof TextDecoder<`u`&&new TextDecoder;try{pu.decode(au,{stream:!0})}catch{}var mu=Object.defineProperty,hu=Math.pow,gu=(e,t)=>mu(e,`name`,{value:t,configurable:!0}),_u=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())});gu((e,t)=>{let n=!1,r=``;return new(L.GridLayer.extend({createTile:gu((t,i)=>{let a=document.createElement(`img`),o=new AbortController,s=o.signal;return a.cancel=()=>{o.abort()},n||=(e.getHeader().then(e=>{e.tileType===1||e.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.`):e.tileType===2?r=`image/png`:e.tileType===3?r=`image/jpeg`:e.tileType===4?r=`image/webp`:e.tileType===5&&(r=`image/avif`)}),!0),e.getZxy(t.z,t.x,t.y,s).then(e=>{if(e){let t=new Blob([e.data],{type:r});a.src=window.URL.createObjectURL(t)}else a.style.display=`none`;a.cancel=void 0,i(void 0,a)}).catch(e=>{if(e.name!==`AbortError`)throw e}),a},`createTile`),_removeTile:gu(function(e){let t=this._tiles[e];t&&(t.el.cancel&&t.el.cancel(),t.el.src&&window.URL.revokeObjectURL(t.el.src),t.el.width=0,t.el.height=0,t.el.deleted=!0,L.DomUtil.remove(t.el),delete this._tiles[e],this.fire(`tileunload`,{tile:t.el,coords:this._keyToTileCoords(e)}))},`_removeTile`)}))(t)},`leafletRasterLayer`);var vu=gu(e=>(t,n)=>{if(n instanceof AbortController)return e(t,n);let r=new AbortController;return e(t,r).then(e=>n(void 0,e.data,e.cacheControl||``,e.expires||``),e=>n(e)).catch(e=>n(e)),{cancel:gu(()=>r.abort(),`cancel`)}},`v3compat`),yu=class{constructor(e){this.tilev4=gu((e,t)=>_u(this,null,function*(){if(e.type===`json`){let n=e.url.substr(10),r=this.tiles.get(n);if(r||(r=new Ju(n),this.tiles.set(n,r)),this.metadata){let n=yield r.getTileJson(e.url);return t.signal.throwIfAborted(),{data:n}}let i=yield r.getHeader();return t.signal.throwIfAborted(),(i.minLon>=i.maxLon||i.minLat>=i.maxLat)&&console.error(`Bounds of PMTiles archive ${i.minLon},${i.minLat},${i.maxLon},${i.maxLat} are not valid.`),{data:{tiles:[`${e.url}/{z}/{x}/{y}`],minzoom:i.minZoom,maxzoom:i.maxZoom,bounds:[i.minLon,i.minLat,i.maxLon,i.maxLat]}}}let n=new RegExp(/pmtiles:\/\/(.+)\/(\d+)\/(\d+)\/(\d+)/),r=e.url.match(n);if(!r)throw Error(`Invalid PMTiles protocol URL`);let i=r[1],a=this.tiles.get(i);a||(a=new Ju(i),this.tiles.set(i,a));let o=r[2],s=r[3],c=r[4],l=yield a?.getZxy(+o,+s,+c,t.signal);if(t.signal.throwIfAborted(),l)return{data:new Uint8Array(l.data),cacheControl:l.cacheControl,expires:l.expires};let u=yield a.getHeader();if(u.tileType===1||u.tileType===6){if(this.errorOnMissingTile)throw Error(`Tile not found.`);return{data:new Uint8Array}}return{data:null}}),`tilev4`),this.tile=vu(this.tilev4),this.tiles=new Map,this.metadata=e?.metadata||!1,this.errorOnMissingTile=e?.errorOnMissingTile||!1}add(e){this.tiles.set(e.source.getKey(),e)}get(e){return this.tiles.get(e)}};gu(yu,`Protocol`);var bu=yu;function xu(e,t){return(t>>>0)*4294967296+(e>>>0)}gu(xu,`toNum`);function Su(e,t){let n=t.buf,r=n[t.pos++],i=(r&112)>>4;if(r<128||(r=n[t.pos++],i|=(r&127)<<3,r<128)||(r=n[t.pos++],i|=(r&127)<<10,r<128)||(r=n[t.pos++],i|=(r&127)<<17,r<128)||(r=n[t.pos++],i|=(r&127)<<24,r<128)||(r=n[t.pos++],i|=(r&1)<<31,r<128))return xu(e,i);throw Error(`Expected varint not more than 10 bytes`)}gu(Su,`readVarintRemainder`);function Cu(e){let t=e.buf,n=t[e.pos++],r=n&127;return n<128||(n=t[e.pos++],r|=(n&127)<<7,n<128)||(n=t[e.pos++],r|=(n&127)<<14,n<128)||(n=t[e.pos++],r|=(n&127)<<21,n<128)?r:(n=t[e.pos],r|=(n&15)<<28,Su(r,e))}gu(Cu,`readVarint`);function wu(e,t,n,r,i){return i===0?r===0?[n,t]:[e-1-n,e-1-t]:[t,n]}gu(wu,`rotate`);function Tu(e,t,n){if(e>26)throw Error(`Tile zoom level exceeds max safe number limit (26)`);if(t>=1<<e||n>=1<<e)throw Error(`tile x/y outside zoom level bounds`);let r=((1<<e)*(1<<e)-1)/3,i=e-1,[a,o]=[t,n];for(let e=1<<i;e>0;e>>=1){let t=a&e,n=o&e;r+=(3*t^n)*(1<<i),[a,o]=wu(e,a,o,t,n),i--}return r}gu(Tu,`zxyToTileId`);function Eu(e){let t=3*e+1;return t<4294967296?31-Math.clz32(t):63-Math.clz32(t/4294967296)}gu(Eu,`tileIdToZ`);function Du(e){let t=Eu(e)>>1;if(t>26)throw Error(`Tile zoom level exceeds max safe number limit (26)`);let n=e-((1<<t)*(1<<t)-1)/3,r=0,i=0,a=1<<t;for(let e=1;e<a;e<<=1){let t=e&n/2,a=e&(n^t);[r,i]=wu(e,r,i,t,a),n/=2,r+=t,i+=a}return[t,r,i]}gu(Du,`tileIdToZxy`);var Ou=(e=>(e[e.Unknown=0]=`Unknown`,e[e.None=1]=`None`,e[e.Gzip=2]=`Gzip`,e[e.Brotli=3]=`Brotli`,e[e.Zstd=4]=`Zstd`,e))(Ou||{});function ku(e,t){return _u(this,null,function*(){if(t===1||t===0)return e;if(t===2){if(globalThis.DecompressionStream===void 0)return fu(new Uint8Array(e));let t=new Response(e).body;if(!t)throw Error(`Failed to read response stream`);let n=t.pipeThrough(new globalThis.DecompressionStream(`gzip`));return new Response(n).arrayBuffer()}throw Error(`Compression method not supported`)})}gu(ku,`defaultDecompress`);var Au=(e=>(e[e.Unknown=0]=`Unknown`,e[e.Mvt=1]=`Mvt`,e[e.Png=2]=`Png`,e[e.Jpeg=3]=`Jpeg`,e[e.Webp=4]=`Webp`,e[e.Avif=5]=`Avif`,e[e.Mlt=6]=`Mlt`,e))(Au||{});function ju(e){return e===1?`.mvt`:e===2?`.png`:e===3?`.jpg`:e===4?`.webp`:e===5?`.avif`:e===6?`.mlt`:``}gu(ju,`tileTypeExt`);var Mu=127;function Nu(e,t){let n=0,r=e.length-1;for(;n<=r;){let i=r+n>>1,a=t-e[i].tileId;if(a>0)n=i+1;else if(a<0)r=i-1;else return e[i]}return r>=0&&(e[r].runLength===0||t-e[r].tileId<e[r].runLength)?e[r]:null}gu(Nu,`findTile`);var Pu=class{constructor(e){this.file=e}getKey(){return this.file.name}getBytes(e,t){return _u(this,null,function*(){return{data:yield this.file.slice(e,e+t).arrayBuffer()}})}};gu(Pu,`FileSource`);var Fu=Pu,Iu=class{constructor(e,t=new Headers,n=void 0){this.url=e,this.customHeaders=t,this.credentials=n,this.mustReload=!1;let r=``;`navigator`in globalThis&&(r=globalThis.navigator?.userAgent??``);let i=r.indexOf(`Windows`)>-1,a=/Chrome|Chromium|Edg|OPR|Brave/.test(r);this.chromeWindowsNoCache=!1,i&&a&&(this.chromeWindowsNoCache=!0)}getKey(){return this.url}setHeaders(e){this.customHeaders=e}getBytes(e,t,n,r){return _u(this,null,function*(){let i,a;n?a=n:(i=new AbortController,a=i.signal);let o=new Headers(this.customHeaders);o.set(`range`,`bytes=${e}-${e+t-1}`);let s;this.mustReload?s=`reload`:this.chromeWindowsNoCache&&(s=`no-store`);let c=yield fetch(this.url,{signal:a,cache:s,headers:o,credentials:this.credentials});if(e===0&&c.status===416){let e=c.headers.get(`Content-Range`);if(!e||!e.startsWith(`bytes */`))throw Error(`Missing content-length on 416 response`);let t=+e.substr(8);o.set(`range`,`bytes=0-${t-1}`),c=yield fetch(this.url,{signal:a,cache:`reload`,headers:o,credentials:this.credentials})}let l=c.headers.get(`Etag`);if(l!=null&&l.startsWith(`W/`)&&(l=null),c.status===416||r&&l&&l!==r)throw this.mustReload=!0,new Hu(`Server returned non-matching ETag ${r} after one retry. Check browser extensions and servers for issues that may affect correct ETag headers.`);if(c.status>=300)throw Error(`Bad response code: ${c.status}`);let u=c.headers.get(`Content-Length`);if(c.status===200&&(!u||+u>t))throw i&&i.abort(),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:l||void 0,cacheControl:c.headers.get(`Cache-Control`)||void 0,expires:c.headers.get(`Expires`)||void 0}})}};gu(Iu,`FetchSource`);var Lu=Iu;function Ru(e,t){let n=e.getUint32(t+4,!0),r=e.getUint32(t+0,!0);return n*hu(2,32)+r}gu(Ru,`getUint64`);function zu(e,t){let n=new DataView(e),r=n.getUint8(7);if(r>3)throw Error(`Archive is spec version ${r} but this library supports up to spec version 3`);return{specVersion:r,rootDirectoryOffset:Ru(n,8),rootDirectoryLength:Ru(n,16),jsonMetadataOffset:Ru(n,24),jsonMetadataLength:Ru(n,32),leafDirectoryOffset:Ru(n,40),leafDirectoryLength:Ru(n,48),tileDataOffset:Ru(n,56),tileDataLength:Ru(n,64),numAddressedTiles:Ru(n,72),numTileEntries:Ru(n,80),numTileContents:Ru(n,88),clustered:n.getUint8(96)===1,internalCompression:n.getUint8(97),tileCompression:n.getUint8(98),tileType:n.getUint8(99),minZoom:n.getUint8(100),maxZoom:n.getUint8(101),minLon:n.getInt32(102,!0)/1e7,minLat:n.getInt32(106,!0)/1e7,maxLon:n.getInt32(110,!0)/1e7,maxLat:n.getInt32(114,!0)/1e7,centerZoom:n.getUint8(118),centerLon:n.getInt32(119,!0)/1e7,centerLat:n.getInt32(123,!0)/1e7,etag:t}}gu(zu,`bytesToHeader`);function Bu(e){let t={buf:new Uint8Array(e),pos:0},n=Cu(t),r=[],i=0;for(let e=0;e<n;e++){let e=Cu(t);r.push({tileId:i+e,offset:0,length:0,runLength:1}),i+=e}for(let e=0;e<n;e++)r[e].runLength=Cu(t);for(let e=0;e<n;e++)r[e].length=Cu(t);for(let e=0;e<n;e++){let n=Cu(t);n===0&&e>0?r[e].offset=r[e-1].offset+r[e-1].length:r[e].offset=n-1}return r}gu(Bu,`deserializeIndex`);var Vu=class extends Error{};gu(Vu,`EtagMismatch`);var Hu=Vu;function Uu(e,t){return _u(this,null,function*(){let n=yield e.getBytes(0,16384);if(new DataView(n.data).getUint16(0,!0)!==19792)throw Error(`Wrong magic number for PMTiles archive`);let r=zu(n.data.slice(0,Mu),n.etag),i=n.data.slice(r.rootDirectoryOffset,r.rootDirectoryOffset+r.rootDirectoryLength),a=`${e.getKey()}|${r.etag||``}|${r.rootDirectoryOffset}|${r.rootDirectoryLength}`,o=Bu(yield t(i,r.internalCompression));return[r,[a,o.length,o]]})}gu(Uu,`getHeaderAndRoot`);function Wu(e,t,n,r,i){return _u(this,null,function*(){let a=Bu(yield t((yield e.getBytes(n,r,void 0,i.etag)).data,i.internalCompression));if(a.length===0)throw Error(`Empty directory is invalid`);return a})}gu(Wu,`getDirectory`),gu(class{constructor(e=100,t=!0,n=ku){this.cache=new Map,this.maxCacheEntries=e,this.counter=1,this.decompress=n}getHeader(e){return _u(this,null,function*(){let t=e.getKey(),n=this.cache.get(t);if(n)return n.lastUsed=this.counter++,n.data;let r=yield Uu(e,this.decompress);return r[1]&&this.cache.set(r[1][0],{lastUsed:this.counter++,data:r[1][2]}),this.cache.set(t,{lastUsed:this.counter++,data:r[0]}),this.prune(),r[0]})}getDirectory(e,t,n,r){return _u(this,null,function*(){let i=`${e.getKey()}|${r.etag||``}|${t}|${n}`,a=this.cache.get(i);if(a)return a.lastUsed=this.counter++,a.data;let o=yield Wu(e,this.decompress,t,n,r);return this.cache.set(i,{lastUsed:this.counter++,data:o}),this.prune(),o})}prune(){if(this.cache.size>this.maxCacheEntries){let e=1/0,t;this.cache.forEach((n,r)=>{n.lastUsed<e&&(e=n.lastUsed,t=r)}),t&&this.cache.delete(t)}}invalidate(e){return _u(this,null,function*(){this.cache.delete(e.getKey())})}},`ResolvedValueCache`);var Gu=class{constructor(e=100,t=!0,n=ku){this.cache=new Map,this.invalidations=new Map,this.maxCacheEntries=e,this.counter=1,this.decompress=n}getHeader(e){return _u(this,null,function*(){let t=e.getKey(),n=this.cache.get(t);if(n)return n.lastUsed=this.counter++,yield n.data;let r=new Promise((t,n)=>{Uu(e,this.decompress).then(e=>{e[1]&&this.cache.set(e[1][0],{lastUsed:this.counter++,data:Promise.resolve(e[1][2])}),t(e[0]),this.prune()}).catch(e=>{n(e)})});return this.cache.set(t,{lastUsed:this.counter++,data:r}),r})}getDirectory(e,t,n,r){return _u(this,null,function*(){let i=`${e.getKey()}|${r.etag||``}|${t}|${n}`,a=this.cache.get(i);if(a)return a.lastUsed=this.counter++,yield a.data;let o=new Promise((i,a)=>{Wu(e,this.decompress,t,n,r).then(e=>{i(e),this.prune()}).catch(e=>{a(e)})});return this.cache.set(i,{lastUsed:this.counter++,data:o}),o})}prune(){if(this.cache.size>=this.maxCacheEntries){let e=1/0,t;this.cache.forEach((n,r)=>{n.lastUsed<e&&(e=n.lastUsed,t=r)}),t&&this.cache.delete(t)}}invalidate(e){return _u(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((n,r)=>{this.getHeader(e).then(e=>{n(),this.invalidations.delete(t)}).catch(e=>{r(e)})});this.invalidations.set(t,n)})}};gu(Gu,`SharedPromiseCache`);var Ku=Gu,qu=class{constructor(e,t,n){typeof e==`string`?this.source=new Lu(e):this.source=e,n?this.decompress=n:this.decompress=ku,t?this.cache=t:this.cache=new Ku}getHeader(){return _u(this,null,function*(){return yield this.cache.getHeader(this.source)})}getZxyAttempt(e,t,n,r){return _u(this,null,function*(){let i=Tu(e,t,n),a=yield this.cache.getHeader(this.source);if(e<a.minZoom||e>a.maxZoom)return;let o=a.rootDirectoryOffset,s=a.rootDirectoryLength;for(let e=0;e<=3;e++){let e=Nu(yield this.cache.getDirectory(this.source,o,s,a),i);if(e){if(e.runLength>0){let t=yield this.source.getBytes(a.tileDataOffset+e.offset,e.length,r,a.etag);return{data:yield this.decompress(t.data,a.tileCompression),cacheControl:t.cacheControl,expires:t.expires}}o=a.leafDirectoryOffset+e.offset,s=e.length}else return}throw Error(`Maximum directory depth exceeded`)})}getZxy(e,t,n,r){return _u(this,null,function*(){try{return yield this.getZxyAttempt(e,t,n,r)}catch(i){if(i instanceof Hu)return this.cache.invalidate(this.source),yield this.getZxyAttempt(e,t,n,r);throw i}})}getMetadataAttempt(){return _u(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),r=new TextDecoder(`utf-8`);return JSON.parse(r.decode(n))})}getMetadata(){return _u(this,null,function*(){try{return yield this.getMetadataAttempt()}catch(e){if(e instanceof Hu)return this.cache.invalidate(this.source),yield this.getMetadataAttempt();throw e}})}getTileJson(e){return _u(this,null,function*(){let t=yield this.getHeader(),n=yield this.getMetadata();return{tilejson:`3.0.0`,scheme:`xyz`,tiles:[`${e}/{z}/{x}/{y}${ju(t.tileType)}`],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}})}};gu(qu,`PMTiles`);var Ju=qu,Yu,Xu=2,Zu=[200,500];function Qu(e,t){return t?.aborted===!0||e instanceof DOMException&&e.name===`AbortError`}var $u=class{#e;constructor(e){this.#e=e}getKey(){return this.#e}async getBytes(e,t,n){let r={Range:`bytes=${e}-${e+t-1}`};for(let e=0;;e++){let t;try{t=await fetch(this.#e,{signal:n,cache:`no-store`,headers:r})}catch(t){if(Qu(t,n)||e>=Xu)throw t;await this.#t(e,n);continue}if(t.status<300){let e=t.headers.get(`ETag`)??void 0;return e?.startsWith(`W/`)&&(e=void 0),{data:await t.arrayBuffer(),etag:e,cacheControl:t.headers.get(`Cache-Control`)??void 0,expires:t.headers.get(`Expires`)??void 0}}if(t.status>=500&&e<Xu){await this.#t(e,n);continue}throw Error(`PMTiles fetch failed: ${t.status} for ${this.#e}`)}}#t(e,t){let n=Zu[e]??Zu[Zu.length-1];return new Promise((e,r)=>{let i=setTimeout(e,n);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(new DOMException(`Aborted`,`AbortError`))},{once:!0})})}};function ed(){Yu||(Yu=new bu,Al.default.addProtocol(`pmtiles`,Yu.tile))}function td(e){Yu||ed();let t=new $u(e);Yu?.get(t.getKey())||Yu?.add(new Ju(t))}var nd=1,rd={fill:`fill-opacity`,line:`line-opacity`,raster:`raster-opacity`};function id(e){return rd[e]??`raster-opacity`}function ad(e,t,n=`basemap`){let r=xl(e,t),i=Object.keys(r.sources),a=r.layers.map(e=>({id:e.id,type:e.type,minzoom:e.minzoom??0,themePaint:e.metadata?.[ll]})),o=i[0],s,c=e=>{let t=e.getSource(o)?.maxzoom;if(t===void 0)return!1;for(let n of a)e.getLayer(n.id)&&e.setLayerZoomRange(n.id,n.minzoom,t+nd);return!0};return{id:fl(e.identifier),title:e.name,band:n,supportsOpacity:!0,layerIds:a.map(e=>e.id),add(e){for(let t of i){let n=r.sources[t];`url`in n&&typeof n.url==`string`&&n.url.startsWith(`pmtiles://`)&&td(n.url.slice(ul.length)),e.map.getSource(t)||e.map.addSource(t,n)}for(let t of r.layers)e.map.getLayer(t.id)||e.map.addLayer(t,e.beforeIdFor(n));if(!o)return;s&&=(e.map.off(`sourcedata`,s),void 0);let t=()=>e.map.isSourceLoaded(o)&&c(e.map);if(!t()){let n=r=>{r.sourceId===o&&r.isSourceLoaded&&t()&&(e.map.off(`sourcedata`,n),s===n&&(s=void 0))};s=n,e.map.on(`sourcedata`,n)}},remove(e){s&&=(e.map.off(`sourcedata`,s),void 0);for(let t of a)e.map.getLayer(t.id)&&e.map.removeLayer(t.id);for(let t of i)e.map.getSource(t)&&e.map.removeSource(t)},setVisible(e,t){for(let n of a)e.map.setLayoutProperty(n.id,`visibility`,t?`visible`:`none`)},setOpacity(e,t){for(let n of a)e.map.setPaintProperty(n.id,id(n.type),t)},applyTheme(e,t){for(let n of a){if(n.type===`raster`){cl(e.map,n.id,t);continue}if(!n.themePaint)continue;let r=n.type===`line`?`line-color`:`fill-color`;e.map.setPaintProperty(n.id,r,t[n.themePaint])}}}}function od(){return{type:`FeatureCollection`,features:[]}}function sd(e,t,n){let r=new Uint8ClampedArray(e*e*4),i=e/2;for(let a=0;a<e;a+=1)for(let o=0;o<e;o+=1){if(!n(o,a,i))continue;let s=(a*e+o)*4;r[s]=t.r,r[s+1]=t.g,r[s+2]=t.b,r[s+3]=t.a}return new ImageData(r,e,e)}var cd=[`basemap`,`bathymetry`,`track`,`weather`,`routes`,`safety`,`traffic`,`vessel`,`overlay-top`];function ld(e){return`__z__${e}`}function ud(e){for(let t of cd){let n=ld(t);e.getLayer(n)||e.addLayer({id:n,type:`background`,layout:{visibility:`none`}})}}function dd(e){let t=cd[cd.indexOf(e)+1];return t?ld(t):void 0}var fd=class{#e;#t=new Map;#n=new Map;#r;#i;#a;#o;#s;#c;constructor(e,t={}){this.#e=e,this.#r=t.saved??{},this.#i=t.onChange,this.#a=t.savedOrder?[...t.savedOrder]:[],this.#o=t.onOrderChange,this.#s=t.pinned??[],this.#c=t.exclusive??[]}async register(e){await this.#l(e),this.#f()}async registerAll(e){for(let t of e)await this.#l(t);this.#f()}async#l(e){if(this.#t.has(e.id))throw Error(`duplicate overlay id: ${e.id}`);this.#t.set(e.id,e);let t=this.#r[e.id],n=t?{...t}:{visible:e.defaultVisible??!0,opacity:e.defaultOpacity??1},r=this.#n.get(e.id)??n;r.visible&&this.#c.find(t=>t.includes(e.id))?.some(t=>t!==e.id&&this.#n.get(t)?.visible)&&(r.visible=!1),this.#n.set(e.id,r),await e.add(this.#e),e.setVisible(this.#e,r.visible),e.setOpacity?.(this.#e,r.opacity)}unregister(e){let t=this.#t.get(e);t&&(t.remove(this.#e),this.#t.delete(e))}toggle(e,t){let n=this.#t.get(e),r=this.#n.get(e);if(!(!n||!r)){if(t){let t=this.#c.find(t=>t.includes(e));for(let n of t??[]){if(n===e)continue;let t=this.#t.get(n),r=this.#n.get(n);t&&r?.visible&&(r.visible=!1,t.setVisible(this.#e,!1))}}r.visible=t,n.setVisible(this.#e,t),this.#u()}}setOpacity(e,t){let n=this.#t.get(e),r=this.#n.get(e);!n||!r||(r.opacity=t,n.setOpacity?.(this.#e,t),this.#u())}reorder(e,t){if(this.#s.includes(e)||!this.#t.has(e))return;let n=this.#d().filter(e=>!this.#s.includes(e)).reverse(),r=n.indexOf(e);n.splice(r,1);let i=Math.max(0,Math.min(t,n.length));n.splice(i,0,e),this.#a=n.reverse(),this.#f(),this.#o?.([...this.#a])}#u(){if(!this.#i)return;let e={};for(let[t,n]of this.#n)e[t]={visible:n.visible,opacity:n.opacity};this.#i(e)}#d(){let e=e=>cd.indexOf(this.#t.get(e)?.band??`basemap`),t=[...this.#t.keys()].filter(e=>!this.#s.includes(e)),n=this.#a.filter(e=>t.includes(e));for(let r of t){if(n.includes(r))continue;let t=e(r),i=n.findIndex(n=>e(n)>t);i<0&&(i=n.length),n.splice(i,0,r)}let r=this.#s.filter(e=>this.#t.has(e));return[...n,...r]}#f(){if(!this.#a.length&&!this.#s.length)return;let e=[];for(let t of this.#d()){let n=this.#t.get(t);if(n)for(let t of n.layerIds)this.#e.map.getLayer(t)&&e.push(t)}let t=ld(`overlay-top`),n=this.#e.map.getLayer(t)?t:void 0;for(let t=e.length-1;t>=0;t--)this.#e.map.moveLayer(e[t],n),n=e[t]}applyTheme(e){for(let t of this.#t.values())t.applyTheme?.(this.#e,e)}async reattachAll(){ud(this.#e.map);for(let[e,t]of this.#t){let n=this.#n.get(e)??{visible:!0,opacity:1};await(t.reattach??t.add).call(t,this.#e),t.setVisible(this.#e,n.visible),t.setOpacity?.(this.#e,n.opacity)}this.#f()}layers(){return this.#d().reverse().flatMap(e=>{let t=this.#t.get(e);if(!t)return[];let n=this.#n.get(e)??{visible:!0,opacity:1};return[{id:e,title:t.title,visible:n.visible,opacity:n.opacity,supportsOpacity:t.supportsOpacity,pinned:this.#s.includes(e),band:t.band}]})}};function pd(e){let{minLon:t,minLat:n,maxLon:r,maxLat:i}=e;if([t,n,r,i].every(Number.isFinite)&&!(t>=r||n>=i))return[t,n,r,i]}function md(e){if(typeof e!=`object`||!e)return;let t=e.vector_layers;if(!Array.isArray(t))return;let n=[];for(let e of t){let t=e?.id;typeof t==`string`&&n.push(t)}return n.length>0?n:void 0}function hd(e){if(typeof e!=`object`||!e)return;let t=e.name;return typeof t==`string`&&t.length>0?t:void 0}function gd(e,t){return{name:hd(t),kind:e.tileType===Au.Mvt||e.tileType===Au.Mlt?`vector`:`raster`,bounds:pd(e),minzoom:e.minZoom,maxzoom:e.maxZoom,vectorLayers:md(t)}}async function _d(e){let t=typeof e!=`string`,n=new Ju(t?new Fu(e):new $u(e)),r=await n.getHeader(),i;try{i=await n.getMetadata()}catch{i=void 0}let a=gd(r,i);return t&&(a.byteSize=e.size),a}function vd(e){function t(t){t.map.getSource(e.sourceId)?.setData(e.features())}return{id:e.id,title:e.title,band:e.band,supportsOpacity:!0,layerIds:[e.layerId],add(t){t.map.hasImage(e.iconId)||t.map.addImage(e.iconId,e.iconImage(e.defaultColor),{pixelRatio:e.pixelRatio??1});let n={type:`geojson`,data:e.features()};t.map.addSource(e.sourceId,n);let r={id:e.layerId,type:`symbol`,source:e.sourceId,layout:{"icon-image":e.iconId,"icon-rotate":[`get`,`heading`],"icon-rotation-alignment":`map`,"icon-allow-overlap":!0,"icon-ignore-placement":!0}};t.map.addLayer(r,t.beforeIdFor(e.band))},sync(n){e.beforeSync?.(),e.shouldRefresh()&&t(n)},applyTheme(t,n){let r=e.iconImage(e.paintColor(n));t.map.hasImage(e.iconId)?t.map.updateImage(e.iconId,r):t.map.addImage(e.iconId,r,{pixelRatio:e.pixelRatio??1})},setVisible(t,n){t.map.setLayoutProperty(e.layerId,`visibility`,n?`visible`:`none`)},setOpacity(t,n){t.map.setPaintProperty(e.layerId,`icon-opacity`,n)},remove(t){t.map.getLayer(e.layerId)&&t.map.removeLayer(e.layerId),t.map.getSource(e.sourceId)&&t.map.removeSource(e.sourceId)}}}var yd=[0,30],bd=2;function xd(e){let t;try{let n=e.view?[e.view.lon,e.view.lat]:e.defaultCenter??yd,r=e.view?e.view.zoom:e.defaultZoom??bd;t=new Al.default.Map({container:e.container,style:al(),center:n,zoom:Math.min(r,e.maxZoom??1/0),minZoom:e.minZoom,maxZoom:e.maxZoom,attributionControl:{compact:!0}})}catch(e){return console.error(`Map failed to initialize`,e),{destroy:()=>{}}}let n=t,r=!1,i=0,a=new ResizeObserver(()=>n.resize());a.observe(e.container);let o=!1,s=()=>{o||(o=!0,requestAnimationFrame(()=>{if(o=!1,r)return;let t=n.getCenter();e.onView?.({lat:t.lat,lon:t.lng,zoom:n.getZoom()})}))};return n.on(`move`,s),e.onUserPan&&n.on(`dragstart`,()=>e.onUserPan?.()),e.onClick&&n.on(`click`,t=>e.onClick?.({lng:t.lngLat.lng,lat:t.lngLat.lat})),n.on(`load`,()=>{s();let t={map:n,beforeIdFor:dd};ud(n);let a=new fd(t,e.managerOptions),o=Ol(n,sl(`day`));e.onLoad({map:n,ctx:t,manager:a,recolor:e=>{let t=sl(e);e===`day`?kl(n,o):El(n,t),Dl(n,t),a.applyTheme(t)},isDestroyed:()=>r,runTick:e=>{let n=()=>{for(let n of e)n.sync(t);i=requestAnimationFrame(n)};i=requestAnimationFrame(n)}})}),{destroy:()=>{r=!0,cancelAnimationFrame(i),a.disconnect(),n.remove()}}}function Sd(e,t){let n=e.kind!==`raster`;return{identifier:e.id,name:e.name,type:n?`tileJSON`:`tilelayer`,format:n?`mvt`:`png`,url:t,bounds:e.bounds,minzoom:e.minzoom,maxzoom:e.maxzoom,layers:e.layers}}function Cd(e){try{let t=new URL(e).pathname;return t.slice(t.lastIndexOf(`/`)+1).replace(/\.pmtiles$/i,``)||e}catch{return e}}var wd=class{#e=z(dn([]));get sources(){return W(this.#e)}set sources(e){B(this.#e,e,!0)}#t;#n;constructor(e,t,n){this.#t=e,this.sources=t,this.#n=n}async addUrl(e){let t=await _d(e);this.#r({id:cc(),name:t.name??Cd(e),kind:t.kind,origin:{type:`url`,url:e},bounds:t.bounds,minzoom:t.minzoom,maxzoom:t.maxzoom,layers:t.vectorLayers})}async addFile(e){let t=await _d(e),n=cc();await this.#t.put(n,e),this.#r({id:n,name:t.name??e.name.replace(/\.pmtiles$/i,``),kind:t.kind,origin:{type:`file`,storeId:n},bounds:t.bounds,minzoom:t.minzoom,maxzoom:t.maxzoom,layers:t.vectorLayers,byteSize:t.byteSize??e.size})}rename(e,t){this.sources=this.sources.map(n=>n.id===e?{...n,name:t}:n),this.#n(this.sources)}async remove(e){let t=this.sources.find(t=>t.id===e);t&&(t.origin.type===`file`&&await this.#t.delete(t.origin.storeId),this.sources=this.sources.filter(t=>t.id!==e),this.#n(this.sources))}resolveBlob(e){return this.#t.get(e)}#r(e){this.sources=[...this.sources,e],this.#n(this.sources)}},Td=class{#e;constructor(e){this.#e=e;for(let t of[Us.position,Us.speedOverGround,Us.courseOverGroundTrue,Us.headingTrue])e.cell(t)}get sogMps(){return Bs(this.#t(Us.speedOverGround))}get cogRad(){return Bs(this.#t(Us.courseOverGroundTrue))}get headingRad(){return Bs(this.#t(Us.headingTrue))}get position(){let e=this.#t(Us.position);return Ls(e)?e:void 0}#t(e){return this.#e.cell(e).value}};function Ed(e){return{west:e.getWest(),south:e.getSouth(),east:e.getEast(),north:e.getNorth()}}function Dd(e,t){let n=Math.max(1e-6,e.east-e.west)/Math.max(1e-6,e.north-e.south),r=Math.max(2,Math.round(Math.sqrt(t/n))),i=Math.max(2,Math.floor(t/r));return{lats:Od(e.south,e.north,r),lons:Od(e.west,e.east,i)}}function Od(e,t,n){let r=(t-e)/(n-1);return Array.from({length:n},(t,n)=>e+n*r)}function kd(e,t,n,r){let i=Ad(e.lons,n),a=Ad(e.lats,r);if(!i||!a)return;let o=e.lons.length,s=t[a.i*o+i.i],c=t[a.i*o+i.i+1],l=t[(a.i+1)*o+i.i],u=t[(a.i+1)*o+i.i+1];return lc(lc(s,c,i.f),lc(l,u,i.f),a.f)}function Ad(e,t){if(!(t<e[0]||t>e[e.length-1])){for(let n=0;n<e.length-1;n+=1)if(t<=e[n+1]){let r=e[n+1]-e[n]||1;return{i:n,f:(t-e[n])/r}}return{i:e.length-2,f:1}}}function jd(e,t){let n=e.times;if(n.length===0||t<=n[0])return{lo:0,hi:0,frac:0};if(t>=n[n.length-1])return{lo:n.length-1,hi:n.length-1,frac:0};for(let e=0;e<n.length-1;e+=1)if(t<=n[e+1]){let r=n[e+1]-n[e]||1;return{lo:e,hi:e+1,frac:(t-n[e])/r}}return{lo:n.length-1,hi:n.length-1,frac:0}}var Md=class{#e=z(void 0);get grid(){return W(this.#e)}set grid(e){B(this.#e,e,!0)}#t=z(`idle`);get status(){return W(this.#t)}set status(e){B(this.#t,e,!0)}#n=z(void 0);get bbox(){return W(this.#n)}set bbox(e){B(this.#n,e,!0)}#r=z(0);get selectedTime(){return W(this.#r)}set selectedTime(e){B(this.#r,e,!0)}#i=z(void 0);get radar(){return W(this.#i)}set radar(e){B(this.#i,e,!0)}#a=R(()=>this.grid?jd(this.grid,this.selectedTime):{lo:0,hi:0,frac:0});get bracket(){return W(this.#a)}set bracket(e){B(this.#a,e)}setStatus(e){this.status=e}setGrid(e){this.grid=e,this.status=`ready`;let t=e.times[0],n=e.times[e.times.length-1];t!==void 0&&(this.selectedTime<t||this.selectedTime>n)&&(this.selectedTime=t)}setSelectedTime(e){this.selectedTime=e}setRadar(e){this.radar=e}},Nd=K(`<div class="auth-banner svelte-1s059lv" role="status" aria-live="polite">Requesting access as <strong> </strong>. Approve it in Signal K under Security,
749
+ `);gn(u)||(x=function(e){return e.replace(/\bin\s/g,`varying `).replace(`out highp vec4 fragColor;`,``).replace(/fragColor/g,`gl_FragColor`).replace(/texture\(/g,`texture2D(`)}(x),S=function(e){return e.replace(/\bin\s/g,`attribute `).replace(/\bout\s/g,`varying `).replace(/texture\(/g,`texture2D(`)}(S));let C=u.createShader(u.FRAGMENT_SHADER);if(u.isContextLost())return void(this.failedToCreate=!0);if(u.shaderSource(C,x),u.compileShader(C),!u.getShaderParameter(C,u.COMPILE_STATUS))throw Error(`Could not compile fragment shader: ${u.getShaderInfoLog(C)}`);u.attachShader(this.program,C);let w=u.createShader(u.VERTEX_SHADER);if(u.isContextLost())return void(this.failedToCreate=!0);if(u.shaderSource(w,S),u.compileShader(w),!u.getShaderParameter(w,u.COMPILE_STATUS))throw Error(`Could not compile vertex shader: ${u.getShaderInfoLog(w)}`);u.attachShader(this.program,w),this.attributes={};let T={};this.numAttributes=p.length;for(let e=0;e<this.numAttributes;e++)p[e]&&(u.bindAttribLocation(this.program,e,p[e]),this.attributes[p[e]]=e);if(u.linkProgram(this.program),!u.getProgramParameter(this.program,u.LINK_STATUS))throw Error(`Program failed to link: ${u.getProgramInfoLog(this.program)}`);u.deleteShader(w),u.deleteShader(C);for(let e of y)if(e&&!T[e]){let t=u.getUniformLocation(this.program,e);t&&(T[e]=t)}this.fixedUniforms=i(e,T),this.terrainUniforms=((e,n)=>({u_depth:new t.b_(e,n.u_depth),u_terrain:new t.b_(e,n.u_terrain),u_terrain_dim:new t.bp(e,n.u_terrain_dim),u_terrain_matrix:new t.c0(e,n.u_terrain_matrix),u_terrain_unpack:new t.c1(e,n.u_terrain_unpack),u_terrain_exaggeration:new t.bp(e,n.u_terrain_exaggeration)}))(e,T),this.projectionUniforms=((e,n)=>({u_projection_matrix:new t.c0(e,n.u_projection_matrix),u_projection_tile_mercator_coords:new t.c1(e,n.u_projection_tile_mercator_coords),u_projection_clipping_plane:new t.c1(e,n.u_projection_clipping_plane),u_projection_transition:new t.bp(e,n.u_projection_transition),u_projection_fallback_matrix:new t.c0(e,n.u_projection_fallback_matrix)}))(e,T),this.binderUniforms=r?r.getUniforms(e,T):[]}draw(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v){var y;let b=e.gl;if(this.failedToCreate)return;if(e.program.set(this.program),e.setDepthMode(n),e.setStencilMode(r),e.setColorMode(i),e.setCullFace(a),s){e.activeTexture.set(b.TEXTURE2),b.bindTexture(b.TEXTURE_2D,s.depthTexture),e.activeTexture.set(b.TEXTURE3),b.bindTexture(b.TEXTURE_2D,s.texture);for(let e in this.terrainUniforms)this.terrainUniforms[e].set(s[e])}if(c)for(let e in c)this.projectionUniforms[qn[e]].set(c[e]);if(o)for(let e in this.fixedUniforms)this.fixedUniforms[e].set(o[e]);h&&h.setUniforms(e,this.binderUniforms,p,{zoom:m});let x=0;switch(t){case b.LINES:x=2;break;case b.TRIANGLES:x=3;break;case b.LINE_STRIP:x=1}for(let n of f.get())n.vaos||={},(y=n.vaos)[l]||(y[l]=new Gn),n.vaos[l].bind(e,this,u,h?h.getPaintVertexBuffers():[],d,n.vertexOffset,g,_,v),b.drawElements(t,n.primitiveLength*x,b.UNSIGNED_SHORT,n.primitiveOffset*x*2)}}function Xn(e,n,r){let i=1/t.aK(r,1,n.transform.tileZoom),a=2**r.tileID.overscaledZ,o=r.tileSize*2**n.transform.tileZoom/a,s=o*(r.tileID.canonical.x+r.tileID.wrap*a),c=o*r.tileID.canonical.y;return{u_image:0,u_texsize:r.imageAtlasTexture.size,u_scale:[i,e.fromScale,e.toScale],u_fade:e.t,u_pixel_coord_upper:[s>>16,c>>16],u_pixel_coord_lower:[65535&s,65535&c]}}let Zn=(e,n,r,i)=>{let a=e.style.light,o=a.properties.get(`position`),s=[o.x,o.y,o.z],c=t.c4();a.properties.get(`anchor`)===`viewport`&&t.c5(c,e.transform.bearingInRadians),t.c6(s,s,c);let l=e.transform.transformLightDirection(s),u=a.properties.get(`color`);return{u_lightpos:s,u_lightpos_globe:l,u_lightintensity:a.properties.get(`intensity`),u_lightcolor:[u.r,u.g,u.b],u_vertical_gradient:+n,u_opacity:r,u_fill_translate:i}},Qn=(e,n,r,i,a,o,s)=>t.e(Zn(e,n,r,i),Xn(o,e,s),{u_height_factor:-(2**a.overscaledZ)/s.tileSize/8}),$n=(e,n,r,i)=>t.e(Xn(n,e,r),{u_fill_translate:i}),er=(e,t)=>({u_world:e,u_fill_translate:t}),tr=(e,n,r,i,a)=>t.e($n(e,n,r,a),{u_world:i}),nr=(e,n,r,i,a)=>{let o=e.transform,s,c,l=0;if(r.paint.get(`circle-pitch-alignment`)===`map`){let e=t.aK(n,1,o.zoom);s=!0,c=[e,e],l=e/(t.a6*2**n.tileID.overscaledZ)*2*Math.PI*a}else s=!1,c=o.pixelsToGLUnits;return{u_camera_to_center_distance:o.cameraToCenterDistance,u_scale_with_map:+(r.paint.get(`circle-pitch-scale`)===`map`),u_pitch_with_map:+s,u_device_pixel_ratio:e.pixelRatio,u_extrude_scale:c,u_globe_extrude_scale:l,u_translate:i}},rr=e=>({u_pixel_extrude_scale:[1/e.width,1/e.height]}),ir=e=>({u_viewport_size:[e.width,e.height]}),ar=(e,t=1)=>({u_color:e,u_overlay:0,u_overlay_scale:t}),or=(e,n,r,i)=>{let a=t.aK(e,1,n)/(t.a6*2**e.tileID.overscaledZ)*2*Math.PI*i;return{u_extrude_scale:t.aK(e,1,n),u_intensity:r,u_globe_extrude_scale:a}},sr=(e,n,r,i)=>{let a=t.O();t.c7(a,0,e.width,e.height,0,0,1);let o=e.context.gl;return{u_matrix:a,u_world:[o.drawingBufferWidth,o.drawingBufferHeight],u_image:r,u_color_ramp:i,u_opacity:n.paint.get(`heatmap-opacity`)}},cr=(e,t,n)=>{let r=n.paint.get(`hillshade-accent-color`),i;switch(n.paint.get(`hillshade-method`)){case`basic`:i=4;break;case`combined`:i=1;break;case`igor`:i=2;break;case`multidirectional`:i=3;break;default:i=0}let a=n.getIlluminationProperties();for(let t=0;t<a.directionRadians.length;t++)n.paint.get(`hillshade-illumination-anchor`)===`viewport`&&(a.directionRadians[t]+=e.transform.bearingInRadians);return{u_image:0,u_latrange:ur(0,t.tileID),u_exaggeration:n.paint.get(`hillshade-exaggeration`),u_altitudes:a.altitudeRadians,u_azimuths:a.directionRadians,u_accent:r,u_method:i,u_highlights:a.highlightColor,u_shadows:a.shadowColor}},lr=(e,n)=>{let r=n.stride,i=t.O();return t.c7(i,0,t.a6,-t.a6,0,0,1),t.Q(i,i,[0,-t.a6,0]),{u_matrix:i,u_image:1,u_dimension:[r,r],u_zoom:e.overscaledZ,u_unpack:n.getUnpackVector()}};function ur(e,n){let r=2**n.canonical.z,i=n.canonical.y;return[new t.a7(0,i/r).toLngLat().lat,new t.a7(0,(i+1)/r).toLngLat().lat]}let dr=(e,t,n=0)=>({u_image:0,u_unpack:t.getUnpackVector(),u_dimension:[t.stride,t.stride],u_elevation_stops:1,u_color_stops:4,u_color_ramp_size:n,u_opacity:e.paint.get(`color-relief-opacity`)}),fr=(e,n,r,i)=>{let a=e.transform;return{u_translation:vr(e,n,r),u_ratio:i/t.aK(n,1,a.zoom),u_device_pixel_ratio:e.pixelRatio,u_units_to_pixels:[1/a.pixelsToGLUnits[0],1/a.pixelsToGLUnits[1]]}},pr=(e,n,r,i,a)=>t.e(fr(e,n,r,i),{u_image:0,u_image_height:a}),mr=(e,n,r,i,a)=>{let o=e.transform,s=_r(n,o);return{u_translation:vr(e,n,r),u_texsize:n.imageAtlasTexture.size,u_ratio:i/t.aK(n,1,o.zoom),u_device_pixel_ratio:e.pixelRatio,u_image:0,u_scale:[s,a.fromScale,a.toScale],u_fade:a.t,u_units_to_pixels:[1/o.pixelsToGLUnits[0],1/o.pixelsToGLUnits[1]]}},hr=(e,n,r,i,a)=>{let o=_r(n,e.transform);return t.e(fr(e,n,r,i),{u_tileratio:o,u_crossfade_from:a.fromScale,u_crossfade_to:a.toScale,u_image:0,u_mix:a.t,u_lineatlas_width:e.lineAtlas.width,u_lineatlas_height:e.lineAtlas.height})},gr=(e,n,r,i,a,o)=>{let s=_r(n,e.transform);return t.e(fr(e,n,r,i),{u_image:0,u_image_height:o,u_tileratio:s,u_crossfade_from:a.fromScale,u_crossfade_to:a.toScale,u_image_dash:1,u_mix:a.t,u_lineatlas_width:e.lineAtlas.width,u_lineatlas_height:e.lineAtlas.height})};function _r(e,n){return 1/t.aK(e,1,n.tileZoom)}function vr(e,n,r){return t.aL(e.transform,n,r.paint.get(`line-translate`),r.paint.get(`line-translate-anchor`))}let yr=(e,t,n,r,i)=>{return{u_tl_parent:e,u_scale_parent:t,u_buffer_scale:1,u_fade_t:n.mix,u_opacity:n.opacity*r.paint.get(`raster-opacity`),u_image0:0,u_image1:1,u_brightness_low:r.paint.get(`raster-brightness-min`),u_brightness_high:r.paint.get(`raster-brightness-max`),u_saturation_factor:(o=r.paint.get(`raster-saturation`),o>0?1-1/(1.001-o):-o),u_contrast_factor:(a=r.paint.get(`raster-contrast`),a>0?1/(1-a):1+a),u_spin_weights:br(r.paint.get(`raster-hue-rotate`)),u_coords_top:[i[0].x,i[0].y,i[1].x,i[1].y],u_coords_bottom:[i[3].x,i[3].y,i[2].x,i[2].y]};var a,o};function br(e){e*=Math.PI/180;let t=Math.sin(e),n=Math.cos(e);return[(2*n+1)/3,(-Math.sqrt(3)*t-n+1)/3,(Math.sqrt(3)*t-n+1)/3]}let xr=(e,t,n,r,i,a,o,s,c,l,u,d,f)=>{let p=o.transform;return{u_is_size_zoom_constant:+(e===`constant`||e===`source`),u_is_size_feature_constant:+(e===`constant`||e===`camera`),u_size_t:t?t.uSizeT:0,u_size:t?t.uSize:0,u_camera_to_center_distance:p.cameraToCenterDistance,u_pitch:p.pitch/360*2*Math.PI,u_rotate_symbol:+n,u_aspect_ratio:p.width/p.height,u_fade_change:o.options.fadeDuration?o.symbolFadeChange:1,u_label_plane_matrix:s,u_coord_matrix:c,u_is_text:+u,u_pitch_with_map:+r,u_is_along_line:i,u_is_variable_anchor:a,u_texsize:d,u_texture:0,u_translation:l,u_pitched_scale:f}},Sr=(e,n,r,i,a,o,s,c,l,u,d,f,p,m)=>{let h=s.transform;return t.e(xr(e,n,r,i,a,o,s,c,l,u,d,f,m),{u_gamma_scale:i?Math.cos(h.pitch*Math.PI/180)*h.cameraToCenterDistance:1,u_device_pixel_ratio:s.pixelRatio,u_is_halo:+!!p,u_is_plain:1})},Cr=(e,n,r,i,a,o,s,c,l,u,d,f,p)=>t.e(Sr(e,n,r,i,a,o,s,c,l,u,!0,d,!0,p),{u_texsize_icon:f,u_texture_icon:1}),wr=(e,t)=>({u_opacity:e,u_color:t}),Tr=(e,n,r,i,a)=>t.e(function(e,n,r,i){let a=r.imageManager.getPattern(e.from.toString()),o=r.imageManager.getPattern(e.to.toString()),{width:s,height:c}=r.imageManager.getPixelSize(),l=2**i.tileID.overscaledZ,u=i.tileSize*2**r.transform.tileZoom/l,d=u*(i.tileID.canonical.x+i.tileID.wrap*l),f=u*i.tileID.canonical.y;return{u_image:0,u_pattern_tl_a:a.tl,u_pattern_br_a:a.br,u_pattern_tl_b:o.tl,u_pattern_br_b:o.br,u_texsize:[s,c],u_mix:n.t,u_pattern_size_a:a.displaySize,u_pattern_size_b:o.displaySize,u_scale_a:n.fromScale,u_scale_b:n.toScale,u_tile_units_to_pixels:1/t.aK(i,1,r.transform.tileZoom),u_pixel_coord_upper:[d>>16,f>>16],u_pixel_coord_lower:[65535&d,65535&f]}}(r,a,n,i),{u_opacity:e}),Er=(e,t)=>{},Dr={fillExtrusion:(e,n)=>({u_lightpos:new t.c2(e,n.u_lightpos),u_lightpos_globe:new t.c2(e,n.u_lightpos_globe),u_lightintensity:new t.bp(e,n.u_lightintensity),u_lightcolor:new t.c2(e,n.u_lightcolor),u_vertical_gradient:new t.bp(e,n.u_vertical_gradient),u_opacity:new t.bp(e,n.u_opacity),u_fill_translate:new t.c3(e,n.u_fill_translate)}),fillExtrusionPattern:(e,n)=>({u_lightpos:new t.c2(e,n.u_lightpos),u_lightpos_globe:new t.c2(e,n.u_lightpos_globe),u_lightintensity:new t.bp(e,n.u_lightintensity),u_lightcolor:new t.c2(e,n.u_lightcolor),u_vertical_gradient:new t.bp(e,n.u_vertical_gradient),u_height_factor:new t.bp(e,n.u_height_factor),u_opacity:new t.bp(e,n.u_opacity),u_fill_translate:new t.c3(e,n.u_fill_translate),u_image:new t.b_(e,n.u_image),u_texsize:new t.c3(e,n.u_texsize),u_pixel_coord_upper:new t.c3(e,n.u_pixel_coord_upper),u_pixel_coord_lower:new t.c3(e,n.u_pixel_coord_lower),u_scale:new t.c2(e,n.u_scale),u_fade:new t.bp(e,n.u_fade)}),fill:(e,n)=>({u_fill_translate:new t.c3(e,n.u_fill_translate)}),fillPattern:(e,n)=>({u_image:new t.b_(e,n.u_image),u_texsize:new t.c3(e,n.u_texsize),u_pixel_coord_upper:new t.c3(e,n.u_pixel_coord_upper),u_pixel_coord_lower:new t.c3(e,n.u_pixel_coord_lower),u_scale:new t.c2(e,n.u_scale),u_fade:new t.bp(e,n.u_fade),u_fill_translate:new t.c3(e,n.u_fill_translate)}),fillOutline:(e,n)=>({u_world:new t.c3(e,n.u_world),u_fill_translate:new t.c3(e,n.u_fill_translate)}),fillOutlinePattern:(e,n)=>({u_world:new t.c3(e,n.u_world),u_image:new t.b_(e,n.u_image),u_texsize:new t.c3(e,n.u_texsize),u_pixel_coord_upper:new t.c3(e,n.u_pixel_coord_upper),u_pixel_coord_lower:new t.c3(e,n.u_pixel_coord_lower),u_scale:new t.c2(e,n.u_scale),u_fade:new t.bp(e,n.u_fade),u_fill_translate:new t.c3(e,n.u_fill_translate)}),circle:(e,n)=>({u_camera_to_center_distance:new t.bp(e,n.u_camera_to_center_distance),u_scale_with_map:new t.b_(e,n.u_scale_with_map),u_pitch_with_map:new t.b_(e,n.u_pitch_with_map),u_extrude_scale:new t.c3(e,n.u_extrude_scale),u_device_pixel_ratio:new t.bp(e,n.u_device_pixel_ratio),u_globe_extrude_scale:new t.bp(e,n.u_globe_extrude_scale),u_translate:new t.c3(e,n.u_translate)}),collisionBox:(e,n)=>({u_pixel_extrude_scale:new t.c3(e,n.u_pixel_extrude_scale)}),collisionCircle:(e,n)=>({u_viewport_size:new t.c3(e,n.u_viewport_size)}),debug:(e,n)=>({u_color:new t.b$(e,n.u_color),u_overlay:new t.b_(e,n.u_overlay),u_overlay_scale:new t.bp(e,n.u_overlay_scale)}),depth:Er,clippingMask:Er,heatmap:(e,n)=>({u_extrude_scale:new t.bp(e,n.u_extrude_scale),u_intensity:new t.bp(e,n.u_intensity),u_globe_extrude_scale:new t.bp(e,n.u_globe_extrude_scale)}),heatmapTexture:(e,n)=>({u_matrix:new t.c0(e,n.u_matrix),u_world:new t.c3(e,n.u_world),u_image:new t.b_(e,n.u_image),u_color_ramp:new t.b_(e,n.u_color_ramp),u_opacity:new t.bp(e,n.u_opacity)}),hillshade:(e,n)=>({u_image:new t.b_(e,n.u_image),u_latrange:new t.c3(e,n.u_latrange),u_exaggeration:new t.bp(e,n.u_exaggeration),u_altitudes:new t.c9(e,n.u_altitudes),u_azimuths:new t.c9(e,n.u_azimuths),u_accent:new t.b$(e,n.u_accent),u_method:new t.b_(e,n.u_method),u_shadows:new t.c8(e,n.u_shadows),u_highlights:new t.c8(e,n.u_highlights)}),hillshadePrepare:(e,n)=>({u_matrix:new t.c0(e,n.u_matrix),u_image:new t.b_(e,n.u_image),u_dimension:new t.c3(e,n.u_dimension),u_zoom:new t.bp(e,n.u_zoom),u_unpack:new t.c1(e,n.u_unpack)}),colorRelief:(e,n)=>({u_image:new t.b_(e,n.u_image),u_unpack:new t.c1(e,n.u_unpack),u_dimension:new t.c3(e,n.u_dimension),u_elevation_stops:new t.b_(e,n.u_elevation_stops),u_color_stops:new t.b_(e,n.u_color_stops),u_color_ramp_size:new t.b_(e,n.u_color_ramp_size),u_opacity:new t.bp(e,n.u_opacity)}),line:(e,n)=>({u_translation:new t.c3(e,n.u_translation),u_ratio:new t.bp(e,n.u_ratio),u_device_pixel_ratio:new t.bp(e,n.u_device_pixel_ratio),u_units_to_pixels:new t.c3(e,n.u_units_to_pixels)}),lineGradient:(e,n)=>({u_translation:new t.c3(e,n.u_translation),u_ratio:new t.bp(e,n.u_ratio),u_device_pixel_ratio:new t.bp(e,n.u_device_pixel_ratio),u_units_to_pixels:new t.c3(e,n.u_units_to_pixels),u_image:new t.b_(e,n.u_image),u_image_height:new t.bp(e,n.u_image_height)}),linePattern:(e,n)=>({u_translation:new t.c3(e,n.u_translation),u_texsize:new t.c3(e,n.u_texsize),u_ratio:new t.bp(e,n.u_ratio),u_device_pixel_ratio:new t.bp(e,n.u_device_pixel_ratio),u_image:new t.b_(e,n.u_image),u_units_to_pixels:new t.c3(e,n.u_units_to_pixels),u_scale:new t.c2(e,n.u_scale),u_fade:new t.bp(e,n.u_fade)}),lineSDF:(e,n)=>({u_translation:new t.c3(e,n.u_translation),u_ratio:new t.bp(e,n.u_ratio),u_device_pixel_ratio:new t.bp(e,n.u_device_pixel_ratio),u_units_to_pixels:new t.c3(e,n.u_units_to_pixels),u_image:new t.b_(e,n.u_image),u_mix:new t.bp(e,n.u_mix),u_tileratio:new t.bp(e,n.u_tileratio),u_crossfade_from:new t.bp(e,n.u_crossfade_from),u_crossfade_to:new t.bp(e,n.u_crossfade_to),u_lineatlas_width:new t.bp(e,n.u_lineatlas_width),u_lineatlas_height:new t.bp(e,n.u_lineatlas_height)}),lineGradientSDF:(e,n)=>({u_translation:new t.c3(e,n.u_translation),u_ratio:new t.bp(e,n.u_ratio),u_device_pixel_ratio:new t.bp(e,n.u_device_pixel_ratio),u_units_to_pixels:new t.c3(e,n.u_units_to_pixels),u_image:new t.b_(e,n.u_image),u_image_height:new t.bp(e,n.u_image_height),u_tileratio:new t.bp(e,n.u_tileratio),u_crossfade_from:new t.bp(e,n.u_crossfade_from),u_crossfade_to:new t.bp(e,n.u_crossfade_to),u_image_dash:new t.b_(e,n.u_image_dash),u_mix:new t.bp(e,n.u_mix),u_lineatlas_width:new t.bp(e,n.u_lineatlas_width),u_lineatlas_height:new t.bp(e,n.u_lineatlas_height)}),raster:(e,n)=>({u_tl_parent:new t.c3(e,n.u_tl_parent),u_scale_parent:new t.bp(e,n.u_scale_parent),u_buffer_scale:new t.bp(e,n.u_buffer_scale),u_fade_t:new t.bp(e,n.u_fade_t),u_opacity:new t.bp(e,n.u_opacity),u_image0:new t.b_(e,n.u_image0),u_image1:new t.b_(e,n.u_image1),u_brightness_low:new t.bp(e,n.u_brightness_low),u_brightness_high:new t.bp(e,n.u_brightness_high),u_saturation_factor:new t.bp(e,n.u_saturation_factor),u_contrast_factor:new t.bp(e,n.u_contrast_factor),u_spin_weights:new t.c2(e,n.u_spin_weights),u_coords_top:new t.c1(e,n.u_coords_top),u_coords_bottom:new t.c1(e,n.u_coords_bottom)}),symbolIcon:(e,n)=>({u_is_size_zoom_constant:new t.b_(e,n.u_is_size_zoom_constant),u_is_size_feature_constant:new t.b_(e,n.u_is_size_feature_constant),u_size_t:new t.bp(e,n.u_size_t),u_size:new t.bp(e,n.u_size),u_camera_to_center_distance:new t.bp(e,n.u_camera_to_center_distance),u_pitch:new t.bp(e,n.u_pitch),u_rotate_symbol:new t.b_(e,n.u_rotate_symbol),u_aspect_ratio:new t.bp(e,n.u_aspect_ratio),u_fade_change:new t.bp(e,n.u_fade_change),u_label_plane_matrix:new t.c0(e,n.u_label_plane_matrix),u_coord_matrix:new t.c0(e,n.u_coord_matrix),u_is_text:new t.b_(e,n.u_is_text),u_pitch_with_map:new t.b_(e,n.u_pitch_with_map),u_is_along_line:new t.b_(e,n.u_is_along_line),u_is_variable_anchor:new t.b_(e,n.u_is_variable_anchor),u_texsize:new t.c3(e,n.u_texsize),u_texture:new t.b_(e,n.u_texture),u_translation:new t.c3(e,n.u_translation),u_pitched_scale:new t.bp(e,n.u_pitched_scale)}),symbolSDF:(e,n)=>({u_is_size_zoom_constant:new t.b_(e,n.u_is_size_zoom_constant),u_is_size_feature_constant:new t.b_(e,n.u_is_size_feature_constant),u_size_t:new t.bp(e,n.u_size_t),u_size:new t.bp(e,n.u_size),u_camera_to_center_distance:new t.bp(e,n.u_camera_to_center_distance),u_pitch:new t.bp(e,n.u_pitch),u_rotate_symbol:new t.b_(e,n.u_rotate_symbol),u_aspect_ratio:new t.bp(e,n.u_aspect_ratio),u_fade_change:new t.bp(e,n.u_fade_change),u_label_plane_matrix:new t.c0(e,n.u_label_plane_matrix),u_coord_matrix:new t.c0(e,n.u_coord_matrix),u_is_text:new t.b_(e,n.u_is_text),u_pitch_with_map:new t.b_(e,n.u_pitch_with_map),u_is_along_line:new t.b_(e,n.u_is_along_line),u_is_variable_anchor:new t.b_(e,n.u_is_variable_anchor),u_texsize:new t.c3(e,n.u_texsize),u_texture:new t.b_(e,n.u_texture),u_gamma_scale:new t.bp(e,n.u_gamma_scale),u_device_pixel_ratio:new t.bp(e,n.u_device_pixel_ratio),u_is_halo:new t.b_(e,n.u_is_halo),u_is_plain:new t.b_(e,n.u_is_plain),u_translation:new t.c3(e,n.u_translation),u_pitched_scale:new t.bp(e,n.u_pitched_scale)}),symbolTextAndIcon:(e,n)=>({u_is_size_zoom_constant:new t.b_(e,n.u_is_size_zoom_constant),u_is_size_feature_constant:new t.b_(e,n.u_is_size_feature_constant),u_size_t:new t.bp(e,n.u_size_t),u_size:new t.bp(e,n.u_size),u_camera_to_center_distance:new t.bp(e,n.u_camera_to_center_distance),u_pitch:new t.bp(e,n.u_pitch),u_rotate_symbol:new t.b_(e,n.u_rotate_symbol),u_aspect_ratio:new t.bp(e,n.u_aspect_ratio),u_fade_change:new t.bp(e,n.u_fade_change),u_label_plane_matrix:new t.c0(e,n.u_label_plane_matrix),u_coord_matrix:new t.c0(e,n.u_coord_matrix),u_is_text:new t.b_(e,n.u_is_text),u_pitch_with_map:new t.b_(e,n.u_pitch_with_map),u_is_along_line:new t.b_(e,n.u_is_along_line),u_is_variable_anchor:new t.b_(e,n.u_is_variable_anchor),u_texsize:new t.c3(e,n.u_texsize),u_texsize_icon:new t.c3(e,n.u_texsize_icon),u_texture:new t.b_(e,n.u_texture),u_texture_icon:new t.b_(e,n.u_texture_icon),u_gamma_scale:new t.bp(e,n.u_gamma_scale),u_device_pixel_ratio:new t.bp(e,n.u_device_pixel_ratio),u_is_halo:new t.b_(e,n.u_is_halo),u_translation:new t.c3(e,n.u_translation),u_pitched_scale:new t.bp(e,n.u_pitched_scale)}),background:(e,n)=>({u_opacity:new t.bp(e,n.u_opacity),u_color:new t.b$(e,n.u_color)}),backgroundPattern:(e,n)=>({u_opacity:new t.bp(e,n.u_opacity),u_image:new t.b_(e,n.u_image),u_pattern_tl_a:new t.c3(e,n.u_pattern_tl_a),u_pattern_br_a:new t.c3(e,n.u_pattern_br_a),u_pattern_tl_b:new t.c3(e,n.u_pattern_tl_b),u_pattern_br_b:new t.c3(e,n.u_pattern_br_b),u_texsize:new t.c3(e,n.u_texsize),u_mix:new t.bp(e,n.u_mix),u_pattern_size_a:new t.c3(e,n.u_pattern_size_a),u_pattern_size_b:new t.c3(e,n.u_pattern_size_b),u_scale_a:new t.bp(e,n.u_scale_a),u_scale_b:new t.bp(e,n.u_scale_b),u_pixel_coord_upper:new t.c3(e,n.u_pixel_coord_upper),u_pixel_coord_lower:new t.c3(e,n.u_pixel_coord_lower),u_tile_units_to_pixels:new t.bp(e,n.u_tile_units_to_pixels)}),terrain:(e,n)=>({u_texture:new t.b_(e,n.u_texture),u_ele_delta:new t.bp(e,n.u_ele_delta),u_fog_matrix:new t.c0(e,n.u_fog_matrix),u_fog_color:new t.b$(e,n.u_fog_color),u_fog_ground_blend:new t.bp(e,n.u_fog_ground_blend),u_fog_ground_blend_opacity:new t.bp(e,n.u_fog_ground_blend_opacity),u_horizon_color:new t.b$(e,n.u_horizon_color),u_horizon_fog_blend:new t.bp(e,n.u_horizon_fog_blend),u_is_globe_mode:new t.bp(e,n.u_is_globe_mode)}),terrainDepth:(e,n)=>({u_ele_delta:new t.bp(e,n.u_ele_delta)}),terrainCoords:(e,n)=>({u_texture:new t.b_(e,n.u_texture),u_terrain_coords_id:new t.bp(e,n.u_terrain_coords_id),u_ele_delta:new t.bp(e,n.u_ele_delta)}),projectionErrorMeasurement:(e,n)=>({u_input:new t.bp(e,n.u_input),u_output_expected:new t.bp(e,n.u_output_expected)}),atmosphere:(e,n)=>({u_sun_pos:new t.c2(e,n.u_sun_pos),u_atmosphere_blend:new t.bp(e,n.u_atmosphere_blend),u_globe_position:new t.c2(e,n.u_globe_position),u_globe_radius:new t.bp(e,n.u_globe_radius),u_inv_proj_matrix:new t.c0(e,n.u_inv_proj_matrix)}),sky:(e,n)=>({u_sky_color:new t.b$(e,n.u_sky_color),u_horizon_color:new t.b$(e,n.u_horizon_color),u_horizon:new t.c3(e,n.u_horizon),u_horizon_normal:new t.c3(e,n.u_horizon_normal),u_sky_horizon_blend:new t.bp(e,n.u_sky_horizon_blend),u_sky_blend:new t.bp(e,n.u_sky_blend)})};class Or{constructor(e,t,n){this.context=e;let r=e.gl;this.buffer=r.createBuffer(),this.dynamicDraw=!!n,this.context.unbindVAO(),e.bindElementBuffer.set(this.buffer),r.bufferData(r.ELEMENT_ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?r.DYNAMIC_DRAW:r.STATIC_DRAW),this.dynamicDraw||t.freeBufferAfterUpload()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(e){let t=this.context.gl;if(!this.dynamicDraw)throw Error(`Attempted to update data while not in dynamic mode.`);this.context.unbindVAO(),this.bind(),t.bufferSubData(t.ELEMENT_ARRAY_BUFFER,0,e.arrayBuffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}let kr={Int8:`BYTE`,Uint8:`UNSIGNED_BYTE`,Int16:`SHORT`,Uint16:`UNSIGNED_SHORT`,Int32:`INT`,Uint32:`UNSIGNED_INT`,Float32:`FLOAT`};class W{constructor(e,t,n,r){this.length=t.length,this.attributes=n,this.itemSize=t.bytesPerElement,this.dynamicDraw=r,this.context=e;let i=e.gl;this.buffer=i.createBuffer(),e.bindVertexBuffer.set(this.buffer),i.bufferData(i.ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?i.DYNAMIC_DRAW:i.STATIC_DRAW),this.dynamicDraw||t.freeBufferAfterUpload()}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(e){if(e.length!==this.length)throw Error(`Length of new data is ${e.length}, which doesn't match current length of ${this.length}`);let t=this.context.gl;this.bind(),t.bufferSubData(t.ARRAY_BUFFER,0,e.arrayBuffer)}enableAttributes(e,t){for(let n of this.attributes){let r=t.attributes[n.name];r!==void 0&&e.enableVertexAttribArray(r)}}setVertexAttribPointers(e,t,n){for(let r of this.attributes){let i=t.attributes[r.name];i!==void 0&&e.vertexAttribPointer(i,r.components,e[kr[r.type]],!1,this.itemSize,r.offset+this.itemSize*(n||0))}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class Ar{constructor(e){this.gl=e.gl,this.default=this.getDefault(),this.current=this.default,this.dirty=!1}get(){return this.current}set(e){}getDefault(){return this.default}setDefault(){this.set(this.default)}}class jr extends Ar{getDefault(){return t.bo.transparent}set(e){let t=this.current;(e.r!==t.r||e.g!==t.g||e.b!==t.b||e.a!==t.a||this.dirty)&&(this.gl.clearColor(e.r,e.g,e.b,e.a),this.current=e,this.dirty=!1)}}class Mr extends Ar{getDefault(){return 1}set(e){(e!==this.current||this.dirty)&&(this.gl.clearDepth(e),this.current=e,this.dirty=!1)}}class Nr extends Ar{getDefault(){return 0}set(e){(e!==this.current||this.dirty)&&(this.gl.clearStencil(e),this.current=e,this.dirty=!1)}}class Pr extends Ar{getDefault(){return[!0,!0,!0,!0]}set(e){let t=this.current;(e[0]!==t[0]||e[1]!==t[1]||e[2]!==t[2]||e[3]!==t[3]||this.dirty)&&(this.gl.colorMask(e[0],e[1],e[2],e[3]),this.current=e,this.dirty=!1)}}class Fr extends Ar{getDefault(){return!0}set(e){(e!==this.current||this.dirty)&&(this.gl.depthMask(e),this.current=e,this.dirty=!1)}}class Ir extends Ar{getDefault(){return 255}set(e){(e!==this.current||this.dirty)&&(this.gl.stencilMask(e),this.current=e,this.dirty=!1)}}class Lr extends Ar{getDefault(){return{func:this.gl.ALWAYS,ref:0,mask:255}}set(e){let t=this.current;(e.func!==t.func||e.ref!==t.ref||e.mask!==t.mask||this.dirty)&&(this.gl.stencilFunc(e.func,e.ref,e.mask),this.current=e,this.dirty=!1)}}class Rr extends Ar{getDefault(){let e=this.gl;return[e.KEEP,e.KEEP,e.KEEP]}set(e){let t=this.current;(e[0]!==t[0]||e[1]!==t[1]||e[2]!==t[2]||this.dirty)&&(this.gl.stencilOp(e[0],e[1],e[2]),this.current=e,this.dirty=!1)}}class zr extends Ar{getDefault(){return!1}set(e){if(e===this.current&&!this.dirty)return;let t=this.gl;e?t.enable(t.STENCIL_TEST):t.disable(t.STENCIL_TEST),this.current=e,this.dirty=!1}}class Br extends Ar{getDefault(){return[0,1]}set(e){let t=this.current;(e[0]!==t[0]||e[1]!==t[1]||this.dirty)&&(this.gl.depthRange(e[0],e[1]),this.current=e,this.dirty=!1)}}class Vr extends Ar{getDefault(){return!1}set(e){if(e===this.current&&!this.dirty)return;let t=this.gl;e?t.enable(t.DEPTH_TEST):t.disable(t.DEPTH_TEST),this.current=e,this.dirty=!1}}class Hr extends Ar{getDefault(){return this.gl.LESS}set(e){(e!==this.current||this.dirty)&&(this.gl.depthFunc(e),this.current=e,this.dirty=!1)}}class Ur extends Ar{getDefault(){return!1}set(e){if(e===this.current&&!this.dirty)return;let t=this.gl;e?t.enable(t.BLEND):t.disable(t.BLEND),this.current=e,this.dirty=!1}}class Wr extends Ar{getDefault(){let e=this.gl;return[e.ONE,e.ZERO]}set(e){let t=this.current;(e[0]!==t[0]||e[1]!==t[1]||this.dirty)&&(this.gl.blendFunc(e[0],e[1]),this.current=e,this.dirty=!1)}}class Gr extends Ar{getDefault(){return t.bo.transparent}set(e){let t=this.current;(e.r!==t.r||e.g!==t.g||e.b!==t.b||e.a!==t.a||this.dirty)&&(this.gl.blendColor(e.r,e.g,e.b,e.a),this.current=e,this.dirty=!1)}}class Kr extends Ar{getDefault(){return this.gl.FUNC_ADD}set(e){(e!==this.current||this.dirty)&&(this.gl.blendEquation(e),this.current=e,this.dirty=!1)}}class qr extends Ar{getDefault(){return!1}set(e){if(e===this.current&&!this.dirty)return;let t=this.gl;e?t.enable(t.CULL_FACE):t.disable(t.CULL_FACE),this.current=e,this.dirty=!1}}class Jr extends Ar{getDefault(){return this.gl.BACK}set(e){(e!==this.current||this.dirty)&&(this.gl.cullFace(e),this.current=e,this.dirty=!1)}}class Yr extends Ar{getDefault(){return this.gl.CCW}set(e){(e!==this.current||this.dirty)&&(this.gl.frontFace(e),this.current=e,this.dirty=!1)}}class G extends Ar{getDefault(){return null}set(e){(e!==this.current||this.dirty)&&(this.gl.useProgram(e),this.current=e,this.dirty=!1)}}class Xr extends Ar{getDefault(){return this.gl.TEXTURE0}set(e){(e!==this.current||this.dirty)&&(this.gl.activeTexture(e),this.current=e,this.dirty=!1)}}class Zr extends Ar{getDefault(){let e=this.gl;return[0,0,e.drawingBufferWidth,e.drawingBufferHeight]}set(e){let t=this.current;(e[0]!==t[0]||e[1]!==t[1]||e[2]!==t[2]||e[3]!==t[3]||this.dirty)&&(this.gl.viewport(e[0],e[1],e[2],e[3]),this.current=e,this.dirty=!1)}}class Qr extends Ar{getDefault(){return null}set(e){if(e===this.current&&!this.dirty)return;let t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,e),this.current=e,this.dirty=!1}}class $r extends Ar{getDefault(){return null}set(e){if(e===this.current&&!this.dirty)return;let t=this.gl;t.bindRenderbuffer(t.RENDERBUFFER,e),this.current=e,this.dirty=!1}}class ei extends Ar{getDefault(){return null}set(e){if(e===this.current&&!this.dirty)return;let t=this.gl;t.bindTexture(t.TEXTURE_2D,e),this.current=e,this.dirty=!1}}class ti extends Ar{getDefault(){return null}set(e){if(e===this.current&&!this.dirty)return;let t=this.gl;t.bindBuffer(t.ARRAY_BUFFER,e),this.current=e,this.dirty=!1}}class ni extends Ar{getDefault(){return null}set(e){let t=this.gl;t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,e),this.current=e,this.dirty=!1}}class K extends Ar{getDefault(){return null}set(e){var t;if(e===this.current&&!this.dirty)return;let n=this.gl;gn(n)?n.bindVertexArray(e):(t=n.getExtension(`OES_vertex_array_object`))==null||t.bindVertexArrayOES(e),this.current=e,this.dirty=!1}}class ri extends Ar{getDefault(){return 4}set(e){if(e===this.current&&!this.dirty)return;let t=this.gl;t.pixelStorei(t.UNPACK_ALIGNMENT,e),this.current=e,this.dirty=!1}}class ii extends Ar{getDefault(){return!1}set(e){if(e===this.current&&!this.dirty)return;let t=this.gl;t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e),this.current=e,this.dirty=!1}}class ai extends Ar{getDefault(){return!1}set(e){if(e===this.current&&!this.dirty)return;let t=this.gl;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,e),this.current=e,this.dirty=!1}}class oi extends Ar{constructor(e,t){super(e),this.context=e,this.parent=t}getDefault(){return null}}class q extends oi{setDirty(){this.dirty=!0}set(e){if(e===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);let t=this.gl;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),this.current=e,this.dirty=!1}}class J extends oi{set(e){if(e===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);let t=this.gl;t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.RENDERBUFFER,e),this.current=e,this.dirty=!1}}class si extends oi{set(e){if(e===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);let t=this.gl;t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,e),this.current=e,this.dirty=!1}}let ci=`Framebuffer is not complete`;class li{constructor(e,t,n,r,i){this.context=e,this.width=t,this.height=n;let a=e.gl,o=this.framebuffer=a.createFramebuffer();if(this.colorAttachment=new q(e,o),r)this.depthAttachment=i?new si(e,o):new J(e,o);else if(i)throw Error(`Stencil cannot be set without depth`);if(a.checkFramebufferStatus(a.FRAMEBUFFER)!==a.FRAMEBUFFER_COMPLETE)throw Error(ci)}destroy(){let e=this.context.gl,t=this.colorAttachment.get();if(t&&e.deleteTexture(t),this.depthAttachment){let t=this.depthAttachment.get();t&&e.deleteRenderbuffer(t)}e.deleteFramebuffer(this.framebuffer)}}class ui{constructor(e){if(this.gl=e,this.clearColor=new jr(this),this.clearDepth=new Mr(this),this.clearStencil=new Nr(this),this.colorMask=new Pr(this),this.depthMask=new Fr(this),this.stencilMask=new Ir(this),this.stencilFunc=new Lr(this),this.stencilOp=new Rr(this),this.stencilTest=new zr(this),this.depthRange=new Br(this),this.depthTest=new Vr(this),this.depthFunc=new Hr(this),this.blend=new Ur(this),this.blendFunc=new Wr(this),this.blendColor=new Gr(this),this.blendEquation=new Kr(this),this.cullFace=new qr(this),this.cullFaceSide=new Jr(this),this.frontFace=new Yr(this),this.program=new G(this),this.activeTexture=new Xr(this),this.viewport=new Zr(this),this.bindFramebuffer=new Qr(this),this.bindRenderbuffer=new $r(this),this.bindTexture=new ei(this),this.bindVertexBuffer=new ti(this),this.bindElementBuffer=new ni(this),this.bindVertexArray=new K(this),this.pixelStoreUnpack=new ri(this),this.pixelStoreUnpackPremultiplyAlpha=new ii(this),this.pixelStoreUnpackFlipY=new ai(this),this.extTextureFilterAnisotropic=e.getExtension(`EXT_texture_filter_anisotropic`),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=e.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT)),this.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE),gn(e)){this.HALF_FLOAT=e.HALF_FLOAT;let t=e.getExtension(`EXT_color_buffer_half_float`);this.RGBA16F=e.RGBA16F??t?.RGBA16F_EXT,this.RGB16F=e.RGB16F??t?.RGB16F_EXT,e.getExtension(`EXT_color_buffer_float`)}else{e.getExtension(`EXT_color_buffer_half_float`),e.getExtension(`OES_texture_half_float_linear`);let t=e.getExtension(`OES_texture_half_float`);this.HALF_FLOAT=t?.HALF_FLOAT_OES}}setDefault(){this.unbindVAO(),this.clearColor.setDefault(),this.clearDepth.setDefault(),this.clearStencil.setDefault(),this.colorMask.setDefault(),this.depthMask.setDefault(),this.stencilMask.setDefault(),this.stencilFunc.setDefault(),this.stencilOp.setDefault(),this.stencilTest.setDefault(),this.depthRange.setDefault(),this.depthTest.setDefault(),this.depthFunc.setDefault(),this.blend.setDefault(),this.blendFunc.setDefault(),this.blendColor.setDefault(),this.blendEquation.setDefault(),this.cullFace.setDefault(),this.cullFaceSide.setDefault(),this.frontFace.setDefault(),this.program.setDefault(),this.activeTexture.setDefault(),this.bindFramebuffer.setDefault(),this.pixelStoreUnpack.setDefault(),this.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.pixelStoreUnpackFlipY.setDefault()}setDirty(){this.clearColor.dirty=!0,this.clearDepth.dirty=!0,this.clearStencil.dirty=!0,this.colorMask.dirty=!0,this.depthMask.dirty=!0,this.stencilMask.dirty=!0,this.stencilFunc.dirty=!0,this.stencilOp.dirty=!0,this.stencilTest.dirty=!0,this.depthRange.dirty=!0,this.depthTest.dirty=!0,this.depthFunc.dirty=!0,this.blend.dirty=!0,this.blendFunc.dirty=!0,this.blendColor.dirty=!0,this.blendEquation.dirty=!0,this.cullFace.dirty=!0,this.cullFaceSide.dirty=!0,this.frontFace.dirty=!0,this.program.dirty=!0,this.activeTexture.dirty=!0,this.viewport.dirty=!0,this.bindFramebuffer.dirty=!0,this.bindRenderbuffer.dirty=!0,this.bindTexture.dirty=!0,this.bindVertexBuffer.dirty=!0,this.bindElementBuffer.dirty=!0,this.bindVertexArray.dirty=!0,this.pixelStoreUnpack.dirty=!0,this.pixelStoreUnpackPremultiplyAlpha.dirty=!0,this.pixelStoreUnpackFlipY.dirty=!0}createIndexBuffer(e,t){return new Or(this,e,t)}createVertexBuffer(e,t,n){return new W(this,e,t,n)}createRenderbuffer(e,t,n){let r=this.gl,i=r.createRenderbuffer();return this.bindRenderbuffer.set(i),r.renderbufferStorage(r.RENDERBUFFER,e,t,n),this.bindRenderbuffer.set(null),i}createFramebuffer(e,t,n,r){return new li(this,e,t,n,r)}clear({color:e,depth:t,stencil:n}){let r=this.gl,i=0;e&&(i|=r.COLOR_BUFFER_BIT,this.clearColor.set(e),this.colorMask.set([!0,!0,!0,!0])),t!==void 0&&(i|=r.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(t),this.depthMask.set(!0)),n!==void 0&&(i|=r.STENCIL_BUFFER_BIT,this.clearStencil.set(n),this.stencilMask.set(255)),r.clear(i)}setCullFace(e){!1===e.enable?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(e.mode),this.frontFace.set(e.frontFace))}setDepthMode(e){e.func!==this.gl.ALWAYS||e.mask?(this.depthTest.set(!0),this.depthFunc.set(e.func),this.depthMask.set(e.mask),this.depthRange.set(e.range)):this.depthTest.set(!1)}setStencilMode(e){e.test.func!==this.gl.ALWAYS||e.mask?(this.stencilTest.set(!0),this.stencilMask.set(e.mask),this.stencilOp.set([e.fail,e.depthFail,e.pass]),this.stencilFunc.set({func:e.test.func,ref:e.ref,mask:e.test.mask})):this.stencilTest.set(!1)}setColorMode(e){t.bQ(e.blendFunction,un.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(e.blendFunction),this.blendColor.set(e.blendColor)),this.colorMask.set(e.mask)}createVertexArray(){return gn(this.gl)?this.gl.createVertexArray():this.gl.getExtension(`OES_vertex_array_object`)?.createVertexArrayOES()}deleteVertexArray(e){var t;gn(this.gl)?this.gl.deleteVertexArray(e):(t=this.gl.getExtension(`OES_vertex_array_object`))==null||t.deleteVertexArrayOES(e)}unbindVAO(){this.bindVertexArray.set(null)}}let di;function Y(e,n,r,i,a){let o=e.context,s=e.transform,c=o.gl,l=e.useProgram(`collisionBox`),u=[],d=0,f=0;for(let t of i){let i=n.getTile(t).getBucket(r);if(!i)continue;let p=a?i.textCollisionBox:i.iconCollisionBox,m=i.collisionCircleArray;m.length>0&&(u.push({circleArray:m,circleOffset:f,coord:t}),d+=m.length/4,f=d),p&&l.draw(o,c.LINES,pn.disabled,hn.disabled,e.colorModeForRenderPass(),fn.disabled,rr(e.transform),e.style.map.terrain?.getTerrainData(t),s.getProjectionData({overscaledTileID:t,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),r.id,p.layoutVertexBuffer,p.indexBuffer,p.segments,null,e.transform.zoom,null,null,p.collisionVertexBuffer)}if(!a||!u.length)return;let p=e.useProgram(`collisionCircle`),m=new t.ca;m.resize(4*d),m._trim();let h=0;for(let e of u)for(let t=0;t<e.circleArray.length/4;t++){let n=4*t,r=e.circleArray[n+0],i=e.circleArray[n+1],a=e.circleArray[n+2],o=e.circleArray[n+3];m.emplace(h++,r,i,a,o,0),m.emplace(h++,r,i,a,o,1),m.emplace(h++,r,i,a,o,2),m.emplace(h++,r,i,a,o,3)}(!di||di.length<2*d)&&(di=function(e){let n=2*e,r=new t.cc;r.resize(n),r._trim();for(let e=0;e<n;e++){let t=6*e;r.uint16[t+0]=4*e+0,r.uint16[t+1]=4*e+1,r.uint16[t+2]=4*e+2,r.uint16[t+3]=4*e+2,r.uint16[t+4]=4*e+3,r.uint16[t+5]=4*e+0}return r}(d));let g=o.createIndexBuffer(di,!0),_=o.createVertexBuffer(m,t.cb.members,!0);for(let n of u){let i=ir(e.transform);p.draw(o,c.TRIANGLES,pn.disabled,hn.disabled,e.colorModeForRenderPass(),fn.disabled,i,e.style.map.terrain?.getTerrainData(n.coord),null,r.id,_,g,t.aV.simpleSegment(0,2*n.circleOffset,n.circleArray.length,n.circleArray.length/2),null,e.transform.zoom,null,null,null)}_.destroy(),g.destroy()}let fi=t.ap(new Float32Array(16));function pi(e,n,r,i,a,o){let{horizontalAlign:s,verticalAlign:c}=t.aP(e);return new t.P((-(s-.5)*n/a+i[0])*o,(-(c-.5)*r/a+i[1])*o)}function mi(e,n,r,i,a,o){let s=n.tileAnchorPoint.add(new t.P(n.translation[0],n.translation[1]));if(n.pitchWithMap){let e=i.mult(o);r||(e=e.rotate(-a));let t=s.add(e);return ot(t.x,t.y,n.pitchedLabelPlaneMatrix,n.getElevation).point}if(r){let t=ht(n.tileAnchorPoint.x+1,n.tileAnchorPoint.y,n).point.sub(e),r=Math.atan(t.y/t.x)+(t.x<0?Math.PI:0);return e.add(i.rotate(r))}return e.add(i)}function hi(e,n,r,i,a,o,s,c,l,u,d,f){let p=e.text.placedSymbolArray,m=e.text.dynamicLayoutVertexArray,h=e.icon.dynamicLayoutVertexArray,g={};m.clear();for(let h=0;h<p.length;h++){let _=p.get(h),v=_.hidden||!_.crossTileID||e.allowVerticalPlacement&&!_.placedOrientation?null:i[_.crossTileID];if(v){let i=new t.P(_.anchorX,_.anchorY),p={getElevation:f,width:a.width,height:a.height,pitchedLabelPlaneMatrix:o,pitchWithMap:r,transform:a,tileAnchorPoint:i,translation:u,unwrappedTileID:d},h=r?_t(i.x,i.y,p):ht(i.x,i.y,p),y=st(a.cameraToCenterDistance,h.signedDistanceFromCamera),b=t.ay(e.textSizeData,c,_)*y/t.aJ;r&&(b*=e.tilePixelRatio/s);let{width:x,height:S,anchor:C,textOffset:w,textBoxScale:T}=v,E=pi(C,x,S,w,T,b),D=a.getPitchedTextCorrection(i.x+u[0],i.y+u[1],d),O=mi(h.point,p,n,E,-a.bearingInRadians,D),k=e.allowVerticalPlacement&&_.placedOrientation===t.ax.vertical?Math.PI/2:0;for(let e=0;e<_.numGlyphs;e++)t.aD(m,O,k);l&&_.associatedIconIndex>=0&&(g[_.associatedIconIndex]={shiftedAnchor:O,angle:k})}else St(_.numGlyphs,m)}if(l){h.clear();let n=e.icon.placedSymbolArray;for(let e=0;e<n.length;e++){let r=n.get(e);if(r.hidden)St(r.numGlyphs,h);else{let n=g[e];if(n)for(let e=0;e<r.numGlyphs;e++)t.aD(h,n.shiftedAnchor,n.angle);else St(r.numGlyphs,h)}}e.icon.dynamicLayoutVertexBuffer.updateData(h)}e.text.dynamicLayoutVertexBuffer.updateData(m)}function gi(e,t,n){return n.iconsInText&&t?`symbolTextAndIcon`:e?`symbolSDF`:`symbolIcon`}function _i(e,n,r,i,a,o,s,c,l,u,d,f,p){let m=e.context,h=m.gl,g=e.transform,_=c===`map`,v=l===`map`,y=c!==`viewport`&&r.layout.get(`symbol-placement`)!==`point`,b=_&&!v&&!y,x=!r.layout.get(`symbol-sort-key`).isConstant(),S=!1,C=e.getDepthModeForSublayer(0,pn.ReadOnly),w=r._unevaluatedLayout.hasValue(`text-variable-anchor`)||r._unevaluatedLayout.hasValue(`text-variable-anchor-offset`),T=[],E=g.getCircleRadiusCorrection();for(let c of i){let i=n.getTile(c),l=i.getBucket(r);if(!l)continue;let d=a?l.text:l.icon;if(!d?.segments.get().length||!d.hasVisibleVertices)continue;let f=d.programConfigurations.get(r.id),m=a||l.sdfIcons,C=a?l.textSizeData:l.iconSizeData,D=v||g.pitch!==0,O=e.useProgram(gi(m,a,l),f),k=t.aw(C,g.zoom),A=e.style.map.terrain?.getTerrainData(c),ee,te,ne,re,ie=[0,0],ae=null;if(a)te=i.glyphAtlasTexture,ne=h.LINEAR,ee=i.glyphAtlasTexture.size,l.iconsInText&&(ie=i.imageAtlasTexture.size,ae=i.imageAtlasTexture,re=D||e.options.rotating||e.options.zooming||C.kind===`composite`||C.kind===`camera`?h.LINEAR:h.NEAREST);else{let t=r.layout.get(`icon-size`).constantOr(0)!==1||l.iconsNeedLinear;te=i.imageAtlasTexture,ne=m||e.options.rotating||e.options.zooming||t||D?h.LINEAR:h.NEAREST,ee=i.imageAtlasTexture.size}let oe=t.aK(i,1,e.transform.zoom),se=rt(_,e.transform,oe),ce=it(v,_,e.transform,oe),le=t.aL(g,i,o,s),ue=g.getProjectionData({overscaledTileID:c,applyGlobeMatrix:!p,applyTerrainMatrix:!0}),de=w&&l.hasTextData(),fe=r.layout.get(`icon-text-fit`)!==`none`&&de&&l.hasIconData();if(y){let n=t.O();tt(n,se);let i=e.style.map.terrain?(t,n)=>e.style.map.terrain.getElevation(c,t,n):null;lt(l,e,a,se,n,v,u,r.layout.get(`text-rotation-alignment`)===`map`,c.toUnwrapped(),g.width,g.height,le,i)}let pe=a&&w||fe,me=y||pe?fi:v?se:e.transform.clipSpaceToPixelsMatrix,he=m&&r.paint.get(a?`text-halo-width`:`icon-halo-width`).constantOr(1)!==0,ge;ge=m?l.iconsInText?Cr(C.kind,k,b,v,y,pe,e,me,ce,le,ee,ie,E):Sr(C.kind,k,b,v,y,pe,e,me,ce,le,a,ee,he,E):xr(C.kind,k,b,v,y,pe,e,me,ce,le,a,ee,E);let _e={program:O,buffers:d,uniformValues:ge,projectionData:ue,atlasTexture:te,atlasTextureIcon:ae,atlasInterpolation:ne,atlasInterpolationIcon:re,isSDF:m,hasHalo:he};if(x&&l.canOverlap){S=!0;let e=d.segments.get();for(let n of e)T.push({segments:new t.aV([n]),sortKey:n.sortKey,state:_e,terrainData:A})}else T.push({segments:d.segments,sortKey:0,state:_e,terrainData:A})}S&&T.sort(((e,t)=>e.sortKey-t.sortKey));let D=r.paint.get(a?`text-halo-width`:`icon-halo-width`).constantOr(null)??1/0,O=r.layout.get(`text-letter-spacing`).constantOr(0)*t.aJ<0||D>1;for(let t of T){let n=t.state;m.activeTexture.set(h.TEXTURE0),n.atlasTexture.bind(n.atlasInterpolation,h.CLAMP_TO_EDGE),n.atlasTextureIcon&&(m.activeTexture.set(h.TEXTURE1),n.atlasTextureIcon&&n.atlasTextureIcon.bind(n.atlasInterpolationIcon,h.CLAMP_TO_EDGE));let i=n.isSDF&&n.hasHalo;if(i){let i=n.uniformValues;i.u_is_halo=1,O&&(i.u_is_plain=0,vi(n.buffers,t.segments,r,e,n.program,C,d,f,i,n.projectionData,t.terrainData),i.u_is_halo=0,i.u_is_plain=1)}vi(n.buffers,t.segments,r,e,n.program,C,d,f,n.uniformValues,n.projectionData,t.terrainData),i&&!O&&(n.uniformValues.u_is_halo=0)}}function vi(e,t,n,r,i,a,o,s,c,l,u){let d=r.context;i.draw(d,d.gl.TRIANGLES,a,o,s,fn.backCCW,c,u,l,n.id,e.layoutVertexBuffer,e.indexBuffer,t,n.paint,r.transform.zoom,e.programConfigurations.get(n.id),e.dynamicLayoutVertexBuffer,e.opacityVertexBuffer)}function yi(e,n,r,i,a){let o=e.context,s=o.gl,c=hn.disabled,l=new un([s.ONE,s.ONE],t.bo.transparent,[!0,!0,!0,!0]),u=n.getBucket(r);if(!u)return;let d=i.key,f=r.heatmapFbos.get(d);f||(f=xi(o,n.tileSize,n.tileSize),r.heatmapFbos.set(d,f)),o.bindFramebuffer.set(f.framebuffer),o.viewport.set([0,0,n.tileSize,n.tileSize]),o.clear({color:t.bo.transparent});let p=u.programConfigurations.get(r.id),m=e.useProgram(`heatmap`,p,!a),h=e.transform.getProjectionData({overscaledTileID:n.tileID,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),g=e.style.map.terrain.getTerrainData(i);m.draw(o,s.TRIANGLES,pn.disabled,c,l,fn.disabled,or(n,e.transform.zoom,r.paint.get(`heatmap-intensity`),1),g,h,r.id,u.layoutVertexBuffer,u.indexBuffer,u.segments,r.paint,e.transform.zoom,p)}function bi(e,t,n,r,i){let a=e.context,o=a.gl,s=e.transform;a.setColorMode(e.colorModeForRenderPass());let c=Si(a,t),l=n.key,u=t.heatmapFbos.get(l);if(!u)return;a.activeTexture.set(o.TEXTURE0),o.bindTexture(o.TEXTURE_2D,u.colorAttachment.get()),a.activeTexture.set(o.TEXTURE1),c.bind(o.LINEAR,o.CLAMP_TO_EDGE);let d=s.getProjectionData({overscaledTileID:n,applyTerrainMatrix:i,applyGlobeMatrix:!r});e.useProgram(`heatmapTexture`).draw(a,o.TRIANGLES,pn.disabled,hn.disabled,e.colorModeForRenderPass(),fn.disabled,sr(e,t,0,1),null,d,t.id,e.rasterBoundsBuffer,e.quadTriangleIndexBuffer,e.rasterBoundsSegments,t.paint,s.zoom),u.destroy(),t.heatmapFbos.delete(l)}function xi(e,t,n){let r=e.gl,i=r.createTexture();r.bindTexture(r.TEXTURE_2D,i),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR);let a=e.HALF_FLOAT??r.UNSIGNED_BYTE,o=e.RGBA16F??r.RGBA;r.texImage2D(r.TEXTURE_2D,0,o,t,n,0,r.RGBA,a,null);let s=e.createFramebuffer(t,n,!1,!1);return s.colorAttachment.set(i),s}function Si(e,n){return n.colorRampTexture||=new t.T(e,n.colorRamp,e.gl.RGBA),n.colorRampTexture}function Ci(e,n,r,i,a,o,s,c){let l=256;if(a.stepInterpolant){let i=n.getSource().maxzoom,a=s.canonical.z===i?Math.ceil(1<<e.transform.maxZoom-s.canonical.z):1;l=t.al(t.ce(o.maxLineLength/t.a6*1024*a),256,r.maxTextureSize)}return c.gradient=t.cf({expression:a.gradientExpression(),evaluationKey:`lineProgress`,resolution:l,image:c.gradient||void 0,clips:o.lineClipsArray}),c.texture?c.texture.update(c.gradient):c.texture=new t.T(r,c.gradient,i.RGBA),c.version=a.gradientVersion,c.texture}function wi(e,t,n,r,i){e.activeTexture.set(t.TEXTURE0),n.imageAtlasTexture.bind(t.LINEAR,t.CLAMP_TO_EDGE),r.updatePaintBuffers(i)}function Ti(e,t,n,r,i,a){(i||e.lineAtlas.dirty)&&(t.activeTexture.set(n.TEXTURE0),e.lineAtlas.bind(t)),r.updatePaintBuffers(a)}function Ei(e,t,n,r,i,a,o){let s=a.gradients[i.id],c=s.texture;i.gradientVersion!==s.version&&(c=Ci(e,t,n,r,i,a,o,s)),n.activeTexture.set(r.TEXTURE0),c.bind(i.stepInterpolant?r.NEAREST:r.LINEAR,r.CLAMP_TO_EDGE)}function Di(e,t,n,r,i,a,o,s,c){let l=a.gradients[i.id],u=l.texture;i.gradientVersion!==l.version&&(u=Ci(e,t,n,r,i,a,o,l)),n.activeTexture.set(r.TEXTURE0),u.bind(i.stepInterpolant?r.NEAREST:r.LINEAR,r.CLAMP_TO_EDGE),n.activeTexture.set(r.TEXTURE1),e.lineAtlas.bind(n),s.updatePaintBuffers(c)}function Oi(e,t,n,r,i){if(!n||!r?.imageAtlas)return;let a=r.imageAtlas.patternPositions,o=a[n.to.toString()],s=a[n.from.toString()];if(!o&&s&&(o=s),!s&&o&&(s=o),!o||!s){let e=i.getPaintProperty(t);o=a[e],s=a[e]}o&&s&&e.setConstantPatternPositions(o,s)}function ki(e,n,r,i,a,o,s,c){let l=e.context.gl,u=`fill-pattern`,d=r.paint.get(u),f=d?.constantOr(1),p=r.getCrossfadeParameters(),m,h,g,_,v,y=e.transform,b=r.paint.get(`fill-translate`),x=r.paint.get(`fill-translate-anchor`);s?(h=f&&!r.getPaintProperty(`fill-outline-color`)?`fillOutlinePattern`:`fillOutline`,m=l.LINES):(h=f?`fillPattern`:`fill`,m=l.TRIANGLES);let S=d.constantOr(null);for(let d of i){let i=n.getTile(d);if(f&&!i.patternsLoaded())continue;let C=i.getBucket(r);if(!C)continue;let w=C.programConfigurations.get(r.id),T=e.useProgram(h,w),E=e.style.map.terrain?.getTerrainData(d);f&&(e.context.activeTexture.set(l.TEXTURE0),i.imageAtlasTexture.bind(l.LINEAR,l.CLAMP_TO_EDGE),w.updatePaintBuffers(p)),Oi(w,u,S,i,r);let D=y.getProjectionData({overscaledTileID:d,applyGlobeMatrix:!c,applyTerrainMatrix:!0}),O=t.aL(y,i,b,x);if(s){_=C.indexBuffer2,v=C.segments2;let t=[l.drawingBufferWidth,l.drawingBufferHeight];g=h===`fillOutlinePattern`&&f?tr(e,p,i,t,O):er(t,O)}else _=C.indexBuffer,v=C.segments,g=f?$n(e,p,i,O):{u_fill_translate:O};let k=e.stencilModeForClipping(d);T.draw(e.context,m,a,k,o,fn.backCCW,g,E,D,r.id,C.layoutVertexBuffer,_,v,r.paint,e.transform.zoom,w)}}function Ai(e,n,r,i,a,o,s,c){let l=e.context,u=l.gl,d=`fill-extrusion-pattern`,f=r.paint.get(d),p=f.constantOr(1),m=r.getCrossfadeParameters(),h=r.paint.get(`fill-extrusion-opacity`),g=f.constantOr(null),_=e.transform;for(let f of i){let i=n.getTile(f),v=i.getBucket(r);if(!v)continue;let y=e.style.map.terrain?.getTerrainData(f),b=v.programConfigurations.get(r.id),x=e.useProgram(p?`fillExtrusionPattern`:`fillExtrusion`,b);p&&(e.context.activeTexture.set(u.TEXTURE0),i.imageAtlasTexture.bind(u.LINEAR,u.CLAMP_TO_EDGE),b.updatePaintBuffers(m));let S=_.getProjectionData({overscaledTileID:f,applyGlobeMatrix:!c,applyTerrainMatrix:!0});Oi(b,d,g,i,r);let C=t.aL(_,i,r.paint.get(`fill-extrusion-translate`),r.paint.get(`fill-extrusion-translate-anchor`)),w=r.paint.get(`fill-extrusion-vertical-gradient`),T=p?Qn(e,w,h,C,f,m,i):Zn(e,w,h,C);x.draw(l,l.gl.TRIANGLES,a,o,s,fn.backCCW,T,y,S,r.id,v.layoutVertexBuffer,v.indexBuffer,v.segments,r.paint,e.transform.zoom,b,e.style.map.terrain&&v.centroidVertexBuffer)}}function ji(e,t,n,r,i,a,o,s,c){let l=e.style.projection,u=e.context,d=e.transform,f=u.gl,p=[`#define NUM_ILLUMINATION_SOURCES ${n.paint.get(`hillshade-highlight-color`).values.length}`],m=e.useProgram(`hillshade`,null,!1,p),h=!e.options.moving;for(let p of r){let r=t.getTile(p),g=r.fbo;if(!g)continue;let _=l.getMeshFromTileID(u,p.canonical,s,!0,`raster`),v=e.style.map.terrain?.getTerrainData(p);u.activeTexture.set(f.TEXTURE0),f.bindTexture(f.TEXTURE_2D,g.colorAttachment.get());let y=d.getProjectionData({overscaledTileID:p,aligned:h,applyGlobeMatrix:!c,applyTerrainMatrix:!0});m.draw(u,f.TRIANGLES,a,i[p.overscaledZ],o,fn.backCCW,cr(e,r,n),v,y,n.id,_.vertexBuffer,_.indexBuffer,_.segments)}}let Mi=0;function Ni(e,n,r,i,a,o,s,c,l){let u=e.style.projection,d=e.context,f=e.transform,p=d.gl,m=e.useProgram(`colorRelief`),h=!e.options.moving,g=r.paint.get(`resampling`)===`nearest`?p.NEAREST:p.LINEAR,_=!0,v=0;for(let y of i){let i=n.getTile(y),b=i.dem;if(_){Mi||=p.getParameter(p.MAX_TEXTURE_SIZE);let e=Mi,{elevationTexture:t,colorTexture:n}=r.getColorRampTextures(d,e,b.getUnpackVector());d.activeTexture.set(p.TEXTURE1),t.bind(p.NEAREST,p.CLAMP_TO_EDGE),d.activeTexture.set(p.TEXTURE4),n.bind(p.LINEAR,p.CLAMP_TO_EDGE),_=!1,v=t.size[0]}if(!b?.data)continue;let x=b.stride,S=b.getPixels();if(d.activeTexture.set(p.TEXTURE0),d.pixelStoreUnpackPremultiplyAlpha.set(!1),i.demTexture||=e.getTileTexture(x),i.demTexture){let e=i.demTexture;e.update(S,{premultiply:!1}),e.bind(g,p.CLAMP_TO_EDGE)}else i.demTexture=new t.T(d,S,p.RGBA,{premultiply:!1}),i.demTexture.bind(g,p.CLAMP_TO_EDGE);let C=u.getMeshFromTileID(d,y.canonical,c,!0,`raster`),w=e.style.map.terrain?.getTerrainData(y),T=f.getProjectionData({overscaledTileID:y,aligned:h,applyGlobeMatrix:!l,applyTerrainMatrix:!0});m.draw(d,p.TRIANGLES,o,a[y.overscaledZ],s,fn.backCCW,dr(r,i.dem,v),w,T,r.id,C.vertexBuffer,C.indexBuffer,C.segments)}}let Pi=[new t.P(0,0),new t.P(t.a6,0),new t.P(t.a6,t.a6),new t.P(0,t.a6)];function Fi(e,t,n,r,i,a,o,s,c=!1,l=!1){let u=r[r.length-1].overscaledZ,d=e.context,f=d.gl,p=e.useProgram(`raster`),m=e.transform,h=e.style.projection,g=e.colorModeForRenderPass(),_=!e.options.moving,v=n.paint.get(`raster-opacity`),y=n.paint.get(`resampling`)===`nearest`||n.paint.get(`raster-resampling`)===`nearest`?f.NEAREST:f.LINEAR,b=n.paint.get(`raster-fade-duration`),x=!!e.style.map.terrain;for(let S of r){let r=e.getDepthModeForSublayer(S.overscaledZ-u,v===1?pn.ReadWrite:pn.ReadOnly,f.LESS),C=t.getTile(S);d.activeTexture.set(f.TEXTURE0),C.texture.bind(y,f.CLAMP_TO_EDGE,f.LINEAR_MIPMAP_NEAREST),d.activeTexture.set(f.TEXTURE1);let{parentTile:w,parentScaleBy:T,parentTopLeft:E,fadeValues:D}=Ii(C,t,b,x);C.fadeOpacity=D.tileOpacity,w?(w.fadeOpacity=D.parentTileOpacity,w.texture.bind(y,f.CLAMP_TO_EDGE,f.LINEAR_MIPMAP_NEAREST)):C.texture.bind(y,f.CLAMP_TO_EDGE,f.LINEAR_MIPMAP_NEAREST),C.texture.useMipmap&&d.extTextureFilterAnisotropic&&e.transform.pitch>e.options.anisotropicFilterPitch&&f.texParameterf(f.TEXTURE_2D,d.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,d.extTextureFilterAnisotropicMax);let O=e.style.map.terrain?.getTerrainData(S),k=m.getProjectionData({overscaledTileID:S,aligned:_,applyGlobeMatrix:!l,applyTerrainMatrix:!0}),A=yr(E,T,D.fadeMix,n,s),ee=h.getMeshFromTileID(d,S.canonical,a,o,`raster`);p.draw(d,f.TRIANGLES,r,i?i[S.overscaledZ]:hn.disabled,g,c?fn.frontCCW:fn.backCCW,A,O,k,n.id,ee.vertexBuffer,ee.indexBuffer,ee.segments)}}function Ii(e,n,r,i){let a={parentTile:null,parentScaleBy:1,parentTopLeft:[0,0],fadeValues:{tileOpacity:1,parentTileOpacity:1,fadeMix:{opacity:1,mix:0}}};if(r===0||i)return a;if(e.fadingParentID){let i=n.getLoadedTile(e.fadingParentID);if(!i)return a;let o=2**(i.tileID.overscaledZ-e.tileID.overscaledZ);return{parentTile:i,parentScaleBy:o,parentTopLeft:[e.tileID.canonical.x*o%1,e.tileID.canonical.y*o%1],fadeValues:function(e,n,r){let i=l(),a=(i-n.timeAdded)/r,o=e.fadingDirection===Ne.Incoming,s=t.al((i-e.timeAdded)/r,0,1),c=t.al(1-a,0,1),u=o?s:c;return{tileOpacity:u,parentTileOpacity:o?c:s,fadeMix:{opacity:1,mix:1-u}}}(e,i,r)}}return e.selfFading?{parentTile:null,parentScaleBy:1,parentTopLeft:[0,0],fadeValues:function(e,n){let r=(l()-e.timeAdded)/n,i=t.al(r,0,1);return{tileOpacity:i,fadeMix:{opacity:i,mix:0}}}(e,r)}:a}let Li=new t.bo(1,0,0,1),Ri=new t.bo(0,1,0,1),zi=new t.bo(0,0,1,1),Bi=new t.bo(1,0,1,1),Vi=new t.bo(0,1,1,1);function Hi(e,t,n,r){Wi(e,0,t+n/2,e.transform.width,n,r)}function Ui(e,t,n,r){Wi(e,t-n/2,0,n,e.transform.height,r)}function Wi(e,t,n,r,i,a){let o=e.context,s=o.gl;s.enable(s.SCISSOR_TEST),s.scissor(t*e.pixelRatio,n*e.pixelRatio,r*e.pixelRatio,i*e.pixelRatio),o.clear({color:a}),s.disable(s.SCISSOR_TEST)}function Gi(e,n,r){let i=e.context,a=i.gl,o=e.useProgram(`debug`),s=pn.disabled,c=hn.disabled,l=e.colorModeForRenderPass(),u=`$debug`,d=e.style.map.terrain?.getTerrainData(r);i.activeTexture.set(a.TEXTURE0);let f=n.getTileByID(r.key).latestRawTileData,p=Math.floor((f?.byteLength||0)/1024),m=n.getTile(r).tileSize,h=512/Math.min(m,512)*(r.overscaledZ/e.transform.zoom)*.5,g=r.canonical.toString();r.overscaledZ!==r.canonical.z&&(g+=` => ${r.overscaledZ}`),function(e,t){e.initDebugOverlayCanvas();let n=e.debugOverlayCanvas,r=e.context.gl,i=e.debugOverlayCanvas.getContext(`2d`);i.clearRect(0,0,n.width,n.height),i.shadowColor=`white`,i.shadowBlur=2,i.lineWidth=1.5,i.strokeStyle=`white`,i.textBaseline=`top`,i.font=`bold 36px Open Sans, sans-serif`,i.fillText(t,5,5),i.strokeText(t,5,5),e.debugOverlayTexture.update(n),e.debugOverlayTexture.bind(r.LINEAR,r.CLAMP_TO_EDGE)}(e,`${g} ${p}kB`);let _=e.transform.getProjectionData({overscaledTileID:r,applyGlobeMatrix:!0,applyTerrainMatrix:!0});o.draw(i,a.TRIANGLES,s,c,un.alphaBlended,fn.disabled,ar(t.bo.transparent,h),null,_,u,e.debugBuffer,e.quadTriangleIndexBuffer,e.debugSegments),o.draw(i,a.LINE_STRIP,s,c,l,fn.disabled,ar(t.bo.red),d,_,u,e.debugBuffer,e.tileBorderIndexBuffer,e.debugSegments)}function Ki(e,t,n,r){let{isRenderingGlobe:i}=r,a=e.context,o=a.gl,s=e.transform,c=e.colorModeForRenderPass(),l=e.getDepthModeFor3D(),u=e.useProgram(`terrain`);a.bindFramebuffer.set(null),a.viewport.set([0,0,e.width,e.height]);for(let r of n){let n=t.getTerrainMesh(r.tileID),d=e.renderToTexture.getTexture(r),f=t.getTerrainData(r.tileID);a.activeTexture.set(o.TEXTURE0),o.bindTexture(o.TEXTURE_2D,d.texture);let p=Kn(t.getMeshFrameDelta(s.zoom),s.calculateFogMatrix(r.tileID.toUnwrapped()),e.style.sky,s.pitch,i),m=s.getProjectionData({overscaledTileID:r.tileID,applyTerrainMatrix:!1,applyGlobeMatrix:!0});u.draw(a,o.TRIANGLES,l,hn.disabled,c,fn.backCCW,p,f,m,`terrain`,n.vertexBuffer,n.indexBuffer,n.segments)}}function qi(e,n){if(!n.mesh){let r=new t.aU;r.emplaceBack(-1,-1),r.emplaceBack(1,-1),r.emplaceBack(1,1),r.emplaceBack(-1,1);let i=new t.aW;i.emplaceBack(0,1,2),i.emplaceBack(0,2,3),n.mesh=new Jt(e.createVertexBuffer(r,Yt.members),e.createIndexBuffer(i),t.aV.simpleSegment(0,0,r.length,i.length))}return n.mesh}let Ji={symbol:function(e,n,r,i,a,o){if(e.renderPass!==`translucent`)return;let{isRenderingToTexture:s}=o,c=hn.disabled,l=e.colorModeForRenderPass();(r._unevaluatedLayout.hasValue(`text-variable-anchor`)||r._unevaluatedLayout.hasValue(`text-variable-anchor-offset`))&&function(e,n,r,i,a,o,s,c,l){let u=n.transform,d=n.style.map.terrain,f=a===`map`,p=o===`map`;for(let a of e){let e=i.getTile(a),o=e.getBucket(r);if(!(o?.text)?.segments.get().length)continue;let m=t.aw(o.textSizeData,u.zoom),h=t.aK(e,1,n.transform.zoom),g=rt(f,n.transform,h),_=r.layout.get(`icon-text-fit`)!==`none`&&o.hasIconData();if(m){let n=2**(u.zoom-e.tileID.overscaledZ),r=d?(e,t)=>d.getElevation(a,e,t):null;hi(o,f,p,l,u,g,n,m,_,t.aL(u,e,s,c),a.toUnwrapped(),r)}}}(i,e,r,n,r.layout.get(`text-rotation-alignment`),r.layout.get(`text-pitch-alignment`),r.paint.get(`text-translate`),r.paint.get(`text-translate-anchor`),a),r.paint.get(`icon-opacity`).constantOr(1)!==0&&_i(e,n,r,i,!1,r.paint.get(`icon-translate`),r.paint.get(`icon-translate-anchor`),r.layout.get(`icon-rotation-alignment`),r.layout.get(`icon-pitch-alignment`),r.layout.get(`icon-keep-upright`),c,l,s),r.paint.get(`text-opacity`).constantOr(1)!==0&&_i(e,n,r,i,!0,r.paint.get(`text-translate`),r.paint.get(`text-translate-anchor`),r.layout.get(`text-rotation-alignment`),r.layout.get(`text-pitch-alignment`),r.layout.get(`text-keep-upright`),c,l,s),n.map.showCollisionBoxes&&(Y(e,n,r,i,!0),Y(e,n,r,i,!1))},circle:function(e,n,r,i,a){if(e.renderPass!==`translucent`)return;let{isRenderingToTexture:o}=a,s=r.paint.get(`circle-opacity`),c=r.paint.get(`circle-stroke-width`),l=r.paint.get(`circle-stroke-opacity`),u=!r.layout.get(`circle-sort-key`).isConstant();if(s.constantOr(1)===0&&(c.constantOr(1)===0||l.constantOr(1)===0))return;let d=e.context,f=d.gl,p=e.transform,m=e.getDepthModeForSublayer(0,pn.ReadOnly),h=hn.disabled,g=e.colorModeForRenderPass(),_=[],v=p.getCircleRadiusCorrection();for(let a of i){let i=n.getTile(a),s=i.getBucket(r);if(!s)continue;let c=r.paint.get(`circle-translate`),l=r.paint.get(`circle-translate-anchor`),d=t.aL(p,i,c,l),f=s.programConfigurations.get(r.id),m=e.useProgram(`circle`,f),h=s.layoutVertexBuffer,g=s.indexBuffer,y=e.style.map.terrain?.getTerrainData(a),b={programConfiguration:f,program:m,layoutVertexBuffer:h,indexBuffer:g,uniformValues:nr(e,i,r,d,v),terrainData:y,projectionData:p.getProjectionData({overscaledTileID:a,applyGlobeMatrix:!o,applyTerrainMatrix:!0})};if(u){let e=s.segments.get();for(let n of e)_.push({segments:new t.aV([n]),sortKey:n.sortKey,state:b})}else _.push({segments:s.segments,sortKey:0,state:b})}u&&_.sort(((e,t)=>e.sortKey-t.sortKey));for(let t of _){let{programConfiguration:n,program:i,layoutVertexBuffer:a,indexBuffer:o,uniformValues:s,terrainData:c,projectionData:l}=t.state;i.draw(d,f.TRIANGLES,m,h,g,fn.backCCW,s,c,l,r.id,a,o,t.segments,r.paint,e.transform.zoom,n)}},heatmap:function(e,n,r,i,a){if(r.paint.get(`heatmap-opacity`)===0)return;let o=e.context,{isRenderingToTexture:s,isRenderingGlobe:c}=a;if(e.style.map.terrain){for(let t of i){let i=n.getTile(t);n.hasRenderableParent(t)||(e.renderPass===`offscreen`?yi(e,i,r,t,c):e.renderPass===`translucent`&&bi(e,r,t,s,c))}o.viewport.set([0,0,e.width,e.height])}else e.renderPass===`offscreen`?function(e,n,r,i){let a=e.context,o=a.gl,s=e.transform,c=hn.disabled,l=new un([o.ONE,o.ONE],t.bo.transparent,[!0,!0,!0,!0]);(function(e,n,r){let i=e.gl;e.activeTexture.set(i.TEXTURE1),e.viewport.set([0,0,n.width/4,n.height/4]);let a=r.heatmapFbos.get(t.cd);a?(i.bindTexture(i.TEXTURE_2D,a.colorAttachment.get()),e.bindFramebuffer.set(a.framebuffer)):(a=xi(e,n.width/4,n.height/4),r.heatmapFbos.set(t.cd,a))})(a,e,r),a.clear({color:t.bo.transparent});for(let t of i){if(n.hasRenderableParent(t))continue;let i=n.getTile(t),u=i.getBucket(r);if(!u)continue;let d=u.programConfigurations.get(r.id),f=e.useProgram(`heatmap`,d),p=s.getProjectionData({overscaledTileID:t,applyGlobeMatrix:!0,applyTerrainMatrix:!1}),m=s.getCircleRadiusCorrection();f.draw(a,o.TRIANGLES,pn.disabled,c,l,fn.backCCW,or(i,s.zoom,r.paint.get(`heatmap-intensity`),m),null,p,r.id,u.layoutVertexBuffer,u.indexBuffer,u.segments,r.paint,s.zoom,d)}a.viewport.set([0,0,e.width,e.height])}(e,n,r,i):e.renderPass===`translucent`&&function(e,n){let r=e.context,i=r.gl;r.setColorMode(e.colorModeForRenderPass());let a=n.heatmapFbos.get(t.cd);a&&(r.activeTexture.set(i.TEXTURE0),i.bindTexture(i.TEXTURE_2D,a.colorAttachment.get()),r.activeTexture.set(i.TEXTURE1),Si(r,n).bind(i.LINEAR,i.CLAMP_TO_EDGE),e.useProgram(`heatmapTexture`).draw(r,i.TRIANGLES,pn.disabled,hn.disabled,e.colorModeForRenderPass(),fn.disabled,sr(e,n,0,1),null,null,n.id,e.viewportBuffer,e.quadTriangleIndexBuffer,e.viewportSegments,n.paint,e.transform.zoom))}(e,r)},line:function(e,t,n,r,i){if(e.renderPass!==`translucent`)return;let{isRenderingToTexture:a}=i,o=n.paint.get(`line-opacity`),s=n.paint.get(`line-width`);if(o.constantOr(1)===0||s.constantOr(1)===0)return;let c=e.getDepthModeForSublayer(0,pn.ReadOnly),l=e.colorModeForRenderPass(),u=n.paint.get(`line-dasharray`),d=u.constantOr(1),f=n.paint.get(`line-pattern`),p=f.constantOr(1),m=n.paint.get(`line-gradient`),h=n.getCrossfadeParameters(),g;g=p?`linePattern`:d&&m?`lineGradientSDF`:d?`lineSDF`:m?`lineGradient`:`line`;let _=e.context,v=_.gl,y=e.transform,b=!0;for(let i of r){let r=t.getTile(i);if(p&&!r.patternsLoaded())continue;let o=r.getBucket(n);if(!o)continue;let s=o.programConfigurations.get(n.id),x=e.context.program.get(),S=e.useProgram(g,s),C=b||S.program!==x,w=e.style.map.terrain?.getTerrainData(i),T=f.constantOr(null),E=u?.constantOr(null);if(T&&r.imageAtlas){let e=r.imageAtlas,t=e.patternPositions[T.to.toString()],n=e.patternPositions[T.from.toString()];t&&n&&s.setConstantPatternPositions(t,n)}else if(E){let t=n.layout.get(`line-cap`).constantOr(null)===`round`,r=e.lineAtlas.getDash(E.to,t),i=e.lineAtlas.getDash(E.from,t);s.setConstantDashPositions(r,i)}let D=y.getProjectionData({overscaledTileID:i,applyGlobeMatrix:!a,applyTerrainMatrix:!0}),O=y.getPixelScale(),k;p?(k=mr(e,r,n,O,h),wi(_,v,r,s,h)):d&&m?(k=gr(e,r,n,O,h,o.lineClipsArray.length),Di(e,t,_,v,n,o,i,s,h)):d?(k=hr(e,r,n,O,h),Ti(e,_,v,s,C,h)):m?(k=pr(e,r,n,O,o.lineClipsArray.length),Ei(e,t,_,v,n,o,i)):k=fr(e,r,n,O);let A=e.stencilModeForClipping(i);S.draw(_,v.TRIANGLES,c,A,l,fn.disabled,k,w,D,n.id,o.layoutVertexBuffer,o.indexBuffer,o.segments,n.paint,e.transform.zoom,s,o.layoutVertexBuffer2),b=!1}},fill:function(e,n,r,i,a){let o=r.paint.get(`fill-color`),s=r.paint.get(`fill-opacity`);if(s.constantOr(1)===0)return;let{isRenderingToTexture:c}=a,l=e.colorModeForRenderPass(),u=r.paint.get(`fill-pattern`),d=e.opaquePassEnabledForLayer()&&!u.constantOr(1)&&o.constantOr(t.bo.transparent).a===1&&s.constantOr(0)===1?`opaque`:`translucent`;e.renderPass===d&&ki(e,n,r,i,e.getDepthModeForSublayer(1,e.renderPass===`opaque`?pn.ReadWrite:pn.ReadOnly),l,!1,c),e.renderPass===`translucent`&&r.paint.get(`fill-antialias`)&&ki(e,n,r,i,e.getDepthModeForSublayer(r.getPaintProperty(`fill-outline-color`)?2:0,pn.ReadOnly),l,!0,c)},fillExtrusion:function(e,t,n,r,i){let a=n.paint.get(`fill-extrusion-opacity`);if(a===0)return;let{isRenderingToTexture:o}=i;if(e.renderPass===`translucent`){let i=new pn(e.context.gl.LEQUAL,pn.ReadWrite,e.depthRangeFor3D);if(a!==1||n.paint.get(`fill-extrusion-pattern`).constantOr(1))Ai(e,t,n,r,i,hn.disabled,un.disabled,o),Ai(e,t,n,r,i,e.stencilModeFor3D(),e.colorModeForRenderPass(),o);else{let a=e.colorModeForRenderPass();Ai(e,t,n,r,i,hn.disabled,a,o)}}},hillshade:function(e,n,r,i,a){if(e.renderPass!==`offscreen`&&e.renderPass!==`translucent`)return;let{isRenderingToTexture:o}=a,s=e.context,c=e.style.projection.useSubdivision,l=e.getDepthModeForSublayer(0,pn.ReadOnly),u=e.colorModeForRenderPass();if(e.renderPass===`offscreen`)(function(e,n,r,i,a,o,s){let c=e.context,l=c.gl,u=i.paint.get(`resampling`)===`nearest`?l.NEAREST:l.LINEAR;for(let d of r){let r=n.getTile(d),f=r.dem;if(!f?.data||!r.needsHillshadePrepare)continue;let p=f.dim,m=f.stride,h=f.getPixels();if(c.activeTexture.set(l.TEXTURE1),c.pixelStoreUnpackPremultiplyAlpha.set(!1),r.demTexture||=e.getTileTexture(m),r.demTexture){let e=r.demTexture;e.update(h,{premultiply:!1}),e.bind(l.NEAREST,l.CLAMP_TO_EDGE)}else r.demTexture=new t.T(c,h,l.RGBA,{premultiply:!1}),r.demTexture.bind(l.NEAREST,l.CLAMP_TO_EDGE);c.activeTexture.set(l.TEXTURE0);let g=r.fbo;if(!g){let e=new t.T(c,{width:p,height:p,data:null},l.RGBA);e.bind(u,l.CLAMP_TO_EDGE),g=r.fbo=c.createFramebuffer(p,p,!0,!1),g.colorAttachment.set(e.texture)}c.bindFramebuffer.set(g.framebuffer),c.viewport.set([0,0,p,p]),e.useProgram(`hillshadePrepare`).draw(c,l.TRIANGLES,a,o,s,fn.disabled,lr(r.tileID,f),null,null,i.id,e.rasterBoundsBuffer,e.quadTriangleIndexBuffer,e.rasterBoundsSegments),r.needsHillshadePrepare=!1}})(e,n,i,r,l,hn.disabled,u),s.viewport.set([0,0,e.width,e.height]);else if(e.renderPass===`translucent`)if(c){let[t,a,s]=e.stencilConfigForOverlapTwoPass(i);ji(e,n,r,s,t,l,u,!1,o),ji(e,n,r,s,a,l,u,!0,o)}else{let[t,a]=e.getStencilConfigForOverlapAndUpdateStencilID(i);ji(e,n,r,a,t,l,u,!1,o)}},colorRelief:function(e,t,n,r,i){if(e.renderPass!==`translucent`||!r.length)return;let{isRenderingToTexture:a}=i,o=e.style.projection.useSubdivision,s=e.getDepthModeForSublayer(0,pn.ReadOnly),c=e.colorModeForRenderPass();if(o){let[i,o,l]=e.stencilConfigForOverlapTwoPass(r);Ni(e,t,n,l,i,s,c,!1,a),Ni(e,t,n,l,o,s,c,!0,a)}else{let[i,o]=e.getStencilConfigForOverlapAndUpdateStencilID(r);Ni(e,t,n,o,i,s,c,!1,a)}},raster:function(e,t,n,r,i){if(e.renderPass!==`translucent`||n.paint.get(`raster-opacity`)===0||!r.length)return;let{isRenderingToTexture:a}=i,o=t.getSource(),s=e.style.projection.useSubdivision;if(o instanceof Ce)Fi(e,t,n,r,null,!1,!1,o.tileCoords,o.flippedWindingOrder,a);else if(s){let[i,o,s]=e.stencilConfigForOverlapTwoPass(r);Fi(e,t,n,s,i,!1,!0,Pi,!1,a),Fi(e,t,n,s,o,!0,!0,Pi,!1,a)}else{let[i,o]=e.getStencilConfigForOverlapAndUpdateStencilID(r);Fi(e,t,n,o,i,!1,!0,Pi,!1,a)}},background:function(e,t,n,r,i){let a=n.paint.get(`background-color`),o=n.paint.get(`background-opacity`);if(o===0)return;let{isRenderingToTexture:s}=i,c=e.context,l=c.gl,u=e.style.projection,d=e.transform,f=d.tileSize,p=n.paint.get(`background-pattern`);if(e.isPatternMissing(p))return;let m=!p&&a.a===1&&o===1&&e.opaquePassEnabledForLayer()?`opaque`:`translucent`;if(e.renderPass!==m)return;let h=hn.disabled,g=e.getDepthModeForSublayer(0,m===`opaque`?pn.ReadWrite:pn.ReadOnly),_=e.colorModeForRenderPass(),v=e.useProgram(p?`backgroundPattern`:`background`),y=r||We(d,{tileSize:f,terrain:e.style.map.terrain});p&&(c.activeTexture.set(l.TEXTURE0),e.imageManager.bind(e.context));let b=n.getCrossfadeParameters();for(let t of y){let r=d.getProjectionData({overscaledTileID:t,applyGlobeMatrix:!s,applyTerrainMatrix:!0}),i=p?Tr(o,e,p,{tileID:t,tileSize:f},b):wr(o,a),m=e.style.map.terrain?.getTerrainData(t),y=u.getMeshFromTileID(c,t.canonical,!1,!0,`raster`);v.draw(c,l.TRIANGLES,g,h,_,fn.backCCW,i,m,r,n.id,y.vertexBuffer,y.indexBuffer,y.segments)}},sky:function(e,t){let n=e.context,r=n.gl,i=((e,t,n)=>{let r=Math.cos(t.rollInRadians),i=Math.sin(t.rollInRadians),a=ze(t),o=t.getProjectionData({overscaledTileID:null,applyGlobeMatrix:!0,applyTerrainMatrix:!0}).projectionTransition;return{u_sky_color:e.properties.get(`sky-color`),u_horizon_color:e.properties.get(`horizon-color`),u_horizon:[(t.width/2-a*i)*n,(t.height/2+a*r)*n],u_horizon_normal:[-i,r],u_sky_horizon_blend:e.properties.get(`sky-horizon-blend`)*t.height/2*n,u_sky_blend:o}})(t,e.style.map.transform,e.pixelRatio),a=new pn(r.LEQUAL,pn.ReadWrite,[0,1]),o=hn.disabled,s=e.colorModeForRenderPass(),c=e.useProgram(`sky`),l=qi(n,t);c.draw(n,r.TRIANGLES,a,o,s,fn.disabled,i,null,void 0,`sky`,l.vertexBuffer,l.indexBuffer,l.segments)},atmosphere:function(e,n,r){let i=e.context,a=i.gl,o=e.useProgram(`atmosphere`),s=new pn(a.LEQUAL,pn.ReadOnly,[0,1]),c=e.transform,l=function(e,n){let r=e.properties.get(`position`),i=[-r.x,-r.y,-r.z],a=t.ap(new Float64Array(16));return e.properties.get(`anchor`)===`map`&&(t.be(a,a,n.rollInRadians),t.bf(a,a,-n.pitchInRadians),t.be(a,a,n.bearingInRadians),t.bf(a,a,n.center.lat*Math.PI/180),t.bI(a,a,-n.center.lng*Math.PI/180)),t.cg(i,i,a),i}(r,e.transform),u=c.getProjectionData({overscaledTileID:null,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),d=n.properties.get(`atmosphere-blend`)*u.projectionTransition;if(d===0)return;let f=Tn(c.worldSize,c.center.lat),p=c.inverseProjectionMatrix,m=new Float64Array(4);m[3]=1,t.aE(m,m,c.modelViewProjectionMatrix),m[0]/=m[3],m[1]/=m[3],m[2]/=m[3],m[3]=1,t.aE(m,m,p),m[0]/=m[3],m[1]/=m[3],m[2]/=m[3],m[3]=1;let h=((e,t,n,r,i)=>({u_sun_pos:e,u_atmosphere_blend:t,u_globe_position:n,u_globe_radius:r,u_inv_proj_matrix:i}))(l,d,[m[0],m[1],m[2]],f,p),g=qi(i,n);o.draw(i,a.TRIANGLES,s,hn.disabled,un.alphaBlended,fn.disabled,h,null,null,`atmosphere`,g.vertexBuffer,g.indexBuffer,g.segments)},custom:function(e,t,n,r){let{isRenderingGlobe:i}=r,a=e.context,o=n.implementation,s=e.style.projection,c=e.transform,l=c.getProjectionDataForCustomLayer(i),u={farZ:c.farZ,nearZ:c.nearZ,fov:c.fov*Math.PI/180,modelViewProjectionMatrix:c.modelViewProjectionMatrix,projectionMatrix:c.projectionMatrix,shaderData:{variantName:s.shaderVariantName,vertexShaderPrelude:`const float PI = 3.141592653589793;\nuniform mat4 u_projection_matrix;\n${s.shaderPreludeCode.vertexSource}`,define:s.shaderDefine},defaultProjectionData:l},d=o.renderingMode?o.renderingMode:`2d`;if(e.renderPass===`offscreen`){let t=o.prerender;t&&(e.setCustomLayerDefaults(),a.setColorMode(e.colorModeForRenderPass()),t.call(o,a.gl,u),a.setDirty(),e.setBaseState())}else if(e.renderPass===`translucent`){e.setCustomLayerDefaults(),a.setColorMode(e.colorModeForRenderPass()),a.setStencilMode(hn.disabled);let t=d===`3d`?e.getDepthModeFor3D():e.getDepthModeForSublayer(0,pn.ReadOnly);a.setDepthMode(t),o.render(a.gl,u),a.setDirty(),e.setBaseState(),a.bindFramebuffer.set(null)}},debug:function(e,t,n){for(let r of n)Gi(e,t,r)},debugPadding:function(e){let t=e.transform.padding;Hi(e,e.transform.height-(t.top||0),3,Li),Hi(e,t.bottom||0,3,Ri),Ui(e,t.left||0,3,zi),Ui(e,e.transform.width-(t.right||0),3,Bi);let n=e.transform.centerPoint;(function(e,t,n,r){Wi(e,t-1,n-10,2,20,r),Wi(e,t-10,n-1,20,2,r)})(e,n.x,e.transform.height-n.y,Vi)},terrainDepth:function(e,n){let r=e.context,i=r.gl,a=e.transform,o=un.unblended,s=new pn(i.LEQUAL,pn.ReadWrite,[0,1]),c=n.tileManager.getRenderableTiles(),l=e.useProgram(`terrainDepth`);r.bindFramebuffer.set(n.getFramebuffer(`depth`).framebuffer),r.viewport.set([0,0,e.width/devicePixelRatio,e.height/devicePixelRatio]),r.clear({color:t.bo.transparent,depth:1});for(let e of c){let t=n.getTerrainMesh(e.tileID),c=n.getTerrainData(e.tileID),u=a.getProjectionData({overscaledTileID:e.tileID,applyTerrainMatrix:!1,applyGlobeMatrix:!0}),d={u_ele_delta:n.getMeshFrameDelta(a.zoom)};l.draw(r,i.TRIANGLES,s,hn.disabled,o,fn.backCCW,d,c,u,`terrain`,t.vertexBuffer,t.indexBuffer,t.segments)}r.bindFramebuffer.set(null),r.viewport.set([0,0,e.width,e.height])},terrainCoords:function(e,n){let r=e.context,i=r.gl,a=e.transform,o=un.unblended,s=new pn(i.LEQUAL,pn.ReadWrite,[0,1]),c=n.getCoordsTexture(),l=n.tileManager.getRenderableTiles(),u=e.useProgram(`terrainCoords`);r.bindFramebuffer.set(n.getFramebuffer(`coords`).framebuffer),r.viewport.set([0,0,e.width/devicePixelRatio,e.height/devicePixelRatio]),r.clear({color:t.bo.transparent,depth:1}),n.coordsIndex=[];for(let e of l){let t=n.getTerrainMesh(e.tileID),l=n.getTerrainData(e.tileID);r.activeTexture.set(i.TEXTURE0),i.bindTexture(i.TEXTURE_2D,c.texture);let d={u_terrain_coords_id:(255-n.coordsIndex.length)/255,u_texture:0,u_ele_delta:n.getMeshFrameDelta(a.zoom)},f=a.getProjectionData({overscaledTileID:e.tileID,applyTerrainMatrix:!1,applyGlobeMatrix:!0});u.draw(r,i.TRIANGLES,s,hn.disabled,o,fn.backCCW,d,l,f,`terrain`,t.vertexBuffer,t.indexBuffer,t.segments),n.coordsIndex.push(e.tileID.key)}r.bindFramebuffer.set(null),r.viewport.set([0,0,e.width,e.height])}};class Yi{constructor(e,n){this.drawFunctions=Ji,this.context=new ui(e),this.transform=n,this._tileTextures={},this.terrainFacilitator={depthDirty:!0,coordsDirty:!1,matrix:t.ap(new Float64Array(16)),renderTime:0},this.setup(),this.numSublayers=Qe.maxOverzooming+Qe.maxUnderzooming+1,this.depthEpsilon=1/2**16,this.crossTileSymbolIndex=new Wt}resize(e,t,n){if(this.width=Math.floor(e*n),this.height=Math.floor(t*n),this.pixelRatio=n,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(let e of this.style._order)this.style._layers[e].resize()}setup(){let e=this.context,n=new t.aU;n.emplaceBack(0,0),n.emplaceBack(t.a6,0),n.emplaceBack(0,t.a6),n.emplaceBack(t.a6,t.a6),this.tileExtentBuffer=e.createVertexBuffer(n,Yt.members),this.tileExtentSegments=t.aV.simpleSegment(0,0,4,2);let r=new t.aU;r.emplaceBack(0,0),r.emplaceBack(t.a6,0),r.emplaceBack(0,t.a6),r.emplaceBack(t.a6,t.a6),this.debugBuffer=e.createVertexBuffer(r,Yt.members),this.debugSegments=t.aV.simpleSegment(0,0,4,5);let i=new t.ch;i.emplaceBack(0,0,0,0),i.emplaceBack(t.a6,0,t.a6,0),i.emplaceBack(0,t.a6,0,t.a6),i.emplaceBack(t.a6,t.a6,t.a6,t.a6),this.rasterBoundsBuffer=e.createVertexBuffer(i,Wn.members),this.rasterBoundsSegments=t.aV.simpleSegment(0,0,4,2);let a=new t.aU;a.emplaceBack(0,0),a.emplaceBack(t.a6,0),a.emplaceBack(0,t.a6),a.emplaceBack(t.a6,t.a6),this.rasterBoundsBufferPosOnly=e.createVertexBuffer(a,Yt.members),this.rasterBoundsSegmentsPosOnly=t.aV.simpleSegment(0,0,4,5);let o=new t.aU;o.emplaceBack(0,0),o.emplaceBack(1,0),o.emplaceBack(0,1),o.emplaceBack(1,1),this.viewportBuffer=e.createVertexBuffer(o,Yt.members),this.viewportSegments=t.aV.simpleSegment(0,0,4,2);let s=new t.ci;s.emplaceBack(0),s.emplaceBack(1),s.emplaceBack(3),s.emplaceBack(2),s.emplaceBack(0),this.tileBorderIndexBuffer=e.createIndexBuffer(s);let c=new t.aW;c.emplaceBack(1,0,2),c.emplaceBack(1,2,3),this.quadTriangleIndexBuffer=e.createIndexBuffer(c);let l=this.context.gl;this.stencilClearMode=new hn({func:l.ALWAYS,mask:0},0,255,l.ZERO,l.ZERO,l.ZERO),this.tileExtentMesh=new Jt(this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments)}clearStencil(){let e=this.context,n=e.gl;this.nextStencilID=1,this.currentStencilSource=void 0;let r=t.O();t.c7(r,0,this.width,this.height,0,0,1),t.S(r,r,[n.drawingBufferWidth,n.drawingBufferHeight,0]);let i={mainMatrix:r,tileMercatorCoords:[0,0,1,1],clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:r};this.useProgram(`clippingMask`,null,!0).draw(e,n.TRIANGLES,pn.disabled,this.stencilClearMode,un.disabled,fn.disabled,null,null,i,`$clipping`,this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}_renderTileClippingMasks(e,t,n){if(this.currentStencilSource===e.source||!e.isTileClipped()||!t?.length)return;this.currentStencilSource=e.source,this.nextStencilID+t.length>256&&this.clearStencil();let r=this.context;r.setColorMode(un.disabled),r.setDepthMode(pn.disabled);let i={};for(let e of t)i[e.key]=this.nextStencilID++;this._renderTileMasks(i,t,n,!0),this._renderTileMasks(i,t,n,!1),this._tileClippingMaskIDs=i}_renderTileMasks(e,t,n,r){let i=this.context,a=i.gl,o=this.style.projection,s=this.transform,c=this.useProgram(`clippingMask`);for(let l of t){let t=e[l.key],u=this.style.map.terrain?.getTerrainData(l),d=o.getMeshFromTileID(this.context,l.canonical,r,!0,`stencil`),f=s.getProjectionData({overscaledTileID:l,applyGlobeMatrix:!n,applyTerrainMatrix:!0});c.draw(i,a.TRIANGLES,pn.disabled,new hn({func:a.ALWAYS,mask:0},t,255,a.KEEP,a.KEEP,a.REPLACE),un.disabled,n?fn.disabled:fn.backCCW,null,u,f,`$clipping`,d.vertexBuffer,d.indexBuffer,d.segments)}}_renderTilesDepthBuffer(){let e=this.context,t=e.gl,n=this.style.projection,r=this.transform,i=this.useProgram(`depth`),a=this.getDepthModeFor3D(),o=We(r,{tileSize:r.tileSize});for(let s of o){let o=this.style.map.terrain?.getTerrainData(s),c=n.getMeshFromTileID(this.context,s.canonical,!0,!0,`raster`),l=r.getProjectionData({overscaledTileID:s,applyGlobeMatrix:!0,applyTerrainMatrix:!0});i.draw(e,t.TRIANGLES,a,hn.disabled,un.disabled,fn.backCCW,null,o,l,`$clipping`,c.vertexBuffer,c.indexBuffer,c.segments)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();let e=this.nextStencilID++,t=this.context.gl;return new hn({func:t.NOTEQUAL,mask:255},e,255,t.KEEP,t.KEEP,t.REPLACE)}stencilModeForClipping(e){let t=this.context.gl;return new hn({func:t.EQUAL,mask:255},this._tileClippingMaskIDs[e.key],0,t.KEEP,t.KEEP,t.REPLACE)}getStencilConfigForOverlapAndUpdateStencilID(e){let t=this.context.gl,n=e.sort(((e,t)=>t.overscaledZ-e.overscaledZ)),r=n[n.length-1].overscaledZ,i=n[0].overscaledZ-r+1;if(i>1){this.currentStencilSource=void 0,this.nextStencilID+i>256&&this.clearStencil();let e={};for(let n=0;n<i;n++)e[n+r]=new hn({func:t.GEQUAL,mask:255},n+this.nextStencilID,255,t.KEEP,t.KEEP,t.REPLACE);return this.nextStencilID+=i,[e,n]}return[{[r]:hn.disabled},n]}stencilConfigForOverlapTwoPass(e){let t=this.context.gl,n=e.sort(((e,t)=>t.overscaledZ-e.overscaledZ)),r=n[n.length-1].overscaledZ,i=n[0].overscaledZ-r+1;if(this.clearStencil(),i>1){let e={},a={};for(let n=0;n<i;n++)e[n+r]=new hn({func:t.GREATER,mask:255},i+1+n,255,t.KEEP,t.KEEP,t.REPLACE),a[n+r]=new hn({func:t.GREATER,mask:255},1+n,255,t.KEEP,t.KEEP,t.REPLACE);return this.nextStencilID=2*i+1,[e,a,n]}return this.nextStencilID=3,[{[r]:new hn({func:t.GREATER,mask:255},2,255,t.KEEP,t.KEEP,t.REPLACE)},{[r]:new hn({func:t.GREATER,mask:255},1,255,t.KEEP,t.KEEP,t.REPLACE)},n]}colorModeForRenderPass(){let e=this.context.gl;if(this._showOverdrawInspector){let n=1/8;return new un([e.CONSTANT_COLOR,e.ONE],new t.bo(n,n,n,0),[!0,!0,!0,!0])}return this.renderPass===`opaque`?un.unblended:un.alphaBlended}getDepthModeForSublayer(e,t,n){if(!this.opaquePassEnabledForLayer())return pn.disabled;let r=1-((1+this.currentLayer)*this.numSublayers+e)*this.depthEpsilon;return new pn(n||this.context.gl.LEQUAL,t,[r,r])}getDepthModeFor3D(){return new pn(this.context.gl.LEQUAL,pn.ReadWrite,this.depthRangeFor3D)}opaquePassEnabledForLayer(){return this.currentLayer<this.opaquePassCutoff}render(e,n){var r;this.style=e,this.options=n,this.lineAtlas=e.lineAtlas,this.imageManager=e.imageManager,this.glyphManager=e.glyphManager,this.symbolFadeChange=e.placement.symbolFadeChange(l()),this.imageManager.beginFrame();let i=this.style._order,a=this.style.tileManagers,o={},s={},c={},u={isRenderingToTexture:!1,isRenderingGlobe:e.projection?.transitionState>0};for(let e in a){let t=a[e];t.used&&t.prepare(this.context),o[e]=t.getVisibleCoordinates(!1),s[e]=o[e].slice().reverse(),c[e]=t.getVisibleCoordinates(!0).reverse()}this.opaquePassCutoff=1/0;for(let e=0;e<i.length;e++)if(this.style._layers[i[e]].is3D()){this.opaquePassCutoff=e;break}this.maybeDrawDepth(!1),this.renderToTexture&&(this.renderToTexture.prepareForRender(this.style,this.transform.zoom),this.opaquePassCutoff=0),this.renderPass=`offscreen`;for(let e of i){let t=this.style._layers[e];if(!t.hasOffscreenPass()||t.isHidden(this.transform.zoom))continue;let n=s[t.source];(t.type===`custom`||n.length)&&this.renderLayer(this,a[t.source],t,n,u)}if((r=this.style.projection)==null||r.updateGPUdependent({context:this.context,useProgram:e=>this.useProgram(e)}),this.context.viewport.set([0,0,this.width,this.height]),this.context.bindFramebuffer.set(null),this.context.clear({color:n.showOverdrawInspector?t.bo.black:t.bo.transparent,depth:1}),this.clearStencil(),this.style.sky&&this.drawFunctions.sky(this,this.style.sky),this._showOverdrawInspector=n.showOverdrawInspector,this.depthRangeFor3D=[0,1-(e._order.length+2)*this.numSublayers*this.depthEpsilon],!this.renderToTexture)for(this.renderPass=`opaque`,this.currentLayer=i.length-1;this.currentLayer>=0;this.currentLayer--){let e=this.style._layers[i[this.currentLayer]],t=a[e.source],n=o[e.source];this._renderTileClippingMasks(e,n,!1),this.renderLayer(this,t,e,n,u)}this.renderPass=`translucent`;let d=!1;for(this.currentLayer=0;this.currentLayer<i.length;this.currentLayer++){let e=this.style._layers[i[this.currentLayer]],t=a[e.source];if(this.renderToTexture?.renderLayer(e,u))continue;this.opaquePassEnabledForLayer()||d||(d=!0,u.isRenderingGlobe&&!this.style.map.terrain&&this._renderTilesDepthBuffer());let n=(e.type===`symbol`?c:s)[e.source];this._renderTileClippingMasks(e,o[e.source],!!this.renderToTexture),this.renderLayer(this,t,e,n,u)}if(u.isRenderingGlobe&&this.drawFunctions.atmosphere(this,this.style.sky,this.style.light),this.options.showTileBoundaries){let e=function(e,t){let n=null,r=Object.values(e._layers).flatMap((n=>n.source&&!n.isHidden(t)?[e.tileManagers[n.source]]:[])),i=r.filter((e=>e.getSource().type===`vector`)),a=r.filter((e=>e.getSource().type!==`vector`)),o=e=>{(!n||n.getSource().maxzoom<e.getSource().maxzoom)&&(n=e)};for(let e of i)o(e);if(!n)for(let e of a)o(e);return n}(this.style,this.transform.zoom);e&&this.drawFunctions.debug(this,e,e.getVisibleCoordinates())}this.options.showPadding&&this.drawFunctions.debugPadding(this),this.context.setDefault()}maybeDrawDepth(e){if(!this.style?.map?.terrain)return;let n=this.terrainFacilitator.matrix,r=this.transform.modelViewProjectionMatrix,i=this.terrainFacilitator.depthDirty;i||=e?!t.cj(n,r):!t.ck(n,r),i||=this.style.map.terrain.tileManager.anyTilesAfterTime(this.terrainFacilitator.renderTime),i&&(t.cl(n,r),this.terrainFacilitator.renderTime=Date.now(),this.terrainFacilitator.depthDirty=!1,this.terrainFacilitator.coordsDirty=!0,this.drawFunctions.terrainDepth(this,this.style.map.terrain))}maybeDrawCoords(){var e;(e=this.style?.map)!=null&&e.terrain&&this.terrainFacilitator.coordsDirty&&(this.terrainFacilitator.coordsDirty=!1,this.drawFunctions.terrainCoords(this,this.style.map.terrain))}renderLayer(e,n,r,i,a){if(r.isHidden(this.transform.zoom)||r.type!==`background`&&r.type!==`custom`&&!(i||[]).length)return;this.id=r.id;let o=this.drawFunctions;t.aQ(r)?o.symbol(e,n,r,i,this.style.placement.variableOffsets,a):t.cm(r)?o.circle(e,n,r,i,a):t.cn(r)?o.heatmap(e,n,r,i,a):t.co(r)?o.line(e,n,r,i,a):t.cp(r)?o.fill(e,n,r,i,a):t.cq(r)?o.fillExtrusion(e,n,r,i,a):t.cr(r)?o.hillshade(e,n,r,i,a):t.cs(r)?o.colorRelief(e,n,r,i,a):t.bU(r)?o.raster(e,n,r,i,a):t.ct(r)?o.background(e,n,r,i,a):t.cu(r)&&o.custom(e,n,r,a)}saveTileTexture(e){let t=this._tileTextures[e.size[0]];t?t.length<Yi.MAX_TEXTURE_POOL_SIZE_PER_BUCKET?t.push(e):e.destroy():this._tileTextures[e.size[0]]=[e]}getTileTexture(e){let t=this._tileTextures[e];return t&&t.length>0?t.pop():null}isPatternMissing(e){if(!e)return!1;if(!e.from||!e.to)return!0;let t=this.imageManager.getPattern(e.from.toString()),n=this.imageManager.getPattern(e.to.toString());return!t||!n}useProgram(e,t,n=!1,r=[]){var i;this.cache||={};let a=!!this.style.map.terrain,o=this.style.projection,s=n?Kt.projectionMercator:o.shaderPreludeCode,c=n?Xt:o.shaderDefine,l=e+(t?t.cacheKey:``)+`/${n?Zt:o.shaderVariantName}`+(this._showOverdrawInspector?`/overdraw`:``)+(a?`/terrain`:``)+(r?`/${r.join(`/`)}`:``);return(i=this.cache)[l]||(i[l]=new Yn(this.context,Kt[e],t,Dr[e],this._showOverdrawInspector,a,s,c,r)),this.cache[l]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault()}setBaseState(){let e=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(e.FUNC_ADD)}initDebugOverlayCanvas(){this.debugOverlayCanvas??(this.debugOverlayCanvas=document.createElement(`canvas`),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new t.T(this.context,this.debugOverlayCanvas,this.context.gl.RGBA))}destroy(){var e,t;if(this._tileTextures){for(let e in this._tileTextures){let t=this._tileTextures[e];if(t)for(let e of t)e.destroy()}this._tileTextures={}}if(this.tileExtentBuffer&&this.tileExtentBuffer.destroy(),this.debugBuffer&&this.debugBuffer.destroy(),this.rasterBoundsBuffer&&this.rasterBoundsBuffer.destroy(),this.rasterBoundsBufferPosOnly&&this.rasterBoundsBufferPosOnly.destroy(),this.viewportBuffer&&this.viewportBuffer.destroy(),this.tileBorderIndexBuffer&&this.tileBorderIndexBuffer.destroy(),this.quadTriangleIndexBuffer&&this.quadTriangleIndexBuffer.destroy(),this.tileExtentMesh&&((e=this.tileExtentMesh.vertexBuffer)==null||e.destroy()),this.tileExtentMesh&&((t=this.tileExtentMesh.indexBuffer)==null||t.destroy()),this.debugOverlayTexture&&this.debugOverlayTexture.destroy(),this.cache){for(let e in this.cache){let t=this.cache[e];t!=null&&t.program&&this.context.gl.deleteProgram(t.program)}this.cache={}}this.context&&this.context.setDefault()}overLimit(){let{drawingBufferWidth:e,drawingBufferHeight:t}=this.context.gl;return this.width!==e||this.height!==t}}function Xi(e,t){let n,r=!1,i=null,a=()=>{i=null,r&&=(e(...n),i=setTimeout(a,t),!1)};return(...e)=>(r=!0,n=e,i||a(),i)}Yi.MAX_TEXTURE_POOL_SIZE_PER_BUCKET=50;class Zi{constructor(e){this._getCurrentHash=()=>{let e=window.location.hash.replace(`#`,``);if(this._hashName){let t,n=e.split(`&`).map((e=>e.split(`=`)));for(let e of n)e[0]===this._hashName&&(t=e);return(t&&t[1]||``).split(`/`)}return e.split(`/`)},this._onHashChange=()=>{let e=this._getCurrentHash();if(!this._isValidHash(e))return!1;let t=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(e[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+e[2],+e[1]],zoom:+e[0],bearing:t,pitch:+(e[4]||0)}),!0},this._updateHashUnthrottled=()=>{let e=window.location.href.replace(/(#.*)?$/,this.getHashString());window.history.replaceState(window.history.state,null,e)},this._removeHash=()=>{let e=this._getCurrentHash();if(e.length===0)return;let t=e.join(`/`),n=t;n.split(`&`).length>0&&(n=n.split(`&`)[0]),this._hashName&&(n=`${this._hashName}=${t}`);let r=window.location.hash.replace(n,``);r.startsWith(`#&`)?r=r.slice(0,1)+r.slice(2):r===`#`&&(r=``);let i=window.location.href.replace(/(#.+)?$/,r);i=i.replace(`&&`,`&`),window.history.replaceState(window.history.state,null,i)},this._updateHash=Xi(this._updateHashUnthrottled,300),this._hashName=e&&encodeURIComponent(e)}addTo(e){return this._map=e,addEventListener(`hashchange`,this._onHashChange,!1),this._map.on(`moveend`,this._updateHash),this}remove(){return removeEventListener(`hashchange`,this._onHashChange,!1),this._map.off(`moveend`,this._updateHash),clearTimeout(this._updateHash()),this._removeHash(),delete this._map,this}getHashString(e){let t=this._map.getCenter(),n=Math.round(100*this._map.getZoom())/100,r=10**Math.ceil((n*Math.LN2+Math.log(512/360/.5))/Math.LN10),i=Math.round(t.lng*r)/r,a=Math.round(t.lat*r)/r,o=this._map.getBearing(),s=this._map.getPitch(),c=``;if(c+=e?`/${i}/${a}/${n}`:`${n}/${a}/${i}`,(o||s)&&(c+=`/`+Math.round(10*o)/10),s&&(c+=`/${Math.round(s)}`),this._hashName){let e=this._hashName,t=!1,n=window.location.hash.slice(1).split(`&`).map((n=>{let r=n.split(`=`)[0];return r===e?(t=!0,`${r}=${c}`):n})).filter((e=>e));return t||n.push(`${e}=${c}`),`#${n.join(`&`)}`}return`#${c}`}_isValidHash(e){if(e.length<3||e.some(isNaN))return!1;try{new t.W(+e[2],+e[1])}catch{return!1}let n=+e[0],r=+(e[3]||0),i=+(e[4]||0);return n>=this._map.getMinZoom()&&n<=this._map.getMaxZoom()&&r>=-180&&r<=180&&i>=this._map.getMinPitch()&&i<=this._map.getMaxPitch()}}let Qi={linearity:.3,easing:t.cv(0,0,.3,1)},$i=t.e({deceleration:2500,maxSpeed:1400},Qi),ea=t.e({deceleration:20,maxSpeed:1400},Qi),ta=t.e({deceleration:1e3,maxSpeed:360},Qi),X=t.e({deceleration:1e3,maxSpeed:90},Qi),na=t.e({deceleration:1e3,maxSpeed:360},Qi);class ra{constructor(e){this._map=e,this.clear()}clear(){this._inertiaBuffer=[]}record(e){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:l(),settings:e})}_drainInertiaBuffer(){let e=this._inertiaBuffer,t=l();for(;e.length>0&&t-e[0].time>160;)e.shift()}_onMoveEnd(e){if(this._drainInertiaBuffer(),this._inertiaBuffer.length<2)return;let n={zoom:0,bearing:0,pitch:0,roll:0,pan:new t.P(0,0),pinchAround:void 0,around:void 0};for(let{settings:e}of this._inertiaBuffer)n.zoom+=e.zoomDelta||0,n.bearing+=e.bearingDelta||0,n.pitch+=e.pitchDelta||0,n.roll+=e.rollDelta||0,e.panDelta&&n.pan._add(e.panDelta),e.around&&(n.around=e.around),e.pinchAround&&(n.pinchAround=e.pinchAround);let r=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,i={};if(n.pan.mag()){let a=aa(n.pan.mag(),r,t.e({},$i,e||{})),o=n.pan.mult(a.amount/n.pan.mag()),s=this._map.cameraHelper.handlePanInertia(o,this._map.transform);i.center=s.easingCenter,i.offset=s.easingOffset,ia(i,a)}if(n.zoom){let e=aa(n.zoom,r,ea);i.zoom=t.cw(this._map.transform.zoom+e.amount,this._map.getZoomSnap(),e.amount),ia(i,e)}if(n.bearing){let e=aa(n.bearing,r,ta);i.bearing=this._map.transform.bearing+t.al(e.amount,-179,179),ia(i,e)}if(n.pitch){let e=aa(n.pitch,r,X);i.pitch=this._map.transform.pitch+e.amount,ia(i,e)}if(n.roll){let e=aa(n.roll,r,na);i.roll=this._map.transform.roll+t.al(e.amount,-179,179),ia(i,e)}if(i.zoom||i.bearing){let e=n.pinchAround===void 0?n.around:n.pinchAround;i.around=e?this._map.unproject(e):this._map.getCenter()}return this.clear(),t.e(i,{noMoveStart:!0})}}function ia(e,t){(!e.duration||e.duration<t.duration)&&(e.duration=t.duration,e.easing=t.easing)}function aa(e,n,r){let{maxSpeed:i,linearity:a,deceleration:o}=r,s=t.al(e*a/(n/1e3),-i,i),c=Math.abs(s)/(o*a);return{easing:r.easing,duration:1e3*c,amount:c/2*s}}class oa extends t.n{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(e,n,r,i={}){r=r instanceof MouseEvent?r:new MouseEvent(e,r);let a=d.mousePos(n.getCanvas(),r),o=n.unproject(a);super(e,t.e({point:a,lngLat:o,originalEvent:r},i)),this._defaultPrevented=!1,this.target=n}}class sa extends t.n{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(e,n,r){let i=e===`touchend`?r.changedTouches:r.touches,a=d.touchPos(n.getCanvasContainer(),i),o=a.map((e=>n.unproject(e))),s=a.reduce(((e,t,n,r)=>e.add(t.div(r.length))),new t.P(0,0));super(e,{points:a,point:s,lngLats:o,lngLat:n.unproject(s),originalEvent:r}),this._defaultPrevented=!1}}class ca extends t.n{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(e,t,n){super(e,{originalEvent:n}),this._defaultPrevented=!1}}class la{constructor(e,t){this._map=e,this._clickTolerance=t.clickTolerance}reset(){delete this._mousedownPos}wheel(e){return this._firePreventable(new ca(e.type,this._map,e))}mousedown(e,t){return this._mousedownPos=t,this._firePreventable(new oa(e.type,this._map,e))}mouseup(e){this._map.fire(new oa(e.type,this._map,e))}click(e,t){this._mousedownPos&&this._mousedownPos.dist(t)>=this._clickTolerance||this._map.fire(new oa(e.type,this._map,e))}dblclick(e){return this._firePreventable(new oa(e.type,this._map,e))}mouseover(e){this._map.fire(new oa(e.type,this._map,e))}mouseout(e){this._map.fire(new oa(e.type,this._map,e))}touchstart(e){return this._firePreventable(new sa(e.type,this._map,e))}touchmove(e){this._map.fire(new sa(e.type,this._map,e))}touchend(e){this._map.fire(new sa(e.type,this._map,e))}touchcancel(e){this._map.fire(new sa(e.type,this._map,e))}_firePreventable(e){if(this._map.fire(e),e.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class ua{constructor(e){this._map=e}reset(){this._delayContextMenu=!1,this._ignoreContextMenu=!0,delete this._contextMenuEvent}mousemove(e){this._map.fire(new oa(e.type,this._map,e))}mousedown(){this._delayContextMenu=!0,this._ignoreContextMenu=!1}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new oa(`contextmenu`,this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(e){this._delayContextMenu?this._contextMenuEvent=e:this._ignoreContextMenu||this._map.fire(new oa(e.type,this._map,e)),this._map.listens(`contextmenu`)&&e.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class da{constructor(e){this._map=e}get transform(){return this._map._requestedCameraState||this._map.transform}get center(){return{lng:this.transform.center.lng,lat:this.transform.center.lat}}get zoom(){return this.transform.zoom}get pitch(){return this.transform.pitch}get bearing(){return this.transform.bearing}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this._map.terrain)}}class fa{constructor(e,t){this._map=e,this._tr=new da(e),this._el=e.getCanvasContainer(),this._container=e.getContainer(),this._clickTolerance=t.clickTolerance||1,t.boxZoom&&typeof t.boxZoom==`object`&&(this._boxZoomEnd=t.boxZoom.boxZoomEnd)}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){this.isEnabled()||(this._enabled=!0)}disable(){this.isEnabled()&&(this._enabled=!1)}mousedown(e,t){this.isEnabled()&&e.shiftKey&&e.button===0&&(d.disableDrag(),this._startPos=this._lastPos=t,this._active=!0)}mousemoveWindow(e,t){if(!this._active)return;let n=t;if(this._lastPos.equals(n)||!this._box&&n.dist(this._startPos)<this._clickTolerance)return;let r=this._startPos;this._lastPos=n,this._box||(this._box=d.create(`div`,`maplibregl-boxzoom`,this._container),this._container.classList.add(`maplibregl-crosshair`),this._fireEvent(`boxzoomstart`,e));let i=Math.min(r.x,n.x),a=Math.max(r.x,n.x),o=Math.min(r.y,n.y),s=Math.max(r.y,n.y);this._box.style.transform=`translate(${i}px,${o}px)`,this._box.style.width=a-i+`px`,this._box.style.height=s-o+`px`}mouseupWindow(e,n){if(!this._active||e.button!==0)return;let r=this._startPos,i=n;if(this.reset(),d.suppressClick(),r.x!==i.x||r.y!==i.y)return this._map.fire(new t.n(`boxzoomend`,{originalEvent:e})),this._boxZoomEnd?void this._boxZoomEnd(this._map,r,i,e):{cameraAnimation:e=>e.fitScreenCoordinates(r,i,this._tr.bearing,{linear:!0})};this._fireEvent(`boxzoomcancel`,e)}keydown(e){this._active&&e.keyCode===27&&(this.reset(),this._fireEvent(`boxzoomcancel`,e))}reset(){this._active=!1,this._container.classList.remove(`maplibregl-crosshair`),this._box&&=(this._box.remove(),null),d.enableDrag(),delete this._startPos,delete this._lastPos}_fireEvent(e,n){return this._map.fire(new t.n(e,{originalEvent:n}))}}function pa(e,t){if(e.length!==t.length)throw Error(`The number of touches and points are not equal - touches ${e.length}, points ${t.length}`);let n={};for(let r=0;r<e.length;r++)n[e[r].identifier]=t[r];return n}class ma{constructor(e){this.reset(),this.numTouches=e.numTouches}reset(){delete this.centroid,delete this.startTime,delete this.touches,this.aborted=!1}touchstart(e,n,r){(this.centroid||r.length>this.numTouches)&&(this.aborted=!0),this.aborted||(this.startTime===void 0&&(this.startTime=e.timeStamp),r.length===this.numTouches&&(this.centroid=function(e){let n=new t.P(0,0);for(let t of e)n._add(t);return n.div(e.length)}(n),this.touches=pa(r,n)))}touchmove(e,t,n){if(this.aborted||!this.centroid)return;let r=pa(n,t);for(let e in this.touches){let t=r[e];(!t||t.dist(this.touches[e])>30)&&(this.aborted=!0)}}touchend(e,t,n){if((!this.centroid||e.timeStamp-this.startTime>500)&&(this.aborted=!0),n.length===0){let e=!this.aborted&&this.centroid;if(this.reset(),e)return e}}}class Z{constructor(e){this.singleTap=new ma(e),this.numTaps=e.numTaps,this.reset()}reset(){this.lastTime=1/0,delete this.lastTap,this.count=0,this.singleTap.reset()}touchstart(e,t,n){this.singleTap.touchstart(e,t,n)}touchmove(e,t,n){this.singleTap.touchmove(e,t,n)}touchend(e,t,n){let r=this.singleTap.touchend(e,t,n);if(r){let t=e.timeStamp-this.lastTime<500,n=!this.lastTap||this.lastTap.dist(r)<30;if(t&&n||this.reset(),this.count++,this.lastTime=e.timeStamp,this.lastTap=r,this.count===this.numTaps)return this.reset(),r}}}class ha{constructor(e){this._tr=new da(e),this._zoomIn=new Z({numTouches:1,numTaps:2}),this._zoomOut=new Z({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(e,t,n){this._zoomIn.touchstart(e,t,n),this._zoomOut.touchstart(e,t,n)}touchmove(e,t,n){this._zoomIn.touchmove(e,t,n),this._zoomOut.touchmove(e,t,n)}touchend(e,n,r){let i=this._zoomIn.touchend(e,n,r),a=this._zoomOut.touchend(e,n,r),o=this._tr;return i?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:n=>n.easeTo({duration:300,zoom:t.cw(o.zoom+1,n.getZoomSnap()),around:o.unproject(i)},{originalEvent:e})}):a?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:n=>n.easeTo({duration:300,zoom:t.cw(o.zoom-1,n.getZoomSnap()),around:o.unproject(a)},{originalEvent:e})}):void 0}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class ga{constructor(e){this._enabled=!!e.enable,this._moveStateManager=e.moveStateManager,this._clickTolerance=e.clickTolerance||1,this._moveFunction=e.move,this._activateOnStart=!!e.activateOnStart,e.assignEvents(this),this.reset()}reset(e){this._active=!1,this._moved=!1,delete this._lastPoint,this._moveStateManager.endMove(e)}_move(...e){let t=this._moveFunction(...e);if(t.bearingDelta||t.pitchDelta||t.rollDelta||t.around||t.panDelta)return this._active=!0,t}dragStart(e,t){this.isEnabled()&&!this._lastPoint&&this._moveStateManager.isValidStartEvent(e)&&(this._moveStateManager.startMove(e),this._lastPoint=Array.isArray(t)?t[0]:t,this._activateOnStart&&this._lastPoint&&(this._active=!0))}dragMove(e,t){if(!this.isEnabled())return;let n=this._lastPoint;if(!n)return;if(e.preventDefault(),!this._moveStateManager.isValidMoveEvent(e))return void this.reset(e);let r=Array.isArray(t)?t[0]:t;return!this._moved&&r.dist(n)<this._clickTolerance?void 0:(this._moved=!0,this._lastPoint=r,this._move(n,r))}dragEnd(e){this.isEnabled()&&this._lastPoint&&this._moveStateManager.isValidEndEvent(e)&&(this._moved&&d.suppressClick(),this.reset(e))}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}getClickTolerance(){return this._clickTolerance}}let _a={0:1,2:2};class va{constructor(e){this._correctEvent=e.checkCorrectEvent}startMove(e){this._eventButton=e.button}endMove(e){delete this._eventButton}isValidStartEvent(e){return this._correctEvent(e)}isValidMoveEvent(e){return!function(e,t){let n=_a[t];return e.buttons===void 0||(e.buttons&n)!==n}(e,this._eventButton)}isValidEndEvent(e){return e.button===this._eventButton}}class ya{constructor(){this._firstTouch=void 0}_isOneFingerTouch(e){return e.targetTouches.length===1}_isSameTouchEvent(e){return e.targetTouches[0].identifier===this._firstTouch}startMove(e){this._firstTouch=e.targetTouches[0].identifier}endMove(e){delete this._firstTouch}isValidStartEvent(e){return this._isOneFingerTouch(e)}isValidMoveEvent(e){return this._isOneFingerTouch(e)&&this._isSameTouchEvent(e)}isValidEndEvent(e){return this._isOneFingerTouch(e)&&this._isSameTouchEvent(e)}}class ba{constructor(e=new va({checkCorrectEvent:()=>!0}),t=new ya){this.mouseMoveStateManager=e,this.oneFingerTouchMoveStateManager=t}_executeRelevantHandler(e,t,n){return e instanceof MouseEvent?t(e):typeof TouchEvent<`u`&&e instanceof TouchEvent?n(e):void 0}startMove(e){this._executeRelevantHandler(e,(e=>{this.mouseMoveStateManager.startMove(e)}),(e=>{this.oneFingerTouchMoveStateManager.startMove(e)}))}endMove(e){this._executeRelevantHandler(e,(e=>{this.mouseMoveStateManager.endMove(e)}),(e=>{this.oneFingerTouchMoveStateManager.endMove(e)}))}isValidStartEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidStartEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidStartEvent(e)))}isValidMoveEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidMoveEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidMoveEvent(e)))}isValidEndEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidEndEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidEndEvent(e)))}}let xa=e=>{e.mousedown=e.dragStart,e.mousemoveWindow=e.dragMove,e.mouseup=e.dragEnd,e.contextmenu=e=>{e.preventDefault()}};class Sa{constructor(e,t){this._clickTolerance=e.clickTolerance||1,this._map=t,this.reset()}reset(){this._active=!1,this._touches={},this._sum=new t.P(0,0)}_shouldBePrevented(e){return e<(this._map.cooperativeGestures.isEnabled()?2:1)}touchstart(e,t,n){return this._calculateTransform(e,t,n)}touchmove(e,t,n){if(this._active){if(!this._shouldBePrevented(n.length))return e.preventDefault(),this._calculateTransform(e,t,n);this._map.cooperativeGestures.notifyGestureBlocked(`touch_pan`,e)}}touchend(e,t,n){this._calculateTransform(e,t,n),this._active&&this._shouldBePrevented(n.length)&&this.reset()}touchcancel(){this.reset()}_calculateTransform(e,n,r){r.length>0&&(this._active=!0);let i=pa(r,n),a=new t.P(0,0),o=new t.P(0,0),s=0;for(let e in i){let t=i[e],n=this._touches[e];n&&(a._add(t),o._add(t.sub(n)),s++,i[e]=t)}if(this._touches=i,this._shouldBePrevented(s)||!o.mag())return;let c=o.div(s);return this._sum._add(c),this._sum.mag()<this._clickTolerance?void 0:{around:a.div(s),panDelta:c}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class Ca{constructor(){this.reset()}reset(){this._active=!1,delete this._firstTwoTouches}touchstart(e,t,n){this._firstTwoTouches||n.length<2||(this._firstTwoTouches=[n[0].identifier,n[1].identifier],this._start([t[0],t[1]]))}touchmove(e,t,n){if(!this._firstTwoTouches)return;e.preventDefault();let[r,i]=this._firstTwoTouches,a=wa(n,t,r),o=wa(n,t,i);if(!a||!o)return;let s=this._aroundCenter?null:a.add(o).div(2);return this._move([a,o],s,e)}touchend(e,t,n){if(!this._firstTwoTouches)return;let[r,i]=this._firstTwoTouches,a=wa(n,t,r),o=wa(n,t,i);a&&o||(this._active&&d.suppressClick(),this.reset())}touchcancel(){this.reset()}enable(e){this._enabled=!0,this._aroundCenter=!!e&&e.around===`center`}disable(){this._enabled=!1,this.reset()}isEnabled(){return!!this._enabled}isActive(){return!!this._active}}function wa(e,t,n){for(let r=0;r<e.length;r++)if(e[r].identifier===n)return t[r]}function Ta(e,t){return Math.log(e/t)/Math.LN2}class Ea extends Ca{constructor(){super(),this._zoomRate=1,this._zoomThreshold=.1}setZoomRate(e){this._zoomRate=e??1}setZoomThreshold(e){this._zoomThreshold=e??.1}reset(){super.reset(),delete this._distance,delete this._startDistance}_start(e){this._startDistance=this._distance=e[0].dist(e[1])}_move(e,t){let n=this._distance;if(this._distance=e[0].dist(e[1]),this._active||!(Math.abs(Ta(this._distance,this._startDistance))<this._zoomThreshold))return this._active=!0,{zoomDelta:Ta(this._distance,n)*this._zoomRate,pinchAround:t}}}function Da(e,t){return 180*e.angleWith(t)/Math.PI}class Oa extends Ca{reset(){super.reset(),delete this._minDiameter,delete this._startVector,delete this._vector}_start(e){this._startVector=this._vector=e[0].sub(e[1]),this._minDiameter=e[0].dist(e[1])}_move(e,t,n){let r=this._vector;if(this._vector=e[0].sub(e[1]),this._active||!this._isBelowThreshold(this._vector))return this._active=!0,{bearingDelta:Da(this._vector,r),pinchAround:t}}_isBelowThreshold(e){this._minDiameter=Math.min(this._minDiameter,e.mag());let t=25/(Math.PI*this._minDiameter)*360,n=Da(e,this._startVector);return Math.abs(n)<t}}function ka(e){return Math.abs(e.y)>Math.abs(e.x)}class Aa extends Ca{constructor(e){super(),this._currentTouchCount=0,this._map=e}reset(){super.reset(),this._valid=void 0,delete this._firstMove,delete this._lastPoints}touchstart(e,t,n){super.touchstart(e,t,n),this._currentTouchCount=n.length}_start(e){this._lastPoints=e,ka(e[0].sub(e[1]))&&(this._valid=!1)}_move(e,t,n){if(this._map.cooperativeGestures.isEnabled()&&this._currentTouchCount<3)return;let r=e[0].sub(this._lastPoints[0]),i=e[1].sub(this._lastPoints[1]);return this._valid=this.gestureBeginsVertically(r,i,n.timeStamp),this._valid?(this._lastPoints=e,this._active=!0,{pitchDelta:(r.y+i.y)/2*-.5}):void 0}gestureBeginsVertically(e,t,n){if(this._valid!==void 0)return this._valid;let r=e.mag()>=2,i=t.mag()>=2;if(!r&&!i)return;if(!r||!i)return this._firstMove===void 0&&(this._firstMove=n),n-this._firstMove<100&&void 0;let a=e.y>0==t.y>0;return ka(e)&&ka(t)&&a}}let ja={panStep:100,bearingStep:15,pitchStep:10};class Ma{constructor(e){this._tr=new da(e);let t=ja;this._panStep=t.panStep,this._bearingStep=t.bearingStep,this._pitchStep=t.pitchStep,this._rotationDisabled=!1}reset(){this._active=!1}keydown(e){if(e.altKey||e.ctrlKey||e.metaKey)return;let n=0,r=0,i=0,a=0,o=0;switch(e.keyCode){case 61:case 107:case 171:case 187:n=1;break;case 189:case 109:case 173:n=-1;break;case 37:e.shiftKey?r=-1:(e.preventDefault(),a=-1);break;case 39:e.shiftKey?r=1:(e.preventDefault(),a=1);break;case 38:e.shiftKey?i=1:(e.preventDefault(),o=-1);break;case 40:e.shiftKey?i=-1:(e.preventDefault(),o=1);break;default:return}return this._rotationDisabled&&(r=0,i=0),{cameraAnimation:s=>{let c=this._tr;s.easeTo({duration:300,easeId:`keyboardHandler`,easing:Na,zoom:n?t.cw(c.zoom+n*(e.shiftKey?2:1),s.getZoomSnap()):c.zoom,bearing:c.bearing+r*this._bearingStep,pitch:c.pitch+i*this._pitchStep,offset:[-a*this._panStep,-o*this._panStep],center:c.center},{originalEvent:e})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0}enableRotation(){this._rotationDisabled=!1}}function Na(e){return e*(2-e)}let Pa=4.000244140625;class Fa{constructor(e,t){this._onTimeout=e=>{this._type=`wheel`,this._delta-=this._lastValue,this._active||this._start(e)},this._map=e,this._tr=new da(e),this._triggerRenderFrame=t,this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=.0022222222222222222}setZoomRate(e){this._defaultZoomRate=e}setWheelZoomRate(e){this._wheelZoomRate=e}isEnabled(){return!!this._enabled}isActive(){return!!this._active||this._finishTimeout!==void 0}isZooming(){return!!this._zooming}enable(e){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!e&&e.around===`center`)}disable(){this.isEnabled()&&(this._enabled=!1)}_shouldBePrevented(e){return!!this._map.cooperativeGestures.isEnabled()&&!(e.ctrlKey||this._map.cooperativeGestures.isBypassed(e))}wheel(e){if(!this.isEnabled())return;if(this._shouldBePrevented(e))return void this._map.cooperativeGestures.notifyGestureBlocked(`wheel_zoom`,e);let t=e.deltaMode===WheelEvent.DOM_DELTA_LINE?40*e.deltaY:e.deltaY,n=l(),r=n-(this._lastWheelEventTime||0);this._lastWheelEventTime=n,t!==0&&t%Pa==0?this._type=`wheel`:t!==0&&Math.abs(t)<4?this._type=`trackpad`:r>400?(this._type=null,this._lastValue=t,this._timeout=setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(r*t)<200?`trackpad`:`wheel`,this._timeout&&(clearTimeout(this._timeout),this._timeout=null,t+=this._lastValue)),e.shiftKey&&t&&(t/=4),this._type&&(this._lastWheelEvent=e,this._delta-=t,this._active||this._start(e)),e.preventDefault()}_start(e){if(!this._delta)return;this._needsRerender=!1,this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);let n=d.mousePos(this._map.getCanvas(),e),r=this._tr;this._aroundPoint=this._aroundCenter?r.transform.locationToScreenPoint(t.W.convert(r.center)):n,this._needsRerender||(this._needsRerender=!0,this._triggerRenderFrame())}renderFrame(){if(!this._needsRerender||(this._needsRerender=!1,!this.isActive()))return;let e=this._tr.transform;if(typeof this._lastExpectedZoom==`number`){let t=e.zoom-this._lastExpectedZoom;typeof this._startZoom==`number`&&(this._startZoom+=t),typeof this._targetZoom==`number`&&(this._targetZoom+=t)}if(this._delta!==0){let n=this._type===`wheel`&&Math.abs(this._delta)>Pa?this._wheelZoomRate:this._defaultZoomRate,r=2/(1+Math.exp(-Math.abs(this._delta*n)));this._delta<0&&r!==0&&(r=1/r);let i=typeof this._targetZoom==`number`?t.ao(this._targetZoom):e.scale,a=e.applyConstrain(e.getCameraLngLat(),t.ar(i*r)).zoom,o=this._map.getZoomSnap();if(this._type===`wheel`&&o>0){let n=t.cw(e.zoom,o);this._targetZoom=t.cw(a,o,a-n)}else this._targetZoom=a;this._type===`wheel`&&(this._startZoom=e.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0}let n=typeof this._targetZoom==`number`?this._targetZoom:e.zoom,r=this._startZoom,i=this._easing,a,o=!1;if(this._type===`wheel`&&r&&i){let e=l()-this._lastWheelEventTime,s=Math.min((e+5)/200,1),c=i(s);a=t.H.number(r,n,c),s<1?this._needsRerender=!0:o=!0}else a=n,o=!0;return this._active=!0,o&&(this._active=!1,this._finishTimeout=setTimeout((()=>{this._zooming=!1,this._triggerRenderFrame(),delete this._targetZoom,delete this._lastExpectedZoom,delete this._finishTimeout}),200)),this._lastExpectedZoom=a,{noInertia:!0,needsRenderFrame:!o,zoomDelta:a-e.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}_smoothOutEasing(e){let n=t.cy;if(this._prevEase){let e=this._prevEase,r=(l()-e.start)/e.duration,i=e.easing(r+.01)-e.easing(r),a=.27/Math.sqrt(i*i+1e-4)*.01,o=Math.sqrt(.0729-a*a);n=t.cv(a,o,.25,1)}return this._prevEase={start:l(),duration:e,easing:n},n}reset(){this._active=!1,this._zooming=!1,delete this._targetZoom,delete this._lastExpectedZoom,this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout)}}class Ia{constructor(e,t){this._clickZoom=e,this._tapZoom=t}enable(){this._clickZoom.enable(),this._tapZoom.enable()}disable(){this._clickZoom.disable(),this._tapZoom.disable()}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class La{constructor(e){this._tr=new da(e),this.reset()}reset(){this._active=!1}dblclick(e,n){return e.preventDefault(),{cameraAnimation:r=>{r.easeTo({duration:300,zoom:t.cw(this._tr.zoom+(e.shiftKey?-1:1),r.getZoomSnap()),around:this._tr.unproject(n)},{originalEvent:e})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class Ra{constructor(){this._tap=new Z({numTouches:1,numTaps:1}),this._zoomRate=1,this.reset()}setZoomRate(e){this._zoomRate=e??1}reset(){this._active=!1,delete this._swipePoint,delete this._swipeTouch,delete this._tapTime,delete this._tapPoint,this._tap.reset()}touchstart(e,t,n){if(!this._swipePoint)if(this._tapTime){let r=t[0],i=e.timeStamp-this._tapTime<500,a=this._tapPoint.dist(r)<30;i&&a?n.length>0&&(this._swipePoint=r,this._swipeTouch=n[0].identifier):this.reset()}else this._tap.touchstart(e,t,n)}touchmove(e,t,n){if(this._tapTime){if(this._swipePoint){if(n[0].identifier!==this._swipeTouch)return;let r=t[0],i=r.y-this._swipePoint.y;return this._swipePoint=r,e.preventDefault(),this._active=!0,{zoomDelta:i/128*this._zoomRate}}}else this._tap.touchmove(e,t,n)}touchend(e,t,n){if(this._tapTime)this._swipePoint&&n.length===0&&this.reset();else{let r=this._tap.touchend(e,t,n);r&&(this._tapTime=e.timeStamp,this._tapPoint=r)}}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class za{constructor(e,t,n){this._el=e,this._mousePan=t,this._touchPan=n}enable(e){this._inertiaOptions=e||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add(`maplibregl-touch-drag-pan`)}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove(`maplibregl-touch-drag-pan`)}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class Ba{constructor(e,t,n,r){this._pitchWithRotate=e.pitchWithRotate,this._rollEnabled=e.rollEnabled,this._mouseRotate=t,this._mousePitch=n,this._mouseRoll=r}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable(),this._rollEnabled&&this._mouseRoll.enable()}disable(){this._mouseRotate.disable(),this._mousePitch.disable(),this._mouseRoll.disable()}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())&&(!this._rollEnabled||this._mouseRoll.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()||this._mouseRoll.isActive()}}class Va{constructor(e,t,n,r){this._el=e,this._touchZoom=t,this._touchRotate=n,this._tapDragZoom=r,this._rotationDisabled=!1,this._enabled=!0}enable(e){this._touchZoom.enable(e),this._rotationDisabled||this._touchRotate.enable(e),this._tapDragZoom.enable(),this._el.classList.add(`maplibregl-touch-zoom-rotate`)}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove(`maplibregl-touch-zoom-rotate`)}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}setZoomRate(e){this._touchZoom.setZoomRate(e),this._tapDragZoom.setZoomRate(e)}setZoomThreshold(e){this._touchZoom.setZoomThreshold(e)}disableRotation(){this._rotationDisabled=!0,this._touchRotate.disable()}enableRotation(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable()}}class Ha{constructor(e,t){this._bypassKey=navigator.userAgent.includes(`Mac`)?`metaKey`:`ctrlKey`,this._map=e,this._options=t,this._enabled=!1}isActive(){return!1}reset(){}_setupUI(){if(this._container)return;let e=this._map.getCanvasContainer();e.classList.add(`maplibregl-cooperative-gestures`),this._container=d.create(`div`,`maplibregl-cooperative-gesture-screen`,e);let t=this._map._getUIString(`CooperativeGesturesHandler.WindowsHelpText`);this._bypassKey===`metaKey`&&(t=this._map._getUIString(`CooperativeGesturesHandler.MacHelpText`));let n=this._map._getUIString(`CooperativeGesturesHandler.MobileHelpText`),r=document.createElement(`div`);r.className=`maplibregl-desktop-message`,r.textContent=t,this._container.appendChild(r);let i=document.createElement(`div`);i.className=`maplibregl-mobile-message`,i.textContent=n,this._container.appendChild(i),this._container.setAttribute(`aria-hidden`,`true`)}_destroyUI(){this._container&&(this._container.remove(),this._map.getCanvasContainer().classList.remove(`maplibregl-cooperative-gestures`)),delete this._container}enable(){this._setupUI(),this._enabled=!0}disable(){this._enabled=!1,this._destroyUI()}isEnabled(){return this._enabled}isBypassed(e){return e[this._bypassKey]}notifyGestureBlocked(e,n){this._enabled&&(this._map.fire(new t.n(`cooperativegestureprevented`,{gestureType:e,originalEvent:n})),this._container.classList.add(`maplibregl-show`),setTimeout((()=>{this._container.classList.remove(`maplibregl-show`)}),100))}}let Ua=e=>e.zoom||e.drag||e.roll||e.pitch||e.rotate;class Wa extends t.n{}function Ga(e){return e.panDelta?.mag()||e.zoomDelta||e.bearingDelta||e.pitchDelta||e.rollDelta}class Q{get _ownerDocument(){return this._el?.ownerDocument||document}get _ownerWindow(){return this._el?.ownerDocument?.defaultView||window}constructor(e,n){this.handleWindowEvent=e=>{this.handleEvent(e,`${e.type}Window`)},this.handleEvent=(e,n)=>{if(e.type===`blur`)return void this.stop(!0);this._updatingCamera=!0;let r=e.type===`renderFrame`?void 0:e,i={needsRenderFrame:!1},a={},o={};for(let{handlerName:s,handler:c,allowed:l}of this._handlers){if(!c.isEnabled())continue;let u;if(this._blockedByActive(o,l,s))c.reset();else if(c[n||e.type]){if(t.cz(e,n||e.type)){let t=d.mousePos(this._map.getCanvas(),e);u=c[n||e.type](e,t)}else if(t.cA(e,n||e.type)){let t=this._getMapTouches(e.touches),r=d.touchPos(this._map.getCanvas(),t);u=c[n||e.type](e,r,t)}else t.cB(n||e.type)||(u=c[n||e.type](e));this.mergeHandlerResult(i,a,u,s,r),u!=null&&u.needsRenderFrame&&this._triggerRenderFrame()}(u||c.isActive())&&(o[s]=c)}let s={};for(let e in this._previousActiveHandlers)o[e]||(s[e]=r);this._previousActiveHandlers=o,(Object.keys(s).length||Ga(i))&&(this._changes.push([i,a,s]),this._triggerRenderFrame()),(Object.keys(o).length||Ga(i))&&this._map._stop(!0),this._updatingCamera=!1;let{cameraAnimation:c}=i;c&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],c(this._map))},this._map=e,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new ra(e),this._bearingSnap=n.bearingSnap,this._previousActiveHandlers={},this._eventsInProgress={},this._addDefaultHandlers(n);let r=this._el;this._listeners=[[r,`touchstart`,{passive:!0}],[r,`touchmove`,{passive:!1}],[r,`touchend`,void 0],[r,`touchcancel`,void 0],[r,`mousedown`,void 0],[r,`mousemove`,void 0],[r,`mouseup`,void 0],[this._ownerDocument,`mousemove`,{capture:!0}],[this._ownerDocument,`mouseup`,void 0],[r,`mouseover`,void 0],[r,`mouseout`,void 0],[r,`dblclick`,void 0],[r,`click`,void 0],[r,`keydown`,{capture:!1}],[r,`keyup`,void 0],[r,`wheel`,{passive:!1}],[r,`contextmenu`,void 0],[this._ownerWindow,`blur`,void 0]];for(let[e,t,n]of this._listeners)e.addEventListener(t,e===this._ownerDocument?this.handleWindowEvent:this.handleEvent,n)}destroy(){for(let[e,t,n]of this._listeners)e.removeEventListener(t,e===this._ownerDocument?this.handleWindowEvent:this.handleEvent,n)}_addDefaultHandlers(e){let n=this._map,r=n.getCanvasContainer();this._add(`mapEvent`,new la(n,e));let i=n.boxZoom=new fa(n,e);this._add(`boxZoom`,i),e.interactive&&e.boxZoom&&i.enable();let a=n.cooperativeGestures=new Ha(n,e.cooperativeGestures);this._add(`cooperativeGestures`,a),e.cooperativeGestures&&a.enable();let o=new ha(n),s=new La(n);n.doubleClickZoom=new Ia(s,o),this._add(`tapZoom`,o),this._add(`clickZoom`,s),e.interactive&&e.doubleClickZoom&&n.doubleClickZoom.enable();let c=new Ra;this._add(`tapDragZoom`,c);let l=n.touchPitch=new Aa(n);this._add(`touchPitch`,l),e.interactive&&e.touchPitch&&n.touchPitch.enable(e.touchPitch);let u=()=>n.project(n.getCenter()),d=function({enable:e,clickTolerance:n,aroundCenter:r=!0,minPixelCenterThreshold:i=100,rotateDegreesPerPixelMoved:a=.8},o){return new ga({clickTolerance:n,move:(e,n)=>{let s=o();if(r&&Math.abs(s.y-e.y)>i)return{bearingDelta:t.cx(new t.P(e.x,n.y),n,s)};let c=(n.x-e.x)*a;return r&&n.y<s.y&&(c=-c),{bearingDelta:c}},moveStateManager:new va({checkCorrectEvent:e=>e.button===0&&e.ctrlKey||e.button===2&&!e.ctrlKey}),enable:e,assignEvents:xa})}(e,u),f=function({enable:e,clickTolerance:t,pitchDegreesPerPixelMoved:n=-.5}){return new ga({clickTolerance:t,move:(e,t)=>({pitchDelta:(t.y-e.y)*n}),moveStateManager:new va({checkCorrectEvent:e=>e.button===0&&e.ctrlKey||e.button===2}),enable:e,assignEvents:xa})}(e),p=function({enable:e,clickTolerance:t,rollDegreesPerPixelMoved:n=.3},r){return new ga({clickTolerance:t,move:(e,t)=>{let i=r(),a=(t.x-e.x)*n;return t.y<i.y&&(a=-a),{rollDelta:a}},moveStateManager:new va({checkCorrectEvent:e=>e.button===2&&e.ctrlKey}),enable:e,assignEvents:xa})}(e,u);n.dragRotate=new Ba(e,d,f,p),this._add(`mouseRotate`,d,[`mousePitch`]),this._add(`mousePitch`,f,[`mouseRotate`,`mouseRoll`]),this._add(`mouseRoll`,p,[`mousePitch`]),e.interactive&&e.dragRotate&&n.dragRotate.enable();let m=function({enable:e,clickTolerance:t}){return new ga({clickTolerance:t,move:(e,t)=>({around:t,panDelta:t.sub(e)}),activateOnStart:!0,moveStateManager:new va({checkCorrectEvent:e=>e.button===0&&!e.ctrlKey}),enable:e,assignEvents:xa})}(e),h=new Sa(e,n);n.dragPan=new za(r,m,h),this._add(`mousePan`,m),this._add(`touchPan`,h,[`touchZoom`,`touchRotate`]),e.interactive&&e.dragPan&&n.dragPan.enable(e.dragPan);let g=new Oa,_=new Ea;n.touchZoomRotate=new Va(r,_,g,c),this._add(`touchRotate`,g,[`touchPan`,`touchZoom`]),this._add(`touchZoom`,_,[`touchPan`,`touchRotate`]),e.interactive&&e.touchZoomRotate&&n.touchZoomRotate.enable(e.touchZoomRotate),this._add(`blockableMapEvent`,new ua(n));let v=n.scrollZoom=new Fa(n,(()=>this._triggerRenderFrame()));this._add(`scrollZoom`,v,[`mousePan`]),e.interactive&&e.scrollZoom&&n.scrollZoom.enable(e.scrollZoom);let y=n.keyboard=new Ma(n);this._add(`keyboard`,y),e.interactive&&e.keyboard&&n.keyboard.enable()}_add(e,t,n){this._handlers.push({handlerName:e,handler:t,allowed:n}),this._handlersById[e]=t}stop(e){if(!this._updatingCamera){for(let{handler:e}of this._handlers)e.reset();this._inertia.clear(),this._fireEvents({},{},e),this._changes=[]}}isActive(){for(let{handler:e}of this._handlers)if(e.isActive())return!0;return!1}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return!!Ua(this._eventsInProgress)||this.isZooming()}_blockedByActive(e,t,n){for(let r in e)if(r!==n&&!t?.includes(r))return!0;return!1}_getMapTouches(e){let t=[];for(let n of e)this._el.contains(n.target)&&t.push(n);return t}mergeHandlerResult(e,n,r,i,a){if(!r)return;t.e(e,r);let o={handlerName:i,originalEvent:r.originalEvent||a};r.zoomDelta!==void 0&&(n.zoom=o),r.panDelta!==void 0&&(n.drag=o),r.rollDelta!==void 0&&(n.roll=o),r.pitchDelta!==void 0&&(n.pitch=o),r.bearingDelta!==void 0&&(n.rotate=o)}_applyChanges(){let e={},n={},r={};for(let[i,a,o]of this._changes)i.panDelta&&(e.panDelta=(e.panDelta||new t.P(0,0))._add(i.panDelta)),i.zoomDelta&&(e.zoomDelta=(e.zoomDelta||0)+i.zoomDelta),i.bearingDelta&&(e.bearingDelta=(e.bearingDelta||0)+i.bearingDelta),i.pitchDelta&&(e.pitchDelta=(e.pitchDelta||0)+i.pitchDelta),i.rollDelta&&(e.rollDelta=(e.rollDelta||0)+i.rollDelta),i.around!==void 0&&(e.around=i.around),i.pinchAround!==void 0&&(e.pinchAround=i.pinchAround),i.noInertia&&(e.noInertia=i.noInertia),t.e(n,a),t.e(r,o);this._updateMapTransform(e,n,r),this._changes=[]}_updateMapTransform(e,t,n){let r=this._map,i=r._getTransformForUpdate(),a=r.terrain;if(!(Ga(e)||a&&this._terrainMovement))return void this._fireEvents(t,n,!0);r._stop(!0);let{panDelta:o,zoomDelta:s,bearingDelta:c,pitchDelta:l,rollDelta:u,around:d,pinchAround:f}=e;f!==void 0&&(d=f),d||=r.transform.centerPoint,a&&!i.isPointOnMapSurface(d)&&(d=i.centerPoint);let p={panDelta:o,zoomDelta:s,rollDelta:u,pitchDelta:l,bearingDelta:c,around:d};this._map.cameraHelper.useGlobeControls&&!i.isPointOnMapSurface(d)&&(d=i.centerPoint);let m=d.distSqr(i.centerPoint)<.01?i.center:i.screenPointToLocation(o?d.sub(o):d);this._handleMapControls({terrain:a,tr:i,deltasForHelper:p,preZoomAroundLoc:m,combinedEventsInProgress:t,panDelta:o}),r._applyUpdatedTransform(i),this._map._update(),e.noInertia||this._inertia.record(e),this._fireEvents(t,n,!0)}_handleMapControls({terrain:e,tr:t,deltasForHelper:n,preZoomAroundLoc:r,combinedEventsInProgress:i,panDelta:a}){let o=this._map.cameraHelper;if(o.handleMapControlsRollPitchBearingZoom(n,t),e)return o.useGlobeControls?(this._terrainMovement||!i.drag&&!i.zoom||(this._terrainMovement=!0,this._map._elevationFreeze=!0),void o.handleMapControlsPan(n,t,r)):this._terrainMovement||!i.drag&&!i.zoom?void(i.drag&&this._terrainMovement&&a?t.setCenter(t.screenPointToLocation(t.centerPoint.sub(a))):o.handleMapControlsPan(n,t,r)):(this._terrainMovement=!0,this._map._elevationFreeze=!0,void o.handleMapControlsPan(n,t,r));o.handleMapControlsPan(n,t,r)}_fireEvents(e,n,r){let i=Ua(this._eventsInProgress),a=Ua(e),o={};for(let t in e){let{originalEvent:n}=e[t];this._eventsInProgress[t]||(o[`${t}start`]=n),this._eventsInProgress[t]=e[t]}!i&&a&&this._fireEvent(`movestart`,a.originalEvent);for(let e in o)this._fireEvent(e,o[e]);a&&this._fireEvent(`move`,a.originalEvent);for(let t in e){let{originalEvent:n}=e[t];this._fireEvent(t,n)}let c={},l;for(let e in this._eventsInProgress){let{handlerName:t,originalEvent:r}=this._eventsInProgress[e];this._handlersById[t].isActive()||(delete this._eventsInProgress[e],l=n[t]||r,c[`${e}end`]=l)}for(let e in c)this._fireEvent(e,c[e]);let u=Ua(this._eventsInProgress),d=(i||a)&&!u;if(d&&this._terrainMovement){this._map._elevationFreeze=!1,this._terrainMovement=!1;let e=this._map._getTransformForUpdate();this._map.getCenterClampedToGround()&&e.recalculateZoomAndCenter(this._map.terrain),this._map._applyUpdatedTransform(e)}if(r&&d){this._updatingCamera=!0;let e=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),n=e=>e!==0&&-this._bearingSnap<e&&e<this._bearingSnap;!e||!e.essential&&s.prefersReducedMotion?(this._map.fire(new t.n(`moveend`,{originalEvent:l})),n(this._map.getBearing())&&this._map.resetNorth()):(n(e.bearing||this._map.getBearing())&&(e.bearing=0),e.freezeElevation=!0,this._map.easeTo(e,{originalEvent:l})),this._updatingCamera=!1}}_fireEvent(e,n){this._map.fire(new t.n(e,n?{originalEvent:n}:{}))}_requestFrame(){return this._map.triggerRepaint(),this._map._renderTaskQueue.add((e=>{delete this._frameId,this.handleEvent(new Wa(`renderFrame`,{timeStamp:e})),this._applyChanges()}))}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}class $ extends t.E{constructor(e,t,n){super(),this._renderFrameCallback=()=>{let e=Math.min((l()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(e)),e<1&&this._easeFrameId?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()},this._moving=!1,this._zooming=!1,this.transform=e,this._bearingSnap=n.bearingSnap,this._zoomSnap=n.zoomSnap,this.cameraHelper=t,this.on(`moveend`,(()=>{delete this._requestedCameraState}))}migrateProjection(e,t){e.apply(this.transform,!0),this.transform=e,this.cameraHelper=t}getCenter(){return new t.W(this.transform.center.lng,this.transform.center.lat)}setCenter(e,t){return this.jumpTo({center:e},t)}getCenterElevation(){return this.transform.elevation}setCenterElevation(e,t){return this.jumpTo({elevation:e},t),this}getCenterClampedToGround(){return this._centerClampedToGround}setCenterClampedToGround(e){this._centerClampedToGround=e}panBy(e,n,r){return e=t.P.convert(e).mult(-1),this.panTo(this.transform.center,t.e({offset:e},n),r)}panTo(e,n,r){return this.easeTo(t.e({center:e},n),r)}getZoom(){return this.transform.zoom}setZoom(e,t){return this.jumpTo({zoom:e},t),this}zoomTo(e,n,r){return this.easeTo(t.e({zoom:e},n),r)}zoomIn(e,n){return this.zoomTo(t.cw(this.getZoom()+1,this._zoomSnap),e,n),this}zoomOut(e,n){return this.zoomTo(t.cw(this.getZoom()-1,this._zoomSnap),e,n),this}getVerticalFieldOfView(){return this.transform.fov}setVerticalFieldOfView(e,n){return e!=this.transform.fov&&(this.transform.setFov(e),this.fire(new t.n(`movestart`,n)).fire(new t.n(`move`,n)).fire(new t.n(`moveend`,n))),this}getBearing(){return this.transform.bearing}setZoomSnap(e){return this._zoomSnap=e,this}getZoomSnap(){return this._zoomSnap}setBearing(e,t){return this.jumpTo({bearing:e},t),this}getPadding(){return this.transform.padding}setPadding(e,t){return this.jumpTo({padding:e},t),this}rotateTo(e,n,r){return this.easeTo(t.e({bearing:e},n),r)}resetNorth(e,n){return this.rotateTo(0,t.e({duration:1e3},e),n),this}resetNorthPitch(e,n){return this.easeTo(t.e({bearing:0,pitch:0,roll:0,duration:1e3},e),n),this}snapToNorth(e,t){return Math.abs(this.getBearing())<this._bearingSnap?this.resetNorth(e,t):this}getPitch(){return this.transform.pitch}setPitch(e,t){return this.jumpTo({pitch:e},t),this}getRoll(){return this.transform.roll}setRoll(e,t){return this.jumpTo({roll:e},t),this}cameraForBounds(e,t){e=de.convert(e).adjustAntiMeridian();let n=t?.bearing||0;return this._cameraForBoxAndBearing(e.getNorthWest(),e.getSouthEast(),n,t)}_cameraForBoxAndBearing(e,n,r,i){let a={top:0,bottom:0,right:0,left:0};if(typeof(i=t.e({padding:a,offset:[0,0],maxZoom:this.transform.maxZoom},i)).padding==`number`){let e=i.padding;i.padding={top:e,bottom:e,right:e,left:e}}let o=t.e(a,i.padding);i.padding=o;let s=this.transform,c=new de(e,n),l=this.cameraHelper.cameraForBoxAndBearing(i,o,c,r,s);return l&&this._zoomSnap&&(l.zoom=t.cw(l.zoom,this._zoomSnap,-1)),l}fitBounds(e,t,n){return this._fitInternal(this.cameraForBounds(e,t),t,n)}fitScreenCoordinates(e,n,r,i,a){return this._fitInternal(this._cameraForBoxAndBearing(this.transform.screenPointToLocation(t.P.convert(e)),this.transform.screenPointToLocation(t.P.convert(n)),r,i),i,a)}_fitInternal(e,n,r){return e?(delete(n=t.e(e,n)).padding,n.linear?this.easeTo(n,r):this.flyTo(n,r)):this}jumpTo(e,n){this.stop(),`zoom`in e&&this._zoomSnap&&(e.zoom=t.cw(e.zoom,this._zoomSnap));let r=this._getTransformForUpdate(),i=!1,a=!1,o=!1,s=r.zoom;this.terrain&&r.setElevation(this.terrain.getElevationForLngLatZoom(e.center?t.W.convert(e.center):r.center,e.zoom||r.tileZoom)),this.cameraHelper.handleJumpToCenterZoom(r,e);let c=r.zoom!==s;return`elevation`in e&&r.elevation!==+e.elevation&&r.setElevation(+e.elevation),`bearing`in e&&r.bearing!==+e.bearing&&(i=!0,r.setBearing(+e.bearing)),`pitch`in e&&r.pitch!==+e.pitch&&(a=!0,r.setPitch(+e.pitch)),`roll`in e&&r.roll!==+e.roll&&(o=!0,r.setRoll(+e.roll)),e.padding==null||r.isPaddingEqual(e.padding)||r.setPadding(e.padding),this._applyUpdatedTransform(r),this.fire(new t.n(`movestart`,n)).fire(new t.n(`move`,n)),c&&this.fire(new t.n(`zoomstart`,n)).fire(new t.n(`zoom`,n)).fire(new t.n(`zoomend`,n)),i&&this.fire(new t.n(`rotatestart`,n)).fire(new t.n(`rotate`,n)).fire(new t.n(`rotateend`,n)),a&&this.fire(new t.n(`pitchstart`,n)).fire(new t.n(`pitch`,n)).fire(new t.n(`pitchend`,n)),o&&this.fire(new t.n(`rollstart`,n)).fire(new t.n(`roll`,n)).fire(new t.n(`rollend`,n)),this.fire(new t.n(`moveend`,n))}calculateCameraOptionsFromTo(e,n,r,i=0){let a=t.a7.fromLngLat(e,n),o=t.a7.fromLngLat(r,i),s=o.x-a.x,c=o.y-a.y,l=o.z-a.z,u=Math.hypot(s,c,l);if(u===0)throw Error(`Can't calculate camera options with same From and To`);let d=Math.hypot(s,c),f=t.ar(this.transform.cameraToCenterDistance/u/this.transform.tileSize),p=180*Math.atan2(s,-c)/Math.PI,m=180*Math.acos(d/u)/Math.PI;return m=l<0?90-m:90+m,{center:o.toLngLat(),elevation:i,zoom:f,pitch:m,bearing:p}}calculateCameraOptionsFromCameraLngLatAltRotation(e,t,n,r,i){let a=this.transform.calculateCenterFromCameraLngLatAlt(e,t,n,r);return{center:a.center,elevation:a.elevation,zoom:a.zoom,bearing:n,pitch:r,roll:i}}easeTo(e,n){this._stop(!1,e.easeId),`zoom`in(e=t.e({offset:[0,0],duration:500,easing:t.cy},e))&&this._zoomSnap&&(e.zoom=t.cw(e.zoom,this._zoomSnap)),(!1===e.animate||!e.essential&&s.prefersReducedMotion)&&(e.duration=0);let r=this._getTransformForUpdate(),i=this.getBearing(),a=r.pitch,o=r.roll,c=`bearing`in e?this._normalizeBearing(e.bearing,i):i,l=`pitch`in e?+e.pitch:a,u=`roll`in e?this._normalizeBearing(e.roll,o):o,d=`padding`in e?e.padding:r.padding,f=t.P.convert(e.offset),p,m;e.around&&(p=t.W.convert(e.around),m=r.locationToScreenPoint(p));let h={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching,rolling:this._rolling},g=this.cameraHelper.handleEaseTo(r,{bearing:c,pitch:l,roll:u,padding:d,around:p,aroundPoint:m,offsetAsPoint:f,offset:e.offset,zoom:e.zoom,center:e.center});return this._rotating||=i!==c,this._pitching||=l!==a,this._rolling||=u!==o,this._padding=!r.isPaddingEqual(d),this._zooming||=g.isZooming,this._easeId=e.easeId,this._prepareEase(n,e.noMoveStart,h),this.terrain&&this._prepareElevation(g.elevationCenter),this._ease((t=>{g.easeFunc(t),this.terrain&&!e.freezeElevation&&this._updateElevation(t),this._applyUpdatedTransform(r),this._fireMoveEvents(n)}),(t=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(n,t)}),e),this}_prepareEase(e,n,r={}){this._moving=!0,n||r.moving||this.fire(new t.n(`movestart`,e)),this._zooming&&!r.zooming&&this.fire(new t.n(`zoomstart`,e)),this._rotating&&!r.rotating&&this.fire(new t.n(`rotatestart`,e)),this._pitching&&!r.pitching&&this.fire(new t.n(`pitchstart`,e)),this._rolling&&!r.rolling&&this.fire(new t.n(`rollstart`,e))}_prepareElevation(e){this._elevationCenter=e,this._elevationStart=this.transform.elevation,this._elevationTarget=this.terrain.getElevationForLngLatZoom(e,this.transform.tileZoom),this._elevationFreeze=!0}_updateElevation(e){this._elevationStart!==void 0&&this._elevationCenter!==void 0||this._prepareElevation(this.transform.center),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom));let n=this.terrain.getElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);if(e<1&&n!==this._elevationTarget){let t=this._elevationTarget-this._elevationStart;this._elevationStart+=e*(t-(n-(t*e+this._elevationStart))/(1-e)),this._elevationTarget=n}this.transform.setElevation(t.H.number(this._elevationStart,this._elevationTarget,e))}_finalizeElevation(){this._elevationFreeze=!1,this.getCenterClampedToGround()&&this.transform.recalculateZoomAndCenter(this.terrain)}_getTransformForUpdate(){return this.transformCameraUpdate||this.terrain?(this._requestedCameraState||=this.transform.clone(),this._requestedCameraState):this.transform}_elevateCameraIfInsideTerrain(e){if(!this.terrain&&e.elevation>=0&&e.pitch<=90)return{};let t=e.getCameraLngLat(),n=e.getCameraAltitude(),r=this.terrain?this.terrain.getElevationForLngLatZoom(t,e.zoom):0;if(n<r){let n=this.calculateCameraOptionsFromTo(t,r,e.center,e.elevation);return{pitch:n.pitch,zoom:n.zoom}}return{}}_applyUpdatedTransform(e){let t=[];if(t.push((e=>this._elevateCameraIfInsideTerrain(e))),this.transformCameraUpdate&&t.push((e=>this.transformCameraUpdate(e))),!t.length)return;let n=e.clone();for(let e of t){let t=n.clone(),{center:r,zoom:i,roll:a,pitch:o,bearing:s,elevation:c}=e(t);r&&t.setCenter(r),c!==void 0&&t.setElevation(c),i!==void 0&&t.setZoom(i),a!==void 0&&t.setRoll(a),o!==void 0&&t.setPitch(o),s!==void 0&&t.setBearing(s),n.apply(t,!1)}this.transform.apply(n,!1)}_fireMoveEvents(e){this.fire(new t.n(`move`,e)),this._zooming&&this.fire(new t.n(`zoom`,e)),this._rotating&&this.fire(new t.n(`rotate`,e)),this._pitching&&this.fire(new t.n(`pitch`,e)),this._rolling&&this.fire(new t.n(`roll`,e))}_afterEase(e,n){if(this._easeId&&n&&this._easeId===n)return;delete this._easeId;let r=this._zooming,i=this._rotating,a=this._pitching,o=this._rolling;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._rolling=!1,this._padding=!1,r&&this.fire(new t.n(`zoomend`,e)),i&&this.fire(new t.n(`rotateend`,e)),a&&this.fire(new t.n(`pitchend`,e)),o&&this.fire(new t.n(`rollend`,e)),this.fire(new t.n(`moveend`,e))}flyTo(e,n){if(!e.essential&&s.prefersReducedMotion){let r=t.V(e,[`center`,`zoom`,`bearing`,`pitch`,`roll`,`elevation`,`padding`]);return this.jumpTo(r,n)}this.stop(),`zoom`in(e=t.e({offset:[0,0],speed:1.2,curve:1.42,easing:t.cy},e))&&this._zoomSnap&&(e.zoom=t.cw(e.zoom,this._zoomSnap));let r=this._getTransformForUpdate(),i=r.bearing,a=r.pitch,o=r.roll,c=r.padding,l=`bearing`in e?this._normalizeBearing(e.bearing,i):i,u=`pitch`in e?+e.pitch:a,d=`roll`in e?this._normalizeBearing(e.roll,o):o,f=`padding`in e?e.padding:r.padding,p=t.P.convert(e.offset),m=r.centerPoint.add(p),h=r.screenPointToLocation(m),g=this.cameraHelper.handleFlyTo(r,{bearing:l,pitch:u,roll:d,padding:f,locationAtOffset:h,offsetAsPoint:p,center:e.center,minZoom:e.minZoom,zoom:e.zoom}),_=e.curve,v=Math.max(r.width,r.height),y=v/g.scaleOfZoom,b=g.pixelPathLength;typeof g.scaleOfMinZoom==`number`&&(_=Math.sqrt(v/g.scaleOfMinZoom/b*2));let x=_*_;function S(e){let t=(y*y-v*v+(e?-1:1)*x*x*b*b)/(2*(e?y:v)*x*b);return Math.log(Math.sqrt(t*t+1)-t)}function C(e){return(Math.exp(e)-Math.exp(-e))/2}function w(e){return(Math.exp(e)+Math.exp(-e))/2}let T=S(!1),E=function(e){return w(T)/w(T+_*e)},D=function(e){return v*((w(T)*(C(t=T+_*e)/w(t))-C(T))/x)/b;var t},O=(S(!0)-T)/_;if(Math.abs(b)<2e-6||!isFinite(O)){if(Math.abs(v-y)<1e-6)return this.easeTo(e,n);let t=y<v?-1:1;O=Math.abs(Math.log(y/v))/_,D=()=>0,E=e=>Math.exp(t*_*e)}return e.duration=`duration`in e?+e.duration:1e3*O/(`screenSpeed`in e?+e.screenSpeed/_:+e.speed),e.maxDuration&&e.duration>e.maxDuration&&(e.duration=0),this._zooming=!0,this._rotating=i!==l,this._pitching=u!==a,this._rolling=d!==o,this._padding=!r.isPaddingEqual(f),this._prepareEase(n,!1),this.terrain&&this._prepareElevation(g.targetCenter),this._ease((s=>{let h=s*O,_=1/E(h),v=D(h);this._rotating&&r.setBearing(t.H.number(i,l,s)),this._pitching&&r.setPitch(t.H.number(a,u,s)),this._rolling&&r.setRoll(t.H.number(o,d,s)),this._padding&&(r.interpolatePadding(c,f,s),m=r.centerPoint.add(p)),g.easeFunc(s,_,v,m),this.terrain&&!e.freezeElevation&&this._updateElevation(s),this._applyUpdatedTransform(r),this._fireMoveEvents(n)}),(()=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(n)}),e),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_stop(e,t){var n;if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){let e=this._onEaseEnd;delete this._onEaseEnd,e.call(this,t)}return e||(n=this.handlers)==null||n.stop(!1),this}_ease(e,t,n){!1===n.animate||n.duration===0?(e(1),t()):(this._easeStart=l(),this._easeOptions=n,this._onEaseFrame=e,this._onEaseEnd=t,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_normalizeBearing(e,n){e=t.X(e,-180,180);let r=Math.abs(e-n);return Math.abs(e-360-n)<r&&(e-=360),Math.abs(e+360-n)<r&&(e+=360),e}queryTerrainElevation(e){return this.terrain?this.terrain.getElevationForLngLat(t.W.convert(e),this.transform):null}}let Ka={compact:!0,customAttribution:`<a href="https://maplibre.org/" target="_blank">MapLibre</a>`};class qa{constructor(e=Ka){this._toggleAttribution=()=>{this._container.classList.contains(`maplibregl-compact`)&&(this._container.classList.contains(`maplibregl-compact-show`)?(this._container.setAttribute(`open`,``),this._container.classList.remove(`maplibregl-compact-show`)):(this._container.classList.add(`maplibregl-compact-show`),this._container.removeAttribute(`open`)))},this._updateData=e=>{!e||e.sourceDataType!==`metadata`&&e.sourceDataType!==`visibility`&&e.dataType!==`style`&&e.type!==`terrain`||this._updateAttributions()},this._updateCompact=()=>{this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1===this._compact?this._container.setAttribute(`open`,``):this._container.classList.contains(`maplibregl-compact`)||this._container.classList.contains(`maplibregl-attrib-empty`)||(this._container.setAttribute(`open`,``),this._container.classList.add(`maplibregl-compact`,`maplibregl-compact-show`)):(this._container.setAttribute(`open`,``),this._container.classList.contains(`maplibregl-compact`)&&this._container.classList.remove(`maplibregl-compact`,`maplibregl-compact-show`))},this._updateCompactMinimize=()=>{this._container.classList.contains(`maplibregl-compact`)&&this._container.classList.contains(`maplibregl-compact-show`)&&this._container.classList.remove(`maplibregl-compact-show`)},this.options=e}getDefaultPosition(){return`bottom-right`}onAdd(e){return this._map=e,this._compact=this.options.compact,this._container=d.create(`details`,`maplibregl-ctrl maplibregl-ctrl-attrib`),this._compactButton=d.create(`summary`,`maplibregl-ctrl-attrib-button`,this._container),this._compactButton.addEventListener(`click`,this._toggleAttribution),this._setElementTitle(this._compactButton,`ToggleAttribution`),this._innerContainer=d.create(`div`,`maplibregl-ctrl-attrib-inner`,this._container),this._updateAttributions(),this._updateCompact(),this._map.on(`styledata`,this._updateData),this._map.on(`sourcedata`,this._updateData),this._map.on(`terrain`,this._updateData),this._map.on(`resize`,this._updateCompact),this._map.on(`drag`,this._updateCompactMinimize),this._container}onRemove(){this._container.remove(),this._map.off(`styledata`,this._updateData),this._map.off(`sourcedata`,this._updateData),this._map.off(`terrain`,this._updateData),this._map.off(`resize`,this._updateCompact),this._map.off(`drag`,this._updateCompactMinimize),this._map=void 0,this._compact=void 0,this._attribHTML=void 0}_setElementTitle(e,t){let n=this._map._getUIString(`AttributionControl.${t}`);e.title=n,e.setAttribute(`aria-label`,n)}_updateAttributions(){if(!this._map.style)return;let e=[];if(this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?e=e.concat(this.options.customAttribution.map((e=>typeof e==`string`?e:``))):typeof this.options.customAttribution==`string`&&e.push(this.options.customAttribution)),this._map.style.stylesheet){let e=this._map.style.stylesheet;this.styleOwner=e.owner,this.styleId=e.id}let t=this._map.style.tileManagers;for(let n in t){let r=t[n];if(r.used||r.usedForTerrain){let t=r.getSource();t.attribution&&!e.includes(t.attribution)&&e.push(t.attribution)}}e=e.filter((e=>String(e).trim())),e.sort(((e,t)=>e.length-t.length)),e=e.filter(((t,n)=>{for(let r=n+1;r<e.length;r++)if(e[r].includes(t))return!1;return!0}));let n=e.join(` | `);n!==this._attribHTML&&(this._attribHTML=n,e.length?(this._innerContainer.innerHTML=d.sanitize(n),this._container.classList.remove(`maplibregl-attrib-empty`)):this._container.classList.add(`maplibregl-attrib-empty`),this._updateCompact(),this._editLink=null)}}class Ja{constructor(e={}){this._updateCompact=()=>{let e=this._container.children;if(e.length){let t=e[0];this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1!==this._compact&&t.classList.add(`maplibregl-compact`):t.classList.remove(`maplibregl-compact`)}},this.options=e}getDefaultPosition(){return`bottom-left`}onAdd(e){this._map=e,this._compact=this.options?.compact,this._container=d.create(`div`,`maplibregl-ctrl`);let t=d.create(`a`,`maplibregl-ctrl-logo`);return t.target=`_blank`,t.rel=`noopener nofollow`,t.href=`https://maplibre.org/`,t.setAttribute(`aria-label`,this._map._getUIString(`LogoControl.Title`)),t.setAttribute(`rel`,`noopener nofollow`),this._container.appendChild(t),this._container.style.display=`block`,this._map.on(`resize`,this._updateCompact),this._updateCompact(),this._container}onRemove(){this._container.remove(),this._map.off(`resize`,this._updateCompact),this._map=void 0,this._compact=void 0}}class Ya{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1}add(e){let t=++this._id;return this._queue.push({callback:e,id:t,cancelled:!1}),t}remove(e){let t=this._currentlyRunning,n=t?this._queue.concat(t):this._queue;for(let t of n)if(t.id===e)return void(t.cancelled=!0)}run(e=0){if(this._currentlyRunning)throw Error(`Attempting to run(), but is already running.`);let t=this._currentlyRunning=this._queue;this._queue=[];for(let n of t)if(!n.cancelled&&(n.callback(e),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]}}var Xa=t.aS([{name:`a_pos3d`,type:`Int16`,components:3}]);class Za extends t.E{constructor(e){super(),this._lastTilesetChange=l(),this.tileManager=e,this._tiles={},this._renderableTilesKeys=[],this._sourceTileCache={},this.minzoom=0,this.maxzoom=22,this.deltaZoom=1,this.tileSize=e._source.tileSize*2**this.deltaZoom,e.usedForTerrain=!0,e.tileSize=this.tileSize}destruct(){this.tileManager.usedForTerrain=!1,this.tileManager.tileSize=null}getSource(){return this.tileManager._source}update(e,n){this.tileManager.update(e,n),this._renderableTilesKeys=[];let r={};for(let i of We(e,{tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,reparseOverscaled:!1,terrain:n,calculateTileZoom:this.tileManager._source.calculateTileZoom}))r[i.key]=!0,this._renderableTilesKeys.push(i.key),this._tiles[i.key]||(i.terrainRttPosMatrix32f=new Float64Array(16),t.c7(i.terrainRttPosMatrix32f,0,t.a6,t.a6,0,0,1),this._tiles[i.key]=new Pe(i,this.tileSize),this._lastTilesetChange=l());for(let e in this._tiles)r[e]||delete this._tiles[e]}freeRtt(e){for(let t in this._tiles){let n=this._tiles[t];(!e||n.tileID.equals(e)||n.tileID.isChildOf(e)||e.isChildOf(n.tileID))&&(n.rtt=[])}}getRenderableTiles(){return this._renderableTilesKeys.map((e=>this.getTileByID(e)))}getTileByID(e){return this._tiles[e]}getTerrainCoords(e,t){return t?this._getTerrainCoordsForTileRanges(e,t):this._getTerrainCoordsForRegularTile(e)}_getTerrainCoordsForRegularTile(e){let n={};for(let r of this._renderableTilesKeys){let i=this._tiles[r].tileID,a=e.clone(),o=t.bj();if(i.canonical.equals(e.canonical))t.c7(o,0,t.a6,t.a6,0,0,1);else if(i.canonical.isChildOf(e.canonical)){let n=i.canonical.z-e.canonical.z,r=i.canonical.x-(i.canonical.x>>n<<n),a=i.canonical.y-(i.canonical.y>>n<<n),s=t.a6>>n;t.c7(o,0,s,s,0,0,1),t.Q(o,o,[-r*s,-a*s,0])}else{if(!e.canonical.isChildOf(i.canonical))continue;{let n=e.canonical.z-i.canonical.z,r=e.canonical.x-(e.canonical.x>>n<<n),a=e.canonical.y-(e.canonical.y>>n<<n),s=t.a6>>n;t.c7(o,0,t.a6,t.a6,0,0,1),t.Q(o,o,[r*s,a*s,0]),t.S(o,o,[1/2**n,1/2**n,0])}}a.terrainRttPosMatrix32f=new Float32Array(o),n[r]=a}return n}_getTerrainCoordsForTileRanges(e,n){let r={};for(let i of this._renderableTilesKeys){let a=this._tiles[i].tileID;if(!this._isWithinTileRanges(a,n))continue;let o=e.clone(),s=t.bj();if(a.canonical.z===e.canonical.z){let n=e.canonical.x-a.canonical.x+e.wrap*(1<<e.canonical.z),r=e.canonical.y-a.canonical.y;t.c7(s,0,t.a6,t.a6,0,0,1),t.Q(s,s,[n*t.a6,r*t.a6,0])}else if(a.canonical.z>e.canonical.z){let n=a.canonical.z-e.canonical.z,r=a.canonical.x-(a.canonical.x>>n<<n)+e.wrap*(1<<a.canonical.z),i=a.canonical.y-(a.canonical.y>>n<<n),o=e.canonical.x-(a.canonical.x>>n),c=e.canonical.y-(a.canonical.y>>n),l=t.a6>>n;t.c7(s,0,l,l,0,0,1),t.Q(s,s,[-r*l+o*t.a6,-i*l+c*t.a6,0])}else{let n=e.canonical.z-a.canonical.z,r=e.canonical.x-(e.canonical.x>>n<<n)+e.wrap*(1<<e.canonical.z),i=e.canonical.y-(e.canonical.y>>n<<n),o=(e.canonical.x>>n)-a.canonical.x,c=(e.canonical.y>>n)-a.canonical.y,l=t.a6<<n;t.c7(s,0,l,l,0,0,1),t.Q(s,s,[r*t.a6+o*l,i*t.a6+c*l,0])}o.terrainRttPosMatrix32f=new Float32Array(s),r[i]=o}return r}getSourceTile(e,t){var n,r;let i=this.tileManager._source,a=e.overscaledZ-this.deltaZoom;if(a>i.maxzoom&&(a=i.maxzoom),a<i.minzoom)return;(n=this._sourceTileCache)[r=e.key]||(n[r]=e.scaledTo(a).key);let o=this.findTileInCaches(this._sourceTileCache[e.key]);if(!o?.dem&&t)for(;a>=i.minzoom&&!o?.dem;)o=this.findTileInCaches(e.scaledTo(a--).key);return o}findTileInCaches(e){let t=this.tileManager.getTileByID(e);return t||(t=this.tileManager._outOfViewCache.getByKey(e),t)}anyTilesAfterTime(e=Date.now()){return this._lastTilesetChange>=e}_isWithinTileRanges(e,t){let n=t[e.canonical.z];return!!n&&(e.wrap>n.minWrap||e.wrap<n.maxWrap||e.canonical.x>=n.minTileXWrapped&&e.canonical.x<=n.maxTileXWrapped&&e.canonical.y>=n.minTileY&&e.canonical.y<=n.maxTileY)}}class Qa{constructor(e,t,n){this._meshCache={},this.painter=e,this.tileManager=new Za(t),this.options=n,this.exaggeration=typeof n.exaggeration==`number`?n.exaggeration:1,this.qualityFactor=2,this.meshSize=128,this._demMatrixCache={},this.coordsIndex=[],this._coordsTextureSize=1024}destroy(){this._fbo&&=(this._fbo.destroy(),null),this._fboCoordsTexture&&=(this._fboCoordsTexture.destroy(),null),this._fboDepthTexture&&=(this._fboDepthTexture.destroy(),null),this._emptyDemTexture&&=(this._emptyDemTexture.destroy(),null),this._emptyDepthTexture&&=(this._emptyDepthTexture.destroy(),null),this._coordsTexture&&=(this._coordsTexture.destroy(),null);for(let e in this._meshCache)this._meshCache[e].destroy();this._meshCache={},this.tileManager.destruct()}getDEMElevation(e,n,r,i=t.a6){let a=e.normalizeCoordinates(n,r,i);if(!a)return 0;let o=this.getTerrainData(a.tileID),s=o.tile?.dem;if(!s)return 0;let c=t.cC([],[a.x/i*t.a6,a.y/i*t.a6],o.u_terrain_matrix),l=[c[0]*s.dim,c[1]*s.dim],u=Math.floor(l[0]),d=Math.floor(l[1]),f=l[0]-u,p=l[1]-d;return s.get(u,d)*(1-f)*(1-p)+s.get(u+1,d)*f*(1-p)+s.get(u,d+1)*(1-f)*p+s.get(u+1,d+1)*f*p}getElevationForLngLatZoom(e,n){if(!t.cD(n,e.wrap()))return 0;let{tileID:r,mercatorX:i,mercatorY:a}=this._getOverscaledTileIDFromLngLatZoom(e,n);return this.getElevation(r,i%t.a6,a%t.a6,t.a6)}getElevationForLngLat(e,t){let n=We(t,{maxzoom:this.tileManager.maxzoom,minzoom:this.tileManager.minzoom,tileSize:512,terrain:this}),r=0;for(let e of n)e.canonical.z>r&&(r=Math.min(e.canonical.z,this.tileManager.maxzoom));return this.getElevationForLngLatZoom(e,r)}getElevation(e,n,r,i=t.a6){return this.getDEMElevation(e,n,r,i)*this.exaggeration}getTerrainData(e){if(!this._emptyDemTexture){let e=this.painter.context,n=new t.R({width:1,height:1},new Uint8Array(4));this._emptyDepthTexture=new t.T(e,n,e.gl.RGBA,{premultiply:!1}),this._emptyDemUnpack=[0,0,0,0],this._emptyDemTexture=new t.T(e,new t.R({width:1,height:1}),e.gl.RGBA,{premultiply:!1}),this._emptyDemTexture.bind(e.gl.NEAREST,e.gl.CLAMP_TO_EDGE),this._emptyDemMatrix=t.ap([])}let n=this.tileManager.getSourceTile(e,!0);if(n?.dem&&(!n.demTexture||n.needsTerrainPrepare)){let e=this.painter.context;n.demTexture=this.painter.getTileTexture(n.dem.stride),n.demTexture?n.demTexture.update(n.dem.getPixels(),{premultiply:!1}):n.demTexture=new t.T(e,n.dem.getPixels(),e.gl.RGBA,{premultiply:!1}),n.demTexture.bind(e.gl.NEAREST,e.gl.CLAMP_TO_EDGE),n.needsTerrainPrepare=!1}let r=n&&n.toString()+n.tileID.key+e.key;if(r&&!this._demMatrixCache[r]){let i=this.tileManager.getSource().maxzoom,a=e.canonical.z-n.tileID.canonical.z;e.overscaledZ>e.canonical.z&&(e.canonical.z>=i?a=e.canonical.z-i:t.w(`cannot calculate elevation if elevation maxzoom > source.maxzoom`));let o=e.canonical.x-(e.canonical.x>>a<<a),s=e.canonical.y-(e.canonical.y>>a<<a),c=t.cE(new Float64Array(16),[1/(t.a6<<a),1/(t.a6<<a),0]);t.Q(c,c,[o*t.a6,s*t.a6,0]),this._demMatrixCache[r]={matrix:c,coord:e}}return{u_depth:2,u_terrain:3,u_terrain_dim:n?.dem?.dim||1,u_terrain_matrix:r?this._demMatrixCache[r].matrix:this._emptyDemMatrix,u_terrain_unpack:(n?.dem)?.getUnpackVector()||this._emptyDemUnpack,u_terrain_exaggeration:this.exaggeration,texture:(n?.demTexture||this._emptyDemTexture).texture,depthTexture:(this._fboDepthTexture||this._emptyDepthTexture).texture,tile:n}}getFramebuffer(e){let n=this.painter,r=n.width/devicePixelRatio,i=n.height/devicePixelRatio;return!this._fbo||this._fbo.width===r&&this._fbo.height===i||(this._fbo.destroy(),this._fboCoordsTexture.destroy(),this._fboDepthTexture.destroy(),delete this._fbo,delete this._fboDepthTexture,delete this._fboCoordsTexture),this._fboCoordsTexture||(this._fboCoordsTexture=new t.T(n.context,{width:r,height:i,data:null},n.context.gl.RGBA,{premultiply:!1}),this._fboCoordsTexture.bind(n.context.gl.NEAREST,n.context.gl.CLAMP_TO_EDGE)),this._fboDepthTexture||(this._fboDepthTexture=new t.T(n.context,{width:r,height:i,data:null},n.context.gl.RGBA,{premultiply:!1}),this._fboDepthTexture.bind(n.context.gl.NEAREST,n.context.gl.CLAMP_TO_EDGE)),this._fbo||(this._fbo=n.context.createFramebuffer(r,i,!0,!1),this._fbo.depthAttachment.set(n.context.createRenderbuffer(n.context.gl.DEPTH_COMPONENT16,r,i))),this._fbo.colorAttachment.set(e===`coords`?this._fboCoordsTexture.texture:this._fboDepthTexture.texture),this._fbo}getCoordsTexture(){let e=this.painter.context;if(this._coordsTexture)return this._coordsTexture;let n=new Uint8Array(this._coordsTextureSize*this._coordsTextureSize*4);for(let e=0,t=0;e<this._coordsTextureSize;e++)for(let r=0;r<this._coordsTextureSize;r++,t+=4)n[t+0]=255&r,n[t+1]=255&e,n[t+2]=r>>8<<4|e>>8,n[t+3]=0;let r=new t.R({width:this._coordsTextureSize,height:this._coordsTextureSize},new Uint8Array(n.buffer)),i=new t.T(e,r,e.gl.RGBA,{premultiply:!1});return i.bind(e.gl.NEAREST,e.gl.CLAMP_TO_EDGE),this._coordsTexture=i,i}pointCoordinate(e){this.painter.maybeDrawDepth(!0),this.painter.maybeDrawCoords();let n=new Uint8Array(4),r=this.painter.context,i=r.gl,a=Math.round(e.x*this.painter.pixelRatio/devicePixelRatio),o=Math.round(e.y*this.painter.pixelRatio/devicePixelRatio),s=Math.round(this.painter.height/devicePixelRatio);r.bindFramebuffer.set(this.getFramebuffer(`coords`).framebuffer),i.readPixels(a,s-o-1,1,1,i.RGBA,i.UNSIGNED_BYTE,n),r.bindFramebuffer.set(null);let c=n[0]+(n[2]>>4<<8),l=n[1]+((15&n[2])<<8),u=this.coordsIndex[255-n[3]],d=u&&this.tileManager.getTileByID(u);if(!d)return null;let f=this._coordsTextureSize,p=(1<<d.tileID.canonical.z)*f;return new t.a7((d.tileID.canonical.x*f+c)/p+d.tileID.wrap,(d.tileID.canonical.y*f+l)/p,this.getElevation(d.tileID,c,l,f))}depthAtPoint(e){let t=new Uint8Array(4),n=this.painter.context,r=n.gl;return n.bindFramebuffer.set(this.getFramebuffer(`depth`).framebuffer),r.readPixels(e.x,this.painter.height/devicePixelRatio-e.y-1,1,1,r.RGBA,r.UNSIGNED_BYTE,t),n.bindFramebuffer.set(null),(t[0]/16777216+t[1]/65536+t[2]/256+t[3])/256}getTerrainMesh(e){let n=this.painter.style.projection?.transitionState>0,r=n&&e.canonical.y===0,i=n&&e.canonical.y===(1<<e.canonical.z)-1,a=`m_${r?`n`:``}_${i?`s`:``}`;if(this._meshCache[a])return this._meshCache[a];let o=this.painter.context,s=new t.cF,c=new t.aW,l=this.meshSize,u=t.a6/l,d=l*l;for(let e=0;e<=l;e++)for(let t=0;t<=l;t++)s.emplaceBack(t*u,e*u,0);for(let e=0;e<d;e+=l+1)for(let t=0;t<l;t++)c.emplaceBack(t+e,l+t+e+1,l+t+e+2),c.emplaceBack(t+e,l+t+e+2,t+e+1);let f=s.length,p=f+(l+1),m=(l+1)*l,h=r?t.bq:0,g=+!r,_=i?t.br:t.a6,v=+!i;for(let e=0;e<=l;e++)s.emplaceBack(e*u,h,g);for(let e=0;e<=l;e++)s.emplaceBack(e*u,_,v);for(let e=0;e<l;e++)c.emplaceBack(m+e,p+e,p+e+1),c.emplaceBack(m+e,p+e+1,m+e+1),c.emplaceBack(0+e,f+e+1,f+e),c.emplaceBack(0+e,0+e+1,f+e+1);let y=s.length,b=y+2*(l+1);for(let e of[0,1])for(let n=0;n<=l;n++)for(let r of[0,1])s.emplaceBack(e*t.a6,n*u,r);for(let e=0;e<2*l;e+=2)c.emplaceBack(y+e,y+e+1,y+e+3),c.emplaceBack(y+e,y+e+3,y+e+2),c.emplaceBack(b+e,b+e+3,b+e+1),c.emplaceBack(b+e,b+e+2,b+e+3);let x=new Jt(o.createVertexBuffer(s,Xa.members),o.createIndexBuffer(c),t.aV.simpleSegment(0,0,s.length,c.length));return this._meshCache[a]=x,x}getMeshFrameDelta(e){return 2*Math.PI*t.bD/2**Math.max(e,0)/5}getMinTileElevationForLngLatZoom(e,n){if(!t.cD(n,e.wrap()))return 0;let{tileID:r}=this._getOverscaledTileIDFromLngLatZoom(e,n);return this.getMinMaxElevation(r).minElevation??0}getMinMaxElevation(e){let t=this.getTerrainData(e).tile,n={minElevation:null,maxElevation:null};return t!=null&&t.dem&&(n.minElevation=t.dem.min*this.exaggeration,n.maxElevation=t.dem.max*this.exaggeration),n}_getOverscaledTileIDFromLngLatZoom(e,n){let r=t.a7.fromLngLat(e.wrap()),i=(1<<n)*t.a6,a=r.x*i,o=r.y*i,s=Math.floor(a/t.a6),c=Math.floor(o/t.a6);return{tileID:new t.a3(n,0,n,s,c),mercatorX:a,mercatorY:o}}}class $a{constructor(e,t,n){this._context=e,this._size=t,this._tileSize=n,this._objects=[],this._recentlyUsed=[],this._stamp=0}destruct(){for(let e of this._objects)e.texture.destroy(),e.fbo.destroy()}_createObject(e){let n=this._context.createFramebuffer(this._tileSize,this._tileSize,!0,!0),r=new t.T(this._context,{width:this._tileSize,height:this._tileSize,data:null},this._context.gl.RGBA);return r.bind(this._context.gl.LINEAR,this._context.gl.CLAMP_TO_EDGE),this._context.extTextureFilterAnisotropic&&this._context.gl.texParameterf(this._context.gl.TEXTURE_2D,this._context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,this._context.extTextureFilterAnisotropicMax),n.depthAttachment.set(this._context.createRenderbuffer(this._context.gl.DEPTH_STENCIL,this._tileSize,this._tileSize)),n.colorAttachment.set(r.texture),{id:e,fbo:n,texture:r,stamp:-1,inUse:!1}}getObjectForId(e){return this._objects[e]}useObject(e){e.inUse=!0,this._recentlyUsed=this._recentlyUsed.filter((t=>e.id!==t)),this._recentlyUsed.push(e.id)}stampObject(e){e.stamp=++this._stamp}getOrCreateFreeObject(){for(let e of this._recentlyUsed)if(!this._objects[e].inUse)return this._objects[e];if(this._objects.length>=this._size)throw Error(`No free RenderPool available, call freeAllObjects() required!`);let e=this._createObject(this._objects.length);return this._objects.push(e),e}freeObject(e){e.inUse=!1}freeAllObjects(){for(let e of this._objects)this.freeObject(e)}isFull(){return!(this._objects.length<this._size)&&!1===this._objects.some((e=>!e.inUse))}}let eo={background:!0,fill:!0,line:!0,raster:!0,hillshade:!0,"color-relief":!0};class to{constructor(e,t){this.painter=e,this.terrain=t,this.pool=new $a(e.context,30,t.tileManager.tileSize*t.qualityFactor)}destruct(){this.pool.destruct()}getTexture(e){return this.pool.getObjectForId(e.rtt[this._stacks.length-1].id).texture}prepareForRender(e,t){var n;this._stacks=[],this._prevType=null,this._rttTiles=[],this._renderableTiles=this.terrain.tileManager.getRenderableTiles(),this._renderableLayerIds=e._order.filter((n=>!e._layers[n].isHidden(t))),this._coordsAscending={};for(let t in e.tileManagers){this._coordsAscending[t]={};let r=e.tileManagers[t].getVisibleCoordinates(),i=e.tileManagers[t].getSource(),a=i instanceof Ce?i.terrainTileRanges:null;for(let e of r){let r=this.terrain.tileManager.getTerrainCoords(e,a);for(let e in r)(n=this._coordsAscending[t])[e]||(n[e]=[]),this._coordsAscending[t][e].push(r[e])}}this._rttFingerprints={};for(let t of e._order){let n=e._layers[t],r=n.source;if(eo[n.type]&&!this._rttFingerprints[r]){this._rttFingerprints[r]={};let t=e.tileManagers[r]?.getState().revision??0;for(let e in this._coordsAscending[r])this._rttFingerprints[r][e]=`${this._coordsAscending[r][e].map((e=>e.key)).sort().join()}#${t}`}}for(let e of this._renderableTiles)for(let t in this._rttFingerprints){let n=this._rttFingerprints[t][e.tileID.key];n&&n!==e.rttFingerprint[t]&&(e.rtt=[])}}renderLayer(e,n){if(e.isHidden(this.painter.transform.zoom))return!1;let r=Object.assign(Object.assign({},n),{isRenderingToTexture:!0}),i=e.type,a=this.painter,o=this._renderableLayerIds[this._renderableLayerIds.length-1]===e.id;if(eo[i]&&(this._prevType&&eo[this._prevType]||this._stacks.push([]),this._prevType=i,this._stacks[this._stacks.length-1].push(e.id),!o))return!0;if(eo[this._prevType]||eo[i]&&o){this._prevType=i;let e=this._stacks.length-1,n=this._stacks[e]||[];for(let i of this._renderableTiles){if(this.pool.isFull()&&(Ki(this.painter,this.terrain,this._rttTiles,r),this._rttTiles=[],this.pool.freeAllObjects()),this._rttTiles.push(i),i.rtt[e]){let t=this.pool.getObjectForId(i.rtt[e].id);if(t.stamp===i.rtt[e].stamp){this.pool.useObject(t);continue}}let o=this.pool.getOrCreateFreeObject();this.pool.useObject(o),this.pool.stampObject(o),i.rtt[e]={id:o.id,stamp:o.stamp},a.context.bindFramebuffer.set(o.fbo.framebuffer),a.context.clear({color:t.bo.transparent,stencil:0}),a.currentStencilSource=void 0;for(let e of n){let t=a.style._layers[e],n=t.source?this._coordsAscending[t.source][i.tileID.key]:[i.tileID];a.context.viewport.set([0,0,o.fbo.width,o.fbo.height]),a._renderTileClippingMasks(t,n,!0),a.renderLayer(a,a.style.tileManagers[t.source],t,n,r),t.source&&(i.rttFingerprint[t.source]=this._rttFingerprints[t.source][i.tileID.key])}}return Ki(this.painter,this.terrain,this._rttTiles,r),this._rttTiles=[],this.pool.freeAllObjects(),eo[i]}return!1}}let no={"AttributionControl.ToggleAttribution":`Toggle attribution`,"AttributionControl.MapFeedback":`Map feedback`,"FullscreenControl.Enter":`Enter fullscreen`,"FullscreenControl.Exit":`Exit fullscreen`,"GeolocateControl.FindMyLocation":`Find my location`,"GeolocateControl.LocationNotAvailable":`Location not available`,"LogoControl.Title":`MapLibre logo`,"Map.Title":`Map`,"Marker.Title":`Map marker`,"NavigationControl.ResetBearing":`Drag to rotate map, click to reset north`,"NavigationControl.ZoomIn":`Zoom in`,"NavigationControl.ZoomOut":`Zoom out`,"Popup.Close":`Close popup`,"ScaleControl.Feet":`ft`,"ScaleControl.Meters":`m`,"ScaleControl.Kilometers":`km`,"ScaleControl.Miles":`mi`,"ScaleControl.NauticalMiles":`nm`,"GlobeControl.Enable":`Enable globe`,"GlobeControl.Disable":`Disable globe`,"TerrainControl.Enable":`Enable terrain`,"TerrainControl.Disable":`Disable terrain`,"CooperativeGesturesHandler.WindowsHelpText":`Use Ctrl + scroll to zoom the map`,"CooperativeGesturesHandler.MacHelpText":`Use ⌘ + scroll to zoom the map`,"CooperativeGesturesHandler.MobileHelpText":`Use two fingers to move the map`},ro=n,io={hash:!1,interactive:!0,bearingSnap:7,zoomSnap:0,attributionControl:Ka,maplibreLogo:!1,refreshExpiredTiles:!0,canvasContextAttributes:{antialias:!1,preserveDrawingBuffer:!1,powerPreference:`high-performance`,failIfMajorPerformanceCaveat:!1,desynchronized:!1,contextType:void 0},scrollZoom:!0,minZoom:-2,maxZoom:22,minPitch:0,maxPitch:60,boxZoom:!0,dragRotate:!0,dragPan:!0,keyboard:!0,doubleClickZoom:!0,touchZoomRotate:!0,touchPitch:!0,cooperativeGestures:!1,trackResize:!0,center:[0,0],elevation:0,zoom:0,bearing:0,pitch:0,roll:0,renderWorldCopies:!0,maxTileCacheSize:null,maxTileCacheZoomLevels:t.c.MAX_TILE_CACHE_ZOOM_LEVELS,transformRequest:null,transformCameraUpdate:null,transformConstrain:null,fadeDuration:300,crossSourceCollisions:!0,clickTolerance:3,localIdeographFontFamily:`sans-serif`,pitchWithRotate:!0,rollEnabled:!1,reduceMotion:void 0,validateStyle:!0,maxCanvasSize:[4096,4096],cancelPendingTileRequestsWhileZooming:!0,centerClampedToGround:!0,experimentalZoomLevelsToOverscale:void 0,anisotropicFilterPitch:20},ao=class extends ${get _ownerWindow(){return this._container?.ownerDocument?.defaultView||window}constructor(e){var n;let r=Object.assign(Object.assign(Object.assign({},io),e),{canvasContextAttributes:Object.assign(Object.assign({},io.canvasContextAttributes),e.canvasContextAttributes)});if(r.minZoom!=null&&r.maxZoom!=null&&r.minZoom>r.maxZoom)throw Error(`maxZoom must be greater than or equal to minZoom`);if(r.minPitch!=null&&r.maxPitch!=null&&r.minPitch>r.maxPitch)throw Error(`maxPitch must be greater than or equal to minPitch`);if(r.minPitch!=null&&r.minPitch<0)throw Error(`minPitch must be greater than or equal to 0`);if(r.maxPitch!=null&&r.maxPitch>180)throw Error(`maxPitch must be less than or equal to 180`);let i=new on,a=new ln;r.minZoom!==void 0&&i.setMinZoom(r.minZoom),r.maxZoom!==void 0&&i.setMaxZoom(r.maxZoom),r.minPitch!==void 0&&i.setMinPitch(r.minPitch),r.maxPitch!==void 0&&i.setMaxPitch(r.maxPitch),r.renderWorldCopies!==void 0&&i.setRenderWorldCopies(r.renderWorldCopies),r.transformConstrain!==null&&i.setConstrainOverride(r.transformConstrain),super(i,a,{bearingSnap:r.bearingSnap,zoomSnap:r.zoomSnap}),this._idleTriggered=!1,this._crossFadingFactor=1,this._renderTaskQueue=new Ya,this._controls=[],this._mapId=t.ad(),this._lostContextStyle={style:null,images:null},this._contextLost=e=>{if(e.preventDefault(),this._frameRequest&&=(this._frameRequest.abort(),null),this.painter.destroy(),this._lostContextStyle=this._getStyleAndImages(),this.style){for(let e of Object.values(this.style._layers))if(e.type===`custom`&&console.warn(`Custom layer with id '${e.id}' cannot be restored after WebGL context loss. You will need to re-add it manually after context restoration.`),e._listeners)for(let[t]of Object.entries(e._listeners))console.warn(`Custom layer with id '${e.id}' had event listeners for event '${t}' which cannot be restored after WebGL context loss. You will need to re-add them manually after context restoration.`);this.style.destroy(),this.style=null,this.fire(new t.n(`webglcontextlost`,{originalEvent:e}))}else this.fire(new t.n(`webglcontextlost`,{originalEvent:e}))},this._contextRestored=e=>{this._lostContextStyle.style&&this.setStyle(this._lostContextStyle.style,{diff:!1}),this._lostContextStyle.images&&this.style&&(this.style.imageManager.images=this._lostContextStyle.images),this._lostContextStyle={style:null,images:null},this._setupPainter(),this.resize(),this._update(),this._resizeInternal(),this.fire(new t.n(`webglcontextrestored`,{originalEvent:e}))},this._onMapScroll=e=>{if(e.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1},this._onWindowOnline=()=>{this._update()},this._interactive=r.interactive,this._maxTileCacheSize=r.maxTileCacheSize,this._maxTileCacheZoomLevels=r.maxTileCacheZoomLevels,this._canvasContextAttributes=Object.assign({},r.canvasContextAttributes),this._trackResize=!0===r.trackResize,this._bearingSnap=r.bearingSnap,this._zoomSnap=r.zoomSnap,this._centerClampedToGround=r.centerClampedToGround,this._refreshExpiredTiles=!0===r.refreshExpiredTiles,this._fadeDuration=r.fadeDuration,this._crossSourceCollisions=!0===r.crossSourceCollisions,this._collectResourceTiming=!0===r.collectResourceTiming,this._locale=Object.assign(Object.assign({},no),r.locale),this._clickTolerance=r.clickTolerance,this._overridePixelRatio=r.pixelRatio,this._maxCanvasSize=r.maxCanvasSize,this._zoomLevelsToOverscale=r.experimentalZoomLevelsToOverscale,this.transformCameraUpdate=r.transformCameraUpdate,this.transformConstrain=r.transformConstrain,this.cancelPendingTileRequestsWhileZooming=!0===r.cancelPendingTileRequestsWhileZooming,this.setAnisotropicFilterPitch(r.anisotropicFilterPitch),r.reduceMotion!==void 0&&(s.prefersReducedMotion=r.reduceMotion),this._imageQueueHandle=u.addThrottleControl((()=>this.isMoving())),this._requestManager=new f(r.transformRequest),this._container=this._resolveContainer(r.container),r.maxBounds&&this.setMaxBounds(r.maxBounds),this._setupContainer(),this._setupPainter(),this.on(`move`,(()=>this._update(!1))),this.on(`moveend`,(()=>this._update(!1))),this.on(`zoom`,(()=>this._update(!0))),this.on(`terrain`,(()=>{this.painter.terrainFacilitator.depthDirty=!0,this._update(!0)})),this.once(`idle`,(()=>this._idleTriggered=!0)),typeof window<`u`&&(this._ownerWindow.addEventListener(`online`,this._onWindowOnline,!1),this._setupResizeObserver()),this.handlers=new Q(this,r),this._hash=r.hash?new Zi(typeof r.hash==`string`&&r.hash||void 0).addTo(this):void 0,(n=this._hash)!=null&&n._onHashChange()||(this.jumpTo({center:r.center,elevation:r.elevation,zoom:r.zoom,bearing:r.bearing,pitch:r.pitch,roll:r.roll}),r.bounds&&(this.resize(),this.fitBounds(r.bounds,t.e({},r.fitBoundsOptions,{duration:0}))));let o=typeof r.style==`string`||r.style?.projection?.type!==`globe`;this.resize(null,o),this._localIdeographFontFamily=r.localIdeographFontFamily,this._validateStyle=r.validateStyle,r.style&&this.setStyle(r.style,{localIdeographFontFamily:r.localIdeographFontFamily}),r.attributionControl&&this.addControl(new qa(typeof r.attributionControl==`boolean`?void 0:r.attributionControl)),r.maplibreLogo&&this.addControl(new Ja,r.logoPosition),this.on(`style.load`,(()=>{if(o||this._resizeTransform(),this.transform.unmodified){let e=t.V(this.style.stylesheet,[`center`,`zoom`,`bearing`,`pitch`,`roll`]);this.jumpTo(e)}})),this.on(`data`,(e=>{this._update(e.dataType===`style`),this.fire(new t.n(`${e.dataType}data`,e))})),this.on(`dataloading`,(e=>{this.fire(new t.n(`${e.dataType}dataloading`,e))})),this.on(`dataabort`,(e=>{this.fire(new t.n(`sourcedataabort`,e))}))}_getMapId(){return this._mapId}setGlobalStateProperty(e,t){return this.style.setGlobalStateProperty(e,t),this._update(!0)}getGlobalState(){return this.style.getGlobalState()}addControl(e,n){if(n===void 0&&(n=e.getDefaultPosition?e.getDefaultPosition():`top-right`),!e?.onAdd)return this.fire(new t.l(Error(`Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.`)));let r=e.onAdd(this);this._controls.push(e);let i=this._controlPositions[n];return n.includes(`bottom`)?i.insertBefore(r,i.firstChild):i.appendChild(r),this}removeControl(e){if(!e?.onRemove)return this.fire(new t.l(Error(`Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.`)));let n=this._controls.indexOf(e);return n>-1&&this._controls.splice(n,1),e.onRemove(this),this}hasControl(e){return this._controls.includes(e)}coveringTiles(e){return We(this.transform,e)}calculateCameraOptionsFromTo(e,t,n,r){return r==null&&this.terrain&&(r=this.terrain.getElevationForLngLat(n,this.transform)),super.calculateCameraOptionsFromTo(e,t,n,r)}resize(e,n=!0){if(this._lostContextStyle.style!==null)return this;this._resizeInternal(n);let r=!this._moving;return r&&(this.stop(),this.fire(new t.n(`movestart`,e)).fire(new t.n(`move`,e))),this.fire(new t.n(`resize`,e)),r&&this.fire(new t.n(`moveend`,e)),this}_resizeInternal(e=!0){let[t,n]=this._containerDimensions(),r=this._getClampedPixelRatio(t,n);if(this._resizeCanvas(t,n,r),this.painter.resize(t,n,r),this.painter.overLimit()){let e=this.painter.context.gl;this._maxCanvasSize=[e.drawingBufferWidth,e.drawingBufferHeight];let r=this._getClampedPixelRatio(t,n);this._resizeCanvas(t,n,r),this.painter.resize(t,n,r)}this._resizeTransform(e)}_resizeTransform(e=!0){var t;let[n,r]=this._containerDimensions();this.transform.resize(n,r,e),(t=this._requestedCameraState)==null||t.resize(n,r,e)}_getClampedPixelRatio(e,t){let{0:n,1:r}=this._maxCanvasSize,i=this.getPixelRatio(),a=e*i,o=t*i;return Math.min(a>n?n/a:1,o>r?r/o:1)*i}getPixelRatio(){return this._overridePixelRatio??devicePixelRatio}setPixelRatio(e){this._overridePixelRatio=e,this.resize()}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()}setMaxBounds(e){return this.transform.setMaxBounds(de.convert(e)),this._update()}setMinZoom(e){if((e??=-2)>=-2&&e<=this.transform.maxZoom){let n=this.transform.zoom,r=this._getTransformForUpdate();return r.setMinZoom(e),this._applyUpdatedTransform(r),this._update(),n!==this.transform.zoom&&this.fire(new t.n(`zoomstart`)).fire(new t.n(`zoom`)).fire(new t.n(`zoomend`)).fire(new t.n(`movestart`)).fire(new t.n(`move`)).fire(new t.n(`moveend`)),this}throw Error(`minZoom must be between -2 and the current maxZoom, inclusive`)}getMinZoom(){return this.transform.minZoom}setMaxZoom(e){if((e??=22)>=this.transform.minZoom){let n=this.transform.zoom,r=this._getTransformForUpdate();return r.setMaxZoom(e),this._applyUpdatedTransform(r),this._update(),n!==this.transform.zoom&&this.fire(new t.n(`zoomstart`)).fire(new t.n(`zoom`)).fire(new t.n(`zoomend`)).fire(new t.n(`movestart`)).fire(new t.n(`move`)).fire(new t.n(`moveend`)),this}throw Error(`maxZoom must be greater than the current minZoom`)}getMaxZoom(){return this.transform.maxZoom}setMinPitch(e){if((e??=0)<0)throw Error(`minPitch must be greater than or equal to 0`);if(e>=0&&e<=this.transform.maxPitch){let n=this.transform.pitch,r=this._getTransformForUpdate();return r.setMinPitch(e),this._applyUpdatedTransform(r),this._update(),n!==this.transform.pitch&&this.fire(new t.n(`pitchstart`)).fire(new t.n(`pitch`)).fire(new t.n(`pitchend`)).fire(new t.n(`movestart`)).fire(new t.n(`move`)).fire(new t.n(`moveend`)),this}throw Error(`minPitch must be between 0 and the current maxPitch, inclusive`)}getMinPitch(){return this.transform.minPitch}setMaxPitch(e){if((e??=60)>180)throw Error(`maxPitch must be less than or equal to 180`);if(e>=this.transform.minPitch){let n=this.transform.pitch,r=this._getTransformForUpdate();return r.setMaxPitch(e),this._applyUpdatedTransform(r),this._update(),n!==this.transform.pitch&&this.fire(new t.n(`pitchstart`)).fire(new t.n(`pitch`)).fire(new t.n(`pitchend`)).fire(new t.n(`movestart`)).fire(new t.n(`move`)).fire(new t.n(`moveend`)),this}throw Error(`maxPitch must be greater than the current minPitch`)}getMaxPitch(){return this.transform.maxPitch}getAnisotropicFilterPitch(){return this._anisotropicFilterPitch}setAnisotropicFilterPitch(e){if((e??=20)>180)throw Error(`anisotropicFilterPitch must be less than or equal to 180`);if(e<0)throw Error(`anisotropicFilterPitch must be greater than or equal to 0`);return this._anisotropicFilterPitch=e,this._update()}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(e){return this.transform.setRenderWorldCopies(e),this._update()}setTransformConstrain(e){return this.transform.setConstrainOverride(e),this._update()}project(e){return this.transform.locationToScreenPoint(t.W.convert(e),this.style&&this.terrain)}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this.terrain)}isMoving(){return this._moving||this.handlers?.isMoving()}isZooming(){return this._zooming||this.handlers?.isZooming()}isRotating(){return this._rotating||this.handlers?.isRotating()}_createDelegatedListener(e,t,n){if(e===`mouseenter`||e===`mouseover`){let r=!1;return{layers:t,listener:n,delegates:{mousemove:i=>{let a=t.filter((e=>this.getLayer(e))),o=a.length===0?[]:this.queryRenderedFeatures(i.point,{layers:a});o.length?r||(r=!0,n.call(this,new oa(e,this,i.originalEvent,{features:o}))):r=!1},mouseout:()=>{r=!1}}}}if(e===`mouseleave`||e===`mouseout`){let r=!1;return{layers:t,listener:n,delegates:{mousemove:i=>{let a=t.filter((e=>this.getLayer(e)));(a.length===0?[]:this.queryRenderedFeatures(i.point,{layers:a})).length?r=!0:r&&(r=!1,n.call(this,new oa(e,this,i.originalEvent)))},mouseout:t=>{r&&(r=!1,n.call(this,new oa(e,this,t.originalEvent)))}}}}{let r=e=>{let r=t.filter((e=>this.getLayer(e))),i=r.length===0?[]:this.queryRenderedFeatures(e.point,{layers:r});i.length&&(e.features=i,n.call(this,e),delete e.features)};return{layers:t,listener:n,delegates:{[e]:r}}}}_saveDelegatedListener(e,t){var n;this._delegatedListeners||={},(n=this._delegatedListeners)[e]||(n[e]=[]),this._delegatedListeners[e].push(t)}_removeDelegatedListener(e,t,n){if(!this._delegatedListeners?.[e])return;let r=this._delegatedListeners[e];for(let e=0;e<r.length;e++){let i=r[e];if(i.listener===n&&i.layers.length===t.length&&i.layers.every((e=>t.includes(e)))){for(let e in i.delegates)this.off(e,i.delegates[e]);r.splice(e,1);return}}}on(e,t,n){if(n===void 0)return super.on(e,t);let r=typeof t==`string`?[t]:t,i=this._createDelegatedListener(e,r,n);this._saveDelegatedListener(e,i);for(let e in i.delegates)this.on(e,i.delegates[e]);return{unsubscribe:()=>{this._removeDelegatedListener(e,r,n)}}}once(e,t,n){if(n===void 0)return super.once(e,t);let r=typeof t==`string`?[t]:t,i=this._createDelegatedListener(e,r,n);for(let t in i.delegates){let a=i.delegates[t];i.delegates[t]=(...t)=>{this._removeDelegatedListener(e,r,n),a(...t)}}this._saveDelegatedListener(e,i);for(let e in i.delegates)this.once(e,i.delegates[e]);return this}off(e,t,n){return n===void 0?super.off(e,t):(this._removeDelegatedListener(e,typeof t==`string`?[t]:t,n),this)}queryRenderedFeatures(e,n){if(!this.style)return[];let r,i=e instanceof t.P||Array.isArray(e),a=i?e:[[0,0],[this.transform.width,this.transform.height]];if(n||=(i?{}:e)||{},a instanceof t.P||typeof a[0]==`number`)r=[t.P.convert(a)];else{let e=t.P.convert(a[0]),n=t.P.convert(a[1]);r=[e,new t.P(n.x,e.y),n,new t.P(e.x,n.y),e]}return this.style.queryRenderedFeatures(r,n,this.transform)}querySourceFeatures(e,t){return this.style.querySourceFeatures(e,t)}setStyle(e,n){return!1!==(n=t.e({},{localIdeographFontFamily:this._localIdeographFontFamily,validate:this._validateStyle},n)).diff&&n.localIdeographFontFamily===this._localIdeographFontFamily&&this.style&&e?(this._diffStyle(e,n),this):(this._localIdeographFontFamily=n.localIdeographFontFamily,this._updateStyle(e,n))}setTransformRequest(e){return this._requestManager.setTransformRequest(e),this}_getUIString(e){let t=this._locale[e];if(t==null)throw Error(`Missing UI string '${e}'`);return t}_updateStyle(e,t){var n,r;if((n=this._diffStyleRequest)==null||n.abort(),this._diffStyleRequest=null,t.transformStyle&&this.style&&!this.style._loaded)return void this.style.once(`style.load`,(()=>this._updateStyle(e,t)));let i=this.style&&t.transformStyle?this.style.serialize():void 0;return this.style&&(this.style.setEventedParent(null),this.style._remove(!e)),e?(this.style=new Un(this,t||{}),this.style.setEventedParent(this,{style:this.style}),typeof e==`string`?this.style.loadURL(e,t,i):this.style.loadJSON(e,t,i),this):(this._frameRequest&&=(this._frameRequest.abort(),null),(r=this.style?.projection)==null||r.destroy(),delete this.style,this)}_lazyInitEmptyStyle(){this.style||(this.style=new Un(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty())}_diffStyle(e,n){return t._(this,void 0,void 0,(function*(){var r;if((r=this._diffStyleRequest)==null||r.abort(),typeof e==`string`){let r=e;this._diffStyleRequest=new AbortController;let i=this._diffStyleRequest;try{let e=yield this._requestManager.transformRequest(r,`Style`);if(i.signal.aborted)return void(this._diffStyleRequest=null);let a=yield t.k(e,i);this._diffStyleRequest=null,this._updateDiff(a.data,n)}catch(e){this._diffStyleRequest=null,t.$(e)||this.fire(new t.l(t.d(e)))}}else typeof e==`object`&&(this._diffStyleRequest=null,this._updateDiff(e,n))}))}_updateDiff(e,n){try{this.style.setState(e,n)&&this._update(!0)}catch(r){t.w(`Unable to perform style diff: ${t.d(r).message}. Rebuilding the style from scratch.`),this._updateStyle(e,n)}}getStyle(){if(this.style)return this.style.serialize()}_getStyleAndImages(){return this.style?{style:this.style.serialize(),images:this.style.imageManager.cloneImages()}:{style:null,images:{}}}isStyleLoaded(){if(this.style)return this.style.loaded();t.w(`There is no style added to the map.`)}addSource(e,t){return this._lazyInitEmptyStyle(),this.style.addSource(e,t),this._update(!0)}isSourceLoaded(e){let n=this.style?.tileManagers[e];if(n!==void 0)return n.loaded();this.fire(new t.l(Error(`There is no tile manager with ID '${e}'`)))}setTerrain(e){if(this.style._checkLoaded(),this._terrainDataCallback&&this.style.off(`data`,this._terrainDataCallback),e){let n=this.style.tileManagers[e.source];if(!n)throw Error(`cannot load terrain, because there exists no source with ID: ${e.source}`);this.terrain===null&&n.reload();for(let n in this.style._layers){let r=this.style._layers[n];r.type===`hillshade`&&r.source===e.source&&t.w(`You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.`),r.type===`color-relief`&&r.source===e.source&&t.w(`You are using the same source for a color-relief layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.`)}this.terrain=new Qa(this.painter,n,e),this.painter.renderToTexture=new to(this.painter,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._terrainDataCallback=t=>{t.dataType===`style`?this.terrain.tileManager.freeRtt():t.dataType===`source`&&t.tile&&(t.sourceId!==e.source||this._elevationFreeze||(this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))),t.source?.type===`image`?this.terrain.tileManager.freeRtt():this.terrain.tileManager.freeRtt(t.tile.tileID))},this.style.on(`data`,this._terrainDataCallback)}else this.terrain&&this.terrain.destroy(),this.terrain=null,this.painter.renderToTexture&&this.painter.renderToTexture.destruct(),this.painter.renderToTexture=null,this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0);return this.fire(new t.n(`terrain`,{terrain:e})),this}getTerrain(){return this.terrain?.options??null}areTilesLoaded(){let e=this.style?.tileManagers;for(let t of Object.values(e))if(!t.areTilesLoaded())return!1;return!0}removeSource(e){return this.style.removeSource(e),this._update(!0)}getSource(e){return this.style.getSource(e)}setSourceTileLodParams(e,t,n){if(n){let r=this.getSource(n);if(!r)throw Error(`There is no source with ID "${n}", cannot set LOD parameters`);r.calculateTileZoom=N(Math.max(1,e),Math.max(1,t))}else for(let n in this.style.tileManagers)this.style.tileManagers[n].getSource().calculateTileZoom=N(Math.max(1,e),Math.max(1,t));return this._update(!0),this}refreshTiles(e,n){let r=this.style.tileManagers[e];if(!r)throw Error(`There is no tile manager with ID "${e}", cannot refresh tile`);n===void 0?r.reload(!0):r.refreshTiles(n.map((e=>new t.aa(e.z,e.x,e.y))))}addImage(e,n,r={}){let{pixelRatio:i=1,sdf:a=!1,stretchX:o,stretchY:c,content:l,textFitWidth:u,textFitHeight:d}=r;if(this._lazyInitEmptyStyle(),!(n instanceof HTMLImageElement||t.b(n))){if(n.width===void 0||n.height===void 0)return this.fire(new t.l(Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));{let{width:r,height:s,data:f}=n,p=n;return this.style.addImage(e,{data:new t.R({width:r,height:s},new Uint8Array(f)),pixelRatio:i,stretchX:o,stretchY:c,content:l,textFitWidth:u,textFitHeight:d,sdf:a,version:0,userImage:p}),p.onAdd&&p.onAdd(this,e),this}}{let{width:r,height:f,data:p}=s.getImageData(n);this.style.addImage(e,{data:new t.R({width:r,height:f},p),pixelRatio:i,stretchX:o,stretchY:c,content:l,textFitWidth:u,textFitHeight:d,sdf:a,version:0})}}updateImage(e,n){let r=this.style.getImage(e);if(!r)return this.fire(new t.l(Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));let{width:i,height:a,data:o}=n instanceof HTMLImageElement||t.b(n)?s.getImageData(n):n;if(i===void 0||a===void 0)return this.fire(new t.l(Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(i!==r.data.width||a!==r.data.height)return this.fire(new t.l(Error(`The width and height of the updated image must be that same as the previous version of the image`)));let c=!(n instanceof HTMLImageElement||t.b(n));return r.data.replace(o,c),this.style.updateImage(e,r),this}getImage(e){return this.style.getImage(e)}hasImage(e){return e?!!this.style.getImage(e):(this.fire(new t.l(Error(`Missing required image id`))),!1)}removeImage(e){this.style.removeImage(e)}loadImage(e){return t._(this,void 0,void 0,(function*(){return u.getImage(yield this._requestManager.transformRequest(e,`Image`),new AbortController)}))}listImages(){return this.style.listImages()}addLayer(e,t){return this._lazyInitEmptyStyle(),this.style.addLayer(e,t),this._update(!0)}moveLayer(e,t){return this.style.moveLayer(e,t),this._update(!0)}removeLayer(e){return this.style.removeLayer(e),this._update(!0)}getLayer(e){return this.style.getLayer(e)}getLayersOrder(){return this.style.getLayersOrder()}setLayerZoomRange(e,t,n){return this.style.setLayerZoomRange(e,t,n),this._update(!0)}setFilter(e,t,n={}){return this.style.setFilter(e,t,n),this._update(!0)}getFilter(e){return this.style.getFilter(e)}setPaintProperty(e,t,n,r={}){return this.style.setPaintProperty(e,t,n,r),this._update(!0)}getPaintProperty(e,t){return this.style.getPaintProperty(e,t)}setLayoutProperty(e,t,n,r={}){return this.style.setLayoutProperty(e,t,n,r),this._update(!0)}getLayoutProperty(e,t){return this.style.getLayoutProperty(e,t)}setGlyphs(e,t={}){return this._lazyInitEmptyStyle(),this.style.setGlyphs(e,t),this._update(!0)}getGlyphs(){return this.style.getGlyphsUrl()}addSprite(e,t,n={}){return this._lazyInitEmptyStyle(),this.style.addSprite(e,t,n,(e=>{e||this._update(!0)})),this}removeSprite(e){return this._lazyInitEmptyStyle(),this.style.removeSprite(e),this._update(!0)}getSprite(){return this.style.getSprite()}setSprite(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSprite(e,t,(e=>{e||this._update(!0)})),this}setLight(e,t={}){return this._lazyInitEmptyStyle(),this.style.setLight(e,t),this._update(!0)}getLight(){return this.style.getLight()}setSky(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSky(e,t),this._update(!0)}getSky(){return this.style.getSky()}setFeatureState(e,t){return this.style.setFeatureState(e,t),this._update()}removeFeatureState(e,t){return this.style.removeFeatureState(e,t),this._update()}getFeatureState(e){return this.style.getFeatureState(e)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}_containerDimensions(){let e=0,t=0;return this._container&&(e=this._container.clientWidth||400,t=this._container.clientHeight||300),[e,t]}_setupResizeObserver(){let e=!1,t=Xi((e=>{this._trackResize&&!this._removed&&(this.resize(e),this.redraw())}),50),n=this._ownerWindow.ResizeObserver??ResizeObserver;this._resizeObserver=new n((n=>{e?t(n):e=!0})),this._resizeObserver.observe(this._container)}_resolveContainer(e){if(typeof e==`string`){let t=document.getElementById(e);if(!t)throw Error(`Container '${e}' not found.`);return t}if(e instanceof HTMLElement||e&&typeof e==`object`&&e.nodeType===1)return e;throw Error(`Invalid type: 'container' must be a String or HTMLElement.`)}_setupContainer(){let e=this._container;e.classList.add(`maplibregl-map`);let t=this._canvasContainer=d.create(`div`,`maplibregl-canvas-container`,e);this._interactive&&t.classList.add(`maplibregl-interactive`),this._canvas=d.create(`canvas`,`maplibregl-canvas`,t),this._canvas.addEventListener(`webglcontextlost`,this._contextLost,!1),this._canvas.addEventListener(`webglcontextrestored`,this._contextRestored,!1),this._canvas.setAttribute(`tabindex`,this._interactive?`0`:`-1`),this._canvas.setAttribute(`aria-label`,this._getUIString(`Map.Title`)),this._canvas.setAttribute(`role`,`region`);let n=this._containerDimensions(),r=this._getClampedPixelRatio(n[0],n[1]);this._resizeCanvas(n[0],n[1],r);let i=this._controlContainer=d.create(`div`,`maplibregl-control-container`,e),a=this._controlPositions={};for(let e of[`top-left`,`top-right`,`bottom-left`,`bottom-right`])a[e]=d.create(`div`,`maplibregl-ctrl-${e} `,i);this._container.addEventListener(`scroll`,this._onMapScroll,!1)}_resizeCanvas(e,t,n){this._canvas.width=Math.floor(n*e),this._canvas.height=Math.floor(n*t),this._canvas.style.width=`${e}px`,this._canvas.style.height=`${t}px`}_setupPainter(){let e=Object.assign(Object.assign({},this._canvasContextAttributes),{alpha:!0,depth:!0,stencil:!0,premultipliedAlpha:!0}),t=null;this._canvas.addEventListener(`webglcontextcreationerror`,(n=>{t={requestedAttributes:e},n&&(t.statusMessage=n.statusMessage,t.type=n.type)}),{once:!0});let n=null;if(n=this._canvasContextAttributes.contextType?this._canvas.getContext(this._canvasContextAttributes.contextType,e):this._canvas.getContext(`webgl2`,e)||this._canvas.getContext(`webgl`,e),!n){let e=`Failed to initialize WebGL`;throw t?(t.message=e,Error(JSON.stringify(t))):Error(e)}this.painter=new Yi(n,this.transform)}migrateProjection(e,n){super.migrateProjection(e,n),this.painter.transform=e,this.fire(new t.n(`projectiontransition`,{newProjection:this.style.projection.name}))}loaded(){return!this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}_update(e){return this.style?._loaded?(this._styleDirty||=e,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(e){return this._update(),this._renderTaskQueue.add(e)}_cancelRenderFrame(e){this._renderTaskQueue.remove(e)}_render(e){var n;let r=this._idleTriggered?this._fadeDuration:0,i=this.style.projection?.transitionState>0;if(this.painter.context.setDirty(),this.painter.setBaseState(),this._renderTaskQueue.run(e),this._removed)return;let a=!1;if(this.style&&this._styleDirty){this._styleDirty=!1;let e=this.transform.zoom,n=l();this.style.zoomHistory.update(e,n);let i=new t.J(e,{now:n,fadeDuration:r,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),o=i.crossFadingFactor();o===1&&o===this._crossFadingFactor||(a=!0,this._crossFadingFactor=o),this.style.update(i)}let o=this.style.projection?.transitionState>0!==i;(n=this.style.projection)==null||n.setErrorQueryLatitudeDegrees(this.transform.center.lat),this.transform.setTransitionState(this.style.projection?.transitionState,this.style.projection?.latitudeErrorCorrectionRadians),this.style&&(this._sourcesDirty||o)&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this.terrain?(this.terrain.tileManager.update(this.transform,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),!this._elevationFreeze&&this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))):(this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0)),this._placementDirty=this.style?._updatePlacement(this.transform,this.showCollisionBoxes,r,this._crossSourceCollisions,o),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:r,showPadding:this.showPadding,anisotropicFilterPitch:this.getAnisotropicFilterPitch()}),this.fire(new t.n(`render`)),this.loaded()&&!this._loaded&&(this._loaded=!0,this.fire(new t.n(`load`))),this.style&&(this.style.hasTransitions()||a)&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles();let s=this._sourcesDirty||this._styleDirty||this._placementDirty;return s||this._repaint?this.triggerRepaint():!this.isMoving()&&this.loaded()&&this.fire(new t.n(`idle`)),!this._loaded||this._fullyLoaded||s||(this._fullyLoaded=!0),this}redraw(){return this.style&&(this._frameRequest&&=(this._frameRequest.abort(),null),this._render(0)),this}remove(){var e,n;this._hash&&this._hash.remove();for(let e of this._controls)e.onRemove(this);this._controls=[],this._frameRequest&&=(this._frameRequest.abort(),null),this._renderTaskQueue.clear(),(e=this._diffStyleRequest)==null||e.abort(),this.painter.destroy(),this.handlers.destroy(),delete this.handlers,this.setStyle(null),typeof window<`u`&&this._ownerWindow.removeEventListener(`online`,this._onWindowOnline,!1),u.removeThrottleControl(this._imageQueueHandle),(n=this._resizeObserver)==null||n.disconnect();let r=this.painter.context.gl.getExtension(`WEBGL_lose_context`);r!=null&&r.loseContext&&r.loseContext(),this._canvas.removeEventListener(`webglcontextrestored`,this._contextRestored,!1),this._canvas.removeEventListener(`webglcontextlost`,this._contextLost,!1),this._canvasContainer.remove(),this._controlContainer.remove(),this._container.removeEventListener(`scroll`,this._onMapScroll,!1),this._container.classList.remove(`maplibregl-map`),this._removed=!0,this.fire(new t.n(`remove`))}triggerRepaint(){this.style&&!this._frameRequest&&(this._frameRequest=new AbortController,s.frame(this._frameRequest,(e=>{this._frameRequest=null;try{this._render(e)}catch(e){if(!t.$(e)&&!function(e){return e.message===ci}(e))throw e}}),(()=>{}),this._ownerWindow))}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(e){this._showTileBoundaries!==e&&(this._showTileBoundaries=e,this._update())}get showPadding(){return!!this._showPadding}set showPadding(e){this._showPadding!==e&&(this._showPadding=e,this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(e){this._showCollisionBoxes!==e&&(this._showCollisionBoxes=e,e?this.style._generateCollisionBoxes():this._update())}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(e){this._showOverdrawInspector!==e&&(this._showOverdrawInspector=e,this._update())}get repaint(){return!!this._repaint}set repaint(e){this._repaint!==e&&(this._repaint=e,this.triggerRepaint())}get vertices(){return!!this._vertices}set vertices(e){this._vertices=e,this._update()}get version(){return ro}getCameraTargetElevation(){return this.transform.elevation}getProjection(){return this.style.getProjection()}setProjection(e){return this._lazyInitEmptyStyle(),this.style.setProjection(e),this._update(!0)}},oo={showCompass:!0,showZoom:!0,visualizePitch:!1,visualizeRoll:!0};class so{constructor(e,n,r=!1){this.mousedown=e=>{this.startMove(e,d.mousePos(this.element,e)),window.addEventListener(`mousemove`,this.mousemove),window.addEventListener(`mouseup`,this.mouseup)},this.mousemove=e=>{this.move(e,d.mousePos(this.element,e))},this.mouseup=e=>{this._rotatePitchHandler.dragEnd(e),this.offTemp()},this.touchstart=e=>{e.targetTouches.length===1?(this._startPos=this._lastPos=d.touchPos(this.element,e.targetTouches)[0],this.startMove(e,this._startPos),window.addEventListener(`touchmove`,this.touchmove,{passive:!1}),window.addEventListener(`touchend`,this.touchend)):this.reset()},this.touchmove=e=>{e.targetTouches.length===1?(this._lastPos=d.touchPos(this.element,e.targetTouches)[0],this.move(e,this._lastPos)):this.reset()},this.touchend=e=>{e.targetTouches.length===0&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)<this._clickTolerance&&this.element.click(),delete this._startPos,delete this._lastPos,this.offTemp()},this.reset=()=>{this._rotatePitchHandler.reset(),delete this._startPos,delete this._lastPos,this.offTemp()},this._clickTolerance=10,this.element=n;let i=new ba;this._rotatePitchHandler=new ga({clickTolerance:3,move:(e,i)=>{let a=n.getBoundingClientRect(),o=new t.P((a.bottom-a.top)/2,(a.right-a.left)/2);return{bearingDelta:t.cx(new t.P(e.x,i.y),i,o),pitchDelta:r?-.5*(i.y-e.y):void 0}},moveStateManager:i,enable:!0,assignEvents:()=>{}}),this.map=e,n.addEventListener(`mousedown`,this.mousedown),n.addEventListener(`touchstart`,this.touchstart,{passive:!1}),n.addEventListener(`touchcancel`,this.reset)}startMove(e,t){this._rotatePitchHandler.dragStart(e,t),d.disableDrag()}move(e,t){let n=this.map,{bearingDelta:r,pitchDelta:i}=this._rotatePitchHandler.dragMove(e,t)||{};r&&n.setBearing(n.getBearing()+r),i&&n.setPitch(n.getPitch()+i)}off(){let e=this.element;e.removeEventListener(`mousedown`,this.mousedown),e.removeEventListener(`touchstart`,this.touchstart),window.removeEventListener(`touchmove`,this.touchmove),window.removeEventListener(`touchend`,this.touchend),e.removeEventListener(`touchcancel`,this.reset),this.offTemp()}offTemp(){d.enableDrag(),window.removeEventListener(`mousemove`,this.mousemove),window.removeEventListener(`mouseup`,this.mouseup),window.removeEventListener(`touchmove`,this.touchmove),window.removeEventListener(`touchend`,this.touchend)}}let co;function lo(e,n,r,i=!1){if(i||!r.getCoveringTilesDetailsProvider().allowWorldCopies())return e?.wrap();let a=new t.W(e.lng,e.lat);if(e=new t.W(e.lng,e.lat),n){let i=new t.W(e.lng-360,e.lat),a=new t.W(e.lng+360,e.lat),o=r.locationToScreenPoint(e).distSqr(n);r.locationToScreenPoint(i).distSqr(n)<o?e=i:r.locationToScreenPoint(a).distSqr(n)<o&&(e=a)}for(;Math.abs(e.lng-r.center.lng)>180;){let t=r.locationToScreenPoint(e);if(t.x>=0&&t.y>=0&&t.x<=r.width&&t.y<=r.height)break;e.lng>r.center.lng?e.lng-=360:e.lng+=360}return e.lng!==a.lng&&r.isPointOnMapSurface(r.locationToScreenPoint(e))?e:a}let uo={center:`translate(-50%,-50%)`,top:`translate(-50%,0)`,"top-left":`translate(0,0)`,"top-right":`translate(-100%,0)`,bottom:`translate(-50%,-100%)`,"bottom-left":`translate(0,-100%)`,"bottom-right":`translate(-100%,-100%)`,left:`translate(0,-50%)`,right:`translate(-100%,-50%)`};function fo(e,t,n){let r=e.classList;for(let e in uo)r.remove(`maplibregl-${n}-anchor-${e}`);r.add(`maplibregl-${n}-anchor-${t}`)}class po extends t.E{constructor(e){if(super(),this._onClick=e=>{this.fire(new t.n(`click`,{originalEvent:e}))},this._onKeyPress=e=>{e.code!==`Space`&&e.code!==`Enter`||this.togglePopup()},this._onMapClick=e=>{let t=e.originalEvent.target,n=this._element;this._popup&&(t===n||n.contains(t))&&this.togglePopup()},this._update=e=>{if(!this._map)return;let t=this._map.loaded()&&!this._map.isMoving();(e?.type===`terrain`||e?.type===`render`&&!t)&&this._map.once(`render`,this._update),this._lngLat=lo(this._lngLat,this._flatPos,this._map.transform),this._flatPos=this._pos=this._map.project(this._lngLat)._add(this._offset),this._map.terrain&&(this._flatPos=this._map.transform.locationToScreenPoint(this._lngLat)._add(this._offset));let n=``;this._rotationAlignment===`viewport`||this._rotationAlignment===`auto`?n=`rotateZ(${this._rotation}deg)`:this._rotationAlignment===`map`&&(n=`rotateZ(${this._rotation-this._map.getBearing()}deg)`);let r=``;this._pitchAlignment===`viewport`||this._pitchAlignment===`auto`?r=`rotateX(0deg)`:this._pitchAlignment===`map`&&(r=`rotateX(${this._map.getPitch()}deg)`),this._subpixelPositioning||e&&e.type!==`moveend`||(this._pos=this._pos.round()),this._element.style.transform=`${uo[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${r} ${n}`,s.frameAsync(new AbortController,this._map._ownerWindow).then((()=>{this._updateOpacity(e?.type===`moveend`)})).catch((()=>{}))},this._onMove=e=>{if(!this._isDragging){let t=this._clickTolerance||this._map._clickTolerance;this._isDragging=e.point.dist(this._pointerdownPos)>=t}this._isDragging&&(this._pos=e.point.sub(this._positionDelta),this._lngLat=this._map.unproject(this._pos),this.setLngLat(this._lngLat),this._element.style.pointerEvents=`none`,this._state===`pending`&&(this._state=`active`,this.fire(new t.n(`dragstart`))),this.fire(new t.n(`drag`)))},this._onUp=()=>{this._element.style.pointerEvents=`auto`,this._positionDelta=null,this._pointerdownPos=null,this._isDragging=!1,this._map.off(`mousemove`,this._onMove),this._map.off(`touchmove`,this._onMove),this._state===`active`&&this.fire(new t.n(`dragend`)),this._state=`inactive`},this._addDragHandler=e=>{this._element.contains(e.originalEvent.target)&&(e.preventDefault(),this._positionDelta=e.point.sub(this._pos).add(this._offset),this._pointerdownPos=e.point,this._state=`pending`,this._map.on(`mousemove`,this._onMove),this._map.on(`touchmove`,this._onMove),this._map.once(`mouseup`,this._onUp),this._map.once(`touchend`,this._onUp))},this._anchor=e?.anchor||`center`,this._color=e?.color||`#3FB1CE`,this._scale=e?.scale||1,this._draggable=e?.draggable||!1,this._clickTolerance=e?.clickTolerance||0,this._subpixelPositioning=e?.subpixelPositioning||!1,this._isDragging=!1,this._state=`inactive`,this._rotation=e?.rotation||0,this._rotationAlignment=e?.rotationAlignment||`auto`,this._pitchAlignment=e?.pitchAlignment&&e.pitchAlignment!==`auto`?e.pitchAlignment:this._rotationAlignment,this.setOpacity(e?.opacity,e?.opacityWhenCovered),e?.element)this._element=e.element,this._offset=t.P.convert(e?.offset||[0,0]);else{this._defaultMarker=!0,this._element=d.create(`div`);let n=d.createNS(`http://www.w3.org/2000/svg`,`svg`);n.setAttributeNS(null,`display`,`block`),n.setAttributeNS(null,`height`,`41px`),n.setAttributeNS(null,`width`,`27px`),n.setAttributeNS(null,`viewBox`,`0 0 27 41`);let r=d.createNS(`http://www.w3.org/2000/svg`,`g`);r.setAttributeNS(null,`stroke`,`none`),r.setAttributeNS(null,`stroke-width`,`1`),r.setAttributeNS(null,`fill`,`none`),r.setAttributeNS(null,`fill-rule`,`evenodd`);let i=d.createNS(`http://www.w3.org/2000/svg`,`g`);i.setAttributeNS(null,`fill-rule`,`nonzero`);let a=d.createNS(`http://www.w3.org/2000/svg`,`g`);a.setAttributeNS(null,`transform`,`translate(3.0, 29.0)`),a.setAttributeNS(null,`fill`,`#000000`);for(let e of[{rx:`10.5`,ry:`5.25002273`},{rx:`10.5`,ry:`5.25002273`},{rx:`9.5`,ry:`4.77275007`},{rx:`8.5`,ry:`4.29549936`},{rx:`7.5`,ry:`3.81822308`},{rx:`6.5`,ry:`3.34094679`},{rx:`5.5`,ry:`2.86367051`},{rx:`4.5`,ry:`2.38636864`}]){let t=d.createNS(`http://www.w3.org/2000/svg`,`ellipse`);t.setAttributeNS(null,`opacity`,`0.04`),t.setAttributeNS(null,`cx`,`10.5`),t.setAttributeNS(null,`cy`,`5.80029008`),t.setAttributeNS(null,`rx`,e.rx),t.setAttributeNS(null,`ry`,e.ry),a.appendChild(t)}let o=d.createNS(`http://www.w3.org/2000/svg`,`g`);o.setAttributeNS(null,`fill`,this._color);let s=d.createNS(`http://www.w3.org/2000/svg`,`path`);s.setAttributeNS(null,`d`,`M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z`),o.appendChild(s);let c=d.createNS(`http://www.w3.org/2000/svg`,`g`);c.setAttributeNS(null,`opacity`,`0.25`),c.setAttributeNS(null,`fill`,`#000000`);let l=d.createNS(`http://www.w3.org/2000/svg`,`path`);l.setAttributeNS(null,`d`,`M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z`),c.appendChild(l);let u=d.createNS(`http://www.w3.org/2000/svg`,`g`);u.setAttributeNS(null,`transform`,`translate(6.0, 7.0)`),u.setAttributeNS(null,`fill`,`#FFFFFF`);let f=d.createNS(`http://www.w3.org/2000/svg`,`g`);f.setAttributeNS(null,`transform`,`translate(8.0, 8.0)`);let p=d.createNS(`http://www.w3.org/2000/svg`,`circle`);p.setAttributeNS(null,`fill`,`#000000`),p.setAttributeNS(null,`opacity`,`0.25`),p.setAttributeNS(null,`cx`,`5.5`),p.setAttributeNS(null,`cy`,`5.5`),p.setAttributeNS(null,`r`,`5.4999962`);let m=d.createNS(`http://www.w3.org/2000/svg`,`circle`);m.setAttributeNS(null,`fill`,`#FFFFFF`),m.setAttributeNS(null,`cx`,`5.5`),m.setAttributeNS(null,`cy`,`5.5`),m.setAttributeNS(null,`r`,`5.4999962`),f.appendChild(p),f.appendChild(m),i.appendChild(a),i.appendChild(o),i.appendChild(c),i.appendChild(u),i.appendChild(f),n.appendChild(i),n.setAttributeNS(null,`height`,41*this._scale+`px`),n.setAttributeNS(null,`width`,27*this._scale+`px`),this._element.appendChild(n),this._offset=t.P.convert(e?.offset||[0,-14])}if(this._element.classList.add(`maplibregl-marker`),this._element.addEventListener(`dragstart`,(e=>{e.preventDefault()})),this._element.addEventListener(`mousedown`,(e=>{e.preventDefault()})),fo(this._element,this._anchor,`marker`),e?.className)for(let t of e.className.split(` `))this._element.classList.add(t);this._popup=null}addTo(e){return this.remove(),this._map=e,this._element.hasAttribute(`aria-label`)||this._element.setAttribute(`aria-label`,e._getUIString(`Marker.Title`)),this._element.hasAttribute(`role`)||this._element.setAttribute(`role`,`button`),e.getCanvasContainer().appendChild(this._element),e.on(`move`,this._update),e.on(`moveend`,this._update),e.on(`terrain`,this._update),e.on(`projectiontransition`,this._update),this._element.addEventListener(`click`,this._onClick),this.setDraggable(this._draggable),this._update(),this._map.on(`click`,this._onMapClick),this}remove(){return this._opacityTimeout&&(clearTimeout(this._opacityTimeout),delete this._opacityTimeout),this._map&&(this._map.off(`click`,this._onMapClick),this._map.off(`move`,this._update),this._map.off(`moveend`,this._update),this._map.off(`terrain`,this._update),this._map.off(`projectiontransition`,this._update),this._map.off(`mousedown`,this._addDragHandler),this._map.off(`touchstart`,this._addDragHandler),this._map.off(`mouseup`,this._onUp),this._map.off(`touchend`,this._onUp),this._map.off(`mousemove`,this._onMove),this._map.off(`touchmove`,this._onMove),delete this._map),this._element.removeEventListener(`click`,this._onClick),this._element.remove(),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.W.convert(e),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this}getElement(){return this._element}setPopup(e){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeEventListener(`keypress`,this._onKeyPress),this._originalTabIndex||this._element.removeAttribute(`tabindex`)),e){if(!(`offset`in e.options)){let t=38.1,n=13.5,r=13.5/Math.SQRT2;e.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[r,-1*(t-n+r)],"bottom-right":[-r,-1*(t-n+r)],left:[n,-1*(t-n)],right:[-13.5,-1*(t-n)]}:this._offset}this._popup=e,this._originalTabIndex=this._element.getAttribute(`tabindex`),this._originalTabIndex||this._element.setAttribute(`tabindex`,`0`),this._element.addEventListener(`keypress`,this._onKeyPress)}return this}setSubpixelPositioning(e){return this._subpixelPositioning=e,this}getPopup(){return this._popup}togglePopup(){let e=this._popup;return this._element.style.opacity===this._opacityWhenCovered||e&&(e.isOpen()?e.remove():(e.setLngLat(this._lngLat),e.addTo(this._map))),this}_updateOpacity(e=!1){var n;let r=this._map?.terrain,i=this._map.transform.isLocationOccluded(this._lngLat);if(!r||i){let e=i?this._opacityWhenCovered:this._opacity;this._element.style.opacity!==e&&(this._element.style.opacity=e,this._element.classList.toggle(`maplibregl-marker-covered`,i));return}if(e)this._opacityTimeout=null;else{if(this._opacityTimeout)return;this._opacityTimeout=setTimeout((()=>{this._opacityTimeout=null}),100)}let a=this._map,o=a.terrain.depthAtPoint(this._pos),s=a.terrain.getElevationForLngLat(this._lngLat,a.transform);if(a.transform.lngLatToCameraDepth(this._lngLat,s)-o<.006)return this._element.style.opacity=this._opacity,void this._element.classList.remove(`maplibregl-marker-covered`);let c=-this._offset.y/a.transform.pixelsPerMeter,l=Math.sin(a.getPitch()*Math.PI/180)*c,u=a.terrain.depthAtPoint(new t.P(this._pos.x,this._pos.y-this._offset.y)),d=a.transform.lngLatToCameraDepth(this._lngLat,s+l)-u>.006;(n=this._popup)!=null&&n.isOpen()&&d&&this._popup.remove(),this._element.style.opacity=d?this._opacityWhenCovered:this._opacity,this._element.classList.toggle(`maplibregl-marker-covered`,d)}getOffset(){return this._offset}setOffset(e){return this._offset=t.P.convert(e),this._update(),this}addClassName(e){this._element.classList.add(e)}removeClassName(e){this._element.classList.remove(e)}toggleClassName(e){return this._element.classList.toggle(e)}setDraggable(e){return this._draggable=!!e,this._map&&(e?(this._map.on(`mousedown`,this._addDragHandler),this._map.on(`touchstart`,this._addDragHandler)):(this._map.off(`mousedown`,this._addDragHandler),this._map.off(`touchstart`,this._addDragHandler))),this}isDraggable(){return this._draggable}setRotation(e){return this._rotation=e||0,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(e){return this._rotationAlignment=e||`auto`,this._update(),this}getRotationAlignment(){return this._rotationAlignment}setPitchAlignment(e){return this._pitchAlignment=e&&e!==`auto`?e:this._rotationAlignment,this._update(),this}getPitchAlignment(){return this._pitchAlignment}setOpacity(e,t){return(this._opacity===void 0||e===void 0&&t===void 0)&&(this._opacity=`1`,this._opacityWhenCovered=`0.2`),e!==void 0&&(this._opacity=String(e)),t!==void 0&&(this._opacityWhenCovered=String(t)),this._map&&this._updateOpacity(!0),this}}let mo={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0},ho=0,go=!1,_o={maxWidth:100,unit:`metric`};function vo(e,t,n){let r=n?.maxWidth||100,i=e._container.clientHeight/2,a=e._container.clientWidth/2,o=e.unproject([a-r/2,i]),s=e.unproject([a+r/2,i]),c=Math.round(e.project(s).x-e.project(o).x),l=Math.min(r,c,e._container.clientWidth),u=o.distanceTo(s);if(n?.unit===`imperial`){let n=3.2808*u;n>5280?yo(t,l,n/5280,e._getUIString(`ScaleControl.Miles`)):yo(t,l,n,e._getUIString(`ScaleControl.Feet`))}else n?.unit===`nautical`?yo(t,l,u/1852,e._getUIString(`ScaleControl.NauticalMiles`)):u>=1e3?yo(t,l,u/1e3,e._getUIString(`ScaleControl.Kilometers`)):yo(t,l,u,e._getUIString(`ScaleControl.Meters`))}function yo(e,t,n,r){let i=function(e){let t=10**(`${Math.floor(e)}`.length-1),n=e/t;return n=n>=10?10:n>=5?5:n>=3?3:n>=2?2:n>=1?1:function(e){let t=10**Math.ceil(-Math.log(e)/Math.LN10);return Math.round(e*t)/t}(n),t*n}(n);e.style.width=i/n*t+`px`,e.innerHTML=`${i}&nbsp;${r}`}let bo={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:``,maxWidth:`240px`,subpixelPositioning:!1,locationOccludedOpacity:void 0,padding:void 0},xo=[`a[href]`,`[tabindex]:not([tabindex='-1'])`,`[contenteditable]:not([contenteditable='false'])`,`button:not([disabled])`,`input:not([disabled])`,`select:not([disabled])`,`textarea:not([disabled])`].join(`, `);function So(e){if(e){if(typeof e==`number`){let n=Math.round(Math.abs(e)/Math.SQRT2);return{center:new t.P(0,0),top:new t.P(0,e),"top-left":new t.P(n,n),"top-right":new t.P(-n,n),bottom:new t.P(0,-e),"bottom-left":new t.P(n,-n),"bottom-right":new t.P(-n,-n),left:new t.P(e,0),right:new t.P(-e,0)}}if(e instanceof t.P||Array.isArray(e)){let n=t.P.convert(e);return{center:n,top:n,"top-left":n,"top-right":n,bottom:n,"bottom-left":n,"bottom-right":n,left:n,right:n}}return{center:t.P.convert(e.center||[0,0]),top:t.P.convert(e.top||[0,0]),"top-left":t.P.convert(e[`top-left`]||[0,0]),"top-right":t.P.convert(e[`top-right`]||[0,0]),bottom:t.P.convert(e.bottom||[0,0]),"bottom-left":t.P.convert(e[`bottom-left`]||[0,0]),"bottom-right":t.P.convert(e[`bottom-right`]||[0,0]),left:t.P.convert(e.left||[0,0]),right:t.P.convert(e.right||[0,0])}}return So(new t.P(0,0))}let Co=n;e.AJAXError=t.cG,e.EXTENT=t.a6,e.Event=t.n,e.Evented=t.E,e.LngLat=t.W,e.MercatorCoordinate=t.a7,e.Point=t.P,e.addProtocol=t.cH,e.config=t.c,e.removeProtocol=t.cI,e.AttributionControl=qa,e.BoxZoomHandler=fa,e.CanvasSource=Te,e.CooperativeGesturesHandler=Ha,e.DoubleClickZoomHandler=Ia,e.DragPanHandler=za,e.DragRotateHandler=Ba,e.EdgeInsets=$t,e.FullscreenControl=class extends t.E{constructor(e={}){var n;super(),this._onFullscreenChange=()=>{let e=window.document.fullscreenElement||window.document.webkitFullscreenElement;for(;e?.shadowRoot?.fullscreenElement;)e=e.shadowRoot.fullscreenElement;e===this._container!==this._fullscreen&&this._handleFullscreenChange()},this._onClickFullscreen=()=>{this._isFullscreen()?this._exitFullscreen():this._requestFullscreen()},this._fullscreen=!1,this._pseudo=(n=e.pseudo)!=null&&n,e!=null&&e.container&&(e.container instanceof HTMLElement?this._container=e.container:t.w(`Full screen control 'container' must be a DOM element.`)),`onfullscreenchange`in document?this._fullscreenchange=`fullscreenchange`:`onmozfullscreenchange`in document?this._fullscreenchange=`mozfullscreenchange`:`onwebkitfullscreenchange`in document?this._fullscreenchange=`webkitfullscreenchange`:`onmsfullscreenchange`in document&&(this._fullscreenchange=`MSFullscreenChange`)}onAdd(e){return this._map=e,this._container||=this._map.getContainer(),this._controlContainer=d.create(`div`,`maplibregl-ctrl maplibregl-ctrl-group`),this._setupUI(),this._controlContainer}onRemove(){this._controlContainer.remove(),this._map=null,window.document.removeEventListener(this._fullscreenchange,this._onFullscreenChange)}_setupUI(){let e=this._fullscreenButton=d.create(`button`,`maplibregl-ctrl-fullscreen`,this._controlContainer);d.create(`span`,`maplibregl-ctrl-icon`,e).setAttribute(`aria-hidden`,`true`),e.type=`button`,this._updateTitle(),this._fullscreenButton.addEventListener(`click`,this._onClickFullscreen),window.document.addEventListener(this._fullscreenchange,this._onFullscreenChange)}_updateTitle(){let e=this._getTitle();this._fullscreenButton.setAttribute(`aria-label`,e),this._fullscreenButton.title=e}_getTitle(){return this._map._getUIString(this._isFullscreen()?`FullscreenControl.Exit`:`FullscreenControl.Enter`)}_isFullscreen(){return this._fullscreen}_handleFullscreenChange(){this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle(`maplibregl-ctrl-shrink`),this._fullscreenButton.classList.toggle(`maplibregl-ctrl-fullscreen`),this._updateTitle(),this._fullscreen?(this.fire(new t.n(`fullscreenstart`)),this._prevCooperativeGesturesEnabled=this._map.cooperativeGestures.isEnabled(),this._map.cooperativeGestures.disable()):(this.fire(new t.n(`fullscreenend`)),this._prevCooperativeGesturesEnabled&&this._map.cooperativeGestures.enable())}_exitFullscreen(){this._pseudo?this._togglePseudoFullScreen():window.document.exitFullscreen?window.document.exitFullscreen():window.document.webkitCancelFullScreen?window.document.webkitCancelFullScreen():this._togglePseudoFullScreen()}_requestFullscreen(){this._pseudo?this._togglePseudoFullScreen():this._container.requestFullscreen?this._container.requestFullscreen():this._container.webkitRequestFullscreen?this._container.webkitRequestFullscreen():this._togglePseudoFullScreen()}_togglePseudoFullScreen(){this._container.classList.toggle(`maplibregl-pseudo-fullscreen`),this._handleFullscreenChange(),this._map.resize()}},e.GeoJSONSource=Se,e.GeolocateControl=class extends t.E{constructor(e){super(),this._onSuccess=e=>{if(this._map){if(this._isOutOfMapMaxBounds(e))return this._setErrorState(),this.fire(new t.n(`outofmaxbounds`,e)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,this._watchState){case`WAITING_ACTIVE`:case`ACTIVE_LOCK`:case`ACTIVE_ERROR`:this._watchState=`ACTIVE_LOCK`,this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-waiting`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-active-error`),this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-active`);break;case`BACKGROUND`:case`BACKGROUND_ERROR`:this._watchState=`BACKGROUND`,this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-waiting`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-background-error`),this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-background`);break;default:throw Error(`Unexpected watchState ${this._watchState}`)}this.options.showUserLocation&&this._watchState!==`OFF`&&this._updateMarker(e),this.options.trackUserLocation&&this._watchState!==`ACTIVE_LOCK`||this._updateCamera(e),this.options.showUserLocation&&this._dotElement.classList.remove(`maplibregl-user-location-dot-stale`),this.fire(new t.n(`geolocate`,e)),this._finish()}},this._updateCamera=e=>{let n=new t.W(e.coords.longitude,e.coords.latitude),r=e.coords.accuracy,i=this._map.getBearing(),a=t.e({bearing:i},this.options.fitBoundsOptions),o=de.fromLngLat(n,r);this._map.fitBounds(o,a,{geolocateSource:!0})},this._updateMarker=e=>{if(e){let n=new t.W(e.coords.longitude,e.coords.latitude);this._accuracyCircleMarker.setLngLat(n).addTo(this._map),this._userLocationDotMarker.setLngLat(n).addTo(this._map),this._accuracy=e.coords.accuracy,this._updateCircleRadiusIfNeeded()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()},this._onUpdate=()=>{this._updateCircleRadiusIfNeeded()},this._onError=e=>{if(this._map){if(e.code===1){this._watchState=`OFF`,this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-waiting`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-active`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-active-error`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-background`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-background-error`),this._geolocateButton.disabled=!0;let e=this._map._getUIString(`GeolocateControl.LocationNotAvailable`);this._geolocateButton.title=e,this._geolocateButton.setAttribute(`aria-label`,e),this._geolocationWatchID!==void 0&&this._clearWatch()}else{if(e.code===3&&go)return;this._setErrorState()}this._watchState!==`OFF`&&this.options.showUserLocation&&this._dotElement.classList.add(`maplibregl-user-location-dot-stale`),this.fire(new t.n(`error`,e)),this._finish()}},this._finish=()=>{this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0},this._onMoveStart=e=>{if(!this._map)return;let n=e?.[0]instanceof ResizeObserverEntry;e.geolocateSource||this._watchState!==`ACTIVE_LOCK`||n||this._map.isZooming()||(this._watchState=`BACKGROUND`,this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-background`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-active`),this.fire(new t.n(`trackuserlocationend`)),this.fire(new t.n(`userlocationlostfocus`)))},this._setupUI=()=>{this._map&&(this._container.addEventListener(`contextmenu`,(e=>{e.preventDefault()})),this._geolocateButton=d.create(`button`,`maplibregl-ctrl-geolocate`,this._container),d.create(`span`,`maplibregl-ctrl-icon`,this._geolocateButton).setAttribute(`aria-hidden`,`true`),this._geolocateButton.type=`button`,this._geolocateButton.disabled=!0)},this._finishSetupUI=e=>{if(this._map){if(!1===e){t.w(`Geolocation support is not available so the GeolocateControl will be disabled.`);let e=this._map._getUIString(`GeolocateControl.LocationNotAvailable`);this._geolocateButton.disabled=!0,this._geolocateButton.title=e,this._geolocateButton.setAttribute(`aria-label`,e)}else{let e=this._map._getUIString(`GeolocateControl.FindMyLocation`);this._geolocateButton.disabled=!1,this._geolocateButton.title=e,this._geolocateButton.setAttribute(`aria-label`,e)}this.options.trackUserLocation&&(this._geolocateButton.setAttribute(`aria-pressed`,`false`),this._watchState=`OFF`),this.options.showUserLocation&&(this._dotElement=d.create(`div`,`maplibregl-user-location-dot`),this._userLocationDotMarker=new po({element:this._dotElement}),this._circleElement=d.create(`div`,`maplibregl-user-location-accuracy-circle`),this._accuracyCircleMarker=new po({element:this._circleElement,pitchAlignment:`map`}),this.options.trackUserLocation&&(this._watchState=`OFF`),this._map.on(`zoom`,this._onUpdate),this._map.on(`move`,this._onUpdate),this._map.on(`rotate`,this._onUpdate),this._map.on(`pitch`,this._onUpdate)),this._geolocateButton.addEventListener(`click`,(()=>this.trigger())),this._setup=!0,this.options.trackUserLocation&&this._map.on(`movestart`,this._onMoveStart)}},this.options=t.e({},mo,e)}onAdd(e){return this._map=e,this._container=d.create(`div`,`maplibregl-ctrl maplibregl-ctrl-group`),this._setupUI(),function(){return t._(this,arguments,void 0,(function*(e=!1){if(co!==void 0&&!e)return co;if(window.navigator.permissions===void 0)return co=!!window.navigator.geolocation,co;try{co=(yield window.navigator.permissions.query({name:`geolocation`})).state!==`denied`}catch{co=!!window.navigator.geolocation}return co}))}().then((e=>this._finishSetupUI(e))),this._container}onRemove(){this._geolocationWatchID!==void 0&&(window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),this._container.remove(),this._map.off(`movestart`,this._onMoveStart),this._map.off(`zoom`,this._onUpdate),this._map.off(`move`,this._onUpdate),this._map.off(`rotate`,this._onUpdate),this._map.off(`pitch`,this._onUpdate),this._map=void 0,ho=0,go=!1}_isOutOfMapMaxBounds(e){let t=this._map.getMaxBounds(),n=e.coords;return t&&(n.longitude<t.getWest()||n.longitude>t.getEast()||n.latitude<t.getSouth()||n.latitude>t.getNorth())}_setErrorState(){switch(this._watchState){case`WAITING_ACTIVE`:this._watchState=`ACTIVE_ERROR`,this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-active`),this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-active-error`);break;case`ACTIVE_LOCK`:this._watchState=`ACTIVE_ERROR`,this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-active`),this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-active-error`),this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-waiting`);break;case`BACKGROUND`:this._watchState=`BACKGROUND_ERROR`,this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-background`),this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-background-error`),this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-waiting`);break;case`ACTIVE_ERROR`:case`BACKGROUND_ERROR`:case`OFF`:case void 0:break;default:throw Error(`Unexpected watchState ${this._watchState}`)}}_updateCircleRadiusIfNeeded(){let e=this._userLocationDotMarker.getLngLat();if(!(this.options.showUserLocation&&this.options.showAccuracyCircle&&this._accuracy&&e))return;let t=this._map.project(e),n=this._map.unproject([t.x+100,t.y]),r=e.distanceTo(n)/100,i=2*this._accuracy/r;this._circleElement.style.width=`${i.toFixed(2)}px`,this._circleElement.style.height=`${i.toFixed(2)}px`}trigger(){if(!this._setup)return t.w(`Geolocate control triggered before added to a map`),!1;if(this.options.trackUserLocation){switch(this._watchState){case`OFF`:this._watchState=`WAITING_ACTIVE`,this.fire(new t.n(`trackuserlocationstart`));break;case`WAITING_ACTIVE`:case`ACTIVE_LOCK`:case`ACTIVE_ERROR`:case`BACKGROUND_ERROR`:ho--,go=!1,this._watchState=`OFF`,this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-waiting`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-active`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-active-error`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-background`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-background-error`),this.fire(new t.n(`trackuserlocationend`));break;case`BACKGROUND`:this._watchState=`ACTIVE_LOCK`,this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-background`),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new t.n(`trackuserlocationstart`)),this.fire(new t.n(`userlocationfocus`));break;default:throw Error(`Unexpected watchState ${this._watchState}`)}switch(this._watchState){case`WAITING_ACTIVE`:this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-waiting`),this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-active`);break;case`ACTIVE_LOCK`:this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-active`);break;case`OFF`:break;default:throw Error(`Unexpected watchState ${this._watchState}`)}if(this._watchState===`OFF`&&this._geolocationWatchID!==void 0)this._clearWatch();else if(this._geolocationWatchID===void 0){let e;this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-waiting`),this._geolocateButton.setAttribute(`aria-pressed`,`true`),ho++,ho>1?(e={maximumAge:6e5,timeout:0},go=!0):(e=this.options.positionOptions,go=!1),this._geolocationWatchID=window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,e)}}else window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return!0}_clearWatch(){window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-waiting`),this._geolocateButton.setAttribute(`aria-pressed`,`false`),this.options.showUserLocation&&this._updateMarker(null)}},e.GlobeControl=class{constructor(){this._toggleProjection=()=>{let e=this._map.getProjection()?.type;this._map.setProjection(e!==`mercator`&&e?{type:`mercator`}:{type:`globe`}),this._updateGlobeIcon()},this._updateGlobeIcon=()=>{this._globeButton.classList.remove(`maplibregl-ctrl-globe`),this._globeButton.classList.remove(`maplibregl-ctrl-globe-enabled`),this._map.getProjection()?.type===`globe`?(this._globeButton.classList.add(`maplibregl-ctrl-globe-enabled`),this._globeButton.title=this._map._getUIString(`GlobeControl.Disable`)):(this._globeButton.classList.add(`maplibregl-ctrl-globe`),this._globeButton.title=this._map._getUIString(`GlobeControl.Enable`))}}onAdd(e){return this._map=e,this._container=d.create(`div`,`maplibregl-ctrl maplibregl-ctrl-group`),this._globeButton=d.create(`button`,`maplibregl-ctrl-globe`,this._container),d.create(`span`,`maplibregl-ctrl-icon`,this._globeButton).setAttribute(`aria-hidden`,`true`),this._globeButton.type=`button`,this._globeButton.addEventListener(`click`,this._toggleProjection),this._updateGlobeIcon(),this._map.on(`styledata`,this._updateGlobeIcon),this._map.on(`projectiontransition`,this._updateGlobeIcon),this._container}onRemove(){this._container.remove(),this._map.off(`styledata`,this._updateGlobeIcon),this._map.off(`projectiontransition`,this._updateGlobeIcon),this._globeButton.removeEventListener(`click`,this._toggleProjection),this._map=void 0}},e.Hash=Zi,e.ImageSource=Ce,e.KeyboardHandler=Ma,e.LngLatBounds=de,e.LogoControl=Ja,e.Map=ao,e.MapLibreMap=ao,e.MapMouseEvent=oa,e.MapTouchEvent=sa,e.MapWheelEvent=ca,e.Marker=po,e.NavigationControl=class{constructor(e){this._updateZoomButtons=()=>{let e=this._map.getZoom(),t=e===this._map.getMaxZoom(),n=e===this._map.getMinZoom();this._zoomInButton.disabled=t,this._zoomOutButton.disabled=n,this._zoomInButton.setAttribute(`aria-disabled`,t.toString()),this._zoomOutButton.setAttribute(`aria-disabled`,n.toString())},this._rotateCompassArrow=()=>{this._compassIcon.style.transform=this.options.visualizePitch&&this.options.visualizeRoll?`scale(${1/Math.cos(this._map.transform.pitchInRadians)**.5}) rotateZ(${-this._map.transform.roll}deg) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizePitch?`scale(${1/Math.cos(this._map.transform.pitchInRadians)**.5}) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizeRoll?`rotate(${-this._map.transform.bearing-this._map.transform.roll}deg)`:`rotate(${-this._map.transform.bearing}deg)`},this._setButtonTitle=(e,t)=>{let n=this._map._getUIString(`NavigationControl.${t}`);e.title=n,e.setAttribute(`aria-label`,n)},this.options=t.e({},oo,e),this._container=d.create(`div`,`maplibregl-ctrl maplibregl-ctrl-group`),this._container.addEventListener(`contextmenu`,(e=>e.preventDefault())),this.options.showZoom&&(this._zoomInButton=this._createButton(`maplibregl-ctrl-zoom-in`,(e=>this._map.zoomIn({},{originalEvent:e}))),d.create(`span`,`maplibregl-ctrl-icon`,this._zoomInButton).setAttribute(`aria-hidden`,`true`),this._zoomOutButton=this._createButton(`maplibregl-ctrl-zoom-out`,(e=>this._map.zoomOut({},{originalEvent:e}))),d.create(`span`,`maplibregl-ctrl-icon`,this._zoomOutButton).setAttribute(`aria-hidden`,`true`)),this.options.showCompass&&(this._compass=this._createButton(`maplibregl-ctrl-compass`,(e=>{this.options.visualizePitch?this._map.resetNorthPitch({},{originalEvent:e}):this._map.resetNorth({},{originalEvent:e})})),this._compassIcon=d.create(`span`,`maplibregl-ctrl-icon`,this._compass),this._compassIcon.setAttribute(`aria-hidden`,`true`))}onAdd(e){return this._map=e,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,`ZoomIn`),this._setButtonTitle(this._zoomOutButton,`ZoomOut`),this._map.on(`zoom`,this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,`ResetBearing`),this.options.visualizePitch&&this._map.on(`pitch`,this._rotateCompassArrow),this.options.visualizeRoll&&this._map.on(`roll`,this._rotateCompassArrow),this._map.on(`rotate`,this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new so(this._map,this._compass,this.options.visualizePitch)),this._container}onRemove(){this._container.remove(),this.options.showZoom&&this._map.off(`zoom`,this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&this._map.off(`pitch`,this._rotateCompassArrow),this.options.visualizeRoll&&this._map.off(`roll`,this._rotateCompassArrow),this._map.off(`rotate`,this._rotateCompassArrow),this._handler.off(),delete this._handler),delete this._map}_createButton(e,t){let n=d.create(`button`,e,this._container);return n.type=`button`,n.addEventListener(`click`,t),n}},e.Popup=class extends t.E{constructor(e){super(),this._updateOpacity=()=>{this.options.locationOccludedOpacity!==void 0&&(this._container.style.opacity=this._map.transform.isLocationOccluded(this.getLngLat())?`${this.options.locationOccludedOpacity}`:``)},this.remove=()=>(this._content&&this._content.remove(),this._container&&(this._container.remove(),delete this._container),this._map&&(this._map.off(`move`,this._update),this._map.off(`move`,this._onClose),this._map.off(`click`,this._onClose),this._map.off(`remove`,this.remove),this._map.off(`terrain`,this._update),this._map.off(`projectiontransition`,this._update),this._map.off(`mousemove`,this._update),this._map.off(`mouseup`,this._update),this._map.off(`drag`,this._update),this._map._canvasContainer.classList.remove(`maplibregl-track-pointer`),delete this._map,this.fire(new t.n(`close`))),this),this._update=e=>{if(!this._map||!this._lngLat&&!this._trackPointer||!this._content)return;if(!this._container){if(this._container=d.create(`div`,`maplibregl-popup`,this._map.getContainer()),this._tip=d.create(`div`,`maplibregl-popup-tip`,this._container),this._container.appendChild(this._content),this.options.className)for(let e of this.options.className.split(` `))this._container.classList.add(e);this._closeButton&&this._closeButton.setAttribute(`aria-label`,this._map._getUIString(`Popup.Close`)),this._trackPointer&&this._container.classList.add(`maplibregl-popup-track-pointer`)}let t;if(this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth&&(this._container.style.maxWidth=this.options.maxWidth),this._lngLat=lo(this._lngLat,this._flatPos,this._map.transform,this._trackPointer),e&&`point`in e&&e.point&&(t=e.point),this._trackPointer&&!t)return;let n=this._flatPos=this._pos=this._trackPointer&&t?t:this._map.project(this._lngLat);this._map.terrain&&(this._flatPos=this._trackPointer&&t?t:this._map.transform.locationToScreenPoint(this._lngLat));let r=this.options.anchor,i=So(this.options.offset);if(!r){let e=this._container.offsetWidth,t=this._container.offsetHeight,a=function(e){return e?{top:e.top??0,right:e.right??0,bottom:e.bottom??0,left:e.left??0}:{top:0,right:0,bottom:0,left:0}}(this.options.padding),o;o=n.y+i.bottom.y<t+a.top?[`top`]:n.y>this._map.transform.height-t-a.bottom?[`bottom`]:[],n.x<e/2+a.left?o.push(`left`):n.x>this._map.transform.width-e/2-a.right&&o.push(`right`),r=o.length===0?`bottom`:o.join(`-`)}let a=n.add(i[r]);this.options.subpixelPositioning||(a=a.round()),this._container.style.transform=`${uo[r]} translate(${a.x}px,${a.y}px)`,fo(this._container,r,`popup`),this._updateOpacity()},this._onClose=()=>{this.remove()},this.options=t.e(Object.create(bo),e)}addTo(e){return this._map&&this.remove(),this._map=e,this.options.closeOnClick&&this._map.on(`click`,this._onClose),this.options.closeOnMove&&this._map.on(`move`,this._onClose),this._map.on(`remove`,this.remove),this._map.on(`terrain`,this._update),this._map.on(`projectiontransition`,this._update),this._update(),this._focusFirstElement(),this._trackPointer?(this._map.on(`mousemove`,this._update),this._map.on(`mouseup`,this._update),this._container&&this._container.classList.add(`maplibregl-popup-track-pointer`),this._map._canvasContainer.classList.add(`maplibregl-track-pointer`)):this._map.on(`move`,this._update),this.fire(new t.n(`open`)),this}isOpen(){return!!this._map}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.W.convert(e),this._pos=null,this._flatPos=null,this._trackPointer=!1,this._update(),this._map&&(this._map.on(`move`,this._update),this._map.off(`mousemove`,this._update),this._container&&this._container.classList.remove(`maplibregl-popup-track-pointer`),this._map._canvasContainer.classList.remove(`maplibregl-track-pointer`)),this}trackPointer(){return this._trackPointer=!0,this._pos=null,this._flatPos=null,this._update(),this._map&&(this._map.off(`move`,this._update),this._map.on(`mousemove`,this._update),this._map.on(`drag`,this._update),this._container&&this._container.classList.add(`maplibregl-popup-track-pointer`),this._map._canvasContainer.classList.add(`maplibregl-track-pointer`)),this}getElement(){return this._container}setText(e){return this.setDOMContent(document.createTextNode(e))}setHTML(e){let t=document.createDocumentFragment(),n=document.createElement(`body`),r;for(n.innerHTML=e;r=n.firstChild,r;)t.appendChild(r);return this.setDOMContent(t)}getMaxWidth(){return this._container?.style.maxWidth}setMaxWidth(e){return this.options.maxWidth=e,this._update(),this}setDOMContent(e){if(this._content)for(;this._content.hasChildNodes();)this._content.firstChild&&this._content.removeChild(this._content.firstChild);else this._content=d.create(`div`,`maplibregl-popup-content`,this._container);return this._content.appendChild(e),this._createCloseButton(),this._update(),this._focusFirstElement(),this}addClassName(e){return this._container&&this._container.classList.add(e),this}removeClassName(e){return this._container&&this._container.classList.remove(e),this}setOffset(e){return this.options.offset=e,this._update(),this}toggleClassName(e){if(this._container)return this._container.classList.toggle(e)}setSubpixelPositioning(e){this.options.subpixelPositioning=e}setPadding(e){this.options.padding=e,this._update()}_createCloseButton(){this.options.closeButton&&(this._closeButton=d.create(`button`,`maplibregl-popup-close-button`,this._content),this._closeButton.type=`button`,this._closeButton.innerHTML=`&#215;`,this._closeButton.addEventListener(`click`,this._onClose))}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;let e=this._container.querySelector(xo);e&&e.focus()}},e.RasterDEMTileSource=he,e.RasterTileSource=me,e.ScaleControl=class{constructor(e){this._onMove=()=>{vo(this._map,this._container,this.options)},this.setUnit=e=>{this.options.unit=e,vo(this._map,this._container,this.options)},this.options=Object.assign(Object.assign({},_o),e)}getDefaultPosition(){return`bottom-left`}onAdd(e){return this._map=e,this._container=d.create(`div`,`maplibregl-ctrl maplibregl-ctrl-scale`,e.getContainer()),this._map.on(`move`,this._onMove),this._onMove(),this._container}onRemove(){this._container.remove(),this._map.off(`move`,this._onMove),this._map=void 0}},e.ScrollZoomHandler=Fa,e.Style=Un,e.TerrainControl=class{constructor(e){this._toggleTerrain=()=>{this._map.getTerrain()?this._map.setTerrain(null):this._map.setTerrain(this.options),this._updateTerrainIcon()},this._updateTerrainIcon=()=>{this._terrainButton.classList.remove(`maplibregl-ctrl-terrain`),this._terrainButton.classList.remove(`maplibregl-ctrl-terrain-enabled`),this._map.terrain?(this._terrainButton.classList.add(`maplibregl-ctrl-terrain-enabled`),this._terrainButton.title=this._map._getUIString(`TerrainControl.Disable`)):(this._terrainButton.classList.add(`maplibregl-ctrl-terrain`),this._terrainButton.title=this._map._getUIString(`TerrainControl.Enable`))},this.options=e}onAdd(e){return this._map=e,this._container=d.create(`div`,`maplibregl-ctrl maplibregl-ctrl-group`),this._terrainButton=d.create(`button`,`maplibregl-ctrl-terrain`,this._container),d.create(`span`,`maplibregl-ctrl-icon`,this._terrainButton).setAttribute(`aria-hidden`,`true`),this._terrainButton.type=`button`,this._terrainButton.addEventListener(`click`,this._toggleTerrain),this._updateTerrainIcon(),this._map.on(`terrain`,this._updateTerrainIcon),this._container}onRemove(){this._container.remove(),this._map.off(`terrain`,this._updateTerrainIcon),this._map=void 0}},e.TwoFingersTouchPitchHandler=Aa,e.TwoFingersTouchRotateHandler=Oa,e.TwoFingersTouchZoomHandler=Ea,e.TwoFingersTouchZoomRotateHandler=Va,e.VectorTileSource=pe,e.VideoSource=we,e.addSourceType=(e,n)=>t._(void 0,void 0,void 0,(function*(){if(De(e))throw Error(`A source type called "${e}" already exists.`);((e,t)=>{Ee[e]=t})(e,n)})),e.clearPrewarmedResources=function(){let e=te;e&&(e.isPreloaded()&&e.numActive()===1?(e.release(k),te=null):console.warn(`Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()`))},e.createTileMesh=yn,e.getGlobalDispatcher=ae,e.getMaxParallelImageRequests=function(){return t.c.MAX_PARALLEL_IMAGE_REQUESTS},e.getRTLTextPluginStatus=function(){return je().getRTLTextPluginStatus()},e.getVersion=function(){return Co},e.getWorkerCount=function(){return A.workerCount},e.getWorkerUrl=function(){return t.c.WORKER_URL},e.importScriptInWorkers=function(e){return ae().broadcast(`IS`,e)},e.isTimeFrozen=function(){return c.isFrozen()},e.now=l,e.prewarm=function(){re().acquire(k)},e.restoreNow=function(){c.restoreNow()},e.setMaxParallelImageRequests=function(e){t.c.MAX_PARALLEL_IMAGE_REQUESTS=e},e.setNow=function(e){c.setNow(e)},e.setRTLTextPlugin=function(e,t){return je().setRTLTextPlugin(e,t)},e.setWorkerCount=function(e){A.workerCount=e},e.setWorkerUrl=function(e){t.c.WORKER_URL=e}})),e}))}))(),1),jl=Uint8Array,Ml=Uint16Array,Nl=Int32Array,Pl=new jl([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]),Fl=new jl([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]),Il=new jl([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ll=function(e,t){for(var n=new Ml(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new Nl(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},Rl=Ll(Pl,2),zl=Rl.b,Bl=Rl.r;zl[28]=258,Bl[258]=28;var Vl=Ll(Fl,0),Hl=Vl.b;Vl.r;for(var Ul=new Ml(32768),Wl=0;Wl<32768;++Wl){var Gl=(Wl&43690)>>1|(Wl&21845)<<1;Gl=(Gl&52428)>>2|(Gl&13107)<<2,Gl=(Gl&61680)>>4|(Gl&3855)<<4,Ul[Wl]=((Gl&65280)>>8|(Gl&255)<<8)>>1}for(var Kl=(function(e,t,n){for(var r=e.length,i=0,a=new Ml(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new Ml(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new Ml(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[Ul[d]>>c]=l}else for(s=new Ml(r),i=0;i<r;++i)e[i]&&(s[i]=Ul[o[e[i]-1]++]>>15-e[i]);return s}),ql=new jl(288),Wl=0;Wl<144;++Wl)ql[Wl]=8;for(var Wl=144;Wl<256;++Wl)ql[Wl]=9;for(var Wl=256;Wl<280;++Wl)ql[Wl]=7;for(var Wl=280;Wl<288;++Wl)ql[Wl]=8;for(var Jl=new jl(32),Wl=0;Wl<32;++Wl)Jl[Wl]=5;var Yl=Kl(ql,9,1),Xl=Kl(Jl,5,1),Zl=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},Ql=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},$l=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},eu=function(e){return(e+7)/8|0},tu=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new jl(e.subarray(t,n))},nu=[`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`],ru=function(e,t,n){var r=Error(t||nu[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,ru),!n)throw r;return r},iu=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new jl(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new jl(i*3));var l=function(e){var t=n.length;if(e>t){var r=new jl(Math.max(t*2,e));r.set(n),n=r}},u=t.f||0,d=t.p||0,f=t.b||0,p=t.l,m=t.d,h=t.m,g=t.n,_=i*8;do{if(!p){u=Ql(e,d,1);var v=Ql(e,d+1,3);if(d+=3,!v){var y=eu(d)+4,b=e[y-4]|e[y-3]<<8,x=y+b;if(x>i){c&&ru(0);break}s&&l(f+b),n.set(e.subarray(y,x),f),t.b=f+=b,t.p=d=x*8,t.f=u;continue}else if(v==1)p=Yl,m=Xl,h=9,g=5;else if(v==2){var S=Ql(e,d,31)+257,C=Ql(e,d+10,15)+4,w=S+Ql(e,d+5,31)+1;d+=14;for(var T=new jl(w),E=new jl(19),D=0;D<C;++D)E[Il[D]]=Ql(e,d+D*3,7);d+=C*3;for(var O=Zl(E),k=(1<<O)-1,A=Kl(E,O,1),D=0;D<w;){var ee=A[Ql(e,d,k)];d+=ee&15;var y=ee>>4;if(y<16)T[D++]=y;else{var te=0,ne=0;for(y==16?(ne=3+Ql(e,d,3),d+=2,te=T[D-1]):y==17?(ne=3+Ql(e,d,7),d+=3):y==18&&(ne=11+Ql(e,d,127),d+=7);ne--;)T[D++]=te}}var re=T.subarray(0,S),ie=T.subarray(S);h=Zl(re),g=Zl(ie),p=Kl(re,h,1),m=Kl(ie,g,1)}else ru(1);if(d>_){c&&ru(0);break}}s&&l(f+131072);for(var ae=(1<<h)-1,oe=(1<<g)-1,se=d;;se=d){var te=p[$l(e,d)&ae],ce=te>>4;if(d+=te&15,d>_){c&&ru(0);break}if(te||ru(2),ce<256)n[f++]=ce;else if(ce==256){se=d,p=null;break}else{var le=ce-254;if(ce>264){var D=ce-257,ue=Pl[D];le=Ql(e,d,(1<<ue)-1)+zl[D],d+=ue}var de=m[$l(e,d)&oe],fe=de>>4;de||ru(3),d+=de&15;var ie=Hl[fe];if(fe>3){var ue=Fl[fe];ie+=$l(e,d)&(1<<ue)-1,d+=ue}if(d>_){c&&ru(0);break}s&&l(f+131072);var pe=f+le;if(f<ie){var me=a-ie,he=Math.min(ie,pe);for(me+f<0&&ru(3);f<he;++f)n[f]=r[me+f]}for(;f<pe;++f)n[f]=n[f-ie]}}t.l=p,t.p=se,t.b=f,t.f=u,p&&(u=1,t.m=h,t.d=m,t.n=g)}while(!u);return f!=n.length&&o?tu(n,0,f):n.subarray(0,f)},au=new jl(0),ou=function(e){(e[0]!=31||e[1]!=139||e[2]!=8)&&ru(6,`invalid gzip data`);var t=e[3],n=10;t&4&&(n+=(e[10]|e[11]<<8)+2);for(var r=(t>>3&1)+(t>>4&1);r>0;r-=!e[n++]);return n+(t&2)},su=function(e){var t=e.length;return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0},cu=function(e,t){return((e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31)&&ru(6,`invalid zlib data`),(e[1]>>5&1)==+!t&&ru(6,`invalid zlib data: `+(e[1]&32?`need`:`unexpected`)+` dictionary`),(e[1]>>3&4)+2};function lu(e,t){return iu(e,{i:2},t&&t.out,t&&t.dictionary)}function uu(e,t){var n=ou(e);return n+8>e.length&&ru(6,`invalid gzip data`),iu(e.subarray(n,-8),{i:2},t&&t.out||new jl(su(e)),t&&t.dictionary)}function du(e,t){return iu(e.subarray(cu(e,t&&t.dictionary),-4),{i:2},t&&t.out,t&&t.dictionary)}function fu(e,t){return e[0]==31&&e[1]==139&&e[2]==8?uu(e,t):(e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31?lu(e,t):du(e,t)}var pu=typeof TextDecoder<`u`&&new TextDecoder;try{pu.decode(au,{stream:!0})}catch{}var mu=Object.defineProperty,hu=Math.pow,gu=(e,t)=>mu(e,`name`,{value:t,configurable:!0}),_u=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())});gu((e,t)=>{let n=!1,r=``;return new(L.GridLayer.extend({createTile:gu((t,i)=>{let a=document.createElement(`img`),o=new AbortController,s=o.signal;return a.cancel=()=>{o.abort()},n||=(e.getHeader().then(e=>{e.tileType===1||e.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.`):e.tileType===2?r=`image/png`:e.tileType===3?r=`image/jpeg`:e.tileType===4?r=`image/webp`:e.tileType===5&&(r=`image/avif`)}),!0),e.getZxy(t.z,t.x,t.y,s).then(e=>{if(e){let t=new Blob([e.data],{type:r});a.src=window.URL.createObjectURL(t)}else a.style.display=`none`;a.cancel=void 0,i(void 0,a)}).catch(e=>{if(e.name!==`AbortError`)throw e}),a},`createTile`),_removeTile:gu(function(e){let t=this._tiles[e];t&&(t.el.cancel&&t.el.cancel(),t.el.src&&window.URL.revokeObjectURL(t.el.src),t.el.width=0,t.el.height=0,t.el.deleted=!0,L.DomUtil.remove(t.el),delete this._tiles[e],this.fire(`tileunload`,{tile:t.el,coords:this._keyToTileCoords(e)}))},`_removeTile`)}))(t)},`leafletRasterLayer`);var vu=gu(e=>(t,n)=>{if(n instanceof AbortController)return e(t,n);let r=new AbortController;return e(t,r).then(e=>n(void 0,e.data,e.cacheControl||``,e.expires||``),e=>n(e)).catch(e=>n(e)),{cancel:gu(()=>r.abort(),`cancel`)}},`v3compat`),yu=class{constructor(e){this.tilev4=gu((e,t)=>_u(this,null,function*(){if(e.type===`json`){let n=e.url.substr(10),r=this.tiles.get(n);if(r||(r=new Ju(n),this.tiles.set(n,r)),this.metadata){let n=yield r.getTileJson(e.url);return t.signal.throwIfAborted(),{data:n}}let i=yield r.getHeader();return t.signal.throwIfAborted(),(i.minLon>=i.maxLon||i.minLat>=i.maxLat)&&console.error(`Bounds of PMTiles archive ${i.minLon},${i.minLat},${i.maxLon},${i.maxLat} are not valid.`),{data:{tiles:[`${e.url}/{z}/{x}/{y}`],minzoom:i.minZoom,maxzoom:i.maxZoom,bounds:[i.minLon,i.minLat,i.maxLon,i.maxLat]}}}let n=new RegExp(/pmtiles:\/\/(.+)\/(\d+)\/(\d+)\/(\d+)/),r=e.url.match(n);if(!r)throw Error(`Invalid PMTiles protocol URL`);let i=r[1],a=this.tiles.get(i);a||(a=new Ju(i),this.tiles.set(i,a));let o=r[2],s=r[3],c=r[4],l=yield a?.getZxy(+o,+s,+c,t.signal);if(t.signal.throwIfAborted(),l)return{data:new Uint8Array(l.data),cacheControl:l.cacheControl,expires:l.expires};let u=yield a.getHeader();if(u.tileType===1||u.tileType===6){if(this.errorOnMissingTile)throw Error(`Tile not found.`);return{data:new Uint8Array}}return{data:null}}),`tilev4`),this.tile=vu(this.tilev4),this.tiles=new Map,this.metadata=e?.metadata||!1,this.errorOnMissingTile=e?.errorOnMissingTile||!1}add(e){this.tiles.set(e.source.getKey(),e)}get(e){return this.tiles.get(e)}};gu(yu,`Protocol`);var bu=yu;function xu(e,t){return(t>>>0)*4294967296+(e>>>0)}gu(xu,`toNum`);function Su(e,t){let n=t.buf,r=n[t.pos++],i=(r&112)>>4;if(r<128||(r=n[t.pos++],i|=(r&127)<<3,r<128)||(r=n[t.pos++],i|=(r&127)<<10,r<128)||(r=n[t.pos++],i|=(r&127)<<17,r<128)||(r=n[t.pos++],i|=(r&127)<<24,r<128)||(r=n[t.pos++],i|=(r&1)<<31,r<128))return xu(e,i);throw Error(`Expected varint not more than 10 bytes`)}gu(Su,`readVarintRemainder`);function Cu(e){let t=e.buf,n=t[e.pos++],r=n&127;return n<128||(n=t[e.pos++],r|=(n&127)<<7,n<128)||(n=t[e.pos++],r|=(n&127)<<14,n<128)||(n=t[e.pos++],r|=(n&127)<<21,n<128)?r:(n=t[e.pos],r|=(n&15)<<28,Su(r,e))}gu(Cu,`readVarint`);function wu(e,t,n,r,i){return i===0?r===0?[n,t]:[e-1-n,e-1-t]:[t,n]}gu(wu,`rotate`);function Tu(e,t,n){if(e>26)throw Error(`Tile zoom level exceeds max safe number limit (26)`);if(t>=1<<e||n>=1<<e)throw Error(`tile x/y outside zoom level bounds`);let r=((1<<e)*(1<<e)-1)/3,i=e-1,[a,o]=[t,n];for(let e=1<<i;e>0;e>>=1){let t=a&e,n=o&e;r+=(3*t^n)*(1<<i),[a,o]=wu(e,a,o,t,n),i--}return r}gu(Tu,`zxyToTileId`);function Eu(e){let t=3*e+1;return t<4294967296?31-Math.clz32(t):63-Math.clz32(t/4294967296)}gu(Eu,`tileIdToZ`);function Du(e){let t=Eu(e)>>1;if(t>26)throw Error(`Tile zoom level exceeds max safe number limit (26)`);let n=e-((1<<t)*(1<<t)-1)/3,r=0,i=0,a=1<<t;for(let e=1;e<a;e<<=1){let t=e&n/2,a=e&(n^t);[r,i]=wu(e,r,i,t,a),n/=2,r+=t,i+=a}return[t,r,i]}gu(Du,`tileIdToZxy`);var Ou=(e=>(e[e.Unknown=0]=`Unknown`,e[e.None=1]=`None`,e[e.Gzip=2]=`Gzip`,e[e.Brotli=3]=`Brotli`,e[e.Zstd=4]=`Zstd`,e))(Ou||{});function ku(e,t){return _u(this,null,function*(){if(t===1||t===0)return e;if(t===2){if(globalThis.DecompressionStream===void 0)return fu(new Uint8Array(e));let t=new Response(e).body;if(!t)throw Error(`Failed to read response stream`);let n=t.pipeThrough(new globalThis.DecompressionStream(`gzip`));return new Response(n).arrayBuffer()}throw Error(`Compression method not supported`)})}gu(ku,`defaultDecompress`);var Au=(e=>(e[e.Unknown=0]=`Unknown`,e[e.Mvt=1]=`Mvt`,e[e.Png=2]=`Png`,e[e.Jpeg=3]=`Jpeg`,e[e.Webp=4]=`Webp`,e[e.Avif=5]=`Avif`,e[e.Mlt=6]=`Mlt`,e))(Au||{});function ju(e){return e===1?`.mvt`:e===2?`.png`:e===3?`.jpg`:e===4?`.webp`:e===5?`.avif`:e===6?`.mlt`:``}gu(ju,`tileTypeExt`);var Mu=127;function Nu(e,t){let n=0,r=e.length-1;for(;n<=r;){let i=r+n>>1,a=t-e[i].tileId;if(a>0)n=i+1;else if(a<0)r=i-1;else return e[i]}return r>=0&&(e[r].runLength===0||t-e[r].tileId<e[r].runLength)?e[r]:null}gu(Nu,`findTile`);var Pu=class{constructor(e){this.file=e}getKey(){return this.file.name}getBytes(e,t){return _u(this,null,function*(){return{data:yield this.file.slice(e,e+t).arrayBuffer()}})}};gu(Pu,`FileSource`);var Fu=Pu,Iu=class{constructor(e,t=new Headers,n=void 0){this.url=e,this.customHeaders=t,this.credentials=n,this.mustReload=!1;let r=``;`navigator`in globalThis&&(r=globalThis.navigator?.userAgent??``);let i=r.indexOf(`Windows`)>-1,a=/Chrome|Chromium|Edg|OPR|Brave/.test(r);this.chromeWindowsNoCache=!1,i&&a&&(this.chromeWindowsNoCache=!0)}getKey(){return this.url}setHeaders(e){this.customHeaders=e}getBytes(e,t,n,r){return _u(this,null,function*(){let i,a;n?a=n:(i=new AbortController,a=i.signal);let o=new Headers(this.customHeaders);o.set(`range`,`bytes=${e}-${e+t-1}`);let s;this.mustReload?s=`reload`:this.chromeWindowsNoCache&&(s=`no-store`);let c=yield fetch(this.url,{signal:a,cache:s,headers:o,credentials:this.credentials});if(e===0&&c.status===416){let e=c.headers.get(`Content-Range`);if(!e||!e.startsWith(`bytes */`))throw Error(`Missing content-length on 416 response`);let t=+e.substr(8);o.set(`range`,`bytes=0-${t-1}`),c=yield fetch(this.url,{signal:a,cache:`reload`,headers:o,credentials:this.credentials})}let l=c.headers.get(`Etag`);if(l!=null&&l.startsWith(`W/`)&&(l=null),c.status===416||r&&l&&l!==r)throw this.mustReload=!0,new Hu(`Server returned non-matching ETag ${r} after one retry. Check browser extensions and servers for issues that may affect correct ETag headers.`);if(c.status>=300)throw Error(`Bad response code: ${c.status}`);let u=c.headers.get(`Content-Length`);if(c.status===200&&(!u||+u>t))throw i&&i.abort(),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:l||void 0,cacheControl:c.headers.get(`Cache-Control`)||void 0,expires:c.headers.get(`Expires`)||void 0}})}};gu(Iu,`FetchSource`);var Lu=Iu;function Ru(e,t){let n=e.getUint32(t+4,!0),r=e.getUint32(t+0,!0);return n*hu(2,32)+r}gu(Ru,`getUint64`);function zu(e,t){let n=new DataView(e),r=n.getUint8(7);if(r>3)throw Error(`Archive is spec version ${r} but this library supports up to spec version 3`);return{specVersion:r,rootDirectoryOffset:Ru(n,8),rootDirectoryLength:Ru(n,16),jsonMetadataOffset:Ru(n,24),jsonMetadataLength:Ru(n,32),leafDirectoryOffset:Ru(n,40),leafDirectoryLength:Ru(n,48),tileDataOffset:Ru(n,56),tileDataLength:Ru(n,64),numAddressedTiles:Ru(n,72),numTileEntries:Ru(n,80),numTileContents:Ru(n,88),clustered:n.getUint8(96)===1,internalCompression:n.getUint8(97),tileCompression:n.getUint8(98),tileType:n.getUint8(99),minZoom:n.getUint8(100),maxZoom:n.getUint8(101),minLon:n.getInt32(102,!0)/1e7,minLat:n.getInt32(106,!0)/1e7,maxLon:n.getInt32(110,!0)/1e7,maxLat:n.getInt32(114,!0)/1e7,centerZoom:n.getUint8(118),centerLon:n.getInt32(119,!0)/1e7,centerLat:n.getInt32(123,!0)/1e7,etag:t}}gu(zu,`bytesToHeader`);function Bu(e){let t={buf:new Uint8Array(e),pos:0},n=Cu(t),r=[],i=0;for(let e=0;e<n;e++){let e=Cu(t);r.push({tileId:i+e,offset:0,length:0,runLength:1}),i+=e}for(let e=0;e<n;e++)r[e].runLength=Cu(t);for(let e=0;e<n;e++)r[e].length=Cu(t);for(let e=0;e<n;e++){let n=Cu(t);n===0&&e>0?r[e].offset=r[e-1].offset+r[e-1].length:r[e].offset=n-1}return r}gu(Bu,`deserializeIndex`);var Vu=class extends Error{};gu(Vu,`EtagMismatch`);var Hu=Vu;function Uu(e,t){return _u(this,null,function*(){let n=yield e.getBytes(0,16384);if(new DataView(n.data).getUint16(0,!0)!==19792)throw Error(`Wrong magic number for PMTiles archive`);let r=zu(n.data.slice(0,Mu),n.etag),i=n.data.slice(r.rootDirectoryOffset,r.rootDirectoryOffset+r.rootDirectoryLength),a=`${e.getKey()}|${r.etag||``}|${r.rootDirectoryOffset}|${r.rootDirectoryLength}`,o=Bu(yield t(i,r.internalCompression));return[r,[a,o.length,o]]})}gu(Uu,`getHeaderAndRoot`);function Wu(e,t,n,r,i){return _u(this,null,function*(){let a=Bu(yield t((yield e.getBytes(n,r,void 0,i.etag)).data,i.internalCompression));if(a.length===0)throw Error(`Empty directory is invalid`);return a})}gu(Wu,`getDirectory`),gu(class{constructor(e=100,t=!0,n=ku){this.cache=new Map,this.maxCacheEntries=e,this.counter=1,this.decompress=n}getHeader(e){return _u(this,null,function*(){let t=e.getKey(),n=this.cache.get(t);if(n)return n.lastUsed=this.counter++,n.data;let r=yield Uu(e,this.decompress);return r[1]&&this.cache.set(r[1][0],{lastUsed:this.counter++,data:r[1][2]}),this.cache.set(t,{lastUsed:this.counter++,data:r[0]}),this.prune(),r[0]})}getDirectory(e,t,n,r){return _u(this,null,function*(){let i=`${e.getKey()}|${r.etag||``}|${t}|${n}`,a=this.cache.get(i);if(a)return a.lastUsed=this.counter++,a.data;let o=yield Wu(e,this.decompress,t,n,r);return this.cache.set(i,{lastUsed:this.counter++,data:o}),this.prune(),o})}prune(){if(this.cache.size>this.maxCacheEntries){let e=1/0,t;this.cache.forEach((n,r)=>{n.lastUsed<e&&(e=n.lastUsed,t=r)}),t&&this.cache.delete(t)}}invalidate(e){return _u(this,null,function*(){this.cache.delete(e.getKey())})}},`ResolvedValueCache`);var Gu=class{constructor(e=100,t=!0,n=ku){this.cache=new Map,this.invalidations=new Map,this.maxCacheEntries=e,this.counter=1,this.decompress=n}getHeader(e){return _u(this,null,function*(){let t=e.getKey(),n=this.cache.get(t);if(n)return n.lastUsed=this.counter++,yield n.data;let r=new Promise((t,n)=>{Uu(e,this.decompress).then(e=>{e[1]&&this.cache.set(e[1][0],{lastUsed:this.counter++,data:Promise.resolve(e[1][2])}),t(e[0]),this.prune()}).catch(e=>{n(e)})});return this.cache.set(t,{lastUsed:this.counter++,data:r}),r})}getDirectory(e,t,n,r){return _u(this,null,function*(){let i=`${e.getKey()}|${r.etag||``}|${t}|${n}`,a=this.cache.get(i);if(a)return a.lastUsed=this.counter++,yield a.data;let o=new Promise((i,a)=>{Wu(e,this.decompress,t,n,r).then(e=>{i(e),this.prune()}).catch(e=>{a(e)})});return this.cache.set(i,{lastUsed:this.counter++,data:o}),o})}prune(){if(this.cache.size>=this.maxCacheEntries){let e=1/0,t;this.cache.forEach((n,r)=>{n.lastUsed<e&&(e=n.lastUsed,t=r)}),t&&this.cache.delete(t)}}invalidate(e){return _u(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((n,r)=>{this.getHeader(e).then(e=>{n(),this.invalidations.delete(t)}).catch(e=>{r(e)})});this.invalidations.set(t,n)})}};gu(Gu,`SharedPromiseCache`);var Ku=Gu,qu=class{constructor(e,t,n){typeof e==`string`?this.source=new Lu(e):this.source=e,n?this.decompress=n:this.decompress=ku,t?this.cache=t:this.cache=new Ku}getHeader(){return _u(this,null,function*(){return yield this.cache.getHeader(this.source)})}getZxyAttempt(e,t,n,r){return _u(this,null,function*(){let i=Tu(e,t,n),a=yield this.cache.getHeader(this.source);if(e<a.minZoom||e>a.maxZoom)return;let o=a.rootDirectoryOffset,s=a.rootDirectoryLength;for(let e=0;e<=3;e++){let e=Nu(yield this.cache.getDirectory(this.source,o,s,a),i);if(e){if(e.runLength>0){let t=yield this.source.getBytes(a.tileDataOffset+e.offset,e.length,r,a.etag);return{data:yield this.decompress(t.data,a.tileCompression),cacheControl:t.cacheControl,expires:t.expires}}o=a.leafDirectoryOffset+e.offset,s=e.length}else return}throw Error(`Maximum directory depth exceeded`)})}getZxy(e,t,n,r){return _u(this,null,function*(){try{return yield this.getZxyAttempt(e,t,n,r)}catch(i){if(i instanceof Hu)return this.cache.invalidate(this.source),yield this.getZxyAttempt(e,t,n,r);throw i}})}getMetadataAttempt(){return _u(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),r=new TextDecoder(`utf-8`);return JSON.parse(r.decode(n))})}getMetadata(){return _u(this,null,function*(){try{return yield this.getMetadataAttempt()}catch(e){if(e instanceof Hu)return this.cache.invalidate(this.source),yield this.getMetadataAttempt();throw e}})}getTileJson(e){return _u(this,null,function*(){let t=yield this.getHeader(),n=yield this.getMetadata();return{tilejson:`3.0.0`,scheme:`xyz`,tiles:[`${e}/{z}/{x}/{y}${ju(t.tileType)}`],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}})}};gu(qu,`PMTiles`);var Ju=qu,Yu,Xu=2,Zu=[200,500];function Qu(e,t){return t?.aborted===!0||e instanceof DOMException&&e.name===`AbortError`}var $u=class{#e;constructor(e){this.#e=e}getKey(){return this.#e}async getBytes(e,t,n){let r={Range:`bytes=${e}-${e+t-1}`};for(let e=0;;e++){let t;try{t=await fetch(this.#e,{signal:n,cache:`no-store`,headers:r})}catch(t){if(Qu(t,n)||e>=Xu)throw t;await this.#t(e,n);continue}if(t.status<300){let e=t.headers.get(`ETag`)??void 0;return e?.startsWith(`W/`)&&(e=void 0),{data:await t.arrayBuffer(),etag:e,cacheControl:t.headers.get(`Cache-Control`)??void 0,expires:t.headers.get(`Expires`)??void 0}}if(t.status>=500&&e<Xu){await this.#t(e,n);continue}throw Error(`PMTiles fetch failed: ${t.status} for ${this.#e}`)}}#t(e,t){let n=Zu[e]??Zu[Zu.length-1];return new Promise((e,r)=>{let i=setTimeout(e,n);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(new DOMException(`Aborted`,`AbortError`))},{once:!0})})}};function ed(){Yu||(Yu=new bu,Al.default.addProtocol(`pmtiles`,Yu.tile))}function td(e){Yu||ed();let t=new $u(e);Yu?.get(t.getKey())||Yu?.add(new Ju(t))}var nd=1,rd={fill:`fill-opacity`,line:`line-opacity`,raster:`raster-opacity`};function id(e){return rd[e]??`raster-opacity`}function ad(e,t,n=`basemap`){let r=xl(e,t),i=Object.keys(r.sources),a=r.layers.map(e=>({id:e.id,type:e.type,minzoom:e.minzoom??0,themePaint:e.metadata?.[ll]})),o=i[0],s,c=e=>{let t=e.getSource(o)?.maxzoom;if(t===void 0)return!1;for(let n of a)e.getLayer(n.id)&&e.setLayerZoomRange(n.id,n.minzoom,t+nd);return!0};return{id:fl(e.identifier),title:e.name,band:n,supportsOpacity:!0,layerIds:a.map(e=>e.id),add(e){for(let t of i){let n=r.sources[t];`url`in n&&typeof n.url==`string`&&n.url.startsWith(`pmtiles://`)&&td(n.url.slice(ul.length)),e.map.getSource(t)||e.map.addSource(t,n)}for(let t of r.layers)e.map.getLayer(t.id)||e.map.addLayer(t,e.beforeIdFor(n));if(!o)return;s&&=(e.map.off(`sourcedata`,s),void 0);let t=()=>e.map.isSourceLoaded(o)&&c(e.map);if(!t()){let n=r=>{r.sourceId===o&&r.isSourceLoaded&&t()&&(e.map.off(`sourcedata`,n),s===n&&(s=void 0))};s=n,e.map.on(`sourcedata`,n)}},remove(e){s&&=(e.map.off(`sourcedata`,s),void 0);for(let t of a)e.map.getLayer(t.id)&&e.map.removeLayer(t.id);for(let t of i)e.map.getSource(t)&&e.map.removeSource(t)},setVisible(e,t){for(let n of a)e.map.setLayoutProperty(n.id,`visibility`,t?`visible`:`none`)},setOpacity(e,t){for(let n of a)e.map.setPaintProperty(n.id,id(n.type),t)},applyTheme(e,t){for(let n of a){if(n.type===`raster`){cl(e.map,n.id,t);continue}if(!n.themePaint)continue;let r=n.type===`line`?`line-color`:`fill-color`;e.map.setPaintProperty(n.id,r,t[n.themePaint])}}}}function od(){return{type:`FeatureCollection`,features:[]}}function sd(e,t,n){let r=new Uint8ClampedArray(e*e*4),i=e/2;for(let a=0;a<e;a+=1)for(let o=0;o<e;o+=1){if(!n(o,a,i))continue;let s=(a*e+o)*4;r[s]=t.r,r[s+1]=t.g,r[s+2]=t.b,r[s+3]=t.a}return new ImageData(r,e,e)}var cd=[`basemap`,`bathymetry`,`track`,`weather`,`routes`,`safety`,`traffic`,`vessel`,`overlay-top`];function ld(e){return`__z__${e}`}function ud(e){for(let t of cd){let n=ld(t);e.getLayer(n)||e.addLayer({id:n,type:`background`,layout:{visibility:`none`}})}}function dd(e){let t=cd[cd.indexOf(e)+1];return t?ld(t):void 0}var fd=class{#e;#t=new Map;#n=new Map;#r;#i;#a;#o;#s;#c;constructor(e,t={}){this.#e=e,this.#r=t.saved??{},this.#i=t.onChange,this.#a=t.savedOrder?[...t.savedOrder]:[],this.#o=t.onOrderChange,this.#s=t.pinned??[],this.#c=t.exclusive??[]}async register(e){await this.#l(e),this.#f()}async registerAll(e){for(let t of e)await this.#l(t);this.#f()}async#l(e){if(this.#t.has(e.id))throw Error(`duplicate overlay id: ${e.id}`);this.#t.set(e.id,e);let t=this.#r[e.id],n=t?{...t}:{visible:e.defaultVisible??!0,opacity:e.defaultOpacity??1},r=this.#n.get(e.id)??n;r.visible&&this.#c.find(t=>t.includes(e.id))?.some(t=>t!==e.id&&this.#n.get(t)?.visible)&&(r.visible=!1),this.#n.set(e.id,r),await e.add(this.#e),e.setVisible(this.#e,r.visible),e.setOpacity?.(this.#e,r.opacity)}unregister(e){let t=this.#t.get(e);t&&(t.remove(this.#e),this.#t.delete(e))}toggle(e,t){let n=this.#t.get(e),r=this.#n.get(e);if(!(!n||!r)){if(t){let t=this.#c.find(t=>t.includes(e));for(let n of t??[]){if(n===e)continue;let t=this.#t.get(n),r=this.#n.get(n);t&&r?.visible&&(r.visible=!1,t.setVisible(this.#e,!1))}}r.visible=t,n.setVisible(this.#e,t),this.#u()}}setOpacity(e,t){let n=this.#t.get(e),r=this.#n.get(e);!n||!r||(r.opacity=t,n.setOpacity?.(this.#e,t),this.#u())}reorder(e,t){if(this.#s.includes(e)||!this.#t.has(e))return;let n=this.#d().filter(e=>!this.#s.includes(e)).reverse(),r=n.indexOf(e);n.splice(r,1);let i=Math.max(0,Math.min(t,n.length));n.splice(i,0,e),this.#a=n.reverse(),this.#f(),this.#o?.([...this.#a])}#u(){if(!this.#i)return;let e={};for(let[t,n]of this.#n)e[t]={visible:n.visible,opacity:n.opacity};this.#i(e)}#d(){let e=e=>cd.indexOf(this.#t.get(e)?.band??`basemap`),t=[...this.#t.keys()].filter(e=>!this.#s.includes(e)),n=this.#a.filter(e=>t.includes(e));for(let r of t){if(n.includes(r))continue;let t=e(r),i=n.findIndex(n=>e(n)>t);i<0&&(i=n.length),n.splice(i,0,r)}let r=this.#s.filter(e=>this.#t.has(e));return[...n,...r]}#f(){if(!this.#a.length&&!this.#s.length)return;let e=[];for(let t of this.#d()){let n=this.#t.get(t);if(n)for(let t of n.layerIds)this.#e.map.getLayer(t)&&e.push(t)}let t=ld(`overlay-top`),n=this.#e.map.getLayer(t)?t:void 0;for(let t=e.length-1;t>=0;t--)this.#e.map.moveLayer(e[t],n),n=e[t]}applyTheme(e){for(let t of this.#t.values())t.applyTheme?.(this.#e,e)}async reattachAll(){ud(this.#e.map);for(let[e,t]of this.#t){let n=this.#n.get(e)??{visible:!0,opacity:1};await(t.reattach??t.add).call(t,this.#e),t.setVisible(this.#e,n.visible),t.setOpacity?.(this.#e,n.opacity)}this.#f()}layers(){return this.#d().reverse().flatMap(e=>{let t=this.#t.get(e);if(!t)return[];let n=this.#n.get(e)??{visible:!0,opacity:1};return[{id:e,title:t.title,visible:n.visible,opacity:n.opacity,supportsOpacity:t.supportsOpacity,pinned:this.#s.includes(e),band:t.band}]})}};function pd(e){let{minLon:t,minLat:n,maxLon:r,maxLat:i}=e;if([t,n,r,i].every(Number.isFinite)&&!(t>=r||n>=i))return[t,n,r,i]}function md(e){if(typeof e!=`object`||!e)return;let t=e.vector_layers;if(!Array.isArray(t))return;let n=[];for(let e of t){let t=e?.id;typeof t==`string`&&n.push(t)}return n.length>0?n:void 0}function hd(e){if(typeof e!=`object`||!e)return;let t=e.name;return typeof t==`string`&&t.length>0?t:void 0}function gd(e,t){return{name:hd(t),kind:e.tileType===Au.Mvt||e.tileType===Au.Mlt?`vector`:`raster`,bounds:pd(e),minzoom:e.minZoom,maxzoom:e.maxZoom,vectorLayers:md(t)}}async function _d(e){let t=typeof e!=`string`,n=new Ju(t?new Fu(e):new $u(e)),r=await n.getHeader(),i;try{i=await n.getMetadata()}catch{i=void 0}let a=gd(r,i);return t&&(a.byteSize=e.size),a}function vd(e){function t(t){t.map.getSource(e.sourceId)?.setData(e.features())}return{id:e.id,title:e.title,band:e.band,supportsOpacity:!0,layerIds:[e.layerId],add(t){t.map.hasImage(e.iconId)||t.map.addImage(e.iconId,e.iconImage(e.defaultColor),{pixelRatio:e.pixelRatio??1});let n={type:`geojson`,data:e.features()};t.map.addSource(e.sourceId,n);let r={id:e.layerId,type:`symbol`,source:e.sourceId,layout:{"icon-image":e.iconId,"icon-rotate":[`get`,`heading`],"icon-rotation-alignment":`map`,"icon-allow-overlap":!0,"icon-ignore-placement":!0}};t.map.addLayer(r,t.beforeIdFor(e.band))},sync(n){e.beforeSync?.(),e.shouldRefresh()&&t(n)},applyTheme(t,n){let r=e.iconImage(e.paintColor(n));t.map.hasImage(e.iconId)?t.map.updateImage(e.iconId,r):t.map.addImage(e.iconId,r,{pixelRatio:e.pixelRatio??1})},setVisible(t,n){t.map.setLayoutProperty(e.layerId,`visibility`,n?`visible`:`none`)},setOpacity(t,n){t.map.setPaintProperty(e.layerId,`icon-opacity`,n)},remove(t){t.map.getLayer(e.layerId)&&t.map.removeLayer(e.layerId),t.map.getSource(e.sourceId)&&t.map.removeSource(e.sourceId)}}}var yd=[0,30],bd=2;function xd(e){let t;try{let n=e.view?[e.view.lon,e.view.lat]:e.defaultCenter??yd,r=e.view?e.view.zoom:e.defaultZoom??bd;t=new Al.default.Map({container:e.container,style:al(),center:n,zoom:Math.min(r,e.maxZoom??1/0),minZoom:e.minZoom,maxZoom:e.maxZoom,attributionControl:{compact:!0}})}catch(e){return console.error(`Map failed to initialize`,e),{destroy:()=>{}}}let n=t,r=!1,i=0,a=new ResizeObserver(()=>n.resize());a.observe(e.container);let o=!1,s=()=>{o||(o=!0,requestAnimationFrame(()=>{if(o=!1,r)return;let t=n.getCenter();e.onView?.({lat:t.lat,lon:t.lng,zoom:n.getZoom()})}))};return n.on(`move`,s),e.onUserPan&&n.on(`dragstart`,()=>e.onUserPan?.()),e.onClick&&n.on(`click`,t=>e.onClick?.({lng:t.lngLat.lng,lat:t.lngLat.lat})),n.on(`load`,()=>{s();let t={map:n,beforeIdFor:dd};ud(n);let a=new fd(t,e.managerOptions),o=Ol(n,sl(`day`));e.onLoad({map:n,ctx:t,manager:a,recolor:e=>{let t=sl(e);e===`day`?kl(n,o):El(n,t),Dl(n,t),a.applyTheme(t)},isDestroyed:()=>r,runTick:e=>{let n=()=>{for(let n of e)n.sync(t);i=requestAnimationFrame(n)};i=requestAnimationFrame(n)}})}),{destroy:()=>{r=!0,cancelAnimationFrame(i),a.disconnect(),n.remove()}}}function Sd(e,t){let n=e.kind!==`raster`;return{identifier:e.id,name:e.name,type:n?`tileJSON`:`tilelayer`,format:n?`mvt`:`png`,url:t,bounds:e.bounds,minzoom:e.minzoom,maxzoom:e.maxzoom,layers:e.layers}}function Cd(e){try{let t=new URL(e).pathname;return t.slice(t.lastIndexOf(`/`)+1).replace(/\.pmtiles$/i,``)||e}catch{return e}}var wd=class{#e=z(dn([]));get sources(){return W(this.#e)}set sources(e){B(this.#e,e,!0)}#t;#n;#r;constructor(e,t,n,r){this.#t=e,this.sources=t,this.#n=n,this.#r=r}async addUrl(e){let t=await _d(e);this.#i({id:cc(),name:t.name??Cd(e),kind:t.kind,origin:{type:`url`,url:e},bounds:t.bounds,minzoom:t.minzoom,maxzoom:t.maxzoom,layers:t.vectorLayers})}async addFile(e){let t=await _d(e),n=cc();await this.#t.put(n,e),this.#i({id:n,name:t.name??e.name.replace(/\.pmtiles$/i,``),kind:t.kind,origin:{type:`file`,storeId:n},bounds:t.bounds,minzoom:t.minzoom,maxzoom:t.maxzoom,layers:t.vectorLayers,byteSize:t.byteSize??e.size})}rename(e,t){this.sources=this.sources.map(n=>n.id===e?{...n,name:t}:n),this.#n(this.sources)}async remove(e){let t=this.sources.find(t=>t.id===e);t&&(t.origin.type===`file`&&await this.#t.delete(t.origin.storeId),this.sources=this.sources.filter(t=>t.id!==e),this.#n(this.sources))}resolveBlob(e){return this.#t.get(e)}#i(e){this.sources=[...this.sources,e],this.#n(this.sources),this.#r?.(e)}},Td=class{#e;constructor(e){this.#e=e;for(let t of[Us.position,Us.speedOverGround,Us.courseOverGroundTrue,Us.headingTrue])e.cell(t)}get sogMps(){return Bs(this.#t(Us.speedOverGround))}get cogRad(){return Bs(this.#t(Us.courseOverGroundTrue))}get headingRad(){return Bs(this.#t(Us.headingTrue))}get position(){let e=this.#t(Us.position);return Ls(e)?e:void 0}#t(e){return this.#e.cell(e).value}};function Ed(e){return{west:e.getWest(),south:e.getSouth(),east:e.getEast(),north:e.getNorth()}}function Dd(e,t){let n=Math.max(1e-6,e.east-e.west)/Math.max(1e-6,e.north-e.south),r=Math.max(2,Math.round(Math.sqrt(t/n))),i=Math.max(2,Math.floor(t/r));return{lats:Od(e.south,e.north,r),lons:Od(e.west,e.east,i)}}function Od(e,t,n){let r=(t-e)/(n-1);return Array.from({length:n},(t,n)=>e+n*r)}function kd(e,t,n,r){let i=Ad(e.lons,n),a=Ad(e.lats,r);if(!i||!a)return;let o=e.lons.length,s=t[a.i*o+i.i],c=t[a.i*o+i.i+1],l=t[(a.i+1)*o+i.i],u=t[(a.i+1)*o+i.i+1];return lc(lc(s,c,i.f),lc(l,u,i.f),a.f)}function Ad(e,t){if(!(t<e[0]||t>e[e.length-1])){for(let n=0;n<e.length-1;n+=1)if(t<=e[n+1]){let r=e[n+1]-e[n]||1;return{i:n,f:(t-e[n])/r}}return{i:e.length-2,f:1}}}function jd(e,t){let n=e.times;if(n.length===0||t<=n[0])return{lo:0,hi:0,frac:0};if(t>=n[n.length-1])return{lo:n.length-1,hi:n.length-1,frac:0};for(let e=0;e<n.length-1;e+=1)if(t<=n[e+1]){let r=n[e+1]-n[e]||1;return{lo:e,hi:e+1,frac:(t-n[e])/r}}return{lo:n.length-1,hi:n.length-1,frac:0}}var Md=class{#e=z(void 0);get grid(){return W(this.#e)}set grid(e){B(this.#e,e,!0)}#t=z(`idle`);get status(){return W(this.#t)}set status(e){B(this.#t,e,!0)}#n=z(void 0);get bbox(){return W(this.#n)}set bbox(e){B(this.#n,e,!0)}#r=z(0);get selectedTime(){return W(this.#r)}set selectedTime(e){B(this.#r,e,!0)}#i=z(void 0);get radar(){return W(this.#i)}set radar(e){B(this.#i,e,!0)}#a=R(()=>this.grid?jd(this.grid,this.selectedTime):{lo:0,hi:0,frac:0});get bracket(){return W(this.#a)}set bracket(e){B(this.#a,e)}setStatus(e){this.status=e}setGrid(e){this.grid=e,this.status=`ready`;let t=e.times[0],n=e.times[e.times.length-1];t!==void 0&&(this.selectedTime<t||this.selectedTime>n)&&(this.selectedTime=t)}setSelectedTime(e){this.selectedTime=e}setRadar(e){this.radar=e}},Nd=K(`<div class="auth-banner svelte-1s059lv" role="status" aria-live="polite">Requesting access as <strong> </strong>. Approve it in Signal K under Security,
750
750
  then Access Requests, and this connects on its own. <a class="action svelte-1s059lv" target="_blank" rel="noopener noreferrer">Approve in Signal K</a></div>`),Pd=K(`<div class="auth-banner denied svelte-1s059lv" role="alert">Access was denied. <button type="button" class="svelte-1s059lv">Request again</button></div>`);function Fd(e,t){Qe(t,!0);var n=oi(),r=Sn(n),i=e=>{var n=Nd(),r=H(V(n)),i=V(r,!0);N(r);var a=H(r,2);N(n),U(()=>{J(i,t.auth.clientId),X(a,`href`,t.requestsUrl)}),q(e,n)},a=e=>{var n=Pd(),r=H(V(n));N(n),G(`click`,r,()=>t.auth.requestAccess()),q(e,n)};Y(r,e=>{t.auth.status===`requesting`?e(i):t.auth.status===`denied`&&e(a,1)}),q(e,n),$e()}Xr([`click`]);var Id=[];function Ld(e){e.key===`Escape`&&Id[Id.length-1]?.()}var Rd=(e,t)=>{let n=t,r=document.activeElement instanceof HTMLElement?document.activeElement:null,i=()=>n();return Id.push(i),Id.length===1&&window.addEventListener(`keydown`,Ld),{update(e){n=e},destroy(){let e=Id.indexOf(i);e>=0&&Id.splice(e,1),Id.length===0&&window.removeEventListener(`keydown`,Ld),r?.focus()}}};function zd(e){let t=`${e} ${new Date().toISOString().slice(0,10)}`,n=window.prompt(`Save ${e.toLowerCase()} as`,t);if(n!==null)return n.trim()||t}var Bd=[`day`,`dusk`,`night-red`],Vd=`binnacle:theme`;function Hd(e){return typeof e==`string`&&Bd.includes(e)}var Ud=class{#e=z(`day`);get theme(){return W(this.#e)}set theme(e){B(this.#e,e,!0)}#t;#n;constructor(e,t,n=()=>{}){this.#t=t,this.#n=n,Hd(e)&&(this.theme=e),this.#t(this.theme)}set(e){this.theme=e,this.#t(e),this.#n(e)}cycle(){let e=Bd[(Bd.indexOf(this.theme)+1)%Bd.length];this.set(e)}};function Wd(e){return new Ud(Gd(),t=>{typeof document<`u`&&(document.documentElement.dataset.theme=t),e?.(t)},Kd)}function Gd(){try{return typeof localStorage<`u`?localStorage.getItem(Vd):null}catch{return null}}function Kd(e){try{typeof localStorage<`u`&&localStorage.setItem(Vd,e)}catch{}}var qd=K(`<p class="status svelte-y8hb2y">Reading chart...</p>`),Jd=K(`<p class="status error svelte-y8hb2y"> </p>`),Yd=K(`<div class="add-form svelte-y8hb2y"><div class="field svelte-y8hb2y"><span class="field-label caps-label svelte-y8hb2y" id="add-chart-url-label"><!> From a URL</span> <div class="url-row svelte-y8hb2y"><input class="url svelte-y8hb2y" type="url" placeholder="https://.../chart.pmtiles" aria-labelledby="add-chart-url-label"/> <button type="button" class="btn btn-ghost">Add</button></div></div> <div class="divider svelte-y8hb2y" aria-hidden="true"><span>or</span></div> <div class="field svelte-y8hb2y"><span class="field-label caps-label svelte-y8hb2y" id="add-chart-file-label"><!> From a file</span> <button type="button" aria-labelledby="add-chart-file-label" aria-describedby="add-chart-file-hint"><!> <span class="drop-primary svelte-y8hb2y">Drop a .pmtiles file</span> <span class="drop-secondary svelte-y8hb2y" id="add-chart-file-hint">or tap to browse</span></button> <input class="native-file svelte-y8hb2y" type="file" accept=".pmtiles" tabindex="-1" aria-hidden="true"/></div> <!> <button type="button" class="btn btn-ghost">Close</button></div>`);function Xd(e,t){Qe(t,!0);let n=z(``),r=z(!1),i=z(void 0),a=z(!1),o=z(void 0);async function s(e){B(r,!0),B(i,void 0);try{await e(),t.onDone()}catch(e){B(i,e instanceof Error?e.message:`Could not add that chart.`,!0)}finally{B(r,!1)}}function c(){let e=W(n).trim();e&&s(async()=>{await t.userCharts.addUrl(e),B(n,``)})}function l(e){let n=e.currentTarget,r=n.files?.[0];r&&(s(()=>t.userCharts.addFile(r)),n.value=``)}function u(){W(r)||W(o)?.click()}function d(e){if(e.preventDefault(),B(a,!1),W(r)||!W(o))return;let t=e.dataTransfer?.files?.[0];if(!t)return;let n=new DataTransfer;n.items.add(t),W(o).files=n.files,W(o).dispatchEvent(new Event(`change`,{bubbles:!0}))}function f(e){W(r)||(e.preventDefault(),B(a,!0))}var p=Yd(),m=V(p),h=V(m);$a(V(h),{size:14,"aria-hidden":`true`}),P(),N(h);var g=H(h,2),_=V(g);Qi(_);var v=H(_,2);N(g),N(m);var y=H(m,4),b=V(y);za(V(b),{size:14,"aria-hidden":`true`}),P(),N(b);var x=H(b,2);let S;za(V(x),{size:22,"aria-hidden":`true`}),P(4),N(x);var C=H(x,2);da(C,e=>B(o,e),()=>W(o)),N(y);var w=H(y,2),T=e=>{q(e,qd())},E=e=>{var t=Jd(),n=V(t,!0);N(t),U(()=>J(n,W(i))),q(e,t)};Y(w,e=>{W(r)?e(T):W(i)&&e(E,1)});var D=H(w,2);N(p),U(e=>{_.disabled=W(r),v.disabled=e,S=Li(x,1,`dropzone svelte-y8hb2y`,null,S,{dragging:W(a)}),x.disabled=W(r),C.disabled=W(r),D.disabled=W(r)},[()=>W(r)||!W(n).trim()]),sa(_,()=>W(n),e=>B(n,e)),G(`click`,v,c),G(`click`,x,u),Yr(`dragenter`,x,f),Yr(`dragover`,x,f),Yr(`dragleave`,x,()=>B(a,!1)),Yr(`drop`,x,d),G(`change`,C,l),G(`click`,D,function(...e){t.onDone?.apply(this,e)}),q(e,p),$e()}Xr([`click`,`change`]);var Zd=K(`<label class="layer-toggle svelte-ld9zxu"><input type="checkbox" class="svelte-ld9zxu"/> <span class="title svelte-ld9zxu"> </span></label>`);function Qd(e,t){Qe(t,!0);var n=Zd(),r=V(n);Qi(r);var i=H(r,2),a=V(i,!0);N(i),N(n),U(()=>{ea(r,t.visible),X(r,`aria-label`,`Show ${t.title} on chart`),X(i,`title`,t.title),J(a,t.title)}),G(`change`,r,e=>t.onToggle(e.currentTarget.checked)),q(e,n),$e()}Xr([`change`]);var $d=K(`<button type="button" class="icon-btn"><!></button>`),ef=K(`<div class="opacity-line svelte-f54a5u"><span class="lbl svelte-f54a5u">Opacity</span> <input class="opacity svelte-f54a5u" type="range" min="0" max="1" step="0.05"/> <span class="opacity-val svelte-f54a5u"> </span></div>`),tf=K(`<li><div class="row-main svelte-f54a5u"><button type="button" class="icon-btn handle svelte-f54a5u" aria-keyshortcuts="ArrowUp ArrowDown"><!></button> <!> <!></div> <!></li>`);function nf(e,t){Qe(t,!0);let n=R(()=>Math.round(t.item.opacity*100));var r=tf();let i;var a=V(r),o=V(a);Ya(V(o),{size:18,"aria-hidden":`true`}),N(o);var s=H(o,2);Qd(s,{get title(){return t.item.title},get visible(){return t.item.visible},onToggle:e=>t.view.toggle(t.item.id,e)});var c=H(s,2),l=e=>{var n=$d();So(V(n),{size:18,"aria-hidden":`true`}),N(n),U(()=>X(n,`aria-label`,`Manage ${t.item.title}`)),G(`click`,n,function(...e){t.onManage?.apply(this,e)}),q(e,n)};Y(c,e=>{t.onManage&&e(l)}),N(a);var u=H(a,2),d=e=>{var r=ef(),i=H(V(r),2);Qi(i);var a=H(i,2),o=V(a);N(a),N(r),U(()=>{$i(i,t.item.opacity),X(i,`aria-label`,`${t.item.title} opacity`),J(o,`${W(n)??``}%`)}),G(`input`,i,e=>t.view.setOpacity(t.item.id,Number(e.currentTarget.value))),q(e,r)};Y(u,e=>{t.item.supportsOpacity&&t.item.visible&&e(d)}),N(r),U(()=>{i=Li(r,1,`row svelte-f54a5u`,null,i,{dragging:t.dragging,"drop-before":t.dropBefore,"drop-after":t.dropAfter}),X(r,`data-layer-row`,t.item.id),X(o,`aria-label`,`Move ${t.item.title}, position ${t.index+1} of ${t.count}`)}),G(`pointerdown`,o,function(...e){t.onHandlePointerDown?.apply(this,e)}),G(`keydown`,o,function(...e){t.onHandleKeydown?.apply(this,e)}),q(e,r),$e()}Xr([`pointerdown`,`keydown`,`click`,`input`]);function rf(e){return e===`basemap`||e===`bathymetry`?`Charts and Depth`:e===`weather`?`Weather`:`Overlays`}var af=K(`<div class="svelte-1shuvj5"><dt class="svelte-1shuvj5">Size</dt> <dd class="svelte-1shuvj5"> </dd></div>`),of=K(`<div class="confirm svelte-1shuvj5"><p class="svelte-1shuvj5"> </p> <div class="actions svelte-1shuvj5"><button type="button" class="btn">Cancel</button> <button type="button" class="btn btn-danger">Delete</button></div></div>`),sf=K(`<button type="button" class="btn btn-danger"><!> Delete chart</button>`),cf=K(`<div class="detail svelte-1shuvj5"><header class="svelte-1shuvj5"><button type="button" class="icon-btn" aria-label="Back to layers"><!></button> <h3 class="svelte-1shuvj5">Chart detail</h3></header> <label class="name-field svelte-1shuvj5"><span class="caps-label">Name</span> <input type="text" class="svelte-1shuvj5"/></label> <dl class="svelte-1shuvj5"><div class="svelte-1shuvj5"><dt class="svelte-1shuvj5">Type</dt> <dd class="svelte-1shuvj5"> </dd></div> <div class="svelte-1shuvj5"><dt class="svelte-1shuvj5">Source</dt> <dd class="svelte-1shuvj5"> </dd></div> <div class="svelte-1shuvj5"><dt class="svelte-1shuvj5">Zoom</dt> <dd class="svelte-1shuvj5"> </dd></div> <div class="svelte-1shuvj5"><dt class="svelte-1shuvj5">Bounds</dt> <dd class="svelte-1shuvj5"> </dd></div> <!></dl> <!></div>`);function lf(e,t){Qe(t,!0);let n=z(!1),r=z(``);Ln(()=>{B(r,t.source.name,!0)});function i(){let e=W(r).trim();e&&e!==t.source.name&&t.userCharts.rename(t.source.id,e)}function a(e){if(!e)return`Unknown`;let t=e=>e.toFixed(2);return`${t(e[1])}, ${t(e[0])} to ${t(e[3])}, ${t(e[2])}`}async function o(){t.onBack(),await t.userCharts.remove(t.source.id)}var s=cf(),c=V(s),l=V(c);Da(V(l),{size:18,"aria-hidden":`true`}),N(l),P(2),N(c);var u=H(c,2),d=H(V(u),2);Qi(d),N(u);var f=H(u,2),p=V(f),m=H(V(p),2),h=V(m,!0);N(m),N(p);var g=H(p,2),_=H(V(g),2),v=V(_,!0);N(_),N(g);var y=H(g,2),b=H(V(y),2),x=V(b);N(b),N(y);var S=H(y,2),C=H(V(S),2),w=V(C,!0);N(C),N(S);var T=H(S,2),E=e=>{var n=af(),r=H(V(n),2),i=V(r,!0);N(r),N(n),U(e=>J(i,e),[()=>rc(t.source.byteSize)]),q(e,n)};Y(T,e=>{t.source.byteSize&&e(E)}),N(f);var D=H(f,2),O=e=>{var r=of(),i=V(r),a=V(i);N(i);var s=H(i,2),c=V(s),l=H(c,2);N(s),N(r),U(e=>J(a,`Delete this chart?${e??``}`),[()=>t.source.byteSize?` Frees ${rc(t.source.byteSize)}.`:``]),G(`click`,c,()=>B(n,!1)),G(`click`,l,o),q(e,r)},k=e=>{var t=sf();Ro(V(t),{size:16,"aria-hidden":`true`}),P(),N(t),G(`click`,t,()=>B(n,!0)),q(e,t)};Y(D,e=>{W(n)?e(O):e(k,-1)}),N(s),U(e=>{J(h,t.source.kind===`vector`?`Vector`:`Raster`),J(v,t.source.origin.type===`url`?`URL`:`File (offline)`),J(x,`${t.source.minzoom??0??``} to ${t.source.maxzoom??t.source.minzoom??0??``}`),J(w,e)},[()=>a(t.source.bounds)]),G(`click`,l,function(...e){t.onBack?.apply(this,e)}),Yr(`blur`,d,i),G(`keydown`,d,e=>{e.key===`Enter`&&e.currentTarget.blur()}),sa(d,()=>W(r),e=>B(r,e)),q(e,s),$e()}Xr([`click`,`keydown`]);var uf=K(`<p class="empty svelte-1k55jex">No layers</p>`),df=K(`<li class="pinned-row svelte-1k55jex"><span class="pin svelte-1k55jex" aria-hidden="true"><!></span> <span class="title svelte-1k55jex"> </span> <span class="on-top svelte-1k55jex">On top</span></li>`),ff=K(`<ul class="pinned-list svelte-1k55jex"></ul>`),pf=K(`<li class="group-label caps-label svelte-1k55jex" aria-hidden="true"> </li>`),mf=K(`<!> <!>`,1),hf=K(`<!> <ul class="rows svelte-1k55jex"></ul>`,1),gf=K(`<button type="button" class="add-chart svelte-1k55jex">+ Add a chart</button>`),_f=K(`<div class="add-chart-area svelte-1k55jex"><!></div>`),vf=K(`<aside class="slide-over slide-over--dock-left" aria-label="Layers"><header class="svelte-1k55jex"><h2 class="panel-title svelte-1k55jex">Layers</h2> <button type="button" class="panel-close" aria-label="Close"><!></button></header> <div class="body svelte-1k55jex"><!></div></aside>`);function yf(e,t){Qe(t,!0);let n=R(()=>t.view.items.filter(e=>e.pinned)),r=R(()=>t.view.items.filter(e=>!e.pinned)),i=R(()=>new Map((t.userCharts?.sources??[]).map(e=>[fl(e.id),e.id]))),a=z(!1),o=z(void 0),s=R(()=>W(o)?t.userCharts?.sources.find(e=>e.id===W(o)):void 0),c=z(void 0),l=z(null),u=z(null),d=R(()=>W(l)===null?W(r):W(r).filter(e=>e.id!==W(l)));function f(e){return W(r).findIndex(t=>t.id===e)}function p(e){if(W(l)===null||W(u)===null||e===W(l))return{before:!1,after:!1};let t=W(d).findIndex(t=>t.id===e);return t<0?{before:!1,after:!1}:W(u)===W(d).length?{before:!1,after:t===W(d).length-1}:{before:t===W(u),after:!1}}function m(e){if(!W(c))return 0;let t=[...W(c).querySelectorAll(`[data-layer-row]`)].filter(e=>e.dataset.layerRow!==W(l));for(let n=0;n<t.length;n++){let r=t[n].getBoundingClientRect();if(e<r.top+r.height/2)return n}return t.length}function h(e,n){if(n.button!==0&&n.pointerType===`mouse`)return;n.preventDefault(),B(l,e,!0),B(u,f(e),!0);let r=n.currentTarget;r.setPointerCapture(n.pointerId);let i=new AbortController,{signal:a}=i,o=e=>{i.abort(),r.releasePointerCapture(n.pointerId),e&&W(l)!==null&&W(u)!==null&&t.view.reorder(W(l),W(u)),B(l,null),B(u,null)};r.addEventListener(`pointermove`,e=>{B(u,m(e.clientY),!0)},{signal:a}),r.addEventListener(`pointerup`,()=>o(!0),{signal:a}),r.addEventListener(`pointercancel`,()=>o(!1),{signal:a})}function g(e,n){let i=f(e);if(i<0)return;let a=i;if(n.key===`ArrowUp`)a=i-1;else if(n.key===`ArrowDown`)a=i+1;else return;n.preventDefault(),!(a<0||a>=W(r).length)&&(t.view.reorder(e,a),requestAnimationFrame(()=>{(W(c)?.querySelector(`[data-layer-row="${CSS.escape(e)}"] .handle`))?.focus()}))}var _=vf(),v=V(_),y=H(V(v),2);Ko(V(y),{size:18,"aria-hidden":`true`}),N(y),N(v);var b=H(v,2),x=V(b),S=e=>{var n=oi();pi(Sn(n),()=>W(s).id,e=>{lf(e,{get source(){return W(s)},get userCharts(){return t.userCharts},onBack:()=>B(o,void 0)})}),q(e,n)},C=e=>{var s=mf(),u=Sn(s),d=e=>{q(e,uf())},f=e=>{var a=hf(),s=Sn(a),u=e=>{var t=ff();vi(t,21,()=>W(n),e=>e.id,(e,t)=>{var n=df(),r=V(n);fo(V(r),{size:16}),N(r);var i=H(r,2),a=V(i,!0);N(i),P(2),N(n),U(()=>{X(i,`title`,W(t).title),J(a,W(t).title)}),q(e,n)}),N(t),q(e,t)};Y(s,e=>{W(n).length>0&&e(u)});var d=H(s,2);vi(d,23,()=>W(r),e=>e.id,(e,n,a)=>{let s=R(()=>p(W(n).id)),c=R(()=>W(i).get(W(n).id));var u=mf(),d=Sn(u),f=e=>{var t=pf(),r=V(t,!0);N(t),U(e=>J(r,e),[()=>rf(W(n).band)]),q(e,t)},m=R(()=>W(a)===0||rf(W(r)[W(a)-1].band)!==rf(W(n).band));Y(d,e=>{W(m)&&e(f)});var _=H(d,2);{let e=R(()=>W(l)===W(n).id),i=R(()=>W(c)?()=>B(o,W(c),!0):void 0);nf(_,{get item(){return W(n)},get view(){return t.view},get index(){return W(a)},get count(){return W(r).length},get dragging(){return W(e)},get dropBefore(){return W(s).before},get dropAfter(){return W(s).after},onHandlePointerDown:e=>h(W(n).id,e),onHandleKeydown:e=>g(W(n).id,e),get onManage(){return W(i)}})}q(e,u)}),N(d),da(d,e=>B(c,e),()=>W(c)),q(e,a)};Y(u,e=>{t.view.items.length===0?e(d):e(f,-1)});var m=H(u,2),_=e=>{var n=_f(),r=V(n),i=e=>{Xd(e,{get userCharts(){return t.userCharts},onDone:()=>B(a,!1)})},o=e=>{var t=gf();G(`click`,t,()=>B(a,!0)),q(e,t)};Y(r,e=>{W(a)?e(i):e(o,-1)}),N(n),q(e,n)};Y(m,e=>{t.userCharts&&e(_)}),q(e,s)};Y(x,e=>{W(s)&&t.userCharts?e(S):e(C,-1)}),N(b),N(_),Di(_,(e,t)=>Rd?.(e,t),()=>t.onClose),G(`click`,y,function(...e){t.onClose?.apply(this,e)}),q(e,_),$e()}Xr([`click`]);var bf=class{#e=z(dn([]));get items(){return W(this.#e)}set items(e){B(this.#e,e,!0)}#t;constructor(e){this.#t=e}refresh(){this.items=this.#t.layers()}toggle(e,t){this.#t.toggle(e,t),this.refresh()}setOpacity(e,t){this.#t.setOpacity(e,t);let n=this.items.find(t=>t.id===e);n&&(n.opacity=t)}reorder(e,t){this.#t.reorder(e,t),this.refresh()}},xf=`notifications.navigation.collision`;function Sf(e){let t=e.contacts[0];if(!t)return{state:`normal`,method:[],message:`No collision risk`};let n=t.name||t.id,r=Ec(t.cpaMeters),i=Dc(t.tcpaSeconds),a=e.worst===`danger`;return{state:a?`alarm`:`warn`,method:a?[`visual`,`sound`]:[`visual`],message:`Collision ${e.worst}: ${n} CPA ${r} nm, TCPA ${i} min`}}var Cf=class{#e;#t;#n=!1;constructor(e){this.#e=e}update(e){let t=Sf(e),n=`${t.state}|${e.contacts[0]?.id??``}`;n!==this.#t&&(this.#t=n,!(t.state===`normal`&&!this.#n)&&(this.#n=t.state!==`normal`,this.#e(xf,t)))}},wf=`binnacle-collision`,Tf=`binnacle-collision-ring`,Ef=`collision`;function Df(e){return[`match`,[`get`,`severity`],`danger`,e.danger,`warning`,e.warning,e.warning]}function Of(e){return{type:`FeatureCollection`,features:e.map(e=>({type:`Feature`,geometry:{type:`Point`,coordinates:[e.position.longitude,e.position.latitude]},properties:{severity:e.severity}}))}}function kf(e){let t;return{id:Ef,title:`Collision risk`,band:`safety`,supportsOpacity:!0,layerIds:[Tf],add(n){let r=e.assessment.contacts,i={type:`geojson`,data:Of(r)};n.map.addSource(wf,i);let a={id:Tf,type:`circle`,source:wf,paint:{"circle-radius":[`match`,[`get`,`severity`],`danger`,20,`warning`,16,16],"circle-color":`rgba(0, 0, 0, 0)`,"circle-stroke-width":[`match`,[`get`,`severity`],`danger`,3,`warning`,2,2],"circle-stroke-color":Df(sl(`day`))}};n.map.addLayer(a,n.beforeIdFor(`safety`)),t=r},sync(n){let r=e.assessment.contacts;r!==t&&(t=r,n.map.getSource(wf)?.setData(Of(r)))},applyTheme(e,t){e.map.setPaintProperty(Tf,`circle-stroke-color`,Df(t))},setVisible(e,t){e.map.setLayoutProperty(Tf,`visibility`,t?`visible`:`none`)},setOpacity(e,t){e.map.setPaintProperty(Tf,`circle-stroke-opacity`,t)},remove(e){e.map.getLayer(Tf)&&e.map.removeLayer(Tf),e.map.getSource(wf)&&e.map.removeSource(wf)}}}var Af=K(`<span class="note">computing locally</span>`),jf=K(`<li><span class="name svelte-1xtn712"> </span> <span class="metric">CPA <b> </b> nm</span> <span class="metric">TCPA <b> </b> min</span></li>`),Mf=K(`<p class="more svelte-1xtn712"> </p>`),Nf=K(`<aside class="bottom-strip bottom-strip--alarm" aria-label="Collision danger" aria-live="assertive"><div class="head"><span class="title">Danger</span> <!> <button type="button" class="ack">Acknowledge</button></div> <ul class="list svelte-1xtn712"></ul> <!></aside>`);function Pf(e,t){Qe(t,!0);let n=R(()=>t.collision.assessment.contacts),r=R(()=>W(n).slice(0,4)),i=R(()=>Math.max(0,W(n).length-4)),a=R(()=>W(n).some(e=>e.source===`computed`));var o=oi(),s=Sn(o),c=e=>{var n=Nf(),o=V(n),s=H(V(o),2),c=e=>{q(e,Af())};Y(s,e=>{W(a)&&e(c)});var l=H(s,2);N(o);var u=H(o,2);vi(u,21,()=>W(r),e=>e.id,(e,t)=>{var n=jf(),r=V(n),i=V(r,!0);N(r);var a=H(r,2),o=H(V(a)),s=V(o,!0);N(o),P(),N(a);var c=H(a,2),l=H(V(c)),u=V(l,!0);N(l),P(),N(c),N(n),U((e,r)=>{Li(n,1,`row ${W(t).severity??``}`,`svelte-1xtn712`),J(i,W(t).name||W(t).id),J(s,e),J(u,r)},[()=>Ec(W(t).cpaMeters),()=>Dc(W(t).tcpaSeconds,1)]),q(e,n)}),N(u);var d=H(u,2),f=e=>{var t=Mf(),n=V(t);N(t),U(()=>J(n,`+${W(i)??``} more`)),q(e,t)};Y(d,e=>{W(i)>0&&e(f)}),N(n),G(`click`,l,()=>t.collision.acknowledge()),q(e,n)};Y(s,e=>{W(n).length>0&&!t.collision.suppressed&&e(c)}),q(e,o),$e()}Xr([`click`]);var Ff={frequency:880,beepMs:140,gapMs:90,beeps:2,periodMs:1200,volume:.18};function If(){if(typeof window>`u`)return;let e=window.AudioContext??window.webkitAudioContext;return e?new e:void 0}var Lf=class{#e;#t;#n;prime(){let e=this.#r();e&&e.state===`suspended`&&e.resume()}start(e){if(this.#t!==void 0&&this.#n?.frequency===e.frequency&&this.#n?.periodMs===e.periodMs)return;this.stop();let t=this.#r();t&&(t.state===`suspended`&&t.resume(),this.#n=e,this.#i(t,e),this.#t=setInterval(()=>this.#i(t,e),e.periodMs))}stop(){this.#t!==void 0&&clearInterval(this.#t),this.#t=void 0,this.#n=void 0}#r(){return this.#e||=If(),this.#e}#i(e,t){e.state===`suspended`&&e.resume();let n=(t.beepMs+t.gapMs)/1e3;for(let r=0;r<t.beeps;r+=1)this.#a(e,t,e.currentTime+r*n)}#a(e,t,n){let r=e.createOscillator(),i=e.createGain();r.type=`square`,r.frequency.value=t.frequency;let a=t.beepMs/1e3;i.gain.setValueAtTime(0,n),i.gain.linearRampToValueAtTime(t.volume,n+.012),i.gain.setValueAtTime(t.volume,n+a-.02),i.gain.linearRampToValueAtTime(0,n+a),r.connect(i).connect(e.destination),r.start(n),r.stop(n+a)}},Rf=class{#e;constructor(e=new Lf){this.#e=e}prime(){this.#e.prime()}update(e,t,n){e===`danger`&&!t&&!n?this.#e.start(Ff):this.#e.stop()}stop(){this.#e.stop()}},zf=K(`<section class="thresholds svelte-1m2b4oj" aria-label="Collision thresholds"><div class="group svelte-1m2b4oj"><span class="group-title danger svelte-1m2b4oj">Danger</span> <label class="field svelte-1m2b4oj"><span class="name svelte-1m2b4oj">CPA</span> <input type="number" min="0" step="0.05" aria-label="Danger CPA" class="svelte-1m2b4oj"/> <span class="unit svelte-1m2b4oj">nm</span></label> <label class="field svelte-1m2b4oj"><span class="name svelte-1m2b4oj">TCPA</span> <input type="number" min="0" step="1" aria-label="Danger TCPA" class="svelte-1m2b4oj"/> <span class="unit svelte-1m2b4oj">min</span></label></div> <div class="group svelte-1m2b4oj"><span class="group-title warning svelte-1m2b4oj">Warning</span> <label class="field svelte-1m2b4oj"><span class="name svelte-1m2b4oj">CPA</span> <input type="number" min="0" step="0.05" aria-label="Warning CPA" class="svelte-1m2b4oj"/> <span class="unit svelte-1m2b4oj">nm</span></label> <label class="field svelte-1m2b4oj"><span class="name svelte-1m2b4oj">TCPA</span> <input type="number" min="0" step="1" aria-label="Warning TCPA" class="svelte-1m2b4oj"/> <span class="unit svelte-1m2b4oj">min</span></label></div> <button type="button" class="btn btn-ghost reset svelte-1m2b4oj">Reset to defaults</button></section>`);function Bf(e,t){Qe(t,!0);let n=R(()=>t.thresholds.value);function r(e,n){!Number.isFinite(n)||n<0||t.thresholds.set({...t.thresholds.value,[e]:Cc(n)})}function i(e,n){!Number.isFinite(n)||n<0||t.thresholds.set({...t.thresholds.value,[e]:n*60})}let a=e=>Ec(e),o=e=>Dc(e);var s=zf(),c=V(s),l=H(V(c),2),u=H(V(l),2);Qi(u),P(2),N(l);var d=H(l,2),f=H(V(d),2);Qi(f),P(2),N(d),N(c);var p=H(c,2),m=H(V(p),2),h=H(V(m),2);Qi(h),P(2),N(m);var g=H(m,2),_=H(V(g),2);Qi(_),P(2),N(g),N(p);var v=H(p,2);N(s),U((e,t,n,r)=>{$i(u,e),$i(f,t),$i(h,n),$i(_,r)},[()=>a(W(n).dangerCpaMeters),()=>o(W(n).dangerTcpaSeconds),()=>a(W(n).warningCpaMeters),()=>o(W(n).warningTcpaSeconds)]),G(`change`,u,e=>r(`dangerCpaMeters`,Number(e.currentTarget.value))),G(`change`,f,e=>i(`dangerTcpaSeconds`,Number(e.currentTarget.value))),G(`change`,h,e=>r(`warningCpaMeters`,Number(e.currentTarget.value))),G(`change`,_,e=>i(`warningTcpaSeconds`,Number(e.currentTarget.value))),G(`click`,v,()=>t.thresholds.set({...es})),q(e,s),$e()}Xr([`change`,`click`]);var Vf=K(`<button type="button" class="item svelte-1xvdgg7"><!> <span> </span></button>`),Hf=K(`<div class="divider svelte-1xvdgg7" aria-hidden="true"></div>`),Uf=K(`<span class="empty svelte-1xvdgg7">No options</span>`),Wf=K(`<div class="popout svelte-1xvdgg7" id="app-menu-popout"><!> <!> <!> <!></div>`),Gf=K(`<div class="app-menu svelte-1xvdgg7"><button type="button" class="trigger svelte-1xvdgg7" aria-haspopup="true" aria-controls="app-menu-popout"><!></button> <!></div>`);function Kf(e,t){Qe(t,!0);let n=ha(t,`items`,19,()=>[]),r=ha(t,`label`,3,`Menu`),i=z(!1),a=z(void 0);function o(){B(i,!1)}function s(e){e.disabled||(e.onSelect(),o())}function c(e){W(i)&&W(a)&&!W(a).contains(e.target)&&o()}function l(e){W(i)&&e.key===`Escape`&&o()}var u=Gf();Yr(`pointerdown`,mn,c),Yr(`keydown`,mn,l);var d=V(u);ro(V(d),{size:20,"aria-hidden":`true`}),N(d);var f=H(d,2),p=e=>{var r=Wf(),i=V(r);vi(i,17,n,e=>e.id,(e,t)=>{var n=Vf(),r=V(n),i=e=>{let n=R(()=>W(t).icon);var r=oi();Ti(Sn(r),()=>W(n),(e,t)=>{t(e,{size:16,"aria-hidden":`true`})}),q(e,r)};Y(r,e=>{W(t).icon&&e(i)});var a=H(r,2),o=V(a,!0);N(a),N(n),U(()=>{n.disabled=W(t).disabled,J(o,W(t).label)}),G(`click`,n,()=>s(W(t))),q(e,n)});var a=H(i,2),o=e=>{q(e,Hf())};Y(a,e=>{n().length>0&&t.children&&e(o)});var c=H(a,2);wi(c,()=>t.children??x);var l=H(c,2),u=e=>{q(e,Uf())};Y(l,e=>{n().length===0&&!t.children&&e(u)}),N(r),q(e,r)};Y(f,e=>{W(i)&&e(p)}),N(u),da(u,e=>B(a,e),()=>W(a)),U(()=>{X(d,`aria-expanded`,W(i)),X(d,`aria-label`,r()),X(d,`title`,r())}),G(`click`,d,()=>B(i,!W(i))),q(e,u),$e()}Xr([`click`]);var qf=K(`<div class="submenu-content svelte-k66xob"><!></div>`),Jf=K(`<div class="submenu svelte-k66xob"><button type="button" class="submenu-trigger svelte-k66xob"><!> <span class="submenu-label svelte-k66xob"> </span> <!></button> <!></div>`);function Yf(e,t){Qe(t,!0);let n=z(!1),r=R(()=>`submenu-${t.label.toLowerCase().replace(/\s+/g,`-`)}`);var i=Jf(),a=V(i),o=V(a),s=e=>{let n=R(()=>t.icon);var r=oi();Ti(Sn(r),()=>W(n),(e,t)=>{t(e,{size:16,"aria-hidden":`true`})}),q(e,r)};Y(o,e=>{t.icon&&e(s)});var c=H(o,2),l=V(c,!0);N(c);var u=H(c,2),d=e=>{Na(e,{size:16,"aria-hidden":`true`})},f=e=>{Fa(e,{size:16,"aria-hidden":`true`})};Y(u,e=>{W(n)?e(d):e(f,-1)}),N(a);var p=H(a,2),m=e=>{var n=qf();wi(V(n),()=>t.children),N(n),U(()=>X(n,`id`,W(r))),q(e,n)};Y(p,e=>{W(n)&&e(m)}),N(i),U(()=>{X(a,`aria-expanded`,W(n)),X(a,`aria-controls`,W(r)),J(l,t.label)}),G(`click`,a,()=>B(n,!W(n))),q(e,i),$e()}Xr([`click`]);var Xf={frequency:520,beepMs:180,gapMs:120,beeps:2,periodMs:2500,volume:.14},Zf=class{#e;#t=!1;constructor(e=new Lf){this.#e=e}prime(){this.#e.prime()}update(e,t){if(e&&!t&&!this.#t){this.#t=!0,this.#e.start(Xf);return}(!e||t)&&(this.#t&&this.#e.stop(),this.#t=!1)}stop(){this.#e.stop(),this.#t=!1}},Qf=K(`<span class="note">computing locally</span>`),$f=K(`<span class="steer svelte-q2yqul"> </span>`),ep=K(`<aside class="bottom-strip bottom-strip--accent" aria-label="Active route" aria-live="polite"><div class="head"><span class="title">To</span> <span class="name svelte-q2yqul"> </span> <!> <button type="button" class="ack">Stop</button></div> <div class="row"><span class="metric">DTW <b> </b> nm</span> <span class="metric">BTW <b> </b>&deg;</span> <span class="metric">XTE <!> <b> </b> nm</span> <span class="metric">VMG <b> </b> kn</span> <span class="metric">TTG <b> </b> min</span></div></aside>`);function tp(e,t){Qe(t,!0);let n=R(()=>{let e=Vc(t.guidance.crossTrackErrorMeters??NaN);return e===null?null:e===`port`?`L`:`R`}),r=R(()=>t.guidance.distanceToNextMeters==null?`--`:wc(t.guidance.distanceToNextMeters)),i=R(()=>xc(_c(t.guidance.bearingToNextRad),0)),a=R(()=>t.guidance.crossTrackErrorMeters==null?`--`:wc(Math.abs(t.guidance.crossTrackErrorMeters))),o=R(()=>t.guidance.velocityMadeGoodMps==null?`--`:Tc(t.guidance.velocityMadeGoodMps)),s=R(()=>t.guidance.timeToGoSeconds==null?`--`:Dc(t.guidance.timeToGoSeconds,0));var c=oi(),l=Sn(c),u=e=>{var c=ep(),l=V(c),u=H(V(l),2),d=V(u,!0);N(u);var f=H(u,2),p=e=>{q(e,Qf())};Y(f,e=>{t.guidance.source===`computed`&&e(p)});var m=H(f,2);N(l);var h=H(l,2),g=V(h),_=H(V(g)),v=V(_,!0);N(_),P(),N(g);var y=H(g,2),b=H(V(y)),x=V(b,!0);N(b),P(),N(y);var S=H(y,2),C=H(V(S)),w=e=>{var t=$f(),r=V(t,!0);N(t),U(()=>J(r,W(n))),q(e,t)};Y(C,e=>{W(n)&&e(w)});var T=H(C,2),E=V(T,!0);N(T),P(),N(S);var D=H(S,2),O=H(V(D)),k=V(O,!0);N(O),P(),N(D);var A=H(D,2),ee=H(V(A)),te=V(ee,!0);N(ee),P(),N(A),N(h),N(c),U(()=>{J(d,t.guidance.nextPointName??`--`),J(v,W(r)),J(x,W(i)),J(E,W(a)),J(k,W(o)),J(te,W(s))}),G(`click`,m,function(...e){t.onStop?.apply(this,e)}),q(e,c)};Y(l,e=>{t.guidance.active&&e(u)}),q(e,c),$e()}Xr([`click`]);var np=[`text`,`measure`,`count`,`availability`,`flag`,`rating`,`link`,`note`],rp=`/signalk/v2/api/resources/notes`,ip=`/signalk/v1/api/resources/notes`;function ap(e){return e.replace(/<[^>]*>/g,` `).replace(/\s+/g,` `).trim()}function op(e){try{let t=new URL(e);if(t.protocol===`http:`||t.protocol===`https:`)return t.toString()}catch{}}function sp(e){return np.includes(e)}function cp(e){if(!e||typeof e!=`object`)return;let t=e,n=Ks(t.label);if(n===void 0)return;let r=t.value;if(typeof r!=`string`&&typeof r!=`number`&&typeof r!=`boolean`)return;let i={label:n,value:r};sp(t.kind)&&(i.kind=t.kind);let a=Ks(t.unit);return a!==void 0&&(i.unit=a),i}function lp(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!n||typeof n!=`object`)continue;let e=n,r=Ks(e.title);if(r===void 0||!Array.isArray(e.items))continue;let i=e.items.map(cp).filter(e=>e!==void 0);i.length!==0&&t.push({id:Ks(e.id)??r,title:r,items:i})}return t.length>0?t:void 0}async function up(e,t,n){try{let r=await fetch(e,Ws(t));if(!r.ok)return;let i=Gs(await r.json());if(!i)return;let a=i,o=a.properties??{},s=o.crowsNest,c={id:n,name:Ks(a.name)??Ks(a.title)??n,type:typeof s?.type==`string`?s.type:void 0,attribution:Ks(o.attribution),sources:qs(o.sources),url:Ks(a.url)},l=s?.schemaVersion===1?lp(s.sections):void 0;return l?c.sections=l:c.fallbackText=ap(Ks(a.description)??``)||void 0,c}catch(t){console.warn(`[notes] detail fetch failed: ${e}`,t);return}}async function dp(e,t,n){if(!n)return;let r=`/${encodeURIComponent(n)}`;return await up(`${e}${rp}${r}`,t,n)??await up(`${e}${ip}${r}`,t,n)}function fp(e,t){let n=new Map,r=new Map;return{load(i){let a=n.get(i);if(a)return Promise.resolve(a);let o=r.get(i);if(o)return o;let s=dp(e,t,i).then(e=>(e&&n.set(i,e),e)).finally(()=>{r.delete(i)});return r.set(i,s),s}}}var pp={feature:0,light:1,depth:2,dockage:2,navigation:3,fuel:4,structure:5,mooring:6,daymark:6,contact:7,signals:7,amenities:8,services:9,retail:10,quality:11,remarks:12,notes:12,information:12,business:16,review:17,featuredReview:18,source:20},mp=13;function hp(e){return e.map((e,t)=>({section:e,index:t,rank:pp[e.id]??mp})).sort((e,t)=>e.rank-t.rank||e.index-t.index).map(e=>e.section)}var gp=new Set([`notes`,`note`,`information`,`remark`,`remarks`]);function _p(e,t){let n=e.trim().toLowerCase();return n===t.trim().toLowerCase()||gp.has(n)}function vp(e,t){return t===`flag`&&e.trim().toLowerCase()===`dangerous`}var yp={anchorage:`anchorage`,anchor_berth:`anchorage`,mooring:`anchorage`,marina:`marina`,harbour:`marina`,yacht_club:`marina`,fuel:`fuel`,fuel_station:`fuel`,water:`services`,water_tap:`services`,pumpout:`services`,provisions:`services`,electricity:`services`,repairs:`services`,chandler:`services`,business:`services`,inlet:`inlet`,hazard:`hazard`,obstruction:`hazard`,rock:`hazard`,wreck:`hazard`,beacon_isolated_danger:`hazard`,buoy_isolated_danger:`hazard`,"navigation-structure":`navaid`,beacon_cardinal:`navaid`,beacon_lateral:`navaid`,beacon_safe_water:`navaid`,beacon_special_purpose:`navaid`,buoy_cardinal:`navaid`,buoy_lateral:`navaid`,buoy_safe_water:`navaid`,buoy_special_purpose:`navaid`,light_float:`navaid`,light_major:`navaid`,light_minor:`navaid`,light_vessel:`navaid`,bridge:`bridge`,boatramp:`ramp`,dam:`structure`,lock:`structure`,lock_basin:`structure`,ferry:`structure`},bp=[[`fuel`,`fuel`],[`anchor`,`anchorage`],[`mooring`,`anchorage`],[`marina`,`marina`],[`harbour`,`marina`],[`harbor`,`marina`],[`yacht`,`marina`],[`wreck`,`hazard`],[`rock`,`hazard`],[`obstruction`,`hazard`],[`hazard`,`hazard`],[`danger`,`hazard`],[`buoy`,`navaid`],[`beacon`,`navaid`],[`light`,`navaid`],[`navigation`,`navaid`],[`inlet`,`inlet`],[`pumpout`,`services`],[`pump_out`,`services`],[`water`,`services`],[`provision`,`services`],[`grocery`,`services`],[`repair`,`services`],[`chandler`,`services`],[`business`,`services`],[`bridge`,`bridge`],[`ramp`,`ramp`],[`lock`,`structure`],[`dam`,`structure`],[`ferry`,`structure`]],xp={anchorage:`Anchorage`,marina:`Marina`,fuel:`Fuel`,services:`Services`,inlet:`Inlet`,ramp:`Boat ramp`,bridge:`Bridge`,hazard:`Hazard`,navaid:`Navigation aid`,structure:`Structure`,generic:`Point of interest`},Sp=Object.keys(xp);function Cp(e){if(!e)return`generic`;let t=e.toLowerCase(),n=yp[t];if(n)return n;for(let[e,n]of bp)if(t.includes(e))return n;return`generic`}function wp(e){return xp[e]}function Tp(e){return`binnacle-poi-${e}`}var Ep={hazard:100,navaid:90,inlet:70,anchorage:60,marina:55,fuel:50,services:40,ramp:30,bridge:25,structure:20,generic:0};function Dp(e){return Ep[e]}var Op={Marina:`marina`,Anchorage:`anchorage`,Hazard:`hazard`,Business:`services`,BoatRamp:`ramp`,Bridge:`bridge`,Dam:`structure`,Lock:`structure`,Ferry:`structure`,Inlet:`inlet`,Navigational:`navaid`};function kp(e){return e?Op[e]:void 0}var Ap=K(`<p class="status svelte-1emjs18" role="status">Loading...</p>`),jp=K(`<p class="status svelte-1emjs18" role="alert">Could not load detail.</p> <button type="button" class="btn btn-ghost">Retry</button>`,1),Mp=K(`<div class="alert svelte-1emjs18"> </div>`),Np=K(`<dt class="svelte-1emjs18"> </dt>`),Pp=K(`<div class="note-item svelte-1emjs18"><!> <dd class="prose svelte-1emjs18"> </dd></div>`),Fp=K(`<span class="badge svelte-1emjs18"> </span>`),Ip=K(`<a target="_blank" rel="noopener noreferrer"> </a>`),Lp=K(`<span class="rating svelte-1emjs18" role="img"></span>`),Rp=K(`<div class="item svelte-1emjs18"><dt class="svelte-1emjs18"> </dt> <dd class="svelte-1emjs18"><!></dd></div>`),zp=K(`<section class="svelte-1emjs18"><h3 class="caps-label svelte-1emjs18"> </h3> <dl class="svelte-1emjs18"></dl></section>`),Bp=K(`<p class="prose svelte-1emjs18"> </p>`),Vp=K(`<p class="status svelte-1emjs18" role="status">No additional detail</p>`),Hp=K(`<span class="credit"> </span>`),Up=K(`<a class="source-link svelte-1emjs18" target="_blank" rel="noopener noreferrer">View source <!></a>`),Wp=K(`<footer class="svelte-1emjs18"><!> <!> <!></footer>`),Gp=K(`<aside class="slide-over slide-over--dock-right" aria-label="Point of interest detail"><header class="svelte-1emjs18"><div class="heading svelte-1emjs18"><h2 class="panel-title"> </h2> <span class="type svelte-1emjs18"> </span></div> <button type="button" class="panel-close" aria-label="Close detail"><!></button></header> <div class="body svelte-1emjs18"><!></div> <!></aside>`);function Kp(e,t){Qe(t,!0);let n=z(void 0),r=z(!0),i=z(!1),a=z(0),o=R(()=>({id:t.selection.id,attempt:W(a)}));Ln(()=>{let{id:e}=W(o),a=!0;return B(r,!0),B(i,!1),B(n,void 0),t.load(e).then(e=>{a&&(e?B(n,e,!0):B(i,!0),B(r,!1))}).catch(()=>{a&&(B(i,!0),B(r,!1))}),()=>{a=!1}});let s=[1,2,3,4,5],c=R(()=>W(n)?.sections?hp(W(n).sections):void 0),l=R(()=>W(n)?.attribution??t.selection.attribution),u=R(()=>(W(n)?.sources??[]).filter(e=>e!==W(l))),d=R(()=>op(W(n)?.url??t.selection.url??``));function f(e){return e.unit?`${e.value} ${e.unit}`:String(e.value)}var p=Gp(),m=V(p),h=V(m),g=V(h),_=V(g,!0);N(g);var v=H(g,2),y=V(v,!0);N(v),N(h);var b=H(h,2);Ko(V(b),{size:18,"aria-hidden":`true`}),N(b),N(m);var x=H(m,2),S=V(x),C=e=>{q(e,Ap())},w=e=>{var t=jp();G(`click`,H(Sn(t),2),()=>B(a,W(a)+1)),q(e,t)},T=e=>{var t=oi();vi(Sn(t),17,()=>W(c),e=>e.id,(e,t)=>{var n=zp(),r=V(n),i=V(r,!0);N(r);var a=H(r,2);vi(a,23,()=>W(t).items,(e,t)=>e.label+t,(e,n)=>{let r=R(()=>W(n).kind===`link`&&typeof W(n).value==`string`?op(W(n).value):void 0);var i=oi(),a=Sn(i),o=e=>{var t=Mp(),r=V(t,!0);N(t),U(()=>{X(t,`data-danger`,W(n).value===!0),J(r,W(n).value===!0?`Dangerous to navigation`:`Not a danger to navigation`)}),q(e,t)},c=R(()=>vp(W(n).label,W(n).kind)),l=e=>{var r=Pp(),i=V(r),a=e=>{var t=Np(),r=V(t,!0);N(t),U(()=>J(r,W(n).label)),q(e,t)},o=R(()=>!_p(W(n).label,W(t).title));Y(i,e=>{W(o)&&e(a)});var s=H(i,2),c=V(s,!0);N(s),N(r),U(()=>J(c,W(n).value)),q(e,r)},u=e=>{var t=Rp(),i=V(t),a=V(i,!0);N(i);var o=H(i,2),c=V(o),l=e=>{var t=Fp(),r=V(t,!0);N(t),U(e=>{X(t,`data-value`,e),J(r,W(n).value)},[()=>String(W(n).value).toLowerCase()]),q(e,t)},u=e=>{var t=Fp(),r=V(t,!0);N(t),U(()=>{X(t,`data-value`,W(n).value===!0?`yes`:`no`),J(r,W(n).value===!0?`Yes`:`No`)}),q(e,t)},d=e=>{var t=Ip(),i=V(t,!0);N(t),U(()=>{X(t,`href`,W(r)),J(i,W(n).label)}),q(e,t)},p=e=>{let t=R(()=>Math.round(Number(W(n).value)));var r=Lp();vi(r,20,()=>s,e=>e,(e,n)=>{{let r=R(()=>n<=W(t)?`currentColor`:`none`);Mo(e,{size:14,get fill(){return W(r)},"aria-hidden":`true`})}}),N(r),U(e=>X(r,`aria-label`,e),[()=>`Rating ${Number(W(n).value)} of 5`]),q(e,r)},m=e=>{var t=ai();U(e=>J(t,e),[()=>f(W(n))]),q(e,t)},h=e=>{var t=ai();U(()=>J(t,W(n).value)),q(e,t)};Y(c,e=>{W(n).kind===`availability`?e(l):W(n).kind===`flag`?e(u,1):W(r)?e(d,2):W(n).kind===`rating`?e(p,3):W(n).kind===`measure`?e(m,4):e(h,-1)}),N(o),N(t),U(()=>J(a,W(n).label)),q(e,t)};Y(a,e=>{W(c)?e(o):W(n).kind===`note`?e(l,1):e(u,-1)}),q(e,i)}),N(a),N(n),U(()=>J(i,W(t).title)),q(e,n)}),q(e,t)},E=e=>{var t=Bp(),r=V(t,!0);N(t),U(()=>J(r,W(n).fallbackText)),q(e,t)},D=e=>{q(e,Vp())};Y(S,e=>{W(r)?e(C):W(i)?e(w,1):W(c)?e(T,2):W(n)?.fallbackText?e(E,3):e(D,-1)}),N(x);var O=H(x,2),k=e=>{var t=Wp(),n=V(t),r=e=>{var t=Hp(),n=V(t,!0);N(t),U(()=>J(n,W(l))),q(e,t)};Y(n,e=>{W(l)&&e(r)});var i=H(n,2),a=e=>{var t=Hp(),n=V(t,!0);N(t),U(e=>J(n,e),[()=>W(u).join(`, `)]),q(e,t)};Y(i,e=>{W(u).length>0&&e(a)});var o=H(i,2),s=e=>{var t=Up();Ga(H(V(t)),{size:13,"aria-hidden":`true`}),N(t),U(()=>X(t,`href`,W(d))),q(e,t)};Y(o,e=>{W(d)&&e(s)}),N(t),q(e,t)};Y(O,e=>{(W(l)||W(d))&&e(k)}),N(p),Di(p,(e,t)=>Rd?.(e,t),()=>t.onClose),U(e=>{J(_,t.selection.name),J(y,e)},[()=>wp(t.selection.category)]),G(`click`,b,function(...e){t.onClose?.apply(this,e)}),q(e,p),$e()}Xr([`click`]);var qp={anchorage:`<path d="M12 6v16"/><path d="m19 13 2-1a9 9 0 0 1-18 0l2 1"/><path d="M9 11h6"/><circle cx="12" cy="4" r="2"/>`,marina:`<path d="M10 2v15"/><path d="M7 22a4 4 0 0 1-4-4 1 1 0 0 1 1-1h16a1 1 0 0 1 1 1 4 4 0 0 1-4 4z"/><path d="M9.159 2.46a1 1 0 0 1 1.521-.193l9.977 8.98A1 1 0 0 1 20 13H4a1 1 0 0 1-.824-1.567z"/>`,fuel:`<line x1="3" x2="15" y1="22" y2="22"/><line x1="4" x2="14" y1="9" y2="9"/><path d="M14 22V4a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v18"/><path d="M14 13h2a2 2 0 0 1 2 2v2a2 2 0 0 0 2 2 2 2 0 0 0 2-2V9.83a2 2 0 0 0-.59-1.42L18 5"/>`,services:`<path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>`,inlet:`<path d="M2 6c.6.5 1.2 1 2.5 1C7 7 7 5 9.5 5c2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1"/><path d="M2 12c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1"/><path d="M2 18c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1"/>`,ramp:`<path d="M6 4 14 13"/><path d="M10 4 18 13"/><path d="M3 19c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 1.3 0 1.9-.5 2.5-1"/>`,bridge:`<path d="M4 20V7"/><path d="M20 20V7"/><path d="M4 7c4 8 12 8 16 0"/><path d="M3 14h18"/><path d="M9 14v-2.3"/><path d="M15 14v-2.3"/>`,hazard:`<path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/><path d="M12 9v4"/><path d="M12 17h.01"/>`,navaid:`<path d="M12 2 16 7 12 12 8 7Z"/><path d="M12 12v9"/><path d="M8 21h8"/>`,structure:`<path d="M10 18v-7"/><path d="M11.119 2.205a2 2 0 0 1 1.762 0l7.84 3.846A.5.5 0 0 1 20.5 7h-17a.5.5 0 0 1-.22-.949z"/><path d="M14 18v-7"/><path d="M18 18v-7"/><path d="M3 22h18"/>`,generic:`<path d="M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"/><circle cx="12" cy="10" r="3"/>`};function Jp(e,t){return e===`hazard`?t.danger:e===`navaid`?t.warning:t.note}function Yp(e,t){return[`<svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 30 30">`,`<circle cx="15" cy="15" r="14" fill="${Jp(e,t)}"/>`,`<g transform="translate(3,3)" fill="none" stroke="${t.markerGlyph}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,qp[e],`</g></svg>`].join(``)}var Xp=60;async function Zp(e){if(typeof document>`u`||typeof Image>`u`)return null;try{let t=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(e)}`,n=new Image(Xp,Xp);await new Promise((e,r)=>{n.onload=()=>e(),n.onerror=()=>r(Error(`svg decode failed`)),n.src=t});let r=document.createElement(`canvas`);r.width=Xp,r.height=Xp;let i=r.getContext(`2d`);return i?(i.drawImage(n,0,0,Xp,Xp),i.getImageData(0,0,Xp,Xp)):null}catch{return null}}function Qp(e,t,n){e.hasImage(t)?e.updateImage(t,n):e.addImage(t,n,{pixelRatio:2})}async function $p(e,t){await Promise.all(Sp.map(async n=>{let r=await Zp(Yp(n,t));r&&Qp(e,Tp(n),r)}))}function em(e){let t=e.toLowerCase(),n=t.match(/\b(\d+)\b/),r=n?Number(n[1])%2==0?`starboard`:`port`:`none`;return/lighthouse/.test(t)?{kind:`lighthouse`,side:`none`}:/daybeacon/.test(t)?{kind:`daybeacon`,side:r}:/buoy/.test(t)?{kind:`buoy`,side:r}:/\blight\b|pierhead|breakwater|entrance light|channel light/.test(t)?{kind:`light`,side:`none`}:{kind:`generic`,side:`none`}}function tm({kind:e,side:t}){switch(e){case`generic`:return Tp(`navaid`);case`lighthouse`:return`binnacle-navaid-lighthouse`;case`light`:return`binnacle-navaid-light`;default:return`binnacle-navaid-${e}-${t}`}}var nm=[{kind:`light`,side:`none`},{kind:`lighthouse`,side:`none`},{kind:`buoy`,side:`starboard`},{kind:`buoy`,side:`port`},{kind:`buoy`,side:`none`},{kind:`daybeacon`,side:`starboard`},{kind:`daybeacon`,side:`port`},{kind:`daybeacon`,side:`none`}];function rm(e,t){return e===`starboard`?t.navStarboard:e===`port`?t.navPort:t.note}function im(e,t){let n=rm(e.side,t);switch(e.kind){case`light`:return[`<circle cx="9" cy="23" r="2.2" fill="${t.navLight}"/>`,`<path d="M9 23 C 9 14 14 9 23 7 C 16 12 13 16 12 23 Z" fill="${t.navLight}"/>`].join(``);case`lighthouse`:return[`<path d="M11 26 L12.5 13 L17.5 13 L19 26 Z" fill="${t.note}"/>`,`<rect x="12.5" y="8" width="5" height="5" fill="${t.navLight}"/>`,`<path d="M15 8 L15 4 M12 7 L8 5 M18 7 L22 5" stroke="${t.navLight}"/>`].join(``);case`buoy`:return e.side===`starboard`?`<path d="M15 9 L20 22 L10 22 Z" fill="${n}"/><line x1="15" y1="22" x2="15" y2="26"/>`:e.side===`port`?`<rect x="10" y="10" width="10" height="12" rx="1" fill="${n}"/><line x1="15" y1="22" x2="15" y2="26"/>`:`<circle cx="15" cy="15" r="7" fill="${n}"/><line x1="15" y1="22" x2="15" y2="26"/>`;default:return e.side===`port`?`<line x1="15" y1="26" x2="15" y2="15"/><rect x="9.5" y="5" width="11" height="10" fill="${n}"/>`:`<line x1="15" y1="26" x2="15" y2="14"/><path d="M15 4 L21 14 L9 14 Z" fill="${n}"/>`}}function am(e,t){return[`<svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 30 30" fill="none" `,`stroke="${t.markerGlyph}" stroke-width="1.3" stroke-linejoin="round" stroke-linecap="round">`,im(e,t),`</svg>`].join(``)}async function om(e,t){await Promise.all(nm.map(async n=>{let r=await Zp(am(n,t));r&&Qp(e,tm(n),r)}))}var sm=`/signalk/v2/api/resources/notes`;async function cm(e,t,n){let r=new URLSearchParams({bbox:JSON.stringify(n)}),i;try{let n=await fetch(`${e}${sm}?${r}`,Ws(t));if(!n.ok)return[];i=await n.json()}catch{return[]}let a=Gs(i);if(!a)return[];let o=[];for(let[e,t]of Object.entries(a)){if(!t||typeof t!=`object`)continue;let n=t,r=n.position?.latitude,i=n.position?.longitude;if(typeof r!=`number`||typeof i!=`number`)continue;let a=n.properties??{};o.push({id:e,name:Ks(n.name)??Ks(n.title)??e,position:{latitude:r,longitude:i},category:kp(typeof a.crowsNest?.type==`string`?a.crowsNest.type:void 0)??Cp(Ks(a.skIcon)),url:Ks(n.url),source:Ks(a.source),attribution:Ks(a.attribution)})}return o}var lm=`binnacle-notes`,um=`binnacle-notes-symbol`,dm=`binnacle-notes-cluster-ring`,fm=`binnacle-notes-cluster-icon`,pm=`binnacle-notes-cluster-count`,mm=`binnacle-notes-selected`,hm=`binnacle-notes-selected`,gm=[hm,dm,fm,pm,um],_m=[fm,dm],vm=9,ym=11,bm=44;function xm(...e){for(let t of e){let e=String(t??``);if(e)return e}}var Sm=[`match`,[`get`,`maxRank`],...Sp.filter(e=>e!==`generic`).flatMap(e=>[Dp(e),Tp(e)]),Tp(`generic`)];function Cm(e){return e.category===`navaid`?tm(em(e.name)):Tp(e.category)}function wm(e){return{type:`FeatureCollection`,features:e.map(e=>({type:`Feature`,geometry:{type:`Point`,coordinates:[e.position.longitude,e.position.latitude]},properties:{id:e.id,name:e.name,category:e.category,rank:Dp(e.category),icon:Cm(e),url:e.url??``,source:e.source??``,attribution:e.attribution??``}}))}}var Tm=od();function Em(e,t,n){let r,i,a,o,s=!1,c,l,u,d;function f(e,t){e.map.getSource(lm)?.setData(t)}function p(e,t){let n=e.map.getSource(mm);if(n){if(t?.geometry.type!==`Point`){n.setData(Tm);return}n.setData({type:`FeatureCollection`,features:[{type:`Feature`,geometry:t.geometry,properties:{}}]})}}return{id:`notes`,title:`Points of interest`,band:`routes`,supportsOpacity:!0,layerIds:gm,async add(e){let t=sl(`day`),r=e.beforeIdFor(`routes`),i={type:`geojson`,data:Tm,cluster:!0,clusterMaxZoom:ym,clusterRadius:bm,clusterProperties:{maxRank:[`max`,[`get`,`rank`]]}};e.map.addSource(lm,i),e.map.addSource(mm,{type:`geojson`,data:Tm});let a={id:hm,type:`circle`,source:mm,minzoom:vm,paint:{"circle-radius":15,"circle-color":`rgba(0,0,0,0)`,"circle-stroke-color":t.select,"circle-stroke-width":3}};e.map.addLayer(a,r);let o={id:dm,type:`circle`,source:lm,filter:[`has`,`point_count`],minzoom:vm,paint:{"circle-radius":[`step`,[`get`,`point_count`],18,10,22,50,28],"circle-color":`rgba(0,0,0,0)`,"circle-stroke-color":t.markerGlyph,"circle-stroke-width":2.5,"circle-stroke-opacity":.9}};e.map.addLayer(o,r);let s={id:fm,type:`symbol`,source:lm,filter:[`has`,`point_count`],minzoom:vm,layout:{"icon-image":Sm,"icon-size":.85,"icon-allow-overlap":!0}};e.map.addLayer(s,r);let f={id:pm,type:`symbol`,source:lm,filter:[`has`,`point_count`],minzoom:vm,layout:{"text-field":[`get`,`point_count_abbreviated`],"text-font":[`Noto Sans Regular`],"text-size":11,"text-offset":[1.2,-1.2],"text-allow-overlap":!0},paint:{"text-color":t.markerGlyph,"text-halo-color":t.note,"text-halo-width":2.4}};e.map.addLayer(f,r);let m={id:um,type:`symbol`,source:lm,filter:[`!`,[`has`,`point_count`]],layout:{"icon-image":[`get`,`icon`],"icon-size":[`interpolate`,[`linear`],[`zoom`],9,.6,14,.9],"icon-allow-overlap":!0,"text-field":[`get`,`name`],"text-font":[`Noto Sans Regular`],"text-size":11,"text-offset":[0,1.1],"text-anchor":`top`,"text-optional":!0,"text-max-width":9,"text-padding":6},paint:{"text-color":t.note,"text-halo-color":t.background,"text-halo-width":1.2},minzoom:vm};e.map.addLayer(m,r),c=t=>{let r=t.features?.[0];if(!r)return;let i=r.properties??{},a=String(i.id??``);a&&(p(e,r),n?.({id:a,name:String(i.name??`Point of interest`),category:String(i.category),attribution:xm(i.attribution,i.source),url:xm(i.url)}))},l=t=>{let n=t.features?.[0],r=n?.properties?.cluster_id;if(typeof r!=`number`||n?.geometry.type!==`Point`)return;let i=e.map.getSource(lm);if(!i)return;let a=n.geometry.coordinates;i.getClusterExpansionZoom(r).then(t=>{e.map.easeTo({center:a,zoom:t})})},u=()=>{e.map.getCanvas().style.cursor=`pointer`},d=()=>{e.map.getCanvas().style.cursor=``},e.map.on(`click`,um,c),e.map.on(`mouseenter`,um,u),e.map.on(`mouseleave`,um,d),e.map.on(`click`,dm,l);for(let t of _m)e.map.on(`mouseenter`,t,u),e.map.on(`mouseleave`,t,d);await $p(e.map,t),await om(e.map,t)},sync(n){if(s)return;let c=n.map.getZoom(),l=n.map.getCenter();if(c===i&&l.lng===a&&l.lat===o)return;if(i=c,a=l.lng,o=l.lat,c<vm){r!==`lowzoom`&&(r=`lowzoom`,f(n,Tm));return}let u=`${c.toFixed(0)}|${l.lng.toFixed(2)}|${l.lat.toFixed(2)}`;if(u===r)return;r=u;let d=n.map.getBounds(),p=[d.getWest(),d.getSouth(),d.getEast(),d.getNorth()];s=!0,cm(e,t,p).then(e=>f(n,wm(e))).finally(()=>{s=!1})},deselect(e){p(e,void 0)},applyTheme(e,t){$p(e.map,t),om(e.map,t),e.map.setPaintProperty(um,`text-color`,t.note),e.map.setPaintProperty(um,`text-halo-color`,t.background),e.map.setPaintProperty(dm,`circle-stroke-color`,t.markerGlyph),e.map.setPaintProperty(pm,`text-color`,t.markerGlyph),e.map.setPaintProperty(pm,`text-halo-color`,t.note),e.map.setPaintProperty(hm,`circle-stroke-color`,t.select)},setVisible(e,t){let n=t?`visible`:`none`;for(let t of gm)e.map.setLayoutProperty(t,`visibility`,n)},setOpacity(e,t){e.map.setPaintProperty(um,`icon-opacity`,t),e.map.setPaintProperty(um,`text-opacity`,t),e.map.setPaintProperty(fm,`icon-opacity`,t),e.map.setPaintProperty(dm,`circle-stroke-opacity`,t*.9),e.map.setPaintProperty(pm,`text-opacity`,t),e.map.setPaintProperty(hm,`circle-stroke-opacity`,t)},remove(e){c&&e.map.off(`click`,um,c),u&&e.map.off(`mouseenter`,um,u),d&&e.map.off(`mouseleave`,um,d),l&&e.map.off(`click`,dm,l);for(let t of _m)u&&e.map.off(`mouseenter`,t,u),d&&e.map.off(`mouseleave`,t,d);for(let t of gm)e.map.getLayer(t)&&e.map.removeLayer(t);for(let t of[lm,mm])e.map.getSource(t)&&e.map.removeSource(t)}}}var Dm=`/signalk/v2/api/vessels/self/navigation/course`;function Om(e,t,n,r=0,i=!1){return Xs(`${e}${Dm}/activeRoute`,t,{href:n,pointIndex:r,reverse:i})}function km(e,t,n){return Xs(`${e}${Dm}/activeRoute/nextPoint`,t,{value:n})}function Am(e,t){return Zs(`${e}${Dm}`,t)}async function jm(e,t){let n=async n=>{try{let r=await fetch(`${e}${Dm}${n}`,Ws(t));return r.ok?await r.json():void 0}catch{return}},[r,i]=await Promise.all([n(``),n(`/calcValues`)]);return{info:r,calc:i}}var Mm=K(`<p class="error svelte-813ore" role="alert"> </p>`),Nm=K(`<div class="editing svelte-813ore" role="group" aria-label="Route under edit"><dl class="stats svelte-813ore"><dt class="svelte-813ore">Waypoints</dt> <dd class="svelte-813ore"><span class="num svelte-813ore"> </span><span class="unit svelte-813ore"></span></dd> <dt class="svelte-813ore">Distance</dt> <dd class="svelte-813ore"><span class="num svelte-813ore"> </span> <span class="unit svelte-813ore">nm</span></dd></dl> <p class="hint svelte-813ore">Tap the chart to add waypoints. Drag a point to move it, tap a midpoint to insert one.</p> <div class="controls svelte-813ore"><button type="button" class="btn btn-primary svelte-813ore"><!> Save</button> <button type="button" class="btn"><!> Cancel</button></div></div>`),Pm=K(`<p class="empty svelte-813ore">No routes yet</p>`),Fm=K(`<span class="badge svelte-813ore">Active</span>`),Im=K(`<button type="button" class="icon-btn icon-btn--accent" aria-label="Stop navigation" title="Stop navigation"><!></button>`),Lm=K(`<button type="button" class="icon-btn" aria-label="Activate route" title="Activate route"><!></button>`),Rm=K(`<li><div class="card-head svelte-813ore"><button type="button" class="name svelte-813ore" title="Go to this route on the chart"> </button> <!></div> <dl class="card-stats svelte-813ore"><dt class="svelte-813ore">Distance</dt> <dd class="svelte-813ore"><span class="num svelte-813ore"> </span> nm</dd> <dt class="svelte-813ore">Waypoints</dt> <dd class="svelte-813ore"><span class="num svelte-813ore"> </span></dd></dl> <div class="actions svelte-813ore"><button type="button" class="icon-btn"><!></button> <button type="button" class="icon-btn" aria-label="Edit route" title="Edit"><!></button> <!> <button type="button" class="icon-btn icon-btn--danger svelte-813ore" aria-label="Delete route" title="Delete"><!></button></div></li>`),zm=K(`<ul class="svelte-813ore"></ul>`),Bm=K(`<aside class="slide-over slide-over--dock-left" aria-label="Routes"><header class="svelte-813ore"><h2 class="panel-title svelte-813ore">Routes</h2> <button type="button" class="panel-close" aria-label="Close routes panel" title="Close"><!></button></header> <div class="body svelte-813ore"><!> <div class="controls svelte-813ore"><button type="button" class="btn btn-primary svelte-813ore"><!> New route</button></div> <!> <div class="saved svelte-813ore"><span class="caps-label">Saved routes</span> <!></div></div></aside>`);function Vm(e,t){Qe(t,!0);function n(){let e=zd(`Route`);e!==void 0&&t.onSave(e)}var r=Bm(),i=V(r),a=H(V(i),2);Ko(V(a),{size:18,"aria-hidden":`true`}),N(a),N(i);var o=H(i,2),s=V(o),c=e=>{var n=Mm(),r=V(n,!0);N(n),U(()=>J(r,t.error)),q(e,n)};Y(s,e=>{t.error&&e(c)});var l=H(s,2),u=V(l);go(V(u),{size:16,"aria-hidden":`true`}),P(),N(u),N(l);var d=H(l,2),f=e=>{var r=Nm(),i=V(r),a=H(V(i),2),o=V(a),s=V(o,!0);N(o),P(),N(a);var c=H(a,4),l=V(c),u=V(l,!0);N(l),P(2),N(c),N(i);var d=H(i,4),f=V(d);bo(V(f),{size:16,"aria-hidden":`true`}),P(),N(f);var p=H(f,2);Ko(V(p),{size:16,"aria-hidden":`true`}),P(),N(p),N(d),N(r),U(e=>{J(s,t.working.waypoints.length),J(u,e),f.disabled=t.working.waypoints.length<2},[()=>wc(Xc(t.working.waypoints))]),G(`click`,f,n),G(`click`,p,function(...e){t.onCancelEdit?.apply(this,e)}),q(e,r)};Y(d,e=>{t.working&&e(f)});var p=H(d,2),m=H(V(p),2),h=e=>{q(e,Pm())},g=e=>{var n=zm();vi(n,21,()=>t.routes,e=>e.id,(e,n)=>{var r=Rm();let i;var a=V(r),o=V(a),s=V(o,!0);N(o);var c=H(o,2),l=e=>{q(e,Fm())};Y(c,e=>{W(n).id===t.activeId&&e(l)}),N(a);var u=H(a,2),d=H(V(u),2),f=V(d),p=V(f,!0);N(f),P(),N(d);var m=H(d,4),h=V(m),g=V(h,!0);N(h),N(m),N(u);var _=H(u,2),v=V(_),y=V(v),b=e=>{$(e,{size:18,"aria-hidden":`true`})},x=R(()=>t.shownIds.has(W(n).id)),S=e=>{qa(e,{size:18,"aria-hidden":`true`})};Y(y,e=>{W(x)?e(b):e(S,-1)}),N(v);var C=H(v,2);Oo(V(C),{size:18,"aria-hidden":`true`}),N(C);var w=H(C,2),T=e=>{var n=Im();Ao(V(n),{size:18,"aria-hidden":`true`}),N(n),G(`click`,n,function(...e){t.onStop?.apply(this,e)}),q(e,n)},E=e=>{var r=Lm();so(V(r),{size:18,"aria-hidden":`true`}),N(r),U(()=>r.disabled=t.working!==void 0),G(`click`,r,()=>t.onActivate(W(n).id)),q(e,r)};Y(w,e=>{W(n).id===t.activeId?e(T):e(E,-1)});var D=H(w,2);Ro(V(D),{size:18,"aria-hidden":`true`}),N(D),N(_),N(r),U((e,a,o,c)=>{i=Li(r,1,`svelte-813ore`,null,i,{active:W(n).id===t.activeId}),J(s,W(n).name),J(p,e),J(g,W(n).waypoints.length),X(v,`aria-pressed`,a),X(v,`aria-label`,o),X(v,`title`,c),C.disabled=t.working!==void 0},[()=>wc(Xc(W(n).waypoints)),()=>t.shownIds.has(W(n).id),()=>t.shownIds.has(W(n).id)?`Hide on chart`:`Show on chart`,()=>t.shownIds.has(W(n).id)?`Hide on chart`:`Show on chart`]),G(`click`,o,()=>t.onLocate(W(n).id)),G(`click`,v,()=>t.onToggleShown(W(n).id,!t.shownIds.has(W(n).id))),G(`click`,C,()=>t.onEditRoute(W(n).id)),G(`click`,D,()=>t.onDelete(W(n).id)),q(e,r)}),N(n),q(e,n)};Y(m,e=>{t.routes.length===0?e(h):e(g,-1)}),N(p),N(o),N(r),Di(r,(e,t)=>Rd?.(e,t),()=>t.onClose),U(()=>u.disabled=t.working!==void 0),G(`click`,a,function(...e){t.onClose?.apply(this,e)}),G(`click`,u,function(...e){t.onNew?.apply(this,e)}),q(e,r),$e()}Xr([`click`]);var Hm=`/signalk/v2/api/resources/routes`,Um=`/signalk/v1/api/resources/routes`;function Wm(e,t){return Js(e,[Hm,Um],t,Yc)}function Gm(e,t,n){return Xs(`${e}${Hm}/${encodeURIComponent(n.id)}`,t,Jc(n))}function Km(e,t,n){return Zs(`${e}${Hm}/${encodeURIComponent(n)}`,t)}var qm=K(`<button type="button" class="theme-toggle svelte-15g5e41"><!></button>`);function Jm(e,t){Qe(t,!0);let n={day:Po,dusk:Io,"night-red":ao},r={day:`Day theme`,dusk:`Dusk theme`,"night-red":`Night theme`},i=R(()=>n[t.controller.theme]),a=R(()=>r[t.controller.theme]);var o=qm();Ti(V(o),()=>W(i),(e,t)=>{t(e,{size:20,"aria-hidden":`true`})}),N(o),U(()=>{X(o,`aria-label`,`Switch theme (currently ${W(a)})`),X(o,`title`,W(a))}),G(`click`,o,()=>t.controller.cycle()),q(e,o),$e()}Xr([`click`]);var Ym=K(`<button type="button" class="btn"><!> Resume</button>`),Xm=K(`<button type="button" class="btn"><!> Pause</button>`),Zm=K(`<p class="empty svelte-1td1uw4">None saved yet</p>`),Qm=K(`<li class="svelte-1td1uw4"><span class="name svelte-1td1uw4"> </span> <button type="button" class="icon-btn"><!></button> <button type="button" class="icon-btn" aria-label="Export GeoJSON" title="Export GeoJSON"><!></button> <button type="button" class="icon-btn icon-btn--danger" aria-label="Delete track" title="Delete"><!></button></li>`),$m=K(`<ul class="svelte-1td1uw4"></ul>`),eh=K(`<section class="tracks svelte-1td1uw4" aria-label="Tracks"><div class="controls svelte-1td1uw4"><!> <button type="button" class="btn btn-primary"><!> Save</button> <button type="button" class="btn btn-danger"><!> Clear</button></div> <div class="color-mode svelte-1td1uw4" role="group" aria-label="Track color"><button type="button">Speed</button> <button type="button">Solid</button></div> <dl class="stats svelte-1td1uw4"><dt class="svelte-1td1uw4">Distance</dt> <dd class="svelte-1td1uw4"><span class="num svelte-1td1uw4"> </span> <span class="unit svelte-1td1uw4">nm</span></dd> <dt class="svelte-1td1uw4">Duration</dt> <dd class="svelte-1td1uw4"><span class="num svelte-1td1uw4"> </span> <span class="unit svelte-1td1uw4"></span></dd> <dt class="svelte-1td1uw4">Avg</dt> <dd class="svelte-1td1uw4"><span class="num svelte-1td1uw4"> </span> <span class="unit svelte-1td1uw4">kn</span></dd> <dt class="svelte-1td1uw4">Max</dt> <dd class="svelte-1td1uw4"><span class="num svelte-1td1uw4"> </span> <span class="unit svelte-1td1uw4">kn</span></dd></dl> <div class="saved svelte-1td1uw4"><span class="caps-label">Saved tracks</span> <!></div></section>`);function th(e,t){Qe(t,!0);let n=R(()=>t.recorder.stats),r=R(()=>t.settings.value.colorMode),i=R(()=>t.recorder.points.length>0);function a(e){let t=Math.max(0,Math.round(e)),n=Math.floor(t/3600),r=Math.floor(t%3600/60);return n>0?`${n}h ${r}m`:`${r}m`}function o(){let e=zd(`Track`);e!==void 0&&t.onSave(e)}function s(){window.confirm(`Discard the current track? This cannot be undone.`)&&t.recorder.clear()}function c(e){t.settings.set({...t.settings.value,colorMode:e})}var l=eh(),u=V(l),d=V(u),f=e=>{var n=Ym();mo(V(n),{size:16,"aria-hidden":`true`}),P(),N(n),G(`click`,n,()=>t.recorder.resume()),q(e,n)},p=e=>{var n=Xm();lo(V(n),{size:16,"aria-hidden":`true`}),P(),N(n),G(`click`,n,()=>t.recorder.pause()),q(e,n)};Y(d,e=>{t.recorder.paused?e(f):e(p,-1)});var m=H(d,2);bo(V(m),{size:16,"aria-hidden":`true`}),P(),N(m);var h=H(m,2);Ua(V(h),{size:16,"aria-hidden":`true`}),P(),N(h),N(u);var g=H(u,2),_=V(g);let v;var y=H(_,2);let b;N(g);var x=H(g,2),S=H(V(x),2),C=V(S),w=V(C,!0);N(C),P(2),N(S);var T=H(S,4),E=V(T),D=V(E,!0);N(E),P(2),N(T);var O=H(T,4),k=V(O),A=V(k,!0);N(k),P(2),N(O);var ee=H(O,4),te=V(ee),ne=V(te,!0);N(te),P(2),N(ee),N(x);var re=H(x,2),ie=H(V(re),2),ae=e=>{q(e,Zm())},oe=e=>{var n=$m();vi(n,21,()=>t.saved,e=>e.id,(e,n)=>{var r=Qm(),i=V(r),a=V(i,!0);N(i);var o=H(i,2),s=V(o),c=e=>{$(e,{size:18,"aria-hidden":`true`})},l=R(()=>t.shown.has(W(n).id)),u=e=>{qa(e,{size:18,"aria-hidden":`true`})};Y(s,e=>{W(l)?e(c):e(u,-1)}),N(o);var d=H(o,2);Va(V(d),{size:18,"aria-hidden":`true`}),N(d);var f=H(d,2);Ro(V(f),{size:18,"aria-hidden":`true`}),N(f),N(r),U((e,t,r)=>{X(i,`title`,W(n).name),J(a,W(n).name),X(o,`aria-pressed`,e),X(o,`aria-label`,t),X(o,`title`,r)},[()=>t.shown.has(W(n).id),()=>t.shown.has(W(n).id)?`Hide on chart`:`Show on chart`,()=>t.shown.has(W(n).id)?`Hide on chart`:`Show on chart`]),G(`click`,o,()=>t.onToggleSaved(W(n).id)),G(`click`,d,()=>t.onExport(W(n))),G(`click`,f,()=>t.onDelete(W(n).id)),q(e,r)}),N(n),q(e,n)};Y(ie,e=>{t.saved.length===0?e(ae):e(oe,-1)}),N(re),N(l),U((e,n,i,a)=>{m.disabled=t.recorder.points.length<2,h.disabled=t.recorder.points.length===0,v=Li(_,1,`svelte-1td1uw4`,null,v,{active:W(r)===`speed`}),b=Li(y,1,`svelte-1td1uw4`,null,b,{active:W(r)===`solid`}),J(w,e),J(D,n),J(A,i),J(ne,a)},[()=>W(i)?wc(W(n).distanceMeters):`--`,()=>W(i)?a(W(n).durationSeconds):`--`,()=>W(i)?Tc(W(n).avgSog):`--`,()=>W(i)?Tc(W(n).maxSog):`--`]),G(`click`,m,o),G(`click`,h,s),G(`click`,_,()=>c(`speed`)),G(`click`,y,()=>c(`solid`)),q(e,l),$e()}Xr([`click`]);function nh(e){return rl(e).map(e=>e.map(nl)).filter(e=>e.length>=2)}function rh(e,t){return{type:`Feature`,geometry:{type:`MultiLineString`,coordinates:nh(t)},properties:{name:e,source:`binnacle`}}}function ih(e,t){return JSON.stringify(rh(e,t),null,2)}function ah(e,t){if(typeof document>`u`||typeof URL?.createObjectURL!=`function`)return;let n=new Blob([ih(e,t)],{type:`application/geo+json`}),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=`${e||`track`}.geojson`,i.click(),URL.revokeObjectURL(r)}function oh(e,t){let n=[];for(let r of e)if(t.has(r.id))for(let e of r.points)e.length<2||n.push({type:`Feature`,geometry:{type:`LineString`,coordinates:e.map(nl)},properties:{id:r.id}});return{type:`FeatureCollection`,features:n}}var sh=`/signalk/v2/api/resources/tracks`,ch=`/signalk/v1/api/resources/tracks`;function lh(e){if(!e||typeof e!=`object`)return;let t=e;if(t.geometry&&typeof t.geometry==`object`)return t.geometry;if(t.feature?.geometry&&typeof t.feature.geometry==`object`)return t.feature.geometry;if(t.type===`MultiLineString`||t.type===`LineString`)return t}function uh(e){return Array.isArray(e)&&typeof e[0]==`number`&&typeof e[1]==`number`}function dh(e){if(!Array.isArray(e))return[];let t=[];for(let n of e)uh(n)&&t.push({lat:n[1],lon:n[0],t:0,sog:0});return t}function fh(e){if(e.type===`MultiLineString`&&Array.isArray(e.coordinates))return e.coordinates.map(dh).filter(e=>e.length>=2);if(e.type===`LineString`){let t=dh(e.coordinates);return t.length>=2?[t]:[]}return[]}function ph(e,t){if(e&&typeof e==`object`){let t=e;if(typeof t.properties?.name==`string`&&t.properties.name)return t.properties.name;if(typeof t.name==`string`&&t.name)return t.name}return t}function mh(e,t){let n=lh(t);if(!n)return;let r=fh(n);if(r.length!==0)return{id:e,name:ph(t,e),points:r}}async function hh(e,t){return await Js(e,[sh,ch],t,mh)??[]}function gh(e,t,n,r,i){let a=el(i),o=rh(r,i),s={...o,properties:{...o.properties,distance:a.distanceMeters,timespan:a.durationSeconds}};return Xs(`${e}${sh}/${encodeURIComponent(n)}`,t,s)}function _h(e,t,n){return Zs(`${e}${sh}/${encodeURIComponent(n)}`,t)}function vh(e,t){if(Number.isNaN(t)||t<=e[0][0])return e[0][1];for(let n=0;n<e.length-1;n+=1){let[r,i]=e[n],[a,o]=e[n+1];if(t<=a){let e=(t-r)/(a-r||1);return[i[0]+(o[0]-i[0])*e,i[1]+(o[1]-i[1])*e,i[2]+(o[2]-i[2])*e,i[3]+(o[3]-i[3])*e]}}return e[e.length-1][1]}function yh([e,t,n,r]){return`rgba(${Math.round(e*255)}, ${Math.round(t*255)}, ${Math.round(n*255)}, ${r.toFixed(2)})`}var bh=[[0,[.7,.71,.74,0]],[.3,[.58,.59,.62,.32]],[1,[.42,.43,.46,.62]]],xh=[[0,[.24,.05,.04,0]],[1,[.38,.08,.06,.4]]];function Sh(e,t){return vh(t===`night-red`?xh:bh,e)}function Ch(e,t,n,r){if(!t||t.length===0)return;let i=e.lons.length,a=e.lats.length,o=t[n.lo]??[],s=t[n.hi]??o,c=new Uint8ClampedArray(i*a*4);for(let e=0;e<a;e+=1){let t=a-1-e;for(let a=0;a<i;a+=1){let l=t*i+a,[u,d,f,p]=r(lc(o[l],s[l],n.frac)),m=(e*i+a)*4;c[m]=u*255,c[m+1]=d*255,c[m+2]=f*255,c[m+3]=p*255}}return{data:c,width:i,height:a}}function wh(e,t,n){return Ch(e,e.cloudCover,t,e=>Sh(e,n))}function Th(){return document.createElement(`canvas`)}var Eh=[[0,1e-4],[1e-4,1e-4],[1e-4,0],[0,0]];function Dh(e,t,n=Th){let{id:r,title:i,sourceId:a,layerId:o,defaultOpacity:s,fieldRgba:c}=t,l=n(),u=`day`,d,f=NaN,p;function m(){let t=e.grid,n=t?c(t,e.bracket,u):void 0,r=l.getContext(`2d`);if(!n||!r)return;l.width=n.width,l.height=n.height;let i=r.createImageData(n.width,n.height);i.data.set(n.data),r.putImageData(i,0,0)}function h(){let t=e.grid;if(!t||t.lons.length===0||t.lats.length===0)return;let n=t.lons[0],r=t.lons[t.lons.length-1],i=t.lats[0],a=t.lats[t.lats.length-1];return[[n,a],[r,a],[r,i],[n,i]]}return{id:r,title:i,band:`weather`,supportsOpacity:!0,defaultVisible:!1,defaultOpacity:s,layerIds:[o],add(e){if(!e.map.getSource(a)){let t={type:`canvas`,canvas:l,coordinates:Eh,animate:!0};e.map.addSource(a,t)}if(!e.map.getLayer(o)){let t={id:o,type:`raster`,source:a,paint:{"raster-opacity":1,"raster-resampling":`linear`,"raster-fade-duration":0}};e.map.addLayer(t,e.beforeIdFor(`weather`))}},sync(t){let n=e.grid;if(n===d&&e.selectedTime===f&&u===p)return;d=n,f=e.selectedTime,p=u,m();let r=h(),i=t.map.getSource(a);r&&i?.setCoordinates(r)},remove(e){e.map.getLayer(o)&&e.map.removeLayer(o),e.map.getSource(a)&&e.map.removeSource(a)},setVisible(e,t){e.map.setLayoutProperty(o,`visibility`,t?`visible`:`none`)},setOpacity(e,t){e.map.setPaintProperty(o,`raster-opacity`,t)},applyTheme(e,t){u=t.theme,p=void 0}}}var Oh={wind:`weather-wind`,pressure:`weather-pressure`,waves:`weather-waves`,precip:`weather-precip`,cloud:`weather-cloud`,radar:`weather-radar`},kh=[Oh.waves,Oh.precip,Oh.cloud,Oh.radar];function Ah(e,t){return Dh(e,{id:Oh.cloud,title:`Cloud cover`,sourceId:`binnacle-weather-cloud-field`,layerId:`binnacle-weather-cloud-field-layer`,defaultOpacity:.5,fieldRgba:wh},t)}var jh=[[0,[.4,.7,.95,0]],[.2,[.4,.7,.95,.4]],[1,[.2,.5,.9,.5]],[2.5,[.24,.75,.45,.55]],[5,[.9,.85,.25,.6]],[10,[.94,.55,.22,.65]],[20,[.86,.26,.22,.7]],[40,[.6,.2,.6,.75]]],Mh=[[0,[.28,.03,.02,0]],[1,[.42,.05,.03,.4]],[10,[.6,.08,.04,.58]],[40,[.82,.12,.06,.72]]];function Nh(e,t){return vh(t===`night-red`?Mh:jh,e)}var Ph={day:{line:`rgba(70, 90, 110, 0.85)`,label:`rgba(40, 55, 70, 1)`,halo:`rgba(255, 255, 255, 0.9)`},dusk:{line:`rgba(150, 165, 185, 0.8)`,label:`rgba(205, 215, 230, 1)`,halo:`rgba(10, 14, 22, 0.9)`},"night-red":{line:`rgba(150, 30, 22, 0.85)`,label:`rgba(190, 40, 28, 1)`,halo:`rgba(0, 0, 0, 0.95)`}};function Fh(e){return Ph[e]}var Ih=6,Lh=[[],[[`d`,`a`]],[[`a`,`b`]],[[`d`,`b`]],[[`b`,`c`]],[[`d`,`a`],[`b`,`c`]],[[`a`,`c`]],[[`d`,`c`]],[[`c`,`d`]],[[`c`,`a`]],[[`a`,`b`],[`c`,`d`]],[[`c`,`b`]],[[`d`,`b`]],[[`a`,`b`]],[[`d`,`a`]],[]];function Rh(e,t,n=4){let r=[],i=[],a=e.pressureMsl;if(!a||a.length===0)return Hh(r,i);let o=e.lons.length,s=e.lats.length,c=a[t.lo]??[],l=a[t.hi]??c,u=new Float64Array(o*s),d=1/0,f=-1/0;for(let e=0;e<u.length;e+=1){let n=lc(c[e],l[e],t.frac)/100;u[e]=n,!Number.isNaN(n)&&(n<d&&(d=n),n>f&&(f=n))}if(!Number.isFinite(d)||!Number.isFinite(f))return Hh(r,i);let p=new Map;for(let t=Math.ceil(d/n)*n;t<=f;t+=n)for(let n=0;n<s-1;n+=1)for(let a=0;a<o-1;a+=1){let s=u[n*o+a],c=u[n*o+a+1],l=u[(n+1)*o+a+1],d=u[(n+1)*o+a];if(Number.isNaN(s)||Number.isNaN(c)||Number.isNaN(l)||Number.isNaN(d))continue;let f=s>=t|(c>=t?2:0)|(l>=t?4:0)|(d>=t?8:0);if(f===0||f===15)continue;let m=e.lons[a],h=e.lons[a+1],g=e.lats[n],_=e.lats[n+1],v=e=>{switch(e){case`a`:return[lc(m,h,zh(s,c,t)),g];case`b`:return[h,lc(g,_,zh(c,l,t))];case`c`:return[lc(h,m,zh(l,d,t)),_];default:return[m,lc(_,g,zh(d,s,t))]}};for(let[e,n]of Lh[f]){let a=v(e),o=v(n);r.push(Bh(a,o,t));let s=p.get(t)??0;s%Ih===0&&i.push(Vh([(a[0]+o[0])/2,(a[1]+o[1])/2],t)),p.set(t,s+1)}}return Hh(r,i)}function zh(e,t,n){let r=t-e;return r===0?.5:(n-e)/r}function Bh(e,t,n){return{type:`Feature`,geometry:{type:`LineString`,coordinates:[e,t]},properties:{pressureHpa:n}}}function Vh(e,t){return{type:`Feature`,geometry:{type:`Point`,coordinates:e},properties:{pressureHpa:t}}}function Hh(e,t){return{lines:{type:`FeatureCollection`,features:e},labels:{type:`FeatureCollection`,features:t}}}var Uh=[[0,[.2,.6,.75,0]],[.5,[.2,.6,.75,.45]],[1.5,[.24,.75,.45,.5]],[2.5,[.9,.85,.25,.55]],[4,[.94,.55,.22,.6]],[6,[.86,.26,.22,.62]],[9,[.7,.2,.5,.65]]],Wh=[[0,[.28,.03,.02,0]],[1.5,[.45,.05,.03,.45]],[4,[.62,.08,.04,.55]],[9,[.8,.11,.05,.62]]],Gh={day:`rgba(20, 35, 50, 0.85)`,dusk:`rgba(210, 220, 235, 0.85)`,"night-red":`rgba(200, 50, 35, 0.9)`};function Kh(e,t){return vh(t===`night-red`?Wh:Uh,e)}function qh(e){return Gh[e]}var Jh=[[0,[.16,.66,.79,0]],[3,[.16,.66,.79,.9]],[7,[.22,.77,.41,.9]],[12,[.9,.85,.23,.9]],[18,[.94,.54,.23,.95]],[26,[.88,.28,.23,1]]],Yh=[[0,[.3,.04,.03,0]],[7,[.5,.06,.04,.85]],[18,[.68,.09,.05,.95]],[26,[.85,.13,.07,1]]],Xh=[0,3,7,12,18,26];function Zh(e){return[`interpolate`,[`linear`],[`get`,`speed`],...Xh.flatMap(t=>[t,yh(Qh(t,e))])]}function Qh(e,t){return vh(t===`night-red`?Yh:Jh,e)}var $h=[0,5,10,15,20,26],eg=[.5,1,2,4,6,9],tg=[.2,1,2.5,10,25],ng=[.25,.5,.75,1];function rg([e,t,n]){return yh([e,t,n,1])}function ig(e,t,n,r,i){let a=n[0],o=n[n.length-1],s=o-a||1;return{id:e,title:t,gradient:`linear-gradient(to right, ${n.map(e=>`${rg(r(e))} ${Math.round((e-a)/s*100)}%`).join(`, `)})`,lowLabel:i(a),highLabel:i(o)}}function ag(e,t){switch(e){case Oh.wind:return ig(e,`Wind (kn)`,$h,e=>Qh(e,t),e=>xc(gc(e),1));case Oh.pressure:return{id:e,title:`Pressure`,swatches:[{color:Fh(t).line,label:`isobars, 4 hPa`}]};case Oh.waves:return ig(e,`Waves (m)`,eg,e=>Kh(e,t),e=>xc(e,1));case Oh.precip:return ig(e,`Rain (mm/h)`,tg,e=>Nh(e,t),e=>xc(e,1));case Oh.cloud:return ig(e,`Cloud (%)`,ng,e=>Sh(e,t),e=>xc(e*100,1));case Oh.radar:return{id:e,title:`Rain radar`,swatches:t===`night-red`?[{color:`rgb(90, 26, 20)`,label:`light`},{color:`rgb(140, 36, 26)`,label:`moderate`},{color:`rgb(190, 50, 36)`,label:`heavy`},{color:`rgb(240, 80, 60)`,label:`intense`}]:[{color:`rgb(120, 160, 230)`,label:`light`},{color:`rgb(60, 170, 90)`,label:`moderate`},{color:`rgb(230, 200, 60)`,label:`heavy`},{color:`rgb(220, 70, 60)`,label:`intense`}],note:`live radar, regional resolution`};default:return}}function og(e,t,n){return Ch(e,e.precipitation,t,e=>Nh(e,n))}function sg(e,t){return Dh(e,{id:Oh.precip,title:`Precipitation`,sourceId:`binnacle-weather-precip-field`,layerId:`binnacle-weather-precip-field-layer`,defaultOpacity:.7,fieldRgba:og},t)}var cg=`binnacle-weather-pressure`,lg=`binnacle-weather-pressure-labels`,ug=`binnacle-weather-pressure-line`,dg=`binnacle-weather-pressure-label`;function fg(e){let t,n=NaN;return{id:Oh.pressure,title:`Pressure`,band:`weather`,supportsOpacity:!0,defaultVisible:!1,layerIds:[ug,dg],add(e){let t=Fh(`day`);if(!e.map.getSource(cg)){let t={type:`geojson`,data:od()};e.map.addSource(cg,t)}if(!e.map.getSource(lg)){let t={type:`geojson`,data:od()};e.map.addSource(lg,t)}if(!e.map.getLayer(ug)){let n={id:ug,type:`line`,source:cg,layout:{"line-cap":`round`,"line-join":`round`},paint:{"line-color":t.line,"line-width":1.2,"line-opacity":1}};e.map.addLayer(n,e.beforeIdFor(`weather`))}if(!e.map.getLayer(dg)){let n={id:dg,type:`symbol`,source:lg,layout:{"text-field":[`to-string`,[`get`,`pressureHpa`]],"text-font":[`Noto Sans Regular`],"text-size":11,"symbol-placement":`point`,"text-allow-overlap":!1},paint:{"text-color":t.label,"text-halo-color":t.halo,"text-halo-width":1.4,"text-opacity":1}};e.map.addLayer(n,e.beforeIdFor(`weather`))}},sync(r){let i=e.grid;if(i===t&&e.selectedTime===n)return;t=i,n=e.selectedTime;let a=r.map.getSource(cg),o=r.map.getSource(lg);if(!i){a?.setData(od()),o?.setData(od());return}let{lines:s,labels:c}=Rh(i,e.bracket);a?.setData(s),o?.setData(c)},remove(e){e.map.getLayer(dg)&&e.map.removeLayer(dg),e.map.getLayer(ug)&&e.map.removeLayer(ug),e.map.getSource(lg)&&e.map.removeSource(lg),e.map.getSource(cg)&&e.map.removeSource(cg)},setVisible(e,t){let n=t?`visible`:`none`;e.map.setLayoutProperty(ug,`visibility`,n),e.map.setLayoutProperty(dg,`visibility`,n)},setOpacity(e,t){e.map.setPaintProperty(ug,`line-opacity`,t),e.map.setPaintProperty(dg,`text-opacity`,t)},applyTheme(e,t){let n=Fh(t.theme);e.map.setPaintProperty(ug,`line-color`,n.line),e.map.setPaintProperty(dg,`text-color`,n.label),e.map.setPaintProperty(dg,`text-halo-color`,n.halo)}}}var pg=2,mg=`1_1`;function hg(e,t){return`${e}${t.path}/256/{z}/{x}/{y}/${pg}/${mg}.png`}var gg=`binnacle-weather-radar`,_g=`binnacle-weather-radar-layer`,vg=600,yg=1600,bg=.85;function xg(e,t=()=>performance.now()){let n,r=0,i=0,a=!1,o=bg,s;function c(t){let n=e.radar,i=n?.frames??[];if(!n||i.length===0)return;let c=i[Math.min(r,i.length-1)].path,u=hg(n.host,{time:0,path:c}),d=t.map.getSource(gg);if(d)d.setTiles([u]);else{let e={type:`raster`,tiles:[u],tileSize:256,maxzoom:7,attribution:`RainViewer`};t.map.addSource(gg,e)}if(!t.map.getLayer(_g)){let e={id:_g,type:`raster`,source:gg,layout:{visibility:a?`visible`:`none`},paint:{"raster-opacity":o}};t.map.addLayer(e,t.beforeIdFor(`weather`)),s&&l(t,s)}}function l(e,t){cl(e.map,_g,t)}return{id:Oh.radar,title:`Rain radar`,band:`weather`,supportsOpacity:!0,defaultVisible:!1,defaultOpacity:bg,layerIds:[_g],add(){n=void 0},sync(o){let s=e.radar,l=s?.frames??[];if(s!==n){n=s,r=Math.max(0,l.length-1),s&&l.length>0&&c(o),i=t();return}if(!a||!o.map.getLayer(_g)||!s||l.length<2)return;let u=r===l.length-1?yg:vg,d=t();d-i<u||(i=d,r=(r+1)%l.length,c(o))},remove(e){e.map.getLayer(_g)&&e.map.removeLayer(_g),e.map.getSource(gg)&&e.map.removeSource(gg)},setVisible(e,t){a=t,e.map.getLayer(_g)?e.map.setLayoutProperty(_g,`visibility`,t?`visible`:`none`):t&&c(e)},setOpacity(e,t){o=t,e.map.getLayer(_g)&&e.map.setPaintProperty(_g,`raster-opacity`,t)},applyTheme(e,t){s=t,e.map.getLayer(_g)&&l(e,t)}}}var Sg=`https://api.rainviewer.com/public/weather-maps.json`;async function Cg(e=globalThis.fetch.bind(globalThis)){try{let t=await e(Sg,{credentials:`omit`});if(!t.ok)return;let n=await t.json();if(!n.host||!n.radar)return;let r=[...n.radar.past??[],...n.radar.nowcast??[]].map(e=>({time:e.time*1e3,path:e.path})).sort((e,t)=>e.time-t.time);return r.length===0?void 0:{host:n.host,frames:r}}catch{return}}var wg=`/signalk/v2/api/weather`,Tg=(...e)=>globalThis.fetch(...e);async function Eg(e,t,n=Tg){try{let r=await n(`${e}${wg}/_providers`,Ws(t));return r.ok?Gs(await r.json()):void 0}catch{return}}function Dg(e){if(!e)return;let t=Object.entries(e).filter(e=>!!e[1]&&typeof e[1]==`object`);if(t.length===0)return;let[n,r]=t.find(([,e])=>e.isDefault)??t[0];return r.name??r.provider??n}function Og(e,t,n,r,i){let a=new URLSearchParams({lat:String(n),lon:String(r)});return i!==void 0&&a.set(`count`,String(i)),`${e}${wg}/${t}?${a.toString()}`}async function kg(e,t,n,r,i=Tg){return(await Mg(Og(e,`observations`,t,n),r,i))?.[0]}async function Ag(e,t,n,r,i,a=Tg){return Mg(Og(e,`forecasts/point`,t,n,r),i,a)}async function jg(e,t,n,r,i=Tg){try{let a=await i(Og(e,`warnings`,t,n),Ws(r));if(!a.ok)return;let o=await a.json();return Array.isArray(o)?o:void 0}catch{return}}async function Mg(e,t,n){try{let r=await n(e,Ws(t));if(!r.ok)return;let i=await r.json();return Array.isArray(i)?i:i&&typeof i==`object`?[i]:void 0}catch{return}}function Ng(e){return{timeMs:Date.parse(e.date),windMs:e.wind?.speedTrue,fromRad:e.wind?.directionTrue,gustMs:e.wind?.gust,pressurePa:e.outside?.pressure,airTempK:e.outside?.temperature,cloudFraction:e.outside?.cloudCover,waveHeightM:e.water?.waveSignificantHeight,wavePeriodS:e.water?.wavePeriod,precipitationMm:e.outside?.precipitationVolume}}function Pg(e){let t=e.wind?.speedTrue,n=e.wind?.directionTrue;if(!(t===void 0||n===void 0))return{speedMs:t,fromRad:n,pressurePa:e.outside?.pressure,waveHeightM:e.water?.waveSignificantHeight,wavePeriodS:e.water?.wavePeriod,precipitationMm:e.outside?.precipitationVolume,cloudCoverFraction:e.outside?.cloudCover}}function Fg(e,t){let n,r=1/0;for(let i of e){let e=Date.parse(i.date);if(Number.isNaN(e))continue;let a=Math.abs(e-t);a<r&&(r=a,n=i)}return n}function Ig(e,t){return Math.min(t.end,Math.max(t.start,e))}function Lg(e,t,n){return Ig(e+t*n.stepMs,n)}function Rg(e,t){let n=e+t.stepMs;return n>t.end?t.start:n}function zg(e,t,n,r){let i=kd(e,e.windU[r],t,n),a=kd(e,e.windV[r],t,n);if(i===void 0||a===void 0)return;let o=Math.hypot(i,a),s=(Math.atan2(-i,-a)+2*Math.PI)%(2*Math.PI),c=e.pressureMsl?.[r],l=c?Bg(kd(e,c,t,n)):void 0,u=e.waveHeight?.[r],d=u?Bg(kd(e,u,t,n)):void 0,f=e.wavePeriod?.[r],p=f?Bg(kd(e,f,t,n)):void 0,m=e.precipitation?.[r],h=m?Bg(kd(e,m,t,n)):void 0,g=e.cloudCover?.[r];return{speedMs:o,fromRad:s,pressurePa:l,waveHeightM:d,wavePeriodS:p,precipitationMm:h,cloudCoverFraction:g?Bg(kd(e,g,t,n)):void 0}}function Bg(e){return e===void 0||Number.isNaN(e)?void 0:e}var Vg=K(`<p class="cond-empty svelte-raos6e" role="status">Waiting for a vessel position.</p>`),Hg=K(`<li class="warning svelte-raos6e"><!> <span><b> </b> </span></li>`),Ug=K(`<ul class="warnings svelte-raos6e" role="alert"></ul>`),Wg=K(`<div class="svelte-raos6e"><dt class="svelte-raos6e">Gust</dt> <dd class="svelte-raos6e"><b class="svelte-raos6e"> </b> kn</dd></div>`),Gg=K(`<div class="svelte-raos6e"><dt class="svelte-raos6e">Pressure</dt> <dd class="svelte-raos6e"><b class="svelte-raos6e"> </b> hPa</dd></div>`),Kg=K(`<div class="svelte-raos6e"><dt class="svelte-raos6e">Air</dt> <dd class="svelte-raos6e"><b class="svelte-raos6e"> </b>&deg;C</dd></div>`),qg=K(`<div class="svelte-raos6e"><dt class="svelte-raos6e">Cloud</dt> <dd class="svelte-raos6e"><b class="svelte-raos6e"> </b>%</dd></div>`),Jg=K(`/ <b class="svelte-raos6e"> </b> s`,1),Yg=K(`<div class="svelte-raos6e"><dt class="svelte-raos6e">Sea</dt> <dd class="svelte-raos6e"><b class="svelte-raos6e"> </b> m <!></dd></div>`),Xg=K(`<div class="svelte-raos6e"><dt class="svelte-raos6e">Rain</dt> <dd class="svelte-raos6e"><b class="svelte-raos6e"> </b> mm/h</dd></div>`),Zg=K(`<dl class="now svelte-raos6e"><div class="svelte-raos6e"><dt class="svelte-raos6e">Wind</dt> <dd class="svelte-raos6e"><b class="svelte-raos6e"> </b> </dd></div> <!> <!> <!> <!> <!> <!></dl>`),Qg=K(`<p class="cond-empty svelte-raos6e" role="status">Loading conditions.</p>`),$g=K(`<p class="cond-empty svelte-raos6e" role="status">No conditions for this point</p>`),e_=K(`<span class="f-rain svelte-raos6e"><b class="svelte-raos6e"> </b> mm/h</span>`),t_=K(`<li class="svelte-raos6e"><span class="f-time svelte-raos6e"> </span> <span class="f-wind svelte-raos6e"><b class="svelte-raos6e"> </b> </span> <!></li>`),n_=K(`<ul class="forecast svelte-raos6e"></ul>`),r_=K(`<!> <!> <!>`,1),i_=K(`<section class="conditions svelte-raos6e" aria-label="Conditions at the vessel"><header class="cond-head svelte-raos6e"><span class="caps-label">Here</span> <span class="cond-source svelte-raos6e"> </span></header> <!></section>`);function a_(e,t){Qe(t,!0);let n=6*hc,r=z(!1),i=z(void 0),a=z(dn([])),o=z(dn([])),s=0,c=R(()=>t.providerName??`Open-Meteo`),l=R(()=>t.position?`${t.position.latitude.toFixed(3)},${t.position.longitude.toFixed(3)}`:``);function u(e){let[t,n]=e.split(`,`).map(Number);return[t,n]}Ln(()=>{let e=W(l),n=t.providerName;if(!e){d();return}if(!n)return;let[r,i]=u(e);f(r,i)}),Ln(()=>{let e=W(l),n=t.providerName;if(t.store.selectedTime,!e||n)return;let[r,s]=u(e);B(i,p(r,s),!0),B(a,m(r,s),!0),B(o,[],!0)});function d(){B(i,void 0),B(a,[],!0),B(o,[],!0)}async function f(e,n){let c=++s;B(r,!0);let[l,u,d]=await Promise.all([kg(t.origin,e,n,t.token),Ag(t.origin,e,n,12,t.token),jg(t.origin,e,n,t.token)]);c===s&&(B(i,l?Ng(l):p(e,n),!0),B(a,u?u.map(Ng).slice(0,6):m(e,n),!0),B(o,d??[],!0),B(r,!1))}function p(e,n){let r=t.store.grid;if(!r)return;let i=zg(r,n,e,t.store.bracket.lo);return i?{timeMs:t.store.selectedTime,windMs:i.speedMs,...h(i)}:void 0}function m(e,r){let i=t.store.grid;if(!i)return[];let a=[],o=-1/0;for(let s=0;s<i.times.length&&a.length<6;s++){let c=i.times[s];if(c<t.store.selectedTime||c-o<n)continue;let l=zg(i,r,e,s);l&&(a.push({timeMs:c,windMs:l.speedMs,...h(l)}),o=c)}return a}function h(e){return{fromRad:e.fromRad,pressurePa:e.pressurePa,cloudFraction:e.cloudCoverFraction,waveHeightM:e.waveHeightM,wavePeriodS:e.wavePeriodS,precipitationMm:e.precipitationMm}}let g=e=>xc(gc(e),1),_=e=>xc(_c(e),0),v=e=>xc(yc(e),0),y=e=>xc(bc(e),0),b=e=>xc(e===void 0?void 0:e*100,0);function x(e){return Number.isNaN(e)?``:new Date(e).toLocaleString([],{weekday:`short`,hour:`2-digit`})}var S=i_(),C=V(S),w=H(V(C),2),T=V(w,!0);N(w),N(C);var E=H(C,2),D=e=>{q(e,Vg())},O=e=>{var t=r_(),n=Sn(t),s=e=>{var t=Ug();vi(t,21,()=>W(o),e=>e.startTime+e.type,(e,t)=>{var n=Hg(),r=V(n);Bo(r,{size:14,"aria-hidden":`true`});var i=H(r,2),a=V(i),o=V(a,!0);N(a);var s=H(a);N(i),N(n),U(()=>{J(o,W(t).type),J(s,` ${W(t).details??``}`)}),q(e,n)}),N(t),q(e,t)};Y(n,e=>{W(o).length>0&&e(s)});var c=H(n,2),l=e=>{var t=Zg(),n=V(t),r=H(V(n),2),a=V(r),o=V(a,!0);N(a);var s=H(a);N(r),N(n);var c=H(n,2),l=e=>{var t=Wg(),n=H(V(t),2),r=V(n),a=V(r,!0);N(r),P(),N(n),N(t),U(e=>J(a,e),[()=>g(W(i).gustMs)]),q(e,t)};Y(c,e=>{W(i).gustMs!==void 0&&e(l)});var u=H(c,2),d=e=>{var t=Gg(),n=H(V(t),2),r=V(n),a=V(r,!0);N(r),P(),N(n),N(t),U(e=>J(a,e),[()=>v(W(i).pressurePa)]),q(e,t)};Y(u,e=>{W(i).pressurePa!==void 0&&e(d)});var f=H(u,2),p=e=>{var t=Kg(),n=H(V(t),2),r=V(n),a=V(r,!0);N(r),P(),N(n),N(t),U(e=>J(a,e),[()=>y(W(i).airTempK)]),q(e,t)};Y(f,e=>{W(i).airTempK!==void 0&&e(p)});var m=H(f,2),h=e=>{var t=qg(),n=H(V(t),2),r=V(n),a=V(r,!0);N(r),P(),N(n),N(t),U(e=>J(a,e),[()=>b(W(i).cloudFraction)]),q(e,t)};Y(m,e=>{W(i).cloudFraction!==void 0&&e(h)});var x=H(m,2),S=e=>{var t=Yg(),n=H(V(t),2),r=V(n),a=V(r,!0);N(r);var o=H(r,2),s=e=>{var t=Jg(),n=H(Sn(t)),r=V(n,!0);N(n),P(),U(e=>J(r,e),[()=>xc(W(i).wavePeriodS,1)]),q(e,t)};Y(o,e=>{W(i).wavePeriodS!==void 0&&e(s)}),N(n),N(t),U(e=>J(a,e),[()=>xc(W(i).waveHeightM,1)]),q(e,t)};Y(x,e=>{W(i).waveHeightM!==void 0&&e(S)});var C=H(x,2),w=e=>{var t=Xg(),n=H(V(t),2),r=V(n),a=V(r,!0);N(r),P(),N(n),N(t),U(e=>J(a,e),[()=>xc(W(i).precipitationMm,1)]),q(e,t)};Y(C,e=>{W(i).precipitationMm!==void 0&&W(i).precipitationMm>=.1&&e(w)}),N(t),U((e,t)=>{J(o,e),J(s,` kn ${t??``}°`)},[()=>g(W(i).windMs),()=>_(W(i).fromRad)]),q(e,t)},u=e=>{q(e,Qg())},d=e=>{q(e,$g())};Y(c,e=>{W(i)?e(l):W(r)?e(u,1):e(d,-1)});var f=H(c,2),p=e=>{var t=n_();vi(t,21,()=>W(a),e=>e.timeMs,(e,t)=>{var n=t_(),r=V(n),i=V(r,!0);N(r);var a=H(r,2),o=V(a),s=V(o,!0);N(o);var c=H(o);N(a);var l=H(a,2),u=e=>{var n=e_(),r=V(n),i=V(r,!0);N(r),P(),N(n),U(e=>J(i,e),[()=>xc(W(t).precipitationMm,1)]),q(e,n)};Y(l,e=>{W(t).precipitationMm!==void 0&&W(t).precipitationMm>=.1&&e(u)}),N(n),U((e,t,n)=>{J(i,e),J(s,t),J(c,` kn ${n??``}°`)},[()=>x(W(t).timeMs),()=>g(W(t).windMs),()=>_(W(t).fromRad)]),q(e,n)}),N(t),q(e,t)};Y(f,e=>{W(a).length>0&&e(p)}),q(e,t)};Y(E,e=>{t.position?e(O,-1):e(D)}),N(S),U(()=>J(T,W(c))),q(e,S),$e()}function o_(e,t,n,r){let i=e.lons.length,a=i>1?Math.abs(e.lons[1]-e.lons[0]):1,o=e.lats.length>1?Math.abs(e.lats[1]-e.lats[0]):1,s=Math.min(a,o)*n,c=[];for(let n=0;n<e.lats.length;n+=t)for(let a=0;a<i;a+=t){let t=r(n*i+a);if(!t)continue;let o=e.lons[a],l=e.lats[n];c.push({type:`Feature`,geometry:{type:`LineString`,coordinates:[[o,l],[o+t.u*s,l+t.v*s]]},properties:t.props})}return{type:`FeatureCollection`,features:c}}var s_=2,c_=.5;function l_(e,t){let n=e.waveDirection,r=e.waveHeight;if(!n||!r)return od();let i=n[t.lo]??[],a=n[t.hi]??i,o=r[t.lo]??[],s=r[t.hi]??o;return o_(e,s_,c_,e=>{let n=lc(i[e],a[e],t.frac),r=lc(o[e],s[e],t.frac);if(!(Number.isNaN(n)||Number.isNaN(r)))return{u:-Math.sin(n),v:-Math.cos(n),props:{height:r}}})}function u_(e,t,n){return Ch(e,e.waveHeight,t,e=>Kh(e,n))}var d_=`binnacle-weather-waves-field`,f_=`binnacle-weather-waves-field-layer`,p_=`binnacle-weather-waves-arrows`,m_=`binnacle-weather-waves-arrow-layer`;function h_(e,t){let n=Dh(e,{id:Oh.waves,title:`Waves`,sourceId:d_,layerId:f_,defaultOpacity:.7,fieldRgba:u_},t),r,i=NaN;return{id:n.id,title:n.title,band:`weather`,supportsOpacity:!0,defaultVisible:!1,layerIds:[f_,m_],add(e){if(n.add(e),!e.map.getSource(p_)){let t={type:`geojson`,data:od()};e.map.addSource(p_,t)}if(!e.map.getLayer(m_)){let t={id:m_,type:`line`,source:p_,layout:{"line-cap":`round`},paint:{"line-color":qh(`day`),"line-width":1.5,"line-opacity":1}};e.map.addLayer(t,e.beforeIdFor(`weather`))}},sync(t){n.sync(t);let a=e.grid;a===r&&e.selectedTime===i||(r=a,i=e.selectedTime,t.map.getSource(p_)?.setData(a?l_(a,e.bracket):od()))},remove(e){e.map.getLayer(m_)&&e.map.removeLayer(m_),e.map.getSource(p_)&&e.map.removeSource(p_),n.remove(e)},setVisible(e,t){n.setVisible(e,t),e.map.setLayoutProperty(m_,`visibility`,t?`visible`:`none`)},setOpacity(e,t){n.setOpacity?.(e,t),e.map.setPaintProperty(m_,`line-opacity`,t)},applyTheme(e,t){n.applyTheme?.(e,t),e.map.setPaintProperty(m_,`line-color`,qh(t.theme))}}}var g_=`https://api.open-meteo.com/v1/forecast`,__=`https://marine-api.open-meteo.com/v1/marine`,v_=200;async function y_(e,t,n,r,i,a){let{lats:o,lons:s}=Dd(r,i.maxCells),c=[];for(let e of o)for(let t of s)c.push({lat:e,lon:t});try{let r=x_(c,v_),l=await Promise.all(r.map(r=>a(b_(e,r,t,n,i),{credentials:`omit`}))),u=[];for(let e of l){if(!e.ok)return;let t=await e.json();for(let e of Array.isArray(t)?t:[t])u.push(e)}return{locs:u,lats:o,lons:s}}catch{return}}function b_(e,t,n,r,i){return`${e}?${new URLSearchParams({latitude:t.map(e=>e.lat.toFixed(4)).join(`,`),longitude:t.map(e=>e.lon.toFixed(4)).join(`,`),hourly:n,forecast_days:String(i.forecastDays),timeformat:`unixtime`,...r})}`}function x_(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function S_(e,t,n=NaN){return Array.from({length:e},()=>Array(t).fill(n))}async function C_(e,t,n=globalThis.fetch.bind(globalThis)){let r=await y_(g_,`wind_speed_10m,wind_direction_10m,pressure_msl,precipitation,cloud_cover`,{wind_speed_unit:`ms`},e,t,n);return r?w_(r.locs,r.lats,r.lons):void 0}function w_(e,t,n){let r=e[0]?.hourly;if(!r?.time||r.time.length===0)return;let i=r.time.map(e=>Number(e)*1e3),a=i.length,o=t.length*n.length;if(e.length!==o)return;let s=S_(a,o,0),c=S_(a,o,0),l=S_(a,o),u=S_(a,o),d=S_(a,o);for(let t=0;t<o;t+=1){let n=e[t]?.hourly,r=n?.wind_speed_10m??[],i=n?.wind_direction_10m??[],o=n?.pressure_msl??[],f=n?.precipitation??[],p=n?.cloud_cover??[];for(let e=0;e<a;e+=1){let n=r[e]??0,a=(i[e]??0)*mc;s[e][t]=-n*Math.sin(a),c[e][t]=-n*Math.cos(a);let m=o[e];m!==void 0&&(l[e][t]=m*100);let h=f[e];h!==void 0&&(u[e][t]=h);let g=p[e];g!==void 0&&(d[e][t]=g/100)}}return{lats:t,lons:n,times:i,windU:s,windV:c,pressureMsl:l,precipitation:u,cloudCover:d}}async function T_(e,t,n=globalThis.fetch.bind(globalThis)){let r=await y_(__,`wave_height,wave_direction,wave_period`,{cell_selection:`sea`},e,t,n);return r?E_(r.locs,r.lats.length*r.lons.length):void 0}function E_(e,t){let n=e[0]?.hourly;if(!n?.time||n.time.length===0||e.length!==t)return;let r=n.time.length,i=S_(r,t),a=S_(r,t),o=S_(r,t);for(let n=0;n<t;n+=1){let t=e[n]?.hourly,s=t?.wave_height??[],c=t?.wave_direction??[],l=t?.wave_period??[];for(let e=0;e<r;e+=1){i[e][n]=s[e]??NaN;let t=c[e];a[e][n]=t===void 0?NaN:t*mc,o[e][n]=l[e]??NaN}}return{waveHeight:i,waveDirection:a,wavePeriod:o}}function D_(e,t){return{...e,waveHeight:t.waveHeight,waveDirection:t.waveDirection,wavePeriod:t.wavePeriod}}function O_(e,t,n,r){let i;return()=>(i||=new Promise((i,a)=>{let o=e.open(t,n);o.onupgradeneeded=()=>r(o.result),o.onsuccess=()=>i(o.result),o.onerror=()=>a(o.error),o.onblocked=()=>a(Error(`indexedDB open blocked`))}),i)}function k_(e,t,n,r){let i=O_(e,t,1,r);return{run:(e,t)=>i().then(r=>new Promise((i,a)=>{let o=t(r.transaction(n,e).objectStore(n));o.onsuccess=()=>i(o.result),o.onerror=()=>a(o.error)}))}}function A_(){let e=!1;return{read:async(t,n)=>{if(e)return n();try{return await t()}catch{return e=!0,n()}},write:async(t,n)=>{if(await n(),!e)try{await t()}catch{e=!0}}}}var j_=`values`,M_=`meta`,N_=48;function P_(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}function F_(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function I_(e){let t=new Map;return{get:async e=>t.get(e),put:async(e,n,r)=>{t.set(e,{value:n,expires:r})},prune:async n=>{for(let[e,r]of t)r.expires<=n&&t.delete(e);if(t.size>e){let n=[...t.entries()].sort((e,t)=>e[1].expires-t[1].expires);for(let[r]of n.slice(0,t.size-e))t.delete(r)}}}}function L_(e,t={}){let n=t.maxEntries??N_,r=`factory`in t?t.factory:globalThis.indexedDB;if(!r)return I_(n);let i=I_(n),a=A_(),o=O_(r,e,1,e=>{e.createObjectStore(j_),e.createObjectStore(M_)});return{get:e=>a.read(async()=>{let t=(await o()).transaction([j_,M_],`readonly`),n=t.objectStore(M_).get(e),r=t.objectStore(j_).get(e),[i,a]=await Promise.all([P_(n),P_(r)]);if(!(i===void 0||a===void 0))return{value:a,expires:i}},()=>i.get(e)),put:(e,t,n)=>a.write(async()=>{let r=(await o()).transaction([j_,M_],`readwrite`);r.objectStore(j_).put(t,e),r.objectStore(M_).put(n,e),await F_(r)},()=>i.put(e,t,n)),prune:e=>a.write(async()=>{let t=await o(),r=t.transaction(M_,`readonly`),i=r.objectStore(M_).getAll(),a=r.objectStore(M_).getAllKeys(),[s,c]=await Promise.all([P_(i),P_(a)]),l=c.map((e,t)=>({key:String(e),expires:s[t]})),u=l.filter(t=>t.expires<=e).map(e=>e.key),d=l.filter(t=>t.expires>e).sort((e,t)=>e.expires-t.expires),f=d.length>n?d.slice(0,d.length-n).map(e=>e.key):[],p=[...u,...f];if(p.length===0)return;let m=t.transaction([j_,M_],`readwrite`);for(let e of p)m.objectStore(j_).delete(e),m.objectStore(M_).delete(e);await F_(m)},()=>i.prune(e))}}var R_=`binnacle-pmtiles`,z_=`archives`;function B_(){let e=new Map;return{put:async(t,n)=>{e.set(t,n)},get:async t=>e.get(t),delete:async t=>{e.delete(t)}}}function V_(e=globalThis.indexedDB){if(!e)return B_();let t=B_(),{run:n}=k_(e,R_,z_,e=>e.createObjectStore(z_)),r=A_();return{put:(e,i)=>r.write(()=>n(`readwrite`,t=>t.put(i,e)),()=>t.put(e,i)),get:e=>r.read(()=>n(`readonly`,t=>t.get(e)),()=>t.get(e)),delete:e=>r.write(()=>n(`readwrite`,t=>t.delete(e)),()=>t.delete(e))}}var H_=`binnacle`,U_=`track-points`;function W_(){let e=[];return{all:async()=>e.slice(),append:async t=>{e.push(t)},clear:async()=>{e=[]}}}function G_(e=globalThis.indexedDB){if(!e)return W_();let t=W_(),{run:n}=k_(e,H_,U_,e=>e.createObjectStore(U_,{autoIncrement:!0})),r=A_();return{all:()=>r.read(()=>n(`readonly`,e=>e.getAll()),()=>t.all()),append:e=>r.write(()=>n(`readwrite`,t=>t.add(e)),()=>t.append(e)),clear:()=>r.write(()=>n(`readwrite`,e=>e.clear()),()=>t.clear())}}var K_=3600*1e3,q_=300*1e3,J_=.25,Y_=16,X_=60*1e3,Z_=e=>Math.round(e/J_)*J_;function Q_(e,t,n){return[Z_(e.west),Z_(e.south),Z_(e.east),Z_(e.north),t.maxCells,t.forecastDays,n?`m`:`-`].join(`:`)}var $_={forecast:C_,marine:T_,radar:Cg,now:()=>Date.now(),persist:L_(`binnacle-weather`)};function ev(e={}){let t={...$_,...e},n=new Map,r,i=0;async function a(e,n,r){let[i,a]=await Promise.all([t.forecast(e,n),r?t.marine(e,n):Promise.resolve(void 0)]);return i?{grid:a?D_(i,a):i,partial:r&&!a}:{grid:void 0,partial:!1}}return{async load(e,o,s,c){e.setStatus(`loading`);let l=t.now(),u=Q_(o,s,c.waves),d=(e,t)=>{for(let[e,t]of n)t.expires<=l&&n.delete(e);for(n.set(u,{grid:e,expires:t});n.size>Y_;){let e=n.keys().next().value;if(e===void 0)break;n.delete(e)}},f=async()=>{let e=n.get(u);if(e&&e.expires>l)return{grid:e.grid,partial:!1,fromNetwork:!1};let r=await t.persist.get(u);return r&&r.expires>l?(d(r.value,r.expires),{grid:r.value,partial:!1,fromNetwork:!1}):l<i?{grid:void 0,partial:!1,fromNetwork:!1}:{...await a(o,s,c.waves),fromNetwork:!0}},p;p=c.radar?r&&r.expires>l?Promise.resolve(r.data):t.radar():Promise.resolve(void 0);let[{grid:m,partial:h,fromNetwork:g},_]=await Promise.all([f(),p]);if(m){if(e.setGrid(m),h)i=l+X_;else if(g){let e=l+K_;d(m,e),await t.persist.put(u,m,e),t.persist.prune(l)}}else g&&(i=l+X_),e.setStatus(e.grid?`stale`:`error`);_&&(r={data:_,expires:l+q_},e.setRadar(_))}}}var tv=.5,nv=.4;function rv(e,t){let n=e.windU[t.lo],r=e.windU[t.hi],i=e.windV[t.lo],a=e.windV[t.hi];return o_(e,1,nv,e=>{let o=lc(n[e],r[e],t.frac),s=lc(i[e],a[e],t.frac),c=Math.hypot(o,s);if(!(c<tv))return{u:o/c,v:s/c,props:{speed:c}}})}function iv(e){let t=new Uint8Array(256*4);for(let n=0;n<256;n+=1){let[r,i,a,o]=Qh(n/255*26,e),s=n*4;t[s]=Math.round(r*255),t[s+1]=Math.round(i*255),t[s+2]=Math.round(a*255),t[s+3]=Math.round(o*255)}return t}function av(e,t){let n=e.windU[t.lo],r=e.windV[t.lo];if(!n||!r||n.length===0)return;let i=e.windU[t.hi]??n,a=e.windV[t.hi]??r,o=e.lons.length,s=e.lats.length,c=new Float32Array(o*s),l=new Float32Array(o*s),u=1/0,d=-1/0,f=1/0,p=-1/0;for(let e=0;e<o*s;e+=1){let o=lc(n[e],i[e],t.frac),s=lc(r[e],a[e],t.frac);c[e]=o,l[e]=s,Number.isNaN(o)||(u=Math.min(u,o),d=Math.max(d,o)),Number.isNaN(s)||(f=Math.min(f,s),p=Math.max(p,s))}u>d&&(u=-1,d=1),f>p&&(f=-1,p=1);let m=d-u||1,h=p-f||1,g=new Uint8Array(o*s*4);for(let e=0;e<o*s;e+=1){let t=e*4,n=Number.isNaN(c[e])||Number.isNaN(l[e]);g[t]=n?0:Math.round((c[e]-u)/m*255),g[t+1]=n?0:Math.round((l[e]-f)/h*255),g[t+3]=n?0:255}return{data:g,width:o,height:s,uMin:u,uMax:d,vMin:f,vMax:p,west:e.lons[0],south:e.lats[0],east:e.lons[o-1],north:e.lats[s-1]}}var ov=`
751
751
  precision mediump float;
752
752
  attribute vec2 a_pos;
@@ -827,4 +827,4 @@ uniform sampler2D u_color_ramp;
827
827
  varying float v_speed_t;
828
828
  void main() {
829
829
  gl_FragColor = texture2D(u_color_ramp, vec2(clamp(v_speed_t, 0.0, 1.0), 0.5));
830
- }`;function dv(e,t,n){let r=e.createShader(t);if(!r)throw Error(`createShader failed`);if(e.shaderSource(r,n),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS))throw Error(e.getShaderInfoLog(r)??`shader compile failed`);return r}function fv(e,t,n){let r=e.createProgram();if(!r)throw Error(`createProgram failed`);if(e.attachShader(r,dv(e,e.VERTEX_SHADER,t)),e.attachShader(r,dv(e,e.FRAGMENT_SHADER,n)),e.linkProgram(r),!e.getProgramParameter(r,e.LINK_STATUS))throw Error(e.getProgramInfoLog(r)??`program link failed`);return r}function pv(e,t,n,r,i){let a=e.createTexture();if(!a)throw Error(`createTexture failed`);return e.bindTexture(e.TEXTURE_2D,a),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,r,i,0,e.RGBA,e.UNSIGNED_BYTE,n),e.bindTexture(e.TEXTURE_2D,null),a}function mv(e,t){let n=e.createBuffer();if(!n)throw Error(`createBuffer failed`);return e.bindBuffer(e.ARRAY_BUFFER,n),e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW),n}function hv(){try{let e=document.createElement(`canvas`),t=e.getContext(`webgl`)??e.getContext(`experimental-webgl`);return t?(fv(t,ov,cv),fv(t,lv,uv),!0):!1}catch{return!1}}var gv=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_=0;#v=0;#y;#b;#x;#S;#C;#w;#T=1;constructor(e,t={}){this.#e=e,this.#y=t.resolution??90,this.#b=this.#y*this.#y,this.#x=t.speedFactor??8e-4,this.#S=t.dropRate??.003,this.#C=t.dropRateBump??.01,this.#w=t.fadeOpacity??.96,this.#t=fv(e,ov,cv),this.#n=fv(e,lv,uv),this.#r=fv(e,ov,sv),this.#i={aPos:e.getAttribLocation(this.#r,`a_pos`),uScreen:e.getUniformLocation(this.#r,`u_screen`),uOpacity:e.getUniformLocation(this.#r,`u_opacity`)},this.#a={aPos:e.getAttribLocation(this.#t,`a_pos`),uParticles:e.getUniformLocation(this.#t,`u_particles`),uWind:e.getUniformLocation(this.#t,`u_wind`),uWindMin:e.getUniformLocation(this.#t,`u_wind_min`),uWindMax:e.getUniformLocation(this.#t,`u_wind_max`),uRandSeed:e.getUniformLocation(this.#t,`u_rand_seed`),uSpeedFactor:e.getUniformLocation(this.#t,`u_speed_factor`),uDropRate:e.getUniformLocation(this.#t,`u_drop_rate`),uDropRateBump:e.getUniformLocation(this.#t,`u_drop_rate_bump`)},this.#o={aIndex:e.getAttribLocation(this.#n,`a_index`),uParticles:e.getUniformLocation(this.#n,`u_particles`),uWind:e.getUniformLocation(this.#n,`u_wind`),uColorRamp:e.getUniformLocation(this.#n,`u_color_ramp`),uParticlesRes:e.getUniformLocation(this.#n,`u_particles_res`),uMatrix:e.getUniformLocation(this.#n,`u_matrix`),uWindMin:e.getUniformLocation(this.#n,`u_wind_min`),uWindMax:e.getUniformLocation(this.#n,`u_wind_max`),uBounds:e.getUniformLocation(this.#n,`u_bounds`)},this.#s=mv(e,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]));let n=new Float32Array(this.#b);for(let e=0;e<this.#b;e+=1)n[e]=e;this.#c=mv(e,n);let r=e.createFramebuffer();if(!r)throw Error(`createFramebuffer failed`);this.#l=r,this.#u=pv(e,e.LINEAR,null,256,1);let i=this.#E();this.#p=pv(e,e.NEAREST,i,this.#y,this.#y),this.#m=pv(e,e.NEAREST,i,this.#y,this.#y),this.#h=pv(e,e.NEAREST,null,1,1),this.#g=pv(e,e.NEAREST,null,1,1)}#E(){let e=new Uint8Array(this.#b*4);for(let t=0;t<e.length;t+=1)e[t]=Math.floor(Math.random()*256);return e}setWind(e){this.#f=e;let t=this.#e;this.#d&&t.deleteTexture(this.#d),this.#d=pv(t,t.LINEAR,e.data,e.width,e.height)}setTheme(e){let t=this.#e;t.bindTexture(t.TEXTURE_2D,this.#u),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,256,1,0,t.RGBA,t.UNSIGNED_BYTE,e),t.bindTexture(t.TEXTURE_2D,null)}setOpacity(e){this.#T=e}#D(e,t){if(e===this.#_&&t===this.#v)return;let n=this.#e;n.deleteTexture(this.#h),n.deleteTexture(this.#g);let r=new Uint8Array(e*t*4);this.#h=pv(n,n.NEAREST,r,e,t),this.#g=pv(n,n.NEAREST,r,e,t),this.#_=e,this.#v=t}#O(e,t,n){let r=this.#e;r.bindBuffer(r.ARRAY_BUFFER,e),r.enableVertexAttribArray(t),r.vertexAttribPointer(t,n,r.FLOAT,!1,0,0)}#k(e,t){let n=this.#e,r=this.#i;n.useProgram(this.#r),this.#O(this.#s,r.aPos,2),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,e),n.uniform1i(r.uScreen,0),n.uniform1f(r.uOpacity,t),n.drawArrays(n.TRIANGLES,0,6)}#A(){let e=this.#e;if(!this.#d||!this.#f)return;let t=this.#a;e.bindFramebuffer(e.FRAMEBUFFER,this.#l),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.#m,0),e.viewport(0,0,this.#y,this.#y),e.useProgram(this.#t),this.#O(this.#s,t.aPos,2),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.#p),e.uniform1i(t.uParticles,0),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,this.#d),e.uniform1i(t.uWind,1),e.uniform2f(t.uWindMin,this.#f.uMin,this.#f.vMin),e.uniform2f(t.uWindMax,this.#f.uMax,this.#f.vMax),e.uniform1f(t.uRandSeed,Math.random()),e.uniform1f(t.uSpeedFactor,this.#x),e.uniform1f(t.uDropRate,this.#S),e.uniform1f(t.uDropRateBump,this.#C),e.drawArrays(e.TRIANGLES,0,6);let n=this.#p;this.#p=this.#m,this.#m=n}#j(e){let t=this.#e;if(!this.#d||!this.#f)return;let n=this.#o;t.useProgram(this.#n),this.#O(this.#c,n.aIndex,1),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.#p),t.uniform1i(n.uParticles,0),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.#d),t.uniform1i(n.uWind,1),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.#u),t.uniform1i(n.uColorRamp,2),t.uniform1f(n.uParticlesRes,this.#y),t.uniformMatrix4fv(n.uMatrix,!1,e),t.uniform2f(n.uWindMin,this.#f.uMin,this.#f.vMin),t.uniform2f(n.uWindMax,this.#f.uMax,this.#f.vMax),t.uniform4f(n.uBounds,this.#f.west,this.#f.south,this.#f.east,this.#f.north),t.drawArrays(t.POINTS,0,this.#b)}render(e,t,n,r){let i=this.#e;if(!this.#d||!this.#f)return;this.#D(t,n),i.disable(i.DEPTH_TEST),i.disable(i.STENCIL_TEST),this.#A(),i.bindFramebuffer(i.FRAMEBUFFER,this.#l),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,this.#g,0),i.viewport(0,0,t,n),r?(i.clearColor(0,0,0,0),i.clear(i.COLOR_BUFFER_BIT)):this.#k(this.#h,this.#w),i.enable(i.BLEND),i.blendFunc(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA),this.#j(e),i.disable(i.BLEND),i.bindFramebuffer(i.FRAMEBUFFER,null),i.enable(i.BLEND),i.blendFunc(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA),this.#k(this.#g,this.#T),i.disable(i.BLEND);let a=this.#h;this.#h=this.#g,this.#g=a}dispose(){let e=this.#e;e.deleteProgram(this.#t),e.deleteProgram(this.#n),e.deleteProgram(this.#r),e.deleteBuffer(this.#s),e.deleteBuffer(this.#c),e.deleteFramebuffer(this.#l),e.deleteTexture(this.#u),e.deleteTexture(this.#p),e.deleteTexture(this.#m),e.deleteTexture(this.#h),e.deleteTexture(this.#g),this.#d&&e.deleteTexture(this.#d)}},_v=`binnacle-weather-wind`,vv=`binnacle-weather-wind-line`,yv=`binnacle-weather-wind-particles`;function bv(e){return Array.isArray(e)?e:e.defaultProjectionData?.mainMatrix??[]}function xv(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function Sv(e){let t=hv(),n=`day`,r=1,i=!1,a,o=NaN,s,c=[];function l(e){return Zh(e)}function u(e){if(!e.map.getSource(_v)){let t={type:`geojson`,data:od()};e.map.addSource(_v,t)}if(!e.map.getLayer(vv)){let t={id:vv,type:`line`,source:_v,layout:{"line-cap":`round`,visibility:i?`visible`:`none`},paint:{"line-color":l(n),"line-width":2,"line-opacity":r}};e.map.addLayer(t,e.beforeIdFor(`weather`))}}function d(t){let n=e.grid;t.map.getSource(_v)?.setData(n?rv(n,e.bracket):od())}function f(){if(!s)return;let t=e.grid,n=t?av(t,e.bracket):void 0;n&&s.setWind(n)}function p(e){let t={id:yv,type:`custom`,onAdd(t,i){try{s=new gv(i),s.setTheme(iv(n)),s.setOpacity(r),f()}catch(t){console.warn(`[wind] particle init failed, using arrows`,t),s=void 0,u(e),d(e)}},render(t,n){if(!s||!i)return;let r=bv(n);if(r.length<16)return;let a=!xv(r,c);c=r,s.render(r,t.drawingBufferWidth,t.drawingBufferHeight,a),e.map.triggerRepaint()},onRemove(){s?.dispose(),s=void 0}};e.map.addLayer(t,e.beforeIdFor(`weather`))}return{id:Oh.wind,title:`Wind`,band:`weather`,supportsOpacity:!0,defaultVisible:!1,layerIds:[yv,vv],add(e){a=void 0,o=NaN,t?p(e):u(e)},sync(t){let n=e.grid;n===a&&e.selectedTime===o||(a=n,o=e.selectedTime,f(),!s&&t.map.getLayer(vv)&&d(t))},remove(e){e.map.getLayer(yv)&&e.map.removeLayer(yv),e.map.getLayer(vv)&&e.map.removeLayer(vv),e.map.getSource(_v)&&e.map.removeSource(_v)},setVisible(e,t){i=t,e.map.getLayer(vv)&&e.map.setLayoutProperty(vv,`visibility`,t?`visible`:`none`),t&&e.map.triggerRepaint()},setOpacity(e,t){r=t,s?.setOpacity(t),e.map.getLayer(vv)&&e.map.setPaintProperty(vv,`line-opacity`,t)},applyTheme(e,t){n=t.theme,s?.setTheme(iv(n)),e.map.getLayer(vv)&&e.map.setPaintProperty(vv,`line-color`,l(n))}}}var Cv=class{#e=z(dn(typeof navigator>`u`?!0:navigator.onLine));get online(){return W(this.#e)}set online(e){B(this.#e,e,!0)}#t;constructor(){if(typeof window>`u`)return;let e=()=>{this.online=!0},t=()=>{this.online=!1};window.addEventListener(`online`,e),window.addEventListener(`offline`,t),this.#t=()=>{window.removeEventListener(`online`,e),window.removeEventListener(`offline`,t)}}dispose(){this.#t?.(),this.#t=void 0}},wv=`modulepreload`,Tv=function(e){return`/signalk-binnacle/`+e},Ev={},Dv=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}r=o(t.map(t=>{if(t=Tv(t,n),t in Ev)return;Ev[t]=!0;let r=t.endsWith(`.css`),i=r?`[rel="stylesheet"]`:``;if(n)for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${t}"]${i}`))return;let o=document.createElement(`link`);if(o.rel=r?`stylesheet`:wv,r||(o.as=`script`),o.crossOrigin=``,o.href=t,a&&o.setAttribute(`nonce`,a),document.head.appendChild(o),r)return new Promise((e,n)=>{o.addEventListener(`load`,e),o.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},Ov=`false`,kv=`false`,Av=Ov===`true`,jv=kv===`true`;function Mv(e={}){let{immediate:t=!1,onNeedReload:n,onNeedRefresh:r,onOfflineReady:i,onRegistered:a,onRegisteredSW:o,onRegisterError:s}=e,c,l,u,d=async(e=!0)=>{await l,Av||u?.()};async function f(){if(`serviceWorker`in navigator){if(c=await Dv(async()=>{let{Workbox:e}=await import(`./workbox-window.prod.es5-Bd17z0YL.js`);return{Workbox:e}},[]).then(({Workbox:e})=>new e(`/signalk-binnacle/sw.js`,{scope:`/signalk-binnacle/`,type:`classic`})).catch(e=>{s?.(e)}),!c)return;if(u=()=>{c?.messageSkipWaiting()},!jv)if(Av)c.addEventListener(`activated`,e=>{(e.isUpdate||e.isExternal)&&(n?n():window.location.reload())}),c.addEventListener(`installed`,e=>{e.isUpdate||i?.()});else{let e=!1,t=()=>{e=!0,c?.addEventListener(`controlling`,e=>{e.isUpdate&&(n?n():window.location.reload())}),r?.()};c.addEventListener(`installed`,n=>{n.isUpdate===void 0?n.isExternal===void 0?!e&&i?.():n.isExternal?t():!e&&i?.():n.isUpdate||i?.()}),c.addEventListener(`waiting`,t)}c.register({immediate:t}).then(e=>{o?o(`/signalk-binnacle/sw.js`,e):a?.(e)}).catch(e=>{s?.(e)})}}return l=f(),d}function Nv(e){let t=Mv({onNeedRefresh:()=>e?.(),onRegisterError:e=>console.warn(`[pwa] service worker registration failed`,e)});return{update:()=>void t(!0)}}var Pv=`binnacle-ais-icon`,Fv=28;function Iv(e){return sd(Fv,e,(e,t,n)=>{let r=t/2.6,i=Math.abs(e-n);return t>3&&Math.abs(i-r)<=1.4&&i<=r+1.4||t>=Fv-3&&i<=r})}var Lv=`binnacle-ais`,Rv=`binnacle-ais-symbol`,zv=36e4,Bv=5e3,Vv={r:224,g:160,b:32,a:255};function Hv(e,t){let n=-1,r=0;function i(){return{type:`FeatureCollection`,features:e.list().map(e=>({type:`Feature`,geometry:{type:`Point`,coordinates:[e.position.longitude,e.position.latitude]},properties:{id:e.id,name:e.name??``,heading:vc(e.headingRad,e.cogRad)}}))}}function a(){let e=Date.now();e-r<Bv||(r=e,t.pruneAis(e,zv))}function o(){return t.aisVersion===n?!1:(n=t.aisVersion,!0)}return vd({id:`ais`,title:`AIS targets`,band:`traffic`,sourceId:Lv,layerId:Rv,iconId:Pv,iconImage:Iv,defaultColor:Vv,paintColor:e=>e.aisTarget,features:i,shouldRefresh:o,beforeSync:a})}var Uv=`/signalk/v2/api/resources/charts`,Wv=`/signalk/v1/api/resources/charts`;async function Gv(e,t){return await Js(e,[Uv,Wv],t,(e,t)=>t,(e,t)=>console.warn(`[charts] ${e} returned ${t}`))??[]}var Kv=`streaming-`,qv=e=>`${Kv}${e}`,Jv=e=>`${Kv}${e}-layer`;function Yv(e){let t=qv(e.id),n=Jv(e.id);return{id:e.id,title:e.title,band:`bathymetry`,supportsOpacity:!0,defaultVisible:!1,layerIds:[n],add(r){if(!r.map.getSource(t)){let n={type:`raster`,tiles:[...e.tiles],tileSize:e.tileSize??256,attribution:e.attribution};e.minzoom!==void 0&&(n.minzoom=e.minzoom),e.maxzoom!==void 0&&(n.maxzoom=e.maxzoom),e.bounds&&(n.bounds=e.bounds),r.map.addSource(t,n)}if(!r.map.getLayer(n)){let e={id:n,type:`raster`,source:t};r.map.addLayer(e,r.beforeIdFor(`bathymetry`))}},remove(e){e.map.getLayer(n)&&e.map.removeLayer(n),e.map.getSource(t)&&e.map.removeSource(t)},setVisible(e,t){e.map.setLayoutProperty(n,`visibility`,t?`visible`:`none`)},setOpacity(e,t){e.map.setPaintProperty(n,`raster-opacity`,t)},applyTheme(e,t){cl(e.map,n,t)}}}var Xv=[{id:`depth-gebco`,title:`GEBCO global bathymetry`,tiles:[`https://wms.gebco.net/mapserv?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&LAYERS=GEBCO_LATEST&CRS=EPSG:3857&BBOX={bbox-epsg-3857}&WIDTH=256&HEIGHT=256&FORMAT=image/png&TRANSPARENT=true&STYLES=`],tileSize:256,minzoom:0,maxzoom:12,attribution:`GEBCO_2024 Grid, GEBCO Compilation Group (2024)`},{id:`depth-emodnet`,title:`EMODnet bathymetry (Europe)`,tiles:[`https://ows.emodnet-bathymetry.eu/wms?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&LAYERS=emodnet:mean_multicolour&CRS=EPSG:3857&BBOX={bbox-epsg-3857}&WIDTH=256&HEIGHT=256&FORMAT=image/png&TRANSPARENT=true&STYLES=`],tileSize:256,minzoom:0,maxzoom:12,bounds:[-73.125,5.625,45,90],attribution:`EMODnet Bathymetry Consortium (2022): EMODnet Digital Bathymetry (DTM)`},{id:`depth-noaa-enc`,title:`NOAA ENC chart (US)`,tiles:[`https://gis.charttools.noaa.gov/arcgis/rest/services/MCS/NOAAChartDisplay/MapServer/exts/MaritimeChartService/WMSServer?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&LAYERS=0,1,2,3,4,5,6,7,8,9,10,11,12&CRS=EPSG:3857&BBOX={bbox-epsg-3857}&WIDTH=256&HEIGHT=256&FORMAT=image/png&TRANSPARENT=true&STYLES=`],tileSize:256,minzoom:0,maxzoom:18,bounds:[-180,-15,180,75],attribution:`NOAA Office of Coast Survey, Electronic Navigational Charts (ENC)`},{id:`depth-bluetopo`,title:`NOAA BlueTopo bathymetry (US)`,tiles:[`https://nowcoast.noaa.gov/geoserver/gwc/service/wmts?SERVICE=WMTS&VERSION=1.0.0&REQUEST=GetTile&LAYER=bluetopo:bathymetry&STYLE=&TILEMATRIXSET=EPSG:3857&TILEMATRIX=EPSG:3857:{z}&TILEROW={y}&TILECOL={x}&FORMAT=image/png8`],tileSize:512,minzoom:0,maxzoom:16,bounds:[-138,-53.876,17.046,59.55],attribution:`NOAA Office of Coast Survey, BlueTopo / National Bathymetric Source`}];function Zv(){return Zv=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Zv.apply(null,arguments)}var Qv=`draw`,$v=`edit`,ey=`deleteCoordinate`,ty=`insertMidpoint`,ny;(function(e){e.Commit=`commit`,e.Provisional=`provisional`,e.Finish=`finish`})(ny||={});var ry=`https://raw.githubusercontent.com/JamesLMilner/terra-draw/refs/heads/main/assets/markers/marker-blue.png`,iy={SELECTED:`selected`,MID_POINT:`midPoint`,SELECTION_POINT_FEATURE_ID:`selectionPointFeatureId`,SELECTION_POINT:`selectionPoint`},ay={MODE:`mode`,CURRENTLY_DRAWING:`currentlyDrawing`,EDITED:`edited`,CLOSING_POINT:`closingPoint`,SNAPPING_POINT:`snappingPoint`,COORDINATE_POINT:`coordinatePoint`,COORDINATE_POINT_FEATURE_ID:`coordinatePointFeatureId`,COORDINATE_POINT_IDS:`coordinatePointIds`,PROVISIONAL_COORDINATE_COUNT:`provisionalCoordinateCount`,COMMITTED_COORDINATE_COUNT:`committedCoordinateCount`,MARKER:`marker`},oy=10;function sy(e){return!!(e&&typeof e==`object`&&e&&!Array.isArray(e))}function cy(e){return!!(e&&typeof e==`object`&&`properties`in e&&typeof e.properties==`object`&&e.properties!==null&&`mode`in e.properties)}function ly(e){return!!function(e){return typeof e==`number`&&!isNaN(new Date(e).valueOf())}(e)}var uy=`Feature mode property does not match the mode being added to`,dy;(function(e){e.Drawing=`drawing`,e.Select=`select`,e.Static=`static`,e.Render=`render`})(dy||={});var fy={rightClick:!0,contextMenu:!1,leftClick:!0,onDragStart:!0,onDrag:!0,onDragEnd:!0},py=class{get state(){return this._state}set state(e){throw Error(`Please use the modes lifecycle methods`)}get styles(){return this._styles}set styles(e){if(typeof e!=`object`)throw Error(`Styling must be an object`);this.onStyleChange&&this.onStyleChange([],`styling`),this._styles=e}registerBehaviors(e){}constructor(e,t=!1){this._state=`unregistered`,this._styles={},this.pointerEvents=fy,this.behaviors=[],this.validate=void 0,this.pointerDistance=40,this.coordinatePrecision=void 0,this.undoRedoMaxStackSize=void 0,this.onStyleChange=void 0,this.store=void 0,this.projection=`web-mercator`,this.setDoubleClickToZoom=void 0,this.unproject=void 0,this.project=void 0,this.setCursor=void 0,this.isInitialUpdate=!1,this.type=dy.Drawing,this.mode=`base`,t?this.isInitialUpdate=!0:this.updateOptions(Zv({},e))}updateOptions(e){e!=null&&e.styles&&(this.styles=Zv({},this._styles,e.styles)),e!=null&&e.pointerDistance&&(this.pointerDistance=e.pointerDistance),e!=null&&e.validation&&(this.validate=e&&e.validation),e!=null&&e.projection&&(this.projection=e.projection),e?.pointerEvents!==void 0&&(this.pointerEvents=e.pointerEvents),e!=null&&e.modeName&&!0===this.isInitialUpdate&&(this.mode=e.modeName),this.isInitialUpdate=!1}allowPointerEvent(e,t){return typeof e==`boolean`?e:typeof e!=`function`||e(t)}setDrawing(){if(this._state!==`started`)throw Error(`Mode must be unregistered or stopped to start`);this._state=`drawing`}setStarted(){if(this._state!==`stopped`&&this._state!==`registered`&&this._state!==`drawing`&&this._state!==`selecting`)throw Error(`Mode must be unregistered or stopped to start`);this._state=`started`,this.setDoubleClickToZoom(!1)}setStopped(){if(this._state!==`started`)throw Error(`Mode must be started to be stopped`);this._state=`stopped`,this.setDoubleClickToZoom(!0)}register(e){if(this._state!==`unregistered`)throw Error(`Can not register unless mode is unregistered`);this._state=`registered`,this.store=e.store,this.store.registerOnChange(e.onChange),this.setDoubleClickToZoom=e.setDoubleClickToZoom,this.project=e.project,this.unproject=e.unproject,this.onSelect=e.onSelect,this.onDeselect=e.onDeselect,this.setCursor=e.setCursor,this.onStyleChange=e.onChange,this.onFinish=e.onFinish,this.coordinatePrecision=e.coordinatePrecision,this.undoRedoMaxStackSize=e.undoRedoMaxStackSize,this.registerBehaviors({mode:e.mode,store:this.store,project:this.project,unproject:this.unproject,pointerDistance:this.pointerDistance,coordinatePrecision:e.coordinatePrecision,projection:this.projection,undoRedoMaxStackSize:e.undoRedoMaxStackSize})}validateFeature(e){return this.performFeatureValidation(e)}afterFeatureAdded(e){}afterFeatureUpdated(e){}performFeatureValidation(e){if(this._state===`unregistered`)throw Error(`Mode must be registered`);let t=function(e,t){let n;if(sy(e))if(e.id==null)n=`Feature has no id`;else if(typeof e.id!=`string`&&typeof e.id!=`number`)n=`Feature must be string or number as per GeoJSON spec`;else if(t(e.id))if(sy(e.geometry))if(sy(e.properties))if(typeof e.geometry.type==`string`&&[`Polygon`,`LineString`,`Point`].includes(e.geometry.type))if(Array.isArray(e.geometry.coordinates)){if(!e.properties.mode||typeof e.properties.mode!=`string`)return{valid:!1,reason:`Feature does not have a valid mode property`}}else n=`Feature coordinates is not an array`;else n=`Feature is not Point, LineString or Polygon`;else n=`Feature has no properties`;else n=`Feature has no geometry`;else n=`Feature must match the id strategy (default is UUID4)`;else n=`Feature is not object`;return n?{valid:!1,reason:n}:{valid:!0}}(e,this.store.idStrategy.isValidId);if(!t.valid)return t;if(this.validate){let n=this.validate(e,{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:ny.Provisional});return{valid:t.valid&&n.valid,reason:n.reason}}return{valid:t.valid,reason:t.reason}}validateModeFeature(e,t){let n=this.performFeatureValidation(e);return n.valid?e.properties.mode===this.mode?t(e):{valid:!1,reason:uy}:{valid:!1,reason:n.reason}}onFinish(e,t){}onDeselect(e){}onSelect(e){}onKeyDown(e){}onKeyUp(e){}undo(){}clearHistory(){}undoSize(){return 0}redoSize(){return 0}redo(){}onMouseMove(e){}onClick(e){}onDragStart(e,t){}onDrag(e,t){}onDragEnd(e,t){}getHexColorStylingValue(e,t,n){return this.getStylingValue(e,t,n)}getNumericStylingValue(e,t,n){return this.getStylingValue(e,t,n)}getUrlStylingValue(e,t,n){return this.getStylingValue(e,t,n)}getStylingValue(e,t,n){return e===void 0?t:typeof e==`function`?(r=e(n))??t:e;var r}},my=class extends py{constructor(...e){super(...e),this.type=dy.Select}};function hy(e,t){let n=e=>e*Math.PI/180,r=n(e[1]),i=n(e[0]),a=n(t[1]),o=a-r,s=n(t[0])-i,c=Math.sin(o/2)*Math.sin(o/2)+Math.cos(r)*Math.cos(a)*Math.sin(s/2)*Math.sin(s/2);return 2*Math.atan2(Math.sqrt(c),Math.sqrt(1-c))*6371e3/1e3}var gy=6371008.8;function _y(e){return e%360*Math.PI/180}function vy(e){return e/6371.0088}function yy(e){return e%(2*Math.PI)*180/Math.PI}function by(e,t=9){let n=10**t;return Math.round(e*n)/n}var xy=57.29577951308232,Sy=.017453292519943295,Cy=6378137,wy=(e,t)=>({x:e===0?0:e*Sy*Cy,y:t===0?0:Math.log(Math.tan(Math.PI/4+t*Sy/2))*Cy}),Ty=(e,t)=>({lng:e===0?0:e/Cy*xy,lat:t===0?0:(2*Math.atan(Math.exp(t/Cy))-Math.PI/2)*xy});function Ey(e){let t;if(e.geometry.type===`Polygon`)t=e.geometry.coordinates;else{if(e.geometry.type!==`LineString`)throw Error(`Self intersects only accepts Polygons and LineStrings`);t=[e.geometry.coordinates]}let n=[];for(let e=0;e<t.length;e++)for(let n=0;n<t[e].length-1;n++)for(let r=0;r<t.length;r++)for(let a=0;a<t[r].length-1;a++)i(e,n,r,a);return n.length>0;function r(e){return e<0||e>1}function i(e,i,a,o){let s=t[e][i],c=t[e][i+1],l=t[a][o],u=t[a][o+1],d=function(e,t,n,r){if(Dy(e,n)||Dy(e,r)||Dy(t,n)||Dy(r,n))return null;let i=e[0],a=e[1],o=t[0],s=t[1],c=n[0],l=n[1],u=r[0],d=r[1],f=(i-o)*(l-d)-(a-s)*(c-u);return f===0?null:[((i*s-a*o)*(c-u)-(i-o)*(c*d-l*u))/f,((i*s-a*o)*(l-d)-(a-s)*(c*d-l*u))/f]}(s,c,l,u);if(d===null)return;let f,p;f=c[0]===s[0]?(d[1]-s[1])/(c[1]-s[1]):(d[0]-s[0])/(c[0]-s[0]),p=u[0]===l[0]?(d[1]-l[1])/(u[1]-l[1]):(d[0]-l[0])/(u[0]-l[0]),r(f)||r(p)||(d.toString(),n.push(d))}}function Dy(e,t){return e[0]===t[0]&&e[1]===t[1]}function Oy(e,t){return Ay(e[0])<=t&&Ay(e[1])<=t}function ky(e){return e.length===2&&typeof e[0]==`number`&&typeof e[1]==`number`&&e[0]!==1/0&&e[1]!==1/0&&(n=e[0])>=-180&&n<=180&&(t=e[1])>=-90&&t<=90;var t,n}function Ay(e){let t=1,n=0;for(;Math.round(e*t)/t!==e;)t*=10,n++;return n}var jy=class{constructor({store:e,mode:t,project:n,unproject:r,pointerDistance:i,coordinatePrecision:a,projection:o,undoRedoMaxStackSize:s}){this.store=void 0,this.mode=void 0,this.project=void 0,this.unproject=void 0,this.pointerDistance=void 0,this.coordinatePrecision=void 0,this.projection=void 0,this.undoRedoMaxStackSize=void 0,this.store=e,this.mode=t,this.project=n,this.unproject=r,this.pointerDistance=i,this.coordinatePrecision=a,this.projection=o,this.undoRedoMaxStackSize=s}};function My(e){if(!function(e){let t=e.coordinates[0],n=0;for(let e=0;e<t.length-1;e++){let[r,i]=t[e],[a,o]=t[e+1];n+=(a-r)*(o+i)}return n<0}(e))return{type:`Polygon`,coordinates:[e.coordinates[0].reverse()]}}var Ny=`insert-before`,Py=`insert-after`,Fy=`update`,Iy=`delete`,Ly=`replace`,Ry=class extends jy{constructor(e,t){super(e),this.options=void 0,this.options=t}createPoint({coordinates:e,properties:t,context:n}){if(n?.updateType!==ny.Finish||this.validateGeometryWithUpdateType({geometry:{type:`Point`,coordinates:e},properties:t,updateType:ny.Finish}))return this.handleCreateFeature({geometry:{type:`Point`,coordinates:e},properties:t})}createLineString({coordinates:e,properties:t}){return this.handleCreateFeature({geometry:{type:`LineString`,coordinates:e},properties:t})}createPolygon({coordinates:e,properties:t,context:n}){let r=My({type:`Polygon`,coordinates:[e]}),i={type:`Polygon`,coordinates:r?r.coordinates:[e]};if(n?.updateType!==ny.Finish||this.validateGeometryWithUpdateType({geometry:i,properties:t,updateType:ny.Finish}))return this.handleCreateFeature({geometry:i,properties:t})}createGuidancePoint({coordinate:e,type:t}){return this.createGuidancePoints({coordinates:[e],type:t})[0]}createGuidancePoints({coordinates:e,type:t,additionalProperties:n}){let r=e.map((e,r)=>({type:`Feature`,geometry:{type:`Point`,coordinates:e},properties:Zv({mode:this.mode,[t]:!0},n?n(r):{})}));return this.createFeatures(r)}updatePoint({featureId:e,coordinateMutations:t,propertyMutations:n,context:r}){return this.handleMutateFeature({type:`Point`,featureId:e,coordinateMutations:t,propertyMutations:n,context:r})}updatePolygon({featureId:e,coordinateMutations:t,context:n,propertyMutations:r}){return this.handleMutateFeature({type:`Polygon`,featureId:e,coordinateMutations:t,propertyMutations:r,context:n})}updateLineString({featureId:e,coordinateMutations:t,context:n,propertyMutations:r}){return this.handleMutateFeature({type:`LineString`,featureId:e,coordinateMutations:t,propertyMutations:r,context:n})}deleteFeatureIfPresent(e){e&&this.store.has(e)&&this.store.delete([e])}deleteFeaturesIfPresent(e){if(e.length===0)return;let t=e.filter(e=>this.store.has(e));t.length&&this.store.delete(t)}setDeselected(e){let t=e.filter(e=>this.store.has(e)).map(e=>({featureId:e,properties:{[iy.SELECTED]:!1}}));this.updateFeatureProperties(t)}setSelected(e){let{type:t}=this.store.getGeometryCopy(e),n={featureId:e,propertyMutations:{[iy.SELECTED]:!0},context:{updateType:ny.Commit}};t===`Polygon`?this.updatePolygon(n):t===`LineString`?this.updateLineString(n):t===`Point`&&this.updatePoint(n)}updateGuidancePoints(e){this.updateFeatureGeometries(e.map(({featureId:e,coordinate:t})=>({id:e,geometry:{type:`Point`,coordinates:t}})))}handleCreateFeature({geometry:e,properties:t}){return this.createFeatureWithGeometry({geometry:e,properties:t})}handleMutateFeature({type:e,featureId:t,coordinateMutations:n,propertyMutations:r,context:i}){if(!this.mutateFeature({type:e,featureId:t,coordinateMutations:n,propertyMutations:r,context:i.updateType===ny.Finish?Zv({},i,{correctRightHandRule:!0}):Zv({},i)}))return null;let a=this.buildFeatureWithGeometry(t);return i.updateType!==ny.Finish||n||this.validateGeometryWithUpdateType({geometry:a.geometry,properties:a.properties,updateType:i.updateType})?a:null}mutateFeature({type:e,featureId:t,coordinateMutations:n,propertyMutations:r,context:i}){if(!t)return!1;let a=this.store.getGeometryCopy(t),o=this.store.getPropertiesCopy(t);if(a.type!==e)throw Error(`${e} geometries cannot be updated on features with ${a.type} geometries`);if(n){let e=this.applyCoordinateMutations(a,n);if(i.correctRightHandRule&&e.type===`Polygon`){let t=My(e);t&&(e=t)}if(!this.validateGeometryWithUpdateType({geometry:e,properties:o,updateType:i.updateType}))return!1;this.updateFeatureGeometries([{id:t,geometry:e}])}return r&&this.updateFeatureProperties([{featureId:t,properties:r}]),!0}applyCoordinateMutations(e,t){if(this.isReplaceMutation(t))return Zv({},e,{coordinates:t.coordinates});if(e.type===`Point`)throw Error(`Coordinate mutations are not supported for Point geometries`);let n=e.type===`Polygon`,r=n?e.coordinates[0].slice():e.coordinates.slice(),i=r.length,a=e=>{let t=e<0?i+e:e;if(t<0||t>=i)throw RangeError(`Index ${e} (normalized to ${t}) is out of bounds`);return t},o=Array(i).fill(void 0),s=Array.from({length:i},()=>[]),c=Array.from({length:i},()=>[]),l=[];for(let e of t){if(e.type===Ny||e.type===Py){let t=e.index,n=t<0?i+t:t;if(n<0||n>i)throw RangeError(`Index ${e.index} (normalized to ${n}) is out of bounds`);if(e.type===Ny){if(n>=i)throw RangeError(`INSERT_BEFORE index ${e.index} (normalized to ${n}) is out of bounds for length ${i}`);s[n].push(e)}else n===i?l.push(e):c[n].push(e);continue}let t=a(e.index);o[t]=Zv({},e,{index:t})}let u=[];for(let e=0;e<i;e++){let t=s[e];for(let e of t)u.push(e.coordinate);let n=o[e];n?n.type===Iy||u.push(n.coordinate):u.push(r[e]);let i=c[e];for(let e of i)u.push(e.coordinate)}for(let e of l)u.push(e.coordinate);return Zv({},e,n?{coordinates:[u,...e.coordinates.slice(1)]}:{coordinates:u})}isReplaceMutation(e){return e.type===Ly}createFeatureWithGeometry({geometry:e,properties:t}){let[n]=this.createFeatures([{type:`Feature`,geometry:e,properties:t}]);return{id:n,type:`Feature`,properties:this.store.getPropertiesCopy(n),geometry:this.store.getGeometryCopy(n)}}validateGeometryWithUpdateType({geometry:e,properties:t,updateType:n}){return!this.options.validate||this.options.validate({type:`Feature`,geometry:e,properties:t||{}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:n}).valid}buildFeatureWithGeometry(e){return{id:e,type:`Feature`,properties:this.store.getPropertiesCopy(e),geometry:this.store.getGeometryCopy(e)}}createFeatures(e){return this.store.create(e)}updateFeatureGeometries(e){this.store.updateGeometry(e)}updateFeatureProperties(e){let t=e.map(({featureId:e,properties:t})=>Object.entries(t).map(([t,n])=>({id:e,property:t,value:n}))).flat();this.store.updateProperty(t)}},zy=(e,t)=>{let{x:n,y:r}=e,{x:i,y:a}=t,o=i-n,s=a-r;return Math.sqrt(s*s+o*o)};function By(e,t){return e[0]===t[0]&&e[1]===t[1]}var Vy=class extends jy{constructor(e){super(e)}getGeometryType(e){return this.store.getGeometryCopy(e).type}coordinateAtIndexIsIdentical({featureId:e,newCoordinate:t,index:n}){let r=this.store.getGeometryCopy(e),i;if(r.type===`Polygon`)i=r.coordinates[0][n];else if(r.type===`LineString`)i=r.coordinates[n];else{if(n!==0)throw Error(`Point geometries only have one coordinate at index 0`);i=r.coordinates}return By(t,i)}getGeometry(e){return this.store.getGeometryCopy(e)}getCoordinates(e){let{type:t,coordinates:n}=this.store.getGeometryCopy(e);return t===`Polygon`?n[0]:n}getCoordinate(e,t){let n=this.getCoordinates(e),r=t<0?n.length+t:t;if(r<0||r>=n.length)throw RangeError(`Index ${t} (normalized to ${r}) is out of bounds`);return n[r]}getProperties(e){return this.store.getPropertiesCopy(e)}hasFeature(e){return this.store.has(e)}getAllFeatureIdsWhere(e){return this.store.copyAllWhere(e).map(({id:e})=>e)}};function Hy({unproject:e,point:t,pointerDistance:n}){let r=n/2,{x:i,y:a}=t;return{type:`Feature`,properties:{},geometry:{type:`Polygon`,coordinates:[[e(i-r,a-r),e(i+r,a-r),e(i+r,a+r),e(i-r,a+r),e(i-r,a-r)].map(e=>[e.lng,e.lat])]}}}var Uy=class extends jy{constructor(e){super(e)}create(e){let{containerX:t,containerY:n}=e;return Hy({unproject:this.unproject,point:{x:t,y:n},pointerDistance:this.pointerDistance})}},Wy=class extends jy{constructor(e){super(e)}measure(e,t){let{x:n,y:r}=this.project(t[0],t[1]);return zy({x:n,y:r},{x:e.containerX,y:e.containerY})}},Gy=class extends jy{constructor(e,t,n){super(e),this.config=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.getSnappableCoordinateFirstClick=e=>this.getSnappable(e,e=>!!(e.properties&&e.properties.mode===this.mode)).coordinate,this.getSnappableCoordinate=(e,t)=>this.getSnappable(e,e=>!!(e.properties&&e.properties.mode===this.mode&&e.id!==t)).coordinate,this.config=e,this.pixelDistance=t,this.clickBoundingBox=n}getSnappable(e,t){let n=this.clickBoundingBox.create(e),r=this.store.search(n,t),i={featureId:void 0,featureCoordinateIndex:void 0,coordinate:void 0,minDist:1/0};return r.forEach(t=>{let n;if(t.geometry.type===`Polygon`)n=t.geometry.coordinates[0];else{if(t.geometry.type!==`LineString`)return;n=t.geometry.coordinates}n.forEach((n,r)=>{let a=this.pixelDistance.measure(e,n);a<i.minDist&&a<this.pointerDistance&&(i.coordinate=n,i.minDist=a,i.featureId=t.id,i.featureCoordinateIndex=r)})}),i}};function Ky(e,t,n){let r=_y(e[0]),i=_y(e[1]),a=_y(n),o=vy(t),s=Math.asin(Math.sin(i)*Math.cos(o)+Math.cos(i)*Math.sin(o)*Math.cos(a));return[yy(r+Math.atan2(Math.sin(a)*Math.sin(o)*Math.cos(i),Math.cos(o)-Math.sin(i)*Math.sin(s))),yy(s)]}function qy(e,t){let n=_y(e[0]),r=_y(t[0]),i=_y(e[1]),a=_y(t[1]),o=Math.sin(r-n)*Math.cos(a),s=Math.cos(i)*Math.sin(a)-Math.sin(i)*Math.cos(a)*Math.cos(r-n);return yy(Math.atan2(o,s))}function Jy({x:e,y:t},{x:n,y:r}){let i=n-e,a=r-t;if(i===0&&a===0)return 0;let o=Math.atan2(a,i);return o*=180/Math.PI,o>180?o-=360:o<-180&&(o+=360),o}function Yy(e,t,n){let r=[],i=e.length,a,o,s,c=0;for(let i=0;i<e.length&&!(t>=c&&i===e.length-1);i++){if(c>t&&r.length===0){if(a=t-c,!a)return r.push(e[i]),r;o=qy(e[i],e[i-1])-180,s=Ky(e[i],a,o),r.push(s)}if(c>=n)return a=n-c,a?(o=qy(e[i],e[i-1])-180,s=Ky(e[i],a,o),r.push(s),r):(r.push(e[i]),r);if(c>=t&&r.push(e[i]),i===e.length-1)return r;c+=hy(e[i],e[i+1])}if(c<t&&e.length===i)throw Error(`Start position is beyond line`);let l=e[e.length-1];return[l,l]}function Xy(e){return Math.PI/180*e}function Zy(e){return 180/Math.PI*e}var Qy=class extends jy{constructor(e){super(e),this.config=void 0,this.config=e}generateInsertionCoordinates(e,t,n){let r=[e,t],i=0;for(let e=0;e<r.length-1;e++)i+=hy(r[0],r[1]);if(i<=n)return r;let a=i/n-1;Number.isInteger(a)||(a=Math.floor(a)+1);let o=[];for(let e=0;e<a;e++){let t=Yy(r,n*e,n*(e+1));o.push(t)}let s=[];for(let e=0;e<o.length;e++)s.push(o[e][1]);return this.limitCoordinates(s)}generateInsertionGeodesicCoordinates(e,t,n){let r=hy(e,t),i=function(e,t,n){let r=[],i=Xy(e[1]),a=Xy(e[0]),o=Xy(t[1]),s=Xy(t[0]);n+=1;let c=2*Math.asin(Math.sqrt(Math.sin((o-i)/2)**2+Math.cos(i)*Math.cos(o)*Math.sin((s-a)/2)**2));if(c===0||isNaN(c))return r;for(let e=0;e<=n;e++){let t=e/n,l=Math.sin((1-t)*c)/Math.sin(c),u=Math.sin(t*c)/Math.sin(c),d=l*Math.cos(i)*Math.cos(a)+u*Math.cos(o)*Math.cos(s),f=l*Math.cos(i)*Math.sin(a)+u*Math.cos(o)*Math.sin(s),p=l*Math.sin(i)+u*Math.sin(o);if(isNaN(d)||isNaN(f)||isNaN(p))continue;let m=Math.atan2(p,Math.sqrt(d**2+f**2)),h=Math.atan2(f,d);isNaN(m)||isNaN(h)||r.push([Zy(h),Zy(m)])}return r.slice(1,-1)}(e,t,Math.floor(r/n));return this.limitCoordinates(i)}limitCoordinates(e){return e.map(e=>[by(e[0],this.config.coordinatePrecision),by(e[1],this.config.coordinatePrecision)])}};function $y(e,t){if(e.geometry.type!==`LineString`)return{valid:!1,reason:`Feature is not a LineString`};if(e.geometry.coordinates.length<2)return{valid:!1,reason:`Feature has less than 2 coordinates`};for(let n=0;n<e.geometry.coordinates.length;n++){if(!ky(e.geometry.coordinates[n]))return{valid:!1,reason:`Feature has invalid coordinates`};if(!Oy(e.geometry.coordinates[n],t))return{valid:!1,reason:`Feature has coordinates with excessive precision`}}return{valid:!0}}function eb(e){return Math.sqrt(e[0]**2+e[1]**2+e[2]**2)}function tb(e,t){let n=function(e,t){let[n,r,i]=e,[a,o,s]=t;return n*a+r*o+i*s}(e,t)/(eb(e)*eb(t));return Math.acos(Math.min(Math.max(n,-1),1))}function nb(e){let t=_y(e[1]),n=_y(e[0]);return[Math.cos(t)*Math.cos(n),Math.cos(t)*Math.sin(n),Math.sin(t)]}function rb(e){let[t,n,r]=e,i=yy(Math.asin(r));return[yy(Math.atan2(n,t)),i]}function ib(e,t,n){let r=nb(e),i=nb(t),[a,o,s]=nb(n),[c,l,u]=function(e,t){let[n,r,i]=e,[a,o,s]=t;return[r*s-i*o,i*a-n*s,n*o-r*a]}(r,i),d=l*s-u*o,f=u*a-c*s,p=c*o-l*a,m=p*l-f*u,h=d*u-p*c,g=f*c-d*l,_=1/Math.sqrt(m**2+h**2+g**2),v=[m*_,h*_,g*_],y=[-1*m*_,-1*h*_,-1*g*_],b=tb(r,i),x=tb(r,v),S=tb(i,v),C=tb(r,y),w=tb(i,y),T;return T=x<C&&x<w||S<C&&S<w?v:y,tb(r,T)>b||tb(i,T)>b?hy(rb(T),rb(r))<=hy(rb(T),rb(i))?[rb(r),!0,!1]:[rb(i),!1,!0]:[rb(T),!1,!1]}function ab(e,t,n){let r=t.x-e.x,i=t.y-e.y,a=Math.max(0,Math.min(1,((n.x-e.x)*r+(n.y-e.y)*i)/(r*r+i*i)));return{x:e.x+a*r,y:e.y+a*i}}var ob=class extends jy{constructor(e,t,n){super(e),this.config=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.getSnappableCoordinateFirstClick=e=>{let t=this.getSnappable(e,e=>!!(e.properties&&e.properties.mode===this.mode));return t.coordinate?[by(t.coordinate[0],this.config.coordinatePrecision),by(t.coordinate[1],this.config.coordinatePrecision)]:void 0},this.getSnappableCoordinate=(e,t)=>{let n=this.getSnappable(e,e=>!!(e.properties&&e.properties.mode===this.mode&&e.id!==t));return n.coordinate?[by(n.coordinate[0],this.config.coordinatePrecision),by(n.coordinate[1],this.config.coordinatePrecision)]:void 0},this.config=e,this.pixelDistance=t,this.clickBoundingBox=n}getSnappable(e,t){let n=this.clickBoundingBox.create(e),r=this.store.search(n,t),i={featureId:void 0,featureCoordinateIndex:void 0,coordinate:void 0,minDistance:1/0};return r.forEach(t=>{let n;if(t.geometry.type===`Polygon`)n=t.geometry.coordinates[0];else{if(t.geometry.type!==`LineString`)return;n=t.geometry.coordinates}let r=[];for(let e=0;e<n.length-1;e++)r.push([n[e],n[e+1]]);let a,o=[e.lng,e.lat];if(this.config.projection===`web-mercator`?a=function(e,t){let n=[1/0,1/0],r=1/0,i=0;for(let a of t){let o=a[0],s=a[1],c,l=1/0,u=wy(o[0],o[1]),d=wy(s[0],s[1]),f=wy(e[0],e[1]);if(o[0]===e[0]&&o[1]===e[1])c=o;else if(s[0]===e[0]&&s[1]===e[1])c=s;else{let{x:e,y:t}=ab(u,d,f),{lng:n,lat:r}=Ty(e,t);c=[n,r]}c&&(l=zy(f,wy(c[0],c[1])),l<r&&(n=c,r=l,i=t.indexOf(a)))}return r===1/0?void 0:{coordinate:n,lineIndex:i,distance:r}}(o,r):this.config.projection===`globe`&&(a=function(e,t){let n=[1/0,1/0],r=1/0,i=0;for(let a of t){let o=a[0],s=a[1],c,l=1/0;o[0]===e[0]&&o[1]===e[1]?c=o:s[0]===e[0]&&s[1]===e[1]?c=s:[c]=ib(o,s,e),c&&(l=hy(e,c),l<r&&(n=c,r=l,i=t.indexOf(a)))}return r===1/0?void 0:{coordinate:n,distance:r,lineIndex:i}}(o,r)),!a)return;let s=this.pixelDistance.measure(e,a.coordinate);s<i.minDistance&&s<this.pointerDistance&&(i.featureId=t.id,i.coordinate=[by(a.coordinate[0],this.config.coordinatePrecision),by(a.coordinate[1],this.config.coordinatePrecision)],i.featureCoordinateIndex=a.lineIndex,i.minDistance=s)}),i}};function sb(e){return Array.isArray(e)&&e.length>0&&Array.isArray(e[0])&&Array.isArray(e[0][0])}var cb=e=>sb(e)?e[0].slice(0,-1):e,lb=e=>sb(e)?e[0]:e,ub=class extends jy{constructor(e,t,n,r){super(e),this.config=void 0,this.pixelDistance=void 0,this.mutateFeatureBehavior=void 0,this.readFeatureBehavior=void 0,this._startEndPoints=[],this.config=e,this.pixelDistance=t,this.mutateFeatureBehavior=n,this.readFeatureBehavior=r}get ids(){return this._startEndPoints.concat()}set ids(e){}create(e){if(this.ids.length)throw Error(`Opening and closing points already created`);let t=sb(e),n=lb(e);if(t){if(n.length<=3)throw Error(`Requires at least 4 coordinates`);this._startEndPoints=this.mutateFeatureBehavior.createGuidancePoints({coordinates:[n[0],n[n.length-2]],type:ay.CLOSING_POINT})}else this._startEndPoints=[this.mutateFeatureBehavior.createGuidancePoint({coordinate:n[n.length-2],type:ay.CLOSING_POINT})]}delete(){this.ids.length&&(this.mutateFeatureBehavior.deleteFeaturesIfPresent(this.ids),this._startEndPoints=[])}updateOne(e,t){this.mutateFeatureBehavior.updateGuidancePoints([{featureId:this.ids[e],coordinate:t}])}update(e){let t=lb(e);this.ids.length===1?this.mutateFeatureBehavior.updateGuidancePoints([{featureId:this.ids[0],coordinate:t[t.length-2]}]):this.ids.length===2&&this.mutateFeatureBehavior.updateGuidancePoints([{featureId:this.ids[0],coordinate:t[0]},{featureId:this.ids[1],coordinate:t[t.length-3]}])}isLineStringClosingPoint(e){if(this.ids.length!==1)return{isClosing:!1};let t=this.readFeatureBehavior.getGeometry(this.ids[0]);return{isClosing:this.pixelDistance.measure(e,t.coordinates)<this.pointerDistance}}isPolygonClosingPoints(e){if(this.ids.length!==2)return{isClosing:!1,isPreviousClosing:!1};let t=this.readFeatureBehavior.getGeometry(this.ids[0]),n=this.readFeatureBehavior.getGeometry(this.ids[1]),r=this.pixelDistance.measure(e,t.coordinates),i=this.pixelDistance.measure(e,n.coordinates);return{isClosing:r<this.pointerDistance,isPreviousClosing:i<this.pointerDistance}}},db=class extends jy{constructor(e,t,n){super(e),this.readFeature=void 0,this.mutateFeature=void 0,this.readFeature=t,this.mutateFeature=n}createOrUpdate({featureId:e,featureCoordinates:t}){if(!this.readFeature.hasFeature(e))return void this.deleteOrphanedPoints(e);let n=cb(t),r=this.readFeature.getProperties(e),i=r.coordinatePointIds;if(i)if(i&&i.every(e=>this.readFeature.hasFeature(e))){let t=r.coordinatePointIds,i=t.map(e=>this.readFeature.getGeometry(e).coordinates);if(t.length!==n.length){this.deleteCoordinatePoints(t);let i=this.createPoints(n,r.mode,e);this.setFeatureCoordinatePoints(e,i)}else{let e=[];n.forEach((n,r)=>{n[0]===i[r][0]&&n[1]===i[r][1]||e.push({featureId:t[r],coordinate:n})}),this.mutateFeature.updateGuidancePoints(e)}}else{let t=i.filter(e=>this.readFeature.hasFeature(e));t.length&&this.deleteCoordinatePoints(t);let a=this.createPoints(n,r.mode,e);this.setFeatureCoordinatePoints(e,a)}else{let t=this.createPoints(n,r.mode,e);this.setFeatureCoordinatePoints(e,t)}}deletePointsByFeatureIds(e){for(let t of e)this.deleteIfPresent(t)}updateOneAtIndex(e,t,n){let r=this.readFeature.getProperties(e).coordinatePointIds;r&&r.length!==0&&r[t]!==void 0&&this.mutateFeature.updateGuidancePoints([{featureId:r[t],coordinate:n}])}updateAllInPlace({featureId:e,featureCoordinates:t}){let n=this.readFeature.getProperties(e);if(!n.coordinatePointIds)return;let r=cb(t);r.length===n.coordinatePointIds.length&&this.mutateFeature.updateGuidancePoints(n.coordinatePointIds.map((e,t)=>({featureId:e,coordinate:r[t]})))}createPoints(e,t,n){return this.mutateFeature.createGuidancePoints({coordinates:e,type:ay.COORDINATE_POINT,additionalProperties:e=>({mode:t,[ay.COORDINATE_POINT]:!0,[ay.COORDINATE_POINT_FEATURE_ID]:n,index:e})})}setFeatureCoordinatePoints(e,t,n=ny.Commit){let r=this.readFeature.getGeometryType(e),i={featureId:e,propertyMutations:{[ay.COORDINATE_POINT_IDS]:t},context:{updateType:n}};if(r===`Polygon`)this.mutateFeature.updatePolygon(i);else{if(r!==`LineString`)throw Error(`Unsupported geometry type for coordinate points`);this.mutateFeature.updateLineString(i)}}deleteCoordinatePoints(e){this.mutateFeature.deleteFeaturesIfPresent(e)}deleteIfPresent(e){if(!this.readFeature.hasFeature(e))return;let t=this.readFeature.getProperties(e).coordinatePointIds;t&&(this.deleteCoordinatePoints(t),this.setFeatureCoordinatePoints(e,null))}deleteOrphanedPoints(e){let t=this.readFeature.getAllFeatureIdsWhere(t=>t[ay.COORDINATE_POINT_FEATURE_ID]===e);this.mutateFeature.deleteFeaturesIfPresent(t)}},fb=class{constructor(e){this.undoHistory=[],this.redoHistory=[],this.cloneCoordinatesFunction=void 0,this.maxStackSize=void 0,this.cloneCoordinatesFunction=e=>this.cloneRecursively(e);let t=e?.maxStackSize;this.maxStackSize=t!==void 0&&Number.isFinite(t)?Math.max(0,Math.floor(t)):1/0}setMaxStackSize(e){Number.isFinite(e)?(this.maxStackSize=Math.max(0,Math.floor(e)),this.trimHistoryToMax(this.undoHistory),this.trimHistoryToMax(this.redoHistory)):this.maxStackSize=1/0}trimHistoryToMax(e){if(Number.isFinite(this.maxStackSize))for(;e.length>this.maxStackSize;)e.shift()}pushUndoEntry(e){this.maxStackSize!==0&&(this.undoHistory.push(e),this.trimHistoryToMax(this.undoHistory))}pushRedoEntry(e){this.maxStackSize!==0&&(this.redoHistory.push(e),this.trimHistoryToMax(this.redoHistory))}cloneRecursively(e){return Array.isArray(e)?e.map(e=>this.cloneRecursively(e)):typeof e==`object`&&e?Zv({},e):e}cloneCoordinates(e){return this.cloneCoordinatesFunction(e)}cloneEntry(e){return{featureCoordinates:this.cloneCoordinates(e.featureCoordinates),currentCoordinate:e.currentCoordinate}}clear(){this.undoHistory=[],this.redoHistory=[]}undoSize(){return this.undoHistory.length}redoSize(){return this.redoHistory.length}recordSnapshot(e){this.pushUndoEntry(this.cloneEntry(e)),this.redoHistory=[]}beginUndo(){let e=this.undoHistory.pop();if(!e)return;let t=this.cloneEntry(e);this.pushRedoEntry(t);let n=this.undoHistory[this.undoHistory.length-1];return{undoneEntry:t,previousEntry:n?this.cloneEntry(n):void 0}}takeRedo(){let e=this.redoHistory.pop();if(e)return this.cloneEntry(e)}commitRedo(e){this.pushUndoEntry(this.cloneEntry(e))}},pb={cancel:`Escape`,finish:`Enter`},mb={start:`crosshair`,close:`pointer`,dragStart:`grabbing`,dragEnd:`crosshair`},hb=class extends py{constructor(e){super(e,!0),this.mode=`linestring`,this.currentCoordinate=0,this.currentId=void 0,this.keyEvents=pb,this.snapping=void 0,this.cursors=mb,this.mouseMove=!1,this.insertCoordinates=void 0,this.lastCommittedCoordinates=void 0,this.snappedPointId=void 0,this.lastMouseMoveEvent=void 0,this.showCoordinatePoints=!1,this.finishOnNthCoordinate=void 0,this.editable=!1,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedSnapType=void 0,this.editedInsertIndex=void 0,this.editedPointId=void 0,this.coordinateSnapping=void 0,this.insertPoint=void 0,this.lineSnapping=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.mutateFeature=void 0,this.readFeature=void 0,this.closingPoints=void 0,this.coordinatePoints=void 0,this.undoRedo=void 0,this.updateOptions(e)}updateOptions(e){if(super.updateOptions(e),e?.finishOnNthCoordinate!==void 0&&Number.isInteger(e.finishOnNthCoordinate)&&e.finishOnNthCoordinate>1&&(this.finishOnNthCoordinate=Math.floor(e.finishOnNthCoordinate)),e!=null&&e.cursors&&(this.cursors=Zv({},this.cursors,e.cursors)),e!=null&&e.snapping&&(this.snapping=e.snapping),e?.keyEvents===null?this.keyEvents={cancel:null,finish:null}:e!=null&&e.keyEvents&&(this.keyEvents=Zv({},this.keyEvents,e.keyEvents)),e!=null&&e.insertCoordinates&&(this.insertCoordinates=e.insertCoordinates),e&&e.editable&&(this.editable=e.editable),e?.showCoordinatePoints!==void 0){if(this.showCoordinatePoints=e.showCoordinatePoints,this.coordinatePoints&&!0===e.showCoordinatePoints)this.store.copyAllWhere(e=>e.mode===this.mode).forEach(e=>{this.coordinatePoints.createOrUpdate({featureId:e.id,featureCoordinates:e.geometry.coordinates})});else if(this.coordinatePoints&&!1===this.showCoordinatePoints){let e=this.store.copyAllWhere(e=>e.mode===this.mode&&!!e[ay.COORDINATE_POINT_IDS]?.length);this.coordinatePoints.deletePointsByFeatureIds(e.map(e=>e.id))}}}shouldFinishOnCommit(e){return!!this.finishOnNthCoordinate&&Math.max(0,e.coordinates.length-1)>=this.finishOnNthCoordinate}updateSnappedCoordinate(e){let t=this.snapCoordinate(e);return t?(this.snappedPointId?this.mutateFeature.updateGuidancePoints([{featureId:this.snappedPointId,coordinate:t}]):this.snappedPointId=this.mutateFeature.createGuidancePoint({coordinate:t,type:ay.SNAPPING_POINT}),e.lng=t[0],e.lat=t[1]):this.snappedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),void 0),t}close(){if(this.currentId===void 0)return;let e=this.mutateFeature.updateLineString({featureId:this.currentId,context:{updateType:ny.Finish,action:Qv},coordinateMutations:[{type:Iy,index:-1}],propertyMutations:{[ay.CURRENTLY_DRAWING]:void 0}});if(!e)return;this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:e.geometry.coordinates});let t=this.currentId;this.currentCoordinate=0,this.currentId=void 0,this.lastCommittedCoordinates=void 0,this.undoRedo.clear(),this.state===`drawing`&&this.setStarted(),this.closingPoints.delete(),this.snappedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),void 0),this.editedPointId&&(this.mutateFeature.deleteFeatureIfPresent(this.editedPointId),this.editedPointId=void 0,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedInsertIndex=void 0,this.editedSnapType=void 0),this.onFinish(t,{mode:this.mode,action:Qv})}generateInsertCoordinates(e,t){if(!this.insertCoordinates||!this.lastCommittedCoordinates)throw Error(`Not able to insert coordinates`);if(this.insertCoordinates.strategy!==`amount`)throw Error(`Strategy does not exist`);let n=hy(e,t)/(this.insertCoordinates.value+1),r=[];return this.projection===`globe`?r=this.insertPoint.generateInsertionGeodesicCoordinates(e,t,n):this.projection===`web-mercator`&&(r=this.insertPoint.generateInsertionCoordinates(e,t,n)),r}createLine(e){let t=this.mutateFeature.createLineString({coordinates:[e,e],properties:{mode:this.mode,[ay.CURRENTLY_DRAWING]:!0}});this.lastCommittedCoordinates=t.geometry.coordinates,this.currentId=t.id,this.currentCoordinate++,this.pushHistorySnapshot(this.currentId,this.currentCoordinate),this.setDrawing(),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:t.geometry.coordinates})}firstUpdateToLine(e){if(!this.currentId)return;this.setCursor(this.cursors.close);let t=this.mutateFeature.updateLineString({featureId:this.currentId,context:{updateType:ny.Commit},coordinateMutations:[{type:Py,index:-1,coordinate:e}]});t&&(this.closingPoints.create(t.geometry.coordinates),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:t.geometry.coordinates}),this.lastCommittedCoordinates=t.geometry.coordinates,this.currentCoordinate++,this.pushHistorySnapshot(this.currentId,this.currentCoordinate),this.shouldFinishOnCommit(t.geometry)&&this.close())}updateToLine(e,t){if(!this.currentId)return;let{isClosing:n}=this.closingPoints.isLineStringClosingPoint(e);if(n)return void this.close();this.setCursor(this.cursors.close);let r=this.mutateFeature.updateLineString({featureId:this.currentId,context:{updateType:ny.Commit},coordinateMutations:[{type:Py,index:-1,coordinate:t}]});r&&(this.closingPoints.update(r.geometry.coordinates),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:r.geometry.coordinates}),this.lastCommittedCoordinates=r.geometry.coordinates,this.currentCoordinate++,this.pushHistorySnapshot(this.currentId,this.currentCoordinate),this.shouldFinishOnCommit(r.geometry)&&this.close())}undoSize(){return this.undoRedo.undoSize()}clearHistory(){this.undoRedo.clear()}pushHistorySnapshot(e,t){let n=this.readFeature.getGeometry(e);this.undoRedo.recordSnapshot({featureCoordinates:n.coordinates,currentCoordinate:t})}updateSnappedGuidancePointFromLastMouseMove(){this.snapping&&this.lastMouseMoveEvent?this.updateSnappedCoordinate(this.lastMouseMoveEvent):this.snappedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),void 0)}syncClosingPoints(e){this.currentCoordinate>=2?this.closingPoints.ids.length?this.closingPoints.update(e):this.closingPoints.create(e):this.closingPoints.delete()}undo(){if(this.state!==`drawing`||!this.currentId)return;let e=this.undoRedo.beginUndo();if(!e)return;let{previousEntry:t}=e;if(!t){let e=this.currentId;this.currentId=void 0,this.currentCoordinate=0,this.lastCommittedCoordinates=void 0,this.closingPoints.delete(),this.state===`drawing`&&this.setStarted(),this.showCoordinatePoints&&this.coordinatePoints.deletePointsByFeatureIds([e]),this.mutateFeature.deleteFeatureIfPresent(e),this.updateSnappedGuidancePointFromLastMouseMove();return}let n=this.mutateFeature.updateLineString({featureId:this.currentId,coordinateMutations:{type:Ly,coordinates:t.featureCoordinates},propertyMutations:{[ay.CURRENTLY_DRAWING]:!0},context:{updateType:ny.Commit}});n&&(this.currentCoordinate=t.currentCoordinate,this.lastCommittedCoordinates=n.geometry.coordinates,this.syncClosingPoints(n.geometry.coordinates),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:n.geometry.coordinates}),this.updateSnappedGuidancePointFromLastMouseMove())}redoSize(){return this.undoRedo.redoSize()}redo(){let e=this.undoRedo.takeRedo();if(e){if(this.currentId){let t=this.mutateFeature.updateLineString({featureId:this.currentId,coordinateMutations:{type:Ly,coordinates:e.featureCoordinates},propertyMutations:{[ay.CURRENTLY_DRAWING]:!0},context:{updateType:ny.Commit}});if(!t)return;this.currentCoordinate=e.currentCoordinate,this.lastCommittedCoordinates=t.geometry.coordinates,this.syncClosingPoints(t.geometry.coordinates),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:t.geometry.coordinates})}else{let{id:t,geometry:n}=this.mutateFeature.createLineString({coordinates:e.featureCoordinates,properties:{mode:this.mode,[ay.CURRENTLY_DRAWING]:!0}});this.currentId=t,this.currentCoordinate=e.currentCoordinate,this.lastCommittedCoordinates=n.coordinates,this.state===`started`&&this.setDrawing(),this.syncClosingPoints(n.coordinates),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:t,featureCoordinates:n.coordinates})}this.undoRedo.commitRedo(e),this.updateSnappedGuidancePointFromLastMouseMove()}}registerBehaviors(e){this.insertPoint=new Qy(e),this.clickBoundingBox=new Uy(e),this.pixelDistance=new Wy(e),this.lineSnapping=new ob(e,this.pixelDistance,this.clickBoundingBox),this.coordinateSnapping=new Gy(e,this.pixelDistance,this.clickBoundingBox),this.readFeature=new Vy(e),this.mutateFeature=new Ry(e,{validate:this.validate}),this.closingPoints=new ub(e,this.pixelDistance,this.mutateFeature,this.readFeature),this.coordinatePoints=new db(e,this.readFeature,this.mutateFeature),this.undoRedo=new fb({maxStackSize:e.undoRedoMaxStackSize})}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor(`unset`)}onMouseMove(e){this.mouseMove=!0,this.setCursor(this.cursors.start),this.lastMouseMoveEvent=e;let t=this.updateSnappedCoordinate(e)||[e.lng,e.lat];if(this.currentId===void 0||this.currentCoordinate===0)return;let{isClosing:n}=this.closingPoints.isLineStringClosingPoint(e);n&&this.setCursor(this.cursors.close);let r=[{type:Fy,index:-1,coordinate:t}];if(this.insertCoordinates){let e=this.getInsertCoordinates(t);e&&(r={type:Ly,coordinates:e})}let i=this.mutateFeature.updateLineString({coordinateMutations:r,featureId:this.currentId,context:{updateType:ny.Provisional}});i&&this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:i.geometry.coordinates})}getInsertCoordinates(e){if(!this.lastCommittedCoordinates)return;let t=this.lastCommittedCoordinates[this.lastCommittedCoordinates.length-1];if(By(t,e))return;let n=this.generateInsertCoordinates(t,e);return[...this.lastCommittedCoordinates.slice(0,-1),...n,e]}onRightClick(e){if(!this.editable||this.state!==`started`)return;let{featureId:t,featureCoordinateIndex:n}=this.coordinateSnapping.getSnappable(e,e=>this.lineStringFilter(e));if(!t||n===void 0)return;let r=this.readFeature.getGeometry(t),i;if(r.type!==`LineString`||(i=r.coordinates,i.length<=2))return;let a=this.mutateFeature.updateLineString({featureId:t,coordinateMutations:[{type:Iy,index:n}],context:{updateType:ny.Finish,action:$v}});a&&this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:t,featureCoordinates:a.geometry.coordinates}),this.snappedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),void 0),this.editedPointId&&(this.mutateFeature.deleteFeatureIfPresent(this.editedPointId),this.editedPointId=void 0,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedInsertIndex=void 0,this.editedSnapType=void 0),this.closingPoints.delete(),this.onFinish(t,{mode:this.mode,action:ey})}onLeftClick(e){this.snappedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),void 0);let t=this.snapCoordinate(e)||[e.lng,e.lat];this.currentCoordinate===0?this.createLine(t):this.currentCoordinate===1&&this.currentId?this.firstUpdateToLine(t):this.currentId&&this.updateToLine(e,t)}onClick(e){this.currentId===void 0||this.readFeature.hasFeature(this.currentId)||this.cleanUp(),(e.button===`right`&&this.allowPointerEvent(this.pointerEvents.rightClick,e)||e.button===`left`&&this.allowPointerEvent(this.pointerEvents.leftClick,e)||e.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,e))&&(this.currentCoordinate>0&&!this.mouseMove&&this.onMouseMove(e),this.mouseMove=!1,e.button===`right`?this.onRightClick(e):e.button===`left`&&this.onLeftClick(e))}onKeyDown(){}onKeyUp(e){e.key===this.keyEvents.cancel&&this.cleanUp(),e.key===this.keyEvents.finish&&this.close()}onDragStart(e,t){if(!this.allowPointerEvent(this.pointerEvents.onDragStart,e)||!this.editable)return;let n;if(this.state===`started`){let t=this.lineSnapping.getSnappable(e,e=>this.lineStringFilter(e));t.coordinate&&(this.editedSnapType=`line`,this.editedFeatureCoordinateIndex=t.featureCoordinateIndex,this.editedFeatureId=t.featureId,n=t.coordinate);let r=this.coordinateSnapping.getSnappable(e,e=>this.lineStringFilter(e));r.coordinate&&(this.editedSnapType=`coordinate`,this.editedFeatureCoordinateIndex=r.featureCoordinateIndex,this.editedFeatureId=r.featureId,n=r.coordinate)}this.editedFeatureId&&n&&(this.editedPointId||=this.mutateFeature.createGuidancePoint({coordinate:n,type:ay.EDITED}),this.setCursor(this.cursors.dragStart),t(!1))}onDrag(e,t){if(this.allowPointerEvent(this.pointerEvents.onDrag,e)&&this.editedFeatureId!==void 0&&this.editedFeatureCoordinateIndex!==void 0){if(this.editedSnapType===`coordinate`||this.editedSnapType===`line`&&this.editedInsertIndex!==void 0){let t=this.mutateFeature.updateLineString({featureId:this.editedFeatureId,context:{updateType:ny.Provisional},coordinateMutations:[{type:Fy,index:this.editedFeatureCoordinateIndex,coordinate:[e.lng,e.lat]}]});if(!t)return;this.showCoordinatePoints&&(this.editedInsertIndex===void 0?this.coordinatePoints.updateOneAtIndex(this.editedFeatureId,this.editedFeatureCoordinateIndex,[e.lng,e.lat]):this.coordinatePoints.createOrUpdate({featureId:this.editedFeatureId,featureCoordinates:t.geometry.coordinates}))}else if(this.editedSnapType===`line`&&this.editedInsertIndex===void 0){this.editedInsertIndex=this.editedFeatureCoordinateIndex+1;let e=this.mutateFeature.updateLineString({featureId:this.editedFeatureId,context:{updateType:ny.Provisional}});if(!e)return;this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.editedFeatureId,featureCoordinates:e.geometry.coordinates}),this.editedFeatureCoordinateIndex++}this.snapping&&this.snappedPointId&&(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),this.snappedPointId=void 0),this.editedPointId&&this.mutateFeature.updateGuidancePoints([{featureId:this.editedPointId,coordinate:[e.lng,e.lat]}]),this.mutateFeature.updateLineString({featureId:this.editedFeatureId,context:{updateType:ny.Provisional},propertyMutations:{[ay.EDITED]:!0}})}}onDragEnd(e,t){if(!this.allowPointerEvent(this.pointerEvents.onDragEnd,e)||this.editedFeatureId===void 0||(this.setCursor(this.cursors.dragEnd),!this.mutateFeature.updateLineString({featureId:this.editedFeatureId,propertyMutations:{[ay.EDITED]:!1},context:{updateType:ny.Finish,action:$v}})))return;let n=this.editedFeatureId;t(!0),this.snappedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),void 0),this.editedPointId&&(this.mutateFeature.deleteFeatureIfPresent(this.editedPointId),this.editedPointId=void 0,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedInsertIndex=void 0,this.editedSnapType=void 0),this.closingPoints.delete(),this.onFinish(n,{mode:this.mode,action:$v})}cleanUp(){let e=this.currentId,t=this.snappedPointId;this.snappedPointId=void 0,this.currentId=void 0,this.currentCoordinate=0,this.lastCommittedCoordinates=void 0,this.undoRedo.clear(),this.state===`drawing`&&this.setStarted(),e&&this.showCoordinatePoints&&this.coordinatePoints.deletePointsByFeatureIds([e]),this.mutateFeature.deleteFeatureIfPresent(e),this.mutateFeature.deleteFeatureIfPresent(t),this.closingPoints.delete()}styleFeature(e){let t=Zv({},{polygonFillColor:`#3f97e0`,polygonOutlineColor:`#3f97e0`,polygonOutlineWidth:4,polygonOutlineOpacity:1,polygonFillOpacity:.3,pointColor:`#3f97e0`,pointOpacity:1,pointOutlineColor:`#ffffff`,pointOutlineOpacity:1,pointOutlineWidth:0,pointWidth:6,lineStringColor:`#3f97e0`,lineStringWidth:4,lineStringOpacity:1,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0,lineStringDash:void 0});if(e.type===`Feature`&&e.geometry.type===`LineString`&&e.properties.mode===this.mode)return t.lineStringDash=this.styles.lineStringDash,t.lineStringColor=this.getHexColorStylingValue(this.styles.lineStringColor,t.lineStringColor,e),t.lineStringOpacity=this.getNumericStylingValue(this.styles.lineStringOpacity,t.lineStringOpacity===void 0?1:t.lineStringOpacity,e),t.lineStringWidth=this.getNumericStylingValue(this.styles.lineStringWidth,t.lineStringWidth,e),t.zIndex=oy,t;if(e.type===`Feature`&&e.geometry.type===`Point`&&e.properties.mode===this.mode){let n=e.properties[ay.COORDINATE_POINT],r=e.properties[ay.CLOSING_POINT]?`closingPoint`:e.properties[ay.SNAPPING_POINT]?`snappingPoint`:n?`coordinatePoint`:void 0;if(!r)return t;let i={closingPoint:{width:this.styles.closingPointWidth,color:this.styles.closingPointColor,opacity:this.styles.closingPointOpacity,outlineColor:this.styles.closingPointOutlineColor,outlineWidth:this.styles.closingPointOutlineWidth,outlineOpacity:this.styles.closingPointOutlineOpacity},snappingPoint:{width:this.styles.snappingPointWidth,color:this.styles.snappingPointColor,opacity:this.styles.snappingPointOpacity,outlineColor:this.styles.snappingPointOutlineColor,outlineWidth:this.styles.snappingPointOutlineWidth,outlineOpacity:this.styles.snappingPointOutlineOpacity},coordinatePoint:{width:this.styles.coordinatePointWidth,color:this.styles.coordinatePointColor,opacity:this.styles.coordinatePointOpacity,outlineColor:this.styles.coordinatePointOutlineColor,outlineWidth:this.styles.coordinatePointOutlineWidth,outlineOpacity:this.styles.coordinatePointOutlineOpacity}};return t.pointWidth=this.getNumericStylingValue(i[r].width,t.pointWidth,e),t.pointOpacity=this.getNumericStylingValue(i[r].opacity,1,e),t.pointColor=this.getHexColorStylingValue(i[r].color,t.pointColor,e),t.pointOutlineColor=this.getHexColorStylingValue(i[r].outlineColor,`#ffffff`,e),t.pointOutlineWidth=this.getNumericStylingValue(i[r].outlineWidth,2,e),t.pointOutlineOpacity=this.getNumericStylingValue(i[r].outlineOpacity,1,e),t.zIndex=n?20:50,t}return t}validateFeature(e){return this.validateModeFeature(e,e=>$y(e,this.coordinatePrecision))}lineStringFilter(e){return!!(e.geometry.type===`LineString`&&e.properties&&e.properties.mode===this.mode)}snapCoordinate(e){var t,n,r;let i;if((t=this.snapping)!=null&&t.toLine){let t;t=this.currentId?this.lineSnapping.getSnappableCoordinate(e,this.currentId):this.lineSnapping.getSnappableCoordinateFirstClick(e),t&&(i=t)}if((n=this.snapping)!=null&&n.toCoordinate){let t;t=this.currentId?this.coordinateSnapping.getSnappableCoordinate(e,this.currentId):this.coordinateSnapping.getSnappableCoordinateFirstClick(e),t&&(i=t)}if((r=this.snapping)!=null&&r.toCustom){let t=this.snapping.toCustom(e,{currentCoordinate:this.currentCoordinate,currentId:this.currentId,getCurrentGeometrySnapshot:this.currentId?()=>this.readFeature.getGeometry(this.currentId):()=>null,project:this.project,unproject:this.unproject});t&&(i=t)}return i}afterFeatureUpdated(e){this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:e.id,featureCoordinates:e.geometry.coordinates}),this.editedFeatureId===e.id&&this.editedPointId&&(this.mutateFeature.deleteFeatureIfPresent(this.editedPointId),this.editedPointId=void 0,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedSnapType=void 0),this.snappedPointId&&this.lastMouseMoveEvent&&this.updateSnappedCoordinate(this.lastMouseMoveEvent),this.currentId===e.id&&(this.closingPoints.delete(),this.currentCoordinate=0,this.currentId=void 0,this.lastCommittedCoordinates=void 0,this.undoRedo.clear(),this.state===`drawing`&&this.setStarted())}afterFeatureAdded(e){this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:e.id,featureCoordinates:e.geometry.coordinates})}},gb=`Feature is not a Point`,_b=`Feature has invalid coordinates`,vb=`Feature has coordinates with excessive precision`;function yb(e,t){return e.geometry.type===`Point`?ky(e.geometry.coordinates)?Oy(e.geometry.coordinates,t)?{valid:!0}:{valid:!1,reason:vb}:{valid:!1,reason:_b}:{valid:!1,reason:gb}}var bb=class extends jy{constructor(e,t,n){super(e),this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.pixelDistance=t,this.clickBoundingBox=n}getNearestPointFeature(e){let t=this.clickBoundingBox.create(e),n=this.store.search(t),r,i=1/0;for(let t=0;t<n.length;t++){let a=n[t];if(a.geometry.type!==`Point`||a.properties.mode!==this.mode)continue;let o=this.pixelDistance.measure(e,a.geometry.coordinates);o>i||o>this.pointerDistance||(i=o,r=a)}return r}},xb={create:`crosshair`,dragStart:`grabbing`,dragEnd:`crosshair`},Sb=class extends py{constructor(e){super(e,!0),this.mode=`point`,this.cursors=xb,this.editable=!1,this.editedFeatureId=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.pointSearch=void 0,this.mutateFeature=void 0,this.updateOptions(e)}updateOptions(e){super.updateOptions(e),e!=null&&e.cursors&&(this.cursors=Zv({},this.cursors,e.cursors)),e!=null&&e.editable&&(this.editable=e.editable)}start(){this.setStarted(),this.setCursor(this.cursors.create)}stop(){this.cleanUp(),this.setStopped(),this.setCursor(`unset`)}onClick(e){e.button===`right`&&this.allowPointerEvent(this.pointerEvents.rightClick,e)||e.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,e)?this.onRightClick(e):e.button===`left`&&this.allowPointerEvent(this.pointerEvents.leftClick,e)&&this.onLeftClick(e)}onMouseMove(){}onKeyDown(){}onKeyUp(){}cleanUp(){this.editedFeatureId=void 0}onDragStart(e,t){if(this.allowPointerEvent(this.pointerEvents.onDragStart,e)){if(this.editable){let t=this.pointSearch.getNearestPointFeature(e);this.editedFeatureId=t?.id}this.editedFeatureId&&(this.setCursor(this.cursors.dragStart),t(!1))}}onDrag(e,t){this.allowPointerEvent(this.pointerEvents.onDrag,e)&&this.editedFeatureId!==void 0&&this.mutateFeature.updatePoint({featureId:this.editedFeatureId,coordinateMutations:{type:Ly,coordinates:[e.lng,e.lat]},propertyMutations:{[ay.EDITED]:!0},context:{updateType:ny.Provisional}})}onDragEnd(e,t){if(!this.allowPointerEvent(this.pointerEvents.onDragEnd,e)||this.editedFeatureId===void 0||!this.mutateFeature.updatePoint({featureId:this.editedFeatureId,propertyMutations:{mode:this.mode,[ay.EDITED]:!1},context:{updateType:ny.Finish,action:`edit`}}))return;let n=this.editedFeatureId;this.setCursor(this.cursors.dragEnd),this.editedFeatureId=void 0,t(!0),this.onFinish(n,{mode:this.mode,action:Qv})}registerBehaviors(e){this.pixelDistance=new Wy(e),this.clickBoundingBox=new Uy(e),this.pointSearch=new bb(e,this.pixelDistance,this.clickBoundingBox),this.mutateFeature=new Ry(e,{validate:this.validate})}styleFeature(e){let t=Zv({},{polygonFillColor:`#3f97e0`,polygonOutlineColor:`#3f97e0`,polygonOutlineWidth:4,polygonOutlineOpacity:1,polygonFillOpacity:.3,pointColor:`#3f97e0`,pointOpacity:1,pointOutlineColor:`#ffffff`,pointOutlineOpacity:1,pointOutlineWidth:0,pointWidth:6,lineStringColor:`#3f97e0`,lineStringWidth:4,lineStringOpacity:1,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0,lineStringDash:void 0});if(e.type===`Feature`&&e.geometry.type===`Point`&&e.properties.mode===this.mode){let n=!!(e.id&&this.editedFeatureId===e.id);t.pointWidth=this.getNumericStylingValue(n?this.styles.editedPointWidth:this.styles.pointWidth,t.pointWidth,e),t.pointOpacity=this.getNumericStylingValue(this.styles.pointOpacity,t.pointOpacity===void 0?1:t.pointOpacity,e),t.pointColor=this.getHexColorStylingValue(n?this.styles.editedPointColor:this.styles.pointColor,t.pointColor,e),t.pointOutlineColor=this.getHexColorStylingValue(n?this.styles.editedPointOutlineColor:this.styles.pointOutlineColor,t.pointOutlineColor,e),t.pointOutlineOpacity=this.getNumericStylingValue(this.styles.pointOutlineOpacity,t.pointOutlineOpacity===void 0?1:t.pointOutlineOpacity,e),t.pointOutlineWidth=this.getNumericStylingValue(n?this.styles.editedPointOutlineWidth:this.styles.pointOutlineWidth,2,e),t.zIndex=30}return t}validateFeature(e){return this.validateModeFeature(e,e=>yb(e,this.coordinatePrecision))}onLeftClick(e){let t=this.mutateFeature.createPoint({coordinates:[e.lng,e.lat],properties:{mode:this.mode},context:{updateType:ny.Finish,action:Qv}});t&&this.onFinish(t.id,{mode:this.mode,action:Qv})}onRightClick(e){if(!this.editable)return;let t=this.pointSearch.getNearestPointFeature(e);t&&this.mutateFeature.deleteFeatureIfPresent(t.id)}afterFeatureUpdated(e){this.editedFeatureId===e.id&&(this.editedFeatureId=void 0,this.setCursor(this.cursors.create))}};function Cb(e,t){let n=e,r=t,i=_y(n[1]),a=_y(r[1]),o=_y(r[0]-n[0]);o>Math.PI&&(o-=2*Math.PI),o<-Math.PI&&(o+=2*Math.PI);let s=Math.log(Math.tan(a/2+Math.PI/4)/Math.tan(i/2+Math.PI/4)),c=(yy(Math.atan2(o,s))+360)%360;return c>180?-(360-c):c}function wb(e,t,n){let r=t;t<0&&(r=-Math.abs(r));let i=r/gy,a=e[0]*Math.PI/180,o=_y(e[1]),s=_y(n),c=i*Math.cos(s),l=o+c;Math.abs(l)>Math.PI/2&&(l=l>0?Math.PI-l:-Math.PI-l);let u=Math.log(Math.tan(l/2+Math.PI/4)/Math.tan(o/2+Math.PI/4)),d=Math.abs(u)>1e-11?c/u:Math.cos(o),f=[(180*(a+i*Math.sin(s)/d)/Math.PI+540)%360-180,180*l/Math.PI];return f[0]+=f[0]-e[0]>180?-360:e[0]-f[0]>180?360:0,f}function Tb(e,t,n,r,i){let a=r(e[0],e[1]),o=r(t[0],t[1]),{lng:s,lat:c}=i((a.x+o.x)/2,(a.y+o.y)/2);return[by(s,n),by(c,n)]}function Eb(e,t,n){let r=wb(e,1e3*hy(e,t)/2,Cb(e,t));return[by(r[0],n),by(r[1],n)]}function Db({featureCoords:e,precision:t,unproject:n,project:r,projection:i}){let a=[];for(let o=0;o<e.length-1;o++){let s;if(i===`web-mercator`)s=Tb(e[o],e[o+1],t,r,n);else{if(i!==`globe`)throw Error(`Invalid projection`);s=Eb(e[o],e[o+1],t)}a.push(s)}return a}var Ob=class extends jy{constructor(e,t,n,r,i,a){super(e),this.config=void 0,this.selectionPointBehavior=void 0,this.coordinatePointBehavior=void 0,this.mutateFeature=void 0,this.readFeature=void 0,this.pixelDistance=void 0,this._midPoints=[],this.config=e,this.selectionPointBehavior=t,this.coordinatePointBehavior=n,this.mutateFeature=r,this.readFeature=i,this.pixelDistance=a}getMidpointConfig(e){return{featureCoords:e,precision:this.coordinatePrecision,project:this.config.project,unproject:this.config.unproject,projection:this.config.projection}}get ids(){return this._midPoints.concat()}set ids(e){}getNearestMidPoint(e){let t,n=1/0;return this.ids.forEach(r=>{let i=this.readFeature.getGeometry(r),a=this.pixelDistance.measure(e,i.coordinates);a<this.pointerDistance&&a<n&&(n=a,t=r)}),t}insert({featureId:e,midPointId:t}){let n=this.readFeature.getGeometry(t),{midPointFeatureId:r,midPointSegment:i}=this.readFeature.getProperties(t),a=this.readFeature.getGeometry(r),o={featureId:r,coordinateMutations:[{type:Py,index:i,coordinate:n.coordinates}],context:{updateType:ny.Commit}},s=null;if(a.type===`Polygon`)s=this.mutateFeature.updatePolygon(o);else{if(a.type!==`LineString`)throw Error(`Midpoints can only be added to polygons or linestrings`);s=this.mutateFeature.updateLineString(o)}if(!s)throw Error(`Failed to insert midpoint coordinate`);let c=s.geometry.coordinates;this.readFeature.getProperties(e)[ay.COORDINATE_POINT_IDS]&&this.coordinatePointBehavior.createOrUpdate({featureId:e,featureCoordinates:c}),this.mutateFeature.deleteFeaturesIfPresent([...this.selectionPointBehavior.ids,...this._midPoints]),this.create({featureCoordinates:c,featureId:r}),this.selectionPointBehavior.create({featureCoordinates:c,featureId:e})}create({featureCoordinates:e,featureId:t}){if(!this.readFeature.hasFeature(t))throw Error(`Store does not have feature with this id`);let n=lb(e),r=Db(this.getMidpointConfig(n));this._midPoints=this.mutateFeature.createGuidancePoints({additionalProperties:e=>({mode:this.mode,midPointSegment:e,midPointFeatureId:t,[iy.MID_POINT]:!0}),coordinates:r,type:iy.MID_POINT})}delete(){this._midPoints.length&&(this.mutateFeature.deleteFeaturesIfPresent(this._midPoints),this._midPoints=[])}updateAllInPlace({featureCoordinates:e}){if(this._midPoints.length===0)return;let t=lb(e),n=Db(this.getMidpointConfig(t));this.mutateFeature.updateGuidancePoints(this._midPoints.map((e,t)=>({featureId:e,coordinate:n[t]})))}updateOneAtIndex(e,t){if(e<0&&(e=this._midPoints.length+e),this._midPoints[e]===void 0)return;let n=lb(t),r=Db(this.getMidpointConfig(n));this.mutateFeature.updateGuidancePoints([{featureId:this._midPoints[e],coordinate:r[e]}])}},kb=class extends jy{constructor(e,t){super(e),this.mutateFeature=void 0,this._selectionPoints=[],this.mutateFeature=t}get ids(){return this._selectionPoints.concat()}set ids(e){}create({featureId:e,featureCoordinates:t}){let n=cb(t);this._selectionPoints=this.mutateFeature.createGuidancePoints({coordinates:n,type:iy.SELECTION_POINT,additionalProperties:t=>({[iy.SELECTION_POINT_FEATURE_ID]:e,index:t})})}delete(){this.ids.length&&(this.mutateFeature.deleteFeaturesIfPresent(this.ids),this._selectionPoints=[])}updateAllInPlace({featureCoordinates:e}){if(this._selectionPoints.length===0)return;let t=cb(e);t.length===this._selectionPoints.length&&this.mutateFeature.updateGuidancePoints(this._selectionPoints.map((e,n)=>({featureId:e,coordinate:t[n]})))}updateOneAtIndex(e,t){this._selectionPoints[e]!==void 0&&this.mutateFeature.updateGuidancePoints([{featureId:this._selectionPoints[e],coordinate:t}])}};function Ab(e,t){let n=!1;for(let o=0,s=t.length;o<s;o++){let s=t[o];for(let t=0,o=s.length,c=o-1;t<o;c=t++)(i=s[t])[1]>(r=e)[1]!=(a=s[c])[1]>r[1]&&r[0]<(a[0]-i[0])*(r[1]-i[1])/(a[1]-i[1])+i[0]&&(n=!n)}var r,i,a;return n}var jb=(e,t,n)=>{let r=e=>e*e,i=(e,t)=>r(e.x-t.x)+r(e.y-t.y);return Math.sqrt(((e,t,n)=>{let r=i(t,n);if(r===0)return i(e,t);let a=((e.x-t.x)*(n.x-t.x)+(e.y-t.y)*(n.y-t.y))/r;return a=Math.max(0,Math.min(1,a)),i(e,{x:t.x+a*(n.x-t.x),y:t.y+a*(n.y-t.y)})})(e,t,n))},Mb=class extends jy{constructor(e,t,n){super(e),this.config=void 0,this.createClickBoundingBox=void 0,this.pixelDistance=void 0,this.config=e,this.createClickBoundingBox=t,this.pixelDistance=n}find(e,t){let n,r,i,a=1/0,o=1/0,s=this.createClickBoundingBox.create(e),c=this.store.search(s);for(let s=0;s<c.length;s++){let l=c[s],u=l.geometry;if(u.type===`Point`){if(l.properties.selectionPoint||l.properties.coordinatePoint||!t&&l.properties[iy.MID_POINT])continue;let r=this.pixelDistance.measure(e,u.coordinates);!l.properties[iy.MID_POINT]&&r<this.pointerDistance&&r<a&&(a=r,n=l)}else if(u.type===`LineString`){if(n)continue;for(let t=0;t<u.coordinates.length-1;t++){let n=u.coordinates[t],i=u.coordinates[t+1],a=jb({x:e.containerX,y:e.containerY},this.project(n[0],n[1]),this.project(i[0],i[1]));a<this.pointerDistance&&a<o&&(o=a,r=l)}}else if(u.type===`Polygon`){if(n||r)continue;Ab([e.lng,e.lat],u.coordinates)&&(i=l)}}return{clickedFeature:n||r||i}}},Nb=class extends jy{constructor(e,t,n,r,i,a,o){super(e),this.config=void 0,this.featuresAtCursorEvent=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.coordinatePoints=void 0,this.readFeature=void 0,this.mutateFeature=void 0,this.draggedFeatureId=null,this.dragPosition=void 0,this.config=e,this.featuresAtCursorEvent=t,this.selectionPoints=n,this.midPoints=r,this.coordinatePoints=i,this.readFeature=a,this.mutateFeature=o}startDragging(e,t){this.draggedFeatureId=t,this.dragPosition=[e.lng,e.lat]}stopDragging(){this.draggedFeatureId=null,this.dragPosition=void 0}isDragging(){return this.draggedFeatureId!==null}canDrag(e,t){let{clickedFeature:n}=this.featuresAtCursorEvent.find(e,!0);return!(!n||n.id!==t)}drag(e){if(!this.draggedFeatureId)return;let t=this.readFeature.getGeometry(this.draggedFeatureId),n=[e.lng,e.lat];if(t.type===`Polygon`||t.type===`LineString`){let r,i;if(t.type===`Polygon`?(r=t.coordinates[0],i=r.length-1):(r=t.coordinates,i=r.length),!this.dragPosition)return!1;for(let e=0;e<i;e++){let t=r[e],i,a;if(this.config.projection===`web-mercator`){let e=wy(this.dragPosition[0],this.dragPosition[1]),r=wy(n[0],n[1]),o=wy(t[0],t[1]),s={x:e.x-r.x,y:e.y-r.y},{lng:c,lat:l}=Ty(o.x-s.x,o.y-s.y);i=c,a=l}else{let e=[this.dragPosition[0]-n[0],this.dragPosition[1]-n[1]];i=t[0]-e[0],a=t[1]-e[1]}if(i=by(i,this.config.coordinatePrecision),a=by(a,this.config.coordinatePrecision),i>180||i<-180||a>90||a<-90)return!1;r[e]=[i,a]}t.type===`Polygon`&&(r[r.length-1]=[r[0][0],r[0][1]]);let a=this.draggedFeatureId,o=null;if(t.type===`Polygon`)o=this.mutateFeature.updatePolygon({featureId:a,coordinateMutations:{type:Ly,coordinates:[r]},context:{updateType:ny.Provisional}});else{if(t.type!==`LineString`)return;o=this.mutateFeature.updateLineString({featureId:a,coordinateMutations:{type:Ly,coordinates:r},context:{updateType:ny.Provisional}})}if(!o)return!1;let s=o.geometry.coordinates;this.midPoints.updateAllInPlace({featureCoordinates:s}),this.selectionPoints.updateAllInPlace({featureCoordinates:s}),this.coordinatePoints.updateAllInPlace({featureId:a,featureCoordinates:s}),this.dragPosition=[e.lng,e.lat]}else t.type===`Point`&&(this.mutateFeature.updatePoint({featureId:this.draggedFeatureId,coordinateMutations:{type:Ly,coordinates:n},context:{updateType:ny.Provisional}}),this.dragPosition=[e.lng,e.lat])}},Pb=class extends jy{constructor(e,t,n,r,i,a,o,s,c){super(e),this.config=void 0,this.pixelDistance=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.coordinatePoints=void 0,this.coordinateSnapping=void 0,this.lineSnapping=void 0,this.readFeature=void 0,this.mutateFeature=void 0,this.draggedCoordinate={id:null,index:-1},this.config=e,this.pixelDistance=t,this.selectionPoints=n,this.midPoints=r,this.coordinatePoints=i,this.coordinateSnapping=a,this.lineSnapping=o,this.readFeature=s,this.mutateFeature=c}getClosestCoordinate(e,t){let n={dist:1/0,index:-1,isFirstOrLastPolygonCoord:!1},r;if(t.type===`LineString`)r=t.coordinates;else{if(t.type!==`Polygon`)return n;r=t.coordinates[0]}for(let i=0;i<r.length;i++){let a=this.pixelDistance.measure(e,r[i]);if(a<this.pointerDistance&&a<n.dist){let e=t.type===`Polygon`&&(i===r.length-1||i===0);n.dist=a,n.index=e?0:i,n.isFirstOrLastPolygonCoord=e}}return n}getDraggable(e,t){let n=this.readFeature.getGeometry(t);return this.getClosestCoordinate(e,n)}getDraggableIndex(e,t){let n=this.readFeature.getGeometry(t),r=this.getClosestCoordinate(e,n);return r.index===-1?-1:r.index}snapCoordinate(e,t,n){let r=[e.lng,e.lat],i=e=>!!(e.properties&&e.properties.mode===n.properties.mode&&e.id!==this.draggedCoordinate.id);if(t!=null&&t.toLine){let t;t=this.lineSnapping.getSnappable(e,i).coordinate,t&&(r=t)}if(t.toCoordinate){let t;t=this.coordinateSnapping.getSnappable(e,i).coordinate,t&&(r=t)}if(t!=null&&t.toCustom){let i;i=t.toCustom(e,{currentCoordinate:this.draggedCoordinate.index,currentId:n.id,getCurrentGeometrySnapshot:n.id?()=>this.readFeature.getGeometry(n.id):()=>null,project:this.project,unproject:this.unproject}),i&&(r=i)}return r}drag(e,t,n){let r=this.draggedCoordinate.id;if(r===null)return!1;let i=this.draggedCoordinate.index,a=this.readFeature.getGeometry(r),o=this.readFeature.getProperties(r),s=a.type===`LineString`?a.coordinates:a.coordinates[0],c=a.type===`Polygon`&&(i===s.length-1||i===0),l=this.snapCoordinate(e,n,{type:`Feature`,id:r,geometry:a,properties:o});if(e.lng>180||e.lng<-180||e.lat>90||e.lat<-90)return!1;if(c){let e=s.length-1;s[0]=l,s[e]=l}else s[i]=l;if(a.type!==`Point`&&!t&&Ey({type:`Feature`,geometry:a,properties:{}}))return!1;let u=r,d=null;return a.type===`Polygon`?d=this.mutateFeature.updatePolygon({featureId:u,coordinateMutations:{type:Ly,coordinates:[s]},context:{updateType:ny.Provisional}}):a.type===`LineString`&&(d=this.mutateFeature.updateLineString({featureId:u,coordinateMutations:{type:Ly,coordinates:s},context:{updateType:ny.Provisional}})),!!d&&(this.midPoints.updateOneAtIndex(i>0?i-1:-1,s),this.midPoints.updateOneAtIndex(i,s),this.selectionPoints.updateOneAtIndex(i,l),this.coordinatePoints.updateOneAtIndex(u,i,l),!0)}isDragging(){return this.draggedCoordinate.id!==null}startDragging(e,t){this.draggedCoordinate={id:e,index:t}}stopDragging(){this.draggedCoordinate={id:null,index:-1}}};function Fb(e){let t=0,n=0,r=0;return(e.geometry.type===`Polygon`?e.geometry.coordinates[0].slice(0,-1):e.geometry.coordinates).forEach(e=>{t+=e[0],n+=e[1],r++},!0),[t/r,n/r]}var Ib=(e,t)=>{if(t===0||t===360||t===-360)return e;let n=.017453292519943295*t,r=(e.geometry.type===`Polygon`?e.geometry.coordinates[0]:e.geometry.coordinates).map(([e,t])=>wy(e,t)),i=r.reduce((e,t)=>({x:e.x+t.x,y:e.y+t.y}),{x:0,y:0});i.x/=r.length,i.y/=r.length;let a=r.map(e=>({x:i.x+(e.x-i.x)*Math.cos(n)-(e.y-i.y)*Math.sin(n),y:i.y+(e.x-i.x)*Math.sin(n)+(e.y-i.y)*Math.cos(n)})).map(({x:e,y:t})=>[Ty(e,t).lng,Ty(e,t).lat]);return e.geometry.type===`Polygon`?e.geometry.coordinates[0]=a:e.geometry.coordinates=a,e};function Lb(e){let t=(e.geometry.type===`Polygon`?e.geometry.coordinates[0]:e.geometry.coordinates).map(e=>{let{x:t,y:n}=wy(e[0],e[1]);return[t,n]});return e.geometry.type===`Polygon`?function(e){let t=0,n=0,r=0,i=e.length;for(let a=0;a<i-1;a++){let[i,o]=e[a],[s,c]=e[a+1],l=i*c-s*o;t+=l,n+=(i+s)*l,r+=(o+c)*l}return t/=2,n/=6*t,r/=6*t,{x:n,y:r}}(t):function(e){let t=e.length,n=0,r=0;for(let i=0;i<t;i++){let[t,a]=e[i];n+=t,r+=a}return{x:n/t,y:r/t}}(t)}var Rb=class extends jy{constructor(e,t,n,r,i,a){super(e),this.config=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.coordinatePoints=void 0,this.readFeature=void 0,this.mutateFeature=void 0,this.lastBearing=void 0,this.selectedGeometry=void 0,this.selectedGeometryCentroid=void 0,this.selectedGeometryWebMercatorCentroid=void 0,this.config=e,this.selectionPoints=t,this.midPoints=n,this.coordinatePoints=r,this.readFeature=i,this.mutateFeature=a}reset(){this.lastBearing=void 0,this.selectedGeometry=void 0,this.selectedGeometryWebMercatorCentroid=void 0,this.selectedGeometryCentroid=void 0}rotate(e,t){this.selectedGeometry||=this.readFeature.getGeometry(t);let n=this.selectedGeometry;if(n.type!==`Polygon`&&n.type!==`LineString`)return;let r=[e.lng,e.lat],i,a={type:`Feature`,geometry:n,properties:{}};if(this.config.projection===`web-mercator`){this.selectedGeometryWebMercatorCentroid||=Lb(a);let t=wy(e.lng,e.lat);if(i=Jy(this.selectedGeometryWebMercatorCentroid,t),i===0)return;if(!this.lastBearing)return void(this.lastBearing=i);Ib(a,-(this.lastBearing-i))}else{if(this.config.projection!==`globe`)throw Error(`Unsupported projection`);if(this.selectedGeometryCentroid||=Fb({type:`Feature`,geometry:n,properties:{}}),i=Cb(this.selectedGeometryCentroid,r),!this.lastBearing)return void(this.lastBearing=i+180);(function(e,t){if(t===0||t===360||t===-360)return e;let n=Fb(e);(e.geometry.type===`Polygon`?e.geometry.coordinates[0]:e.geometry.coordinates).forEach(e=>{let r=Cb(n,e)+t,i=wb(n,function(e,t){e[0]+=e[0]-t[0]>180?-360:t[0]-e[0]>180?360:0;let n=gy,r=t[1]*Math.PI/180,i=e[1]*Math.PI/180,a=i-r,o=Math.abs(e[0]-t[0])*Math.PI/180;o>Math.PI&&(o-=2*Math.PI);let s=Math.log(Math.tan(i/2+Math.PI/4)/Math.tan(r/2+Math.PI/4)),c=Math.abs(s)>1e-11?a/s:Math.cos(r);return Math.sqrt(a*a+c*c*o*o)*n}(n,e),r);e[0]=i[0],e[1]=i[1]})})(a,-(this.lastBearing-(i+180)))}let o=n.type===`Polygon`?n.coordinates[0]:n.coordinates;o.forEach(e=>{e[0]=by(e[0],this.coordinatePrecision),e[1]=by(e[1],this.coordinatePrecision)});let s={featureId:t,coordinateMutations:{type:Ly,coordinates:n.type===`Polygon`?[o]:o},context:{updateType:ny.Provisional}},c=null;if(a.geometry.type===`Polygon`)c=this.mutateFeature.updatePolygon(s);else{if(a.geometry.type!==`LineString`)return;c=this.mutateFeature.updateLineString(s)}if(!c)return!1;let l=c.geometry.coordinates;this.midPoints.updateAllInPlace({featureCoordinates:l}),this.selectionPoints.updateAllInPlace({featureCoordinates:l}),this.coordinatePoints.updateAllInPlace({featureId:t,featureCoordinates:l}),this.projection===`web-mercator`?this.lastBearing=i:this.projection===`globe`&&(this.lastBearing=i+180)}},zb=class extends jy{constructor(e,t){super(e),this.config=void 0,this.dragCoordinateResizeBehavior=void 0,this.config=e,this.dragCoordinateResizeBehavior=t}scale(e,t){if(!this.dragCoordinateResizeBehavior.isDragging()){let n=this.dragCoordinateResizeBehavior.getDraggableIndex(e,t);this.dragCoordinateResizeBehavior.startDragging(t,n)}this.dragCoordinateResizeBehavior.drag(e,`center-fixed`)}reset(){this.dragCoordinateResizeBehavior.stopDragging()}};function Bb({coordinates:e,originX:t,originY:n,xScale:r,yScale:i}){r===1&&i===1||e.forEach(e=>{let{x:a,y:o}=wy(e[0],e[1]),{lng:s,lat:c}=Ty(t+(a-t)*r,n+(o-n)*i);e[0]=s,e[1]=c})}var Vb=class extends jy{constructor(e,t,n,r,i,a,o){super(e),this.config=void 0,this.pixelDistance=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.coordinatePoints=void 0,this.readFeature=void 0,this.mutateFeature=void 0,this.minimumScale=1e-4,this.draggedCoordinate={id:null,index:-1},this.boundingBoxMaps={opposite:{0:4,1:5,2:6,3:7,4:0,5:1,6:2,7:3}},this.config=e,this.pixelDistance=t,this.selectionPoints=n,this.midPoints=r,this.coordinatePoints=i,this.readFeature=a,this.mutateFeature=o}getClosestCoordinate(e,t){let n={dist:1/0,index:-1,isFirstOrLastPolygonCoord:!1},r;if(t.type===`LineString`)r=t.coordinates;else{if(t.type!==`Polygon`)return n;r=t.coordinates[0]}for(let i=0;i<r.length;i++){let a=this.pixelDistance.measure(e,r[i]);if(a<this.pointerDistance&&a<n.dist){let e=t.type===`Polygon`&&(i===r.length-1||i===0);n.dist=a,n.index=e?0:i,n.isFirstOrLastPolygonCoord=e}}return n}isValidDragWebMercator(e,t,n){switch(e){case 0:if(t<=0||n>=0)return!1;break;case 1:if(n>=0)return!1;break;case 2:if(t>=0||n>=0)return!1;break;case 3:if(t>=0)return!1;break;case 4:if(t>=0||n<=0)return!1;break;case 5:if(n<=0)return!1;break;case 6:if(t<=0||n<=0)return!1;break;case 7:if(t<=0)return!1}return!0}getSelectedFeatureDataWebMercator(){if(!this.draggedCoordinate.id||this.draggedCoordinate.index===-1)return null;let e=this.getFeature(this.draggedCoordinate.id);if(!e)return null;let t=this.getNormalisedCoordinates(e.geometry);return{boundingBox:this.getBBoxWebMercator(t),feature:e,updatedCoords:t,selectedCoordinate:t[this.draggedCoordinate.index]}}centerWebMercatorDrag(e){let t=this.getSelectedFeatureDataWebMercator();if(!t)return null;let{feature:n,boundingBox:r,updatedCoords:i,selectedCoordinate:a}=t,o=Lb(n);if(!o)return null;let s=wy(a[0],a[1]),{closestBBoxIndex:c}=this.getIndexesWebMercator(r,s),l=wy(e.lng,e.lat);return this.scaleWebMercator({closestBBoxIndex:c,updatedCoords:i,webMercatorCursor:l,webMercatorSelected:s,webMercatorOrigin:o}),i}centerFixedWebMercatorDrag(e){let t=this.getSelectedFeatureDataWebMercator();if(!t)return null;let{feature:n,boundingBox:r,updatedCoords:i,selectedCoordinate:a}=t,o=Lb(n);if(!o)return null;let s=wy(a[0],a[1]),{closestBBoxIndex:c}=this.getIndexesWebMercator(r,s),l=wy(e.lng,e.lat);return this.scaleFixedWebMercator({closestBBoxIndex:c,updatedCoords:i,webMercatorCursor:l,webMercatorSelected:s,webMercatorOrigin:o}),i}scaleFixedWebMercator({closestBBoxIndex:e,webMercatorOrigin:t,webMercatorSelected:n,webMercatorCursor:r,updatedCoords:i}){if(!this.isValidDragWebMercator(e,t.x-r.x,t.y-r.y))return null;let a=zy(t,r)/zy(t,n);return a<0&&(a=this.minimumScale),Bb({coordinates:i,originX:t.x,originY:t.y,xScale:a,yScale:a}),i}oppositeFixedWebMercatorDrag(e){let t=this.getSelectedFeatureDataWebMercator();if(!t)return null;let{boundingBox:n,updatedCoords:r,selectedCoordinate:i}=t,a=wy(i[0],i[1]),{oppositeBboxIndex:o,closestBBoxIndex:s}=this.getIndexesWebMercator(n,a),c={x:n[o][0],y:n[o][1]},l=wy(e.lng,e.lat);return this.scaleFixedWebMercator({closestBBoxIndex:s,updatedCoords:r,webMercatorCursor:l,webMercatorSelected:a,webMercatorOrigin:c}),r}oppositeWebMercatorDrag(e){let t=this.getSelectedFeatureDataWebMercator();if(!t)return null;let{boundingBox:n,updatedCoords:r,selectedCoordinate:i}=t,a=wy(i[0],i[1]),{oppositeBboxIndex:o,closestBBoxIndex:s}=this.getIndexesWebMercator(n,a),c={x:n[o][0],y:n[o][1]},l=wy(e.lng,e.lat);return this.scaleWebMercator({closestBBoxIndex:s,updatedCoords:r,webMercatorCursor:l,webMercatorSelected:a,webMercatorOrigin:c}),r}scaleWebMercator({closestBBoxIndex:e,webMercatorOrigin:t,webMercatorSelected:n,webMercatorCursor:r,updatedCoords:i}){let a=t.x-r.x,o=t.y-r.y;if(!this.isValidDragWebMercator(e,a,o))return null;let s=1;a!==0&&e!==1&&e!==5&&(s=1-(t.x-n.x-a)/a);let c=1;return o!==0&&e!==3&&e!==7&&(c=1-(t.y-n.y-o)/o),this.validateScale(s,c)?(s<0&&(s=this.minimumScale),c<0&&(c=this.minimumScale),this.performWebMercatorScale(i,t.x,t.y,s,c),i):null}getFeature(e){if(this.draggedCoordinate.id===null)return null;let t=this.readFeature.getGeometry(e);return t.type!==`Polygon`&&t.type!==`LineString`?null:{id:e,type:`Feature`,geometry:t,properties:{}}}getNormalisedCoordinates(e){return e.type===`Polygon`?e.coordinates[0]:e.coordinates}validateScale(e,t){return!isNaN(e)&&t<2**53-1&&!isNaN(t)&&t<2**53-1}performWebMercatorScale(e,t,n,r,i){e.forEach(e=>{let{x:a,y:o}=wy(e[0],e[1]),{lng:s,lat:c}=Ty(t+(a-t)*r,n+(o-n)*i);e[0]=s,e[1]=c})}getBBoxWebMercator(e){let t=[1/0,1/0,-1/0,-1/0];(e=e.map(e=>{let{x:t,y:n}=wy(e[0],e[1]);return[t,n]})).forEach(([e,n])=>{e<t[0]&&(t[0]=e),n<t[1]&&(t[1]=n),e>t[2]&&(t[2]=e),n>t[3]&&(t[3]=n)});let[n,r,i,a]=t;return[[n,a],[(n+i)/2,a],[i,a],[i,a+(r-a)/2],[i,r],[(n+i)/2,r],[n,r],[n,a+(r-a)/2]]}getIndexesWebMercator(e,t){let n,r=1/0;for(let i=0;i<e.length;i++){let a=zy({x:t.x,y:t.y},{x:e[i][0],y:e[i][1]});a<r&&(n=i,r=a)}if(n===void 0)throw Error(`No closest coordinate found`);return{oppositeBboxIndex:this.boundingBoxMaps.opposite[n],closestBBoxIndex:n}}isDragging(){return this.draggedCoordinate.id!==null}startDragging(e,t){this.draggedCoordinate={id:e,index:t}}stopDragging(){this.draggedCoordinate={id:null,index:-1}}getDraggableIndex(e,t){let n=this.readFeature.getGeometry(t),r=this.getClosestCoordinate(e,n);return r.index===-1?-1:r.index}drag(e,t){if(!this.draggedCoordinate.id)return!1;let n=this.getFeature(this.draggedCoordinate.id);if(!n)return!1;let r=null;if(t===`center`?r=this.centerWebMercatorDrag(e):t===`opposite`?r=this.oppositeWebMercatorDrag(e):t===`center-fixed`?r=this.centerFixedWebMercatorDrag(e):t===`opposite-fixed`&&(r=this.oppositeFixedWebMercatorDrag(e)),!r)return!1;for(let e=0;e<r.length;e++){let t=r[e];if(t[0]=by(t[0],this.coordinatePrecision),t[1]=by(t[1],this.coordinatePrecision),!Oy(t,this.coordinatePrecision))return!1}let i=n.id,a=null;if(n.geometry.type===`Polygon`?a=this.mutateFeature.updatePolygon({featureId:i,coordinateMutations:{type:Ly,coordinates:[r]},context:{updateType:ny.Provisional}}):n.geometry.type===`LineString`&&(a=this.mutateFeature.updateLineString({featureId:i,coordinateMutations:{type:Ly,coordinates:r},context:{updateType:ny.Provisional}})),!a)return!1;let o=a.geometry.coordinates;return this.midPoints.updateAllInPlace({featureCoordinates:o}),this.selectionPoints.updateAllInPlace({featureCoordinates:o}),this.coordinatePoints.updateAllInPlace({featureId:i,featureCoordinates:o}),!0}},Hb={deselect:`Escape`,delete:`Delete`,rotate:[`Control`,`r`],scale:[`Control`,`s`]},Ub={pointerOver:`move`,dragStart:`move`,dragEnd:`move`,insertMidpoint:`crosshair`},Wb=class extends my{getPointerOverFeatureCursor(){return this.cursors.pointerOverFeature??this.cursors.pointerOver}getPointerOverCoordinateCursor(){return this.cursors.pointerOverCoordinate??this.cursors.pointerOver}getPointerOverResizeHandleCursor(){return this.cursors.pointerOverResizeHandle??this.cursors.pointerOver}constructor(e){super(e,!0),this.mode=`select`,this.allowManualDeselection=!0,this.allowManualSelection=!0,this.dragEventThrottle=5,this.dragEventCount=0,this.selected=[],this.flags={},this.keyEvents=Hb,this.cursors=Ub,this.validations={},this.dragTarget={type:`none`},this.selectionPoints=void 0,this.midPoints=void 0,this.coordinateSnap=void 0,this.featuresAtMouseEvent=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.dragFeature=void 0,this.dragCoordinate=void 0,this.rotateFeature=void 0,this.scaleFeature=void 0,this.dragCoordinateResizeFeature=void 0,this.coordinatePoints=void 0,this.lineSnap=void 0,this.mutateFeature=void 0,this.readFeature=void 0,this.updateOptions(e)}updateOptions(e){if(super.updateOptions(e),this.cursors=e&&e.cursors?Zv({},this.cursors,e.cursors):Ub,e?.keyEvents===null?this.keyEvents={deselect:null,delete:null,rotate:null,scale:null}:e!=null&&e.keyEvents&&(this.keyEvents=Zv({},this.keyEvents,e.keyEvents)),e?.dragEventThrottle!==void 0&&(this.dragEventThrottle=e.dragEventThrottle),e?.allowManualDeselection!==void 0&&(this.allowManualDeselection=e.allowManualDeselection),e?.allowManualSelection!==void 0&&(this.allowManualSelection=e.allowManualSelection),e!=null&&e.flags){this.flags=Zv({},this.flags,e.flags),this.validations={};for(let e in this.flags){let t=this.flags[e].feature;t&&t.validation&&(this.validations[e]=t.validation)}}}selectFeature(e){this.select(e,!1)}setSelecting(){if(this._state!==`started`)throw Error(`Mode must be started to move to selecting state`);this._state=`selecting`}registerBehaviors(e){this.readFeature=new Vy(e),this.mutateFeature=new Ry(e,{validate:(e,t)=>{let n=e.properties.mode;return this.validations&&this.validations[n]?this.validations[n](e,t):{valid:!0}}}),this.pixelDistance=new Wy(e),this.clickBoundingBox=new Uy(e),this.featuresAtMouseEvent=new Mb(e,this.clickBoundingBox,this.pixelDistance),this.selectionPoints=new kb(e,this.mutateFeature),this.coordinatePoints=new db(e,this.readFeature,this.mutateFeature),this.midPoints=new Ob(e,this.selectionPoints,this.coordinatePoints,this.mutateFeature,this.readFeature,this.pixelDistance),this.coordinateSnap=new Gy(e,this.pixelDistance,this.clickBoundingBox),this.lineSnap=new ob(e,this.pixelDistance,this.clickBoundingBox),this.rotateFeature=new Rb(e,this.selectionPoints,this.midPoints,this.coordinatePoints,this.readFeature,this.mutateFeature),this.dragFeature=new Nb(e,this.featuresAtMouseEvent,this.selectionPoints,this.midPoints,this.coordinatePoints,this.readFeature,this.mutateFeature),this.dragCoordinate=new Pb(e,this.pixelDistance,this.selectionPoints,this.midPoints,this.coordinatePoints,this.coordinateSnap,this.lineSnap,this.readFeature,this.mutateFeature),this.dragCoordinateResizeFeature=new Vb(e,this.pixelDistance,this.selectionPoints,this.midPoints,this.coordinatePoints,this.readFeature,this.mutateFeature),this.scaleFeature=new zb(e,this.dragCoordinateResizeFeature)}deselectFeature(e){this.deselect(e)}deselect(e){this.selected.includes(e)&&(this.mutateFeature.setDeselected(this.selected),this.onDeselect(this.selected[0]),this.selected=[],this.selectionPoints.delete(),this.midPoints.delete(),this.dragTarget={type:`none`})}deleteSelected(){this.selected.length&&this.mutateFeature.deleteFeaturesIfPresent(this.selected),this.selected=[],this.dragTarget={type:`none`}}clearDragTargetAndCursor(){this.dragTarget={type:`none`},this.setCursor(`unset`)}getSelectedFlags(e){let t=this.readFeature.getProperties(e),n=this.flags[t.mode]?.feature,r=n?.coordinates;return{featureFlags:n,coordinatesFlags:r,hasDraggableFlags:n&&(n.draggable||r?.draggable||r?.resizable||typeof r?.midpoints==`object`&&r.midpoints.draggable)}}onRightClick(e){if(!this.selectionPoints.ids.length)return;let t,n=1/0;if(this.selectionPoints.ids.forEach(r=>{let i=this.readFeature.getGeometry(r),a=this.pixelDistance.measure(e,i.coordinates);a<this.pointerDistance&&a<n&&(n=a,t=this.readFeature.getProperties(r))}),!t)return;let r=t.selectionPointFeatureId,i=t.index,a=this.readFeature.getProperties(r),o=this.flags[a.mode];if(!(o&&o.feature&&o.feature.coordinates&&o.feature.coordinates.deletable))return;let s=this.readFeature.getGeometry(r),c;if(s.type===`Polygon`){if(c=s.coordinates[0],c.length<=4)return}else if(s.type!==`LineString`||(c=s.coordinates,c.length<=2))return;s.type!==`Polygon`||i!==0&&i!==c.length-1?c.splice(i,1):(c.shift(),c.pop(),c.push([c[0][0],c[0][1]]));let l=null;if(s.type===`Polygon`?l=this.mutateFeature.updatePolygon({featureId:r,coordinateMutations:{type:Ly,coordinates:[c]},context:{updateType:ny.Commit}}):s.type===`LineString`&&(l=this.mutateFeature.updateLineString({featureId:r,coordinateMutations:{type:Ly,coordinates:c},context:{updateType:ny.Commit}})),!l)return;let u=l.geometry.coordinates;this.mutateFeature.deleteFeaturesIfPresent([...this.midPoints.ids,...this.selectionPoints.ids]),a.coordinatePointIds&&this.coordinatePoints.createOrUpdate({featureId:r,featureCoordinates:u}),this.selectionPoints.create({featureCoordinates:u,featureId:r}),o&&o.feature&&o.feature.coordinates&&o.feature.coordinates.midpoints&&this.midPoints.create({featureCoordinates:u,featureId:r}),this.onFinish(r,{action:ey,mode:this.mode})}select(e,t=!0){if(this.selected[0]===e)return;let{mode:n}=this.readFeature.getProperties(e),r=this.flags[n];if(!r||!r.feature)return;let i=this.selected[0];if(i){if(i===e)return;this.deselect(i)}t&&this.setCursor(this.getPointerOverFeatureCursor()),this.selected=[e],this.mutateFeature.setSelected(e),this.onSelect(e);let{type:a,coordinates:o}=this.readFeature.getGeometry(e);a!==`LineString`&&a!==`Polygon`||o&&r&&r.feature.coordinates&&(this.selectionPoints.create({featureCoordinates:o,featureId:e}),r.feature.coordinates.midpoints&&this.midPoints.create({featureCoordinates:o,featureId:e}))}onLeftClick(e){let{clickedFeature:t}=this.featuresAtMouseEvent.find(e,this.selected.length>0),n=this.midPoints.getNearestMidPoint(e),r=this.selected[0];if(r){var i;let{featureFlags:t}=this.getSelectedFlags(r);if(t!=null&&(i=t.coordinates)!=null&&i.midpoints&&n){if(t.coordinates.draggable){let t=this.pixelDistance.measure(e,this.readFeature.getGeometry(n).coordinates),{dist:i}=this.dragCoordinate.getDraggable(e,r);if(i!==void 0&&t>i)return}this.midPoints.insert({featureId:r,midPointId:n}),this.onFinish(this.selected[0],{action:ty,mode:this.mode});return}}if(t!=null&&t.id)this.allowManualSelection&&this.select(t.id,!0);else if(this.selected.length&&this.allowManualDeselection)return void this.deselect(this.selected[0])}start(){this.setStarted(),this.setSelecting()}stop(){this.cleanUp(),this.setStarted(),this.setStopped()}onClick(e){e.button===`right`&&this.allowPointerEvent(this.pointerEvents.rightClick,e)||e.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,e)?this.onRightClick(e):e.button===`left`&&this.allowPointerEvent(this.pointerEvents.leftClick,e)&&this.onLeftClick(e)}canScale(e){return this.keyEvents.scale&&this.keyEvents.scale.every(t=>e.heldKeys.includes(t))}canRotate(e){return this.keyEvents.rotate&&this.keyEvents.rotate.every(t=>e.heldKeys.includes(t))}preventDefaultKeyEvent(e){let t=this.canRotate(e),n=this.canScale(e);(t||n)&&e.preventDefault()}onKeyDown(e){this.preventDefaultKeyEvent(e)}onKeyUp(e){if(this.preventDefaultKeyEvent(e),this.keyEvents.delete&&e.key===this.keyEvents.delete){if(!this.selected.length)return;let e=this.selected[0];this.onDeselect(this.selected[0]),this.coordinatePoints.deletePointsByFeatureIds([e]),this.deleteSelected(),this.selectionPoints.delete(),this.midPoints.delete()}else this.keyEvents.deselect&&e.key===this.keyEvents.deselect&&this.cleanUp()}cleanUp(){this.selected.length&&this.deselect(this.selected[0])}onDragStart(e,t){if(!this.allowPointerEvent(this.pointerEvents.onDragStart,e))return;let n=this.selected[0];if(!n)return;let{featureFlags:r,coordinatesFlags:i,hasDraggableFlags:a}=this.getSelectedFlags(n);if(!a)return;this.dragEventCount=0;let o=this.dragTarget.type!==`none`&&this.dragTarget.featureId===n?this.dragTarget:{type:`none`},s=o.type===`coordinate`?o.coordinateIndex:this.dragCoordinate.getDraggableIndex(e,n),c=o.type===`resize`?o.coordinateIndex:this.dragCoordinateResizeFeature.getDraggableIndex(e,n),l=i?.resizable&&c!==-1,u=i?.draggable&&s!==-1,d=i&&typeof i.midpoints==`object`&&i.midpoints.draggable,f=r?.draggable&&(o.type===`feature`||this.dragFeature.canDrag(e,n));if(l)return this.setCursor(this.cursors.dragStart),this.dragCoordinateResizeFeature.startDragging(n,c),void t(!1);if(u)return this.setCursor(this.cursors.dragStart),this.dragCoordinate.startDragging(n,s),void t(!1);if(d){let r=o.type===`midpoint`?o.midPointId:this.midPoints.getNearestMidPoint(e);if(this.selected.length&&r){this.midPoints.insert({featureId:n,midPointId:r}),this.onFinish(this.selected[0],{action:ty,mode:this.mode});let i=this.dragCoordinate.getDraggableIndex(e,n);this.dragCoordinate.startDragging(n,i),t(!1);return}}if(f)return this.setCursor(this.cursors.dragStart),this.dragFeature.startDragging(e,n),void t(!1);this.setCursor(`unset`)}onDrag(e,t){if(!this.allowPointerEvent(this.pointerEvents.onDrag,e))return;let n=this.selected[0];if(!n)return;let r=this.readFeature.getProperties(n),i=this.flags[r.mode],a=!0===(i&&i.feature&&i.feature.selfIntersectable);if(this.dragEventCount++,this.dragEventCount%this.dragEventThrottle!=0){if(i&&i.feature&&i.feature.rotateable&&this.canRotate(e))return t(!1),void this.rotateFeature.rotate(e,n);if(i&&i.feature&&i.feature.scaleable&&this.canScale(e))return t(!1),void this.scaleFeature.scale(e,n);if(this.dragCoordinateResizeFeature.isDragging()&&i.feature&&i.feature.coordinates&&i.feature.coordinates.resizable){if(this.projection===`globe`)throw Error(`Globe is currently unsupported projection for resizable`);t(!1),this.dragCoordinateResizeFeature.drag(e,i.feature.coordinates.resizable);return}if(this.dragCoordinate.isDragging()){var o;let t=(o=i.feature)==null||(o=o.coordinates)==null?void 0:o.snappable,n={toCoordinate:!1};!0===t?n={toCoordinate:!0}:typeof t==`object`&&(n=t),this.dragCoordinate.drag(e,a,n);return}this.dragFeature.isDragging()?this.dragFeature.drag(e):t(!0)}}onDragEnd(e,t){this.allowPointerEvent(this.pointerEvents.onDragEnd,e)&&(this.setCursor(this.cursors.dragEnd),this.dragCoordinate.isDragging()?this.onFinish(this.selected[0],{mode:this.mode,action:`dragCoordinate`}):this.dragFeature.isDragging()?this.onFinish(this.selected[0],{mode:this.mode,action:`dragFeature`}):this.dragCoordinateResizeFeature.isDragging()&&this.onFinish(this.selected[0],{mode:this.mode,action:`dragCoordinateResize`}),this.dragCoordinate.stopDragging(),this.dragFeature.stopDragging(),this.dragCoordinateResizeFeature.stopDragging(),this.rotateFeature.reset(),this.scaleFeature.reset(),t(!0))}onMouseMove(e){let t=this.selected[0];if(!t)return void this.clearDragTargetAndCursor();if(this.dragFeature.isDragging()||this.dragCoordinate.isDragging()||this.dragCoordinateResizeFeature.isDragging())return;let{featureFlags:n}=this.getSelectedFlags(t);if(!n)return void this.clearDragTargetAndCursor();let r,i=n.coordinates;if(i!=null&&i.midpoints&&(r=this.midPoints.getNearestMidPoint(e),r&&(this.dragTarget={type:`midpoint`,featureId:t,midPointId:r},this.setCursor(this.cursors.insertMidpoint))),i&&i.draggable){let{index:n,dist:i}=this.dragCoordinate.getDraggable(e,t);if(n>-1){if(r&&this.pixelDistance.measure(e,this.readFeature.getGeometry(r).coordinates)<i)return;this.dragTarget={type:`coordinate`,featureId:t,coordinateIndex:n},this.setCursor(this.getPointerOverCoordinateCursor());return}}if(i&&i.resizable){let n=this.dragCoordinateResizeFeature.getDraggableIndex(e,t);if(n>-1)return this.dragTarget={type:`resize`,featureId:t,coordinateIndex:n},void this.setCursor(this.getPointerOverResizeHandleCursor())}if(n.draggable&&this.dragFeature.canDrag(e,t)){if(r)return;this.dragTarget={type:`feature`,featureId:t},this.setCursor(this.getPointerOverFeatureCursor());return}r||this.clearDragTargetAndCursor()}styleFeature(e){let t=Zv({},{polygonFillColor:`#3f97e0`,polygonOutlineColor:`#3f97e0`,polygonOutlineWidth:4,polygonOutlineOpacity:1,polygonFillOpacity:.3,pointColor:`#3f97e0`,pointOpacity:1,pointOutlineColor:`#ffffff`,pointOutlineOpacity:1,pointOutlineWidth:0,pointWidth:6,lineStringColor:`#3f97e0`,lineStringWidth:4,lineStringOpacity:1,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0,lineStringDash:void 0});if(e.properties.mode===this.mode&&e.geometry.type===`Point`){if(e.properties[iy.SELECTION_POINT])return t.pointColor=this.getHexColorStylingValue(this.styles.selectionPointColor,t.pointColor,e),t.pointOpacity=this.getNumericStylingValue(this.styles.selectionPointOpacity,1,e),t.pointOutlineColor=this.getHexColorStylingValue(this.styles.selectionPointOutlineColor,t.pointOutlineColor,e),t.pointWidth=this.getNumericStylingValue(this.styles.selectionPointWidth,t.pointWidth,e),t.pointOutlineOpacity=this.getNumericStylingValue(this.styles.selectionPointOutlineOpacity,1,e),t.pointOutlineWidth=this.getNumericStylingValue(this.styles.selectionPointOutlineWidth,2,e),t.zIndex=30,t;if(e.properties[iy.MID_POINT])return t.pointColor=this.getHexColorStylingValue(this.styles.midPointColor,t.pointColor,e),t.pointOpacity=this.getNumericStylingValue(this.styles.midPointOpacity,1,e),t.pointOutlineColor=this.getHexColorStylingValue(this.styles.midPointOutlineColor,t.pointOutlineColor,e),t.pointWidth=this.getNumericStylingValue(this.styles.midPointWidth,4,e),t.pointOutlineOpacity=this.getNumericStylingValue(this.styles.midPointOutlineOpacity,1,e),t.pointOutlineWidth=this.getNumericStylingValue(this.styles.midPointOutlineWidth,2,e),t.zIndex=50,t}else if(e.properties[iy.SELECTED]){if(e.geometry.type===`Point`&&e.properties[ay.MARKER])return t.markerUrl=this.getUrlStylingValue(this.styles.selectedMarkerUrl,ry,e),t.markerHeight=this.getNumericStylingValue(this.styles.selectedMarkerHeight,40,e),t.markerWidth=this.getNumericStylingValue(this.styles.selectedMarkerWidth,32,e),t;if(e.geometry.type===`Polygon`)return t.polygonFillColor=this.getHexColorStylingValue(this.styles.selectedPolygonColor,t.polygonFillColor,e),t.polygonOutlineWidth=this.getNumericStylingValue(this.styles.selectedPolygonOutlineWidth,t.polygonOutlineWidth,e),t.polygonOutlineColor=this.getHexColorStylingValue(this.styles.selectedPolygonOutlineColor,t.polygonOutlineColor,e),t.polygonOutlineOpacity=this.getNumericStylingValue(this.styles.selectedPolygonOutlineOpacity,1,e),t.polygonFillOpacity=this.getNumericStylingValue(this.styles.selectedPolygonFillOpacity,t.polygonFillOpacity,e),t.zIndex=oy,t;if(e.geometry.type===`LineString`)return t.lineStringColor=this.getHexColorStylingValue(this.styles.selectedLineStringColor,t.lineStringColor,e),t.lineStringWidth=this.getNumericStylingValue(this.styles.selectedLineStringWidth,t.lineStringWidth,e),t.zIndex=oy,t;if(e.geometry.type===`Point`)return t.pointWidth=this.getNumericStylingValue(this.styles.selectedPointWidth,t.pointWidth,e),t.pointColor=this.getHexColorStylingValue(this.styles.selectedPointColor,t.pointColor,e),t.pointOpacity=this.getNumericStylingValue(this.styles.selectedPointOpacity,1,e),t.pointOutlineColor=this.getHexColorStylingValue(this.styles.selectedPointOutlineColor,t.pointOutlineColor,e),t.pointOutlineOpacity=this.getNumericStylingValue(this.styles.selectedPointOutlineOpacity,1,e),t.pointOutlineWidth=this.getNumericStylingValue(this.styles.selectedPointOutlineWidth,t.pointOutlineWidth,e),t.zIndex=oy,t}return t}afterFeatureUpdated(e){if(this.selected.length&&e.id===this.selected[0]){var t,n;let r=this.flags[e.properties.mode];if(r==null||(t=r.feature)==null||!t.coordinates)return;let i=e.geometry.type,a=e.id;if(this.selectionPoints.delete(),this.midPoints.delete(),i!==`LineString`&&i!==`Polygon`)return;let o=e.geometry.coordinates;this.selectionPoints.create({featureCoordinates:o,featureId:a}),r!=null&&(n=r.feature)!=null&&(n=n.coordinates)!=null&&n.midpoints&&this.midPoints.create({featureCoordinates:o,featureId:a})}}},Gb=class extends py{constructor(...e){super(...e),this.type=dy.Static,this.mode=`static`}start(){}stop(){}onKeyUp(){}onKeyDown(){}onClick(){}onDragStart(){}onDrag(){}onDragEnd(){}onMouseMove(){}cleanUp(){}styleFeature(){return Zv({},{polygonFillColor:`#3f97e0`,polygonOutlineColor:`#3f97e0`,polygonOutlineWidth:4,polygonOutlineOpacity:1,polygonFillOpacity:.3,pointColor:`#3f97e0`,pointOpacity:1,pointOutlineColor:`#ffffff`,pointOutlineOpacity:1,pointOutlineWidth:0,pointWidth:6,lineStringColor:`#3f97e0`,lineStringWidth:4,lineStringOpacity:1,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0,lineStringDash:void 0})}};function Kb(e,t,n,r,i){for(;r>n;){if(r-n>600){let a=r-n+1,o=t-n+1,s=Math.log(a),c=.5*Math.exp(2*s/3),l=.5*Math.sqrt(s*c*(a-c)/a)*(o-a/2<0?-1:1);Kb(e,t,Math.max(n,Math.floor(t-o*c/a+l)),Math.min(r,Math.floor(t+(a-o)*c/a+l)),i)}let a=e[t],o=n,s=r;for(qb(e,n,t),i(e[r],a)>0&&qb(e,n,r);o<s;){for(qb(e,o,s),o++,s--;i(e[o],a)<0;)o++;for(;i(e[s],a)>0;)s--}i(e[n],a)===0?qb(e,n,s):(s++,qb(e,s,r)),s<=t&&(n=s+1),t<=s&&(r=s-1)}}function qb(e,t,n){let r=e[t];e[t]=e[n],e[n]=r}function Jb(e,t){Yb(e,0,e.children.length,t,e)}function Yb(e,t,n,r,i){i||=ix([]),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(let a=t;a<n;a++){let t=e.children[a];Xb(i,e.leaf?r(t):t)}return i}function Xb(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function Zb(e,t){return e.minX-t.minX}function Qb(e,t){return e.minY-t.minY}function $b(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function ex(e){return e.maxX-e.minX+(e.maxY-e.minY)}function tx(e,t){let n=Math.max(e.minX,t.minX),r=Math.max(e.minY,t.minY),i=Math.min(e.maxX,t.maxX),a=Math.min(e.maxY,t.maxY);return Math.max(0,i-n)*Math.max(0,a-r)}function nx(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function rx(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function ix(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function ax(e,t,n,r,i){let a=[t,n];for(;a.length;){if((n=a.pop())-(t=a.pop())<=r)continue;let o=t+Math.ceil((n-t)/r/2)*r;Kb(e,o,t,n,i),a.push(t,o,o,n)}}var ox=class{constructor(e){this._maxEntries=void 0,this._minEntries=void 0,this.data=void 0,this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}search(e){let t=this.data,n=[];if(!rx(e,t))return n;let r=this.toBBox,i=[];for(;t;){for(let a=0;a<t.children.length;a++){let o=t.children[a],s=t.leaf?r(o):o;rx(e,s)&&(t.leaf?n.push(o):nx(e,s)?this._all(o,n):i.push(o))}t=i.pop()}return n}collides(e){let t=this.data;if(rx(e,t)){let n=[];for(;t;){for(let r=0;r<t.children.length;r++){let i=t.children[r],a=t.leaf?this.toBBox(i):i;if(rx(e,a)){if(t.leaf||nx(e,a))return!0;n.push(i)}}t=n.pop()}}return!1}load(e){if(e.length<this._minEntries){for(let t=0;t<e.length;t++)this.insert(e[t]);return}let t=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===t.height)this._splitRoot(this.data,t);else{if(this.data.height<t.height){let e=this.data;this.data=t,t=e}this._insert(t,this.data.height-t.height-1,!0)}else this.data=t}insert(e){this._insert(e,this.data.height-1)}clear(){this.data=ix([])}remove(e){let t=this.data,n=this.toBBox(e),r=[],i=[],a,o,s=!1;for(;t||r.length;){if(t||(t=r.pop(),o=r[r.length-1],a=i.pop(),s=!0),t.leaf){let n=t.children.indexOf(e);n!==-1&&(t.children.splice(n,1),r.push(t),this._condense(r))}s||t.leaf||!nx(t,n)?o?(a++,t=o.children[a],s=!1):t=null:(r.push(t),i.push(a),a=0,o=t,t=t.children[0])}}toBBox(e){return e}compareMinX(e,t){return e.minX-t.minX}compareMinY(e,t){return e.minY-t.minY}_all(e,t){let n=[];for(;e;)e.leaf?t.push(...e.children):n.push(...e.children),e=n.pop();return t}_build(e,t,n,r){let i=n-t+1,a,o=this._maxEntries;if(i<=o)return a=ix(e.slice(t,n+1)),Jb(a,this.toBBox),a;r||(r=Math.ceil(Math.log(i)/Math.log(o)),o=Math.ceil(i/o**(r-1))),a=ix([]),a.leaf=!1,a.height=r;let s=Math.ceil(i/o),c=s*Math.ceil(Math.sqrt(o));ax(e,t,n,c,this.compareMinX);for(let i=t;i<=n;i+=c){let t=Math.min(i+c-1,n);ax(e,i,t,s,this.compareMinY);for(let n=i;n<=t;n+=s){let i=Math.min(n+s-1,t);a.children.push(this._build(e,n,i,r-1))}}return Jb(a,this.toBBox),a}_chooseSubtree(e,t,n,r){for(;r.push(t),!t.leaf&&r.length-1!==n;){let n,r=1/0,o=1/0;for(let s=0;s<t.children.length;s++){let c=t.children[s],l=$b(c),u=(i=e,a=c,(Math.max(a.maxX,i.maxX)-Math.min(a.minX,i.minX))*(Math.max(a.maxY,i.maxY)-Math.min(a.minY,i.minY))-l);u<o?(o=u,r=l<r?l:r,n=c):u===o&&l<r&&(r=l,n=c)}t=n||t.children[0]}var i,a;return t}_insert(e,t,n){let r=n?e:this.toBBox(e),i=[],a=this._chooseSubtree(r,this.data,t,i);for(a.children.push(e),Xb(a,r);t>=0&&i[t].children.length>this._maxEntries;)this._split(i,t),t--;this._adjustParentBBoxes(r,i,t)}_split(e,t){let n=e[t],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);let a=this._chooseSplitIndex(n,i,r),o=ix(n.children.splice(a,n.children.length-a));o.height=n.height,o.leaf=n.leaf,Jb(n,this.toBBox),Jb(o,this.toBBox),t?e[t-1].children.push(o):this._splitRoot(n,o)}_splitRoot(e,t){this.data=ix([e,t]),this.data.height=e.height+1,this.data.leaf=!1,Jb(this.data,this.toBBox)}_chooseSplitIndex(e,t,n){let r,i=1/0,a=1/0;for(let o=t;o<=n-t;o++){let t=Yb(e,0,o,this.toBBox),s=Yb(e,o,n,this.toBBox),c=tx(t,s),l=$b(t)+$b(s);c<i?(i=c,r=o,a=l<a?l:a):c===i&&l<a&&(a=l,r=o)}return r||n-t}_chooseSplitAxis(e,t,n){let r=e.leaf?this.compareMinX:Zb,i=e.leaf?this.compareMinY:Qb;this._allDistMargin(e,t,n,r)<this._allDistMargin(e,t,n,i)&&e.children.sort(r)}_allDistMargin(e,t,n,r){e.children.sort(r);let i=this.toBBox,a=Yb(e,0,t,i),o=Yb(e,n-t,n,i),s=ex(a)+ex(o);for(let r=t;r<n-t;r++){let t=e.children[r];Xb(a,e.leaf?i(t):t),s+=ex(a)}for(let r=n-t-1;r>=t;r--){let t=e.children[r];Xb(o,e.leaf?i(t):t),s+=ex(o)}return s}_adjustParentBBoxes(e,t,n){for(let r=n;r>=0;r--)Xb(t[r],e)}_condense(e){for(let t,n=e.length-1;n>=0;n--)e[n].children.length===0?n>0?(t=e[n-1].children,t.splice(t.indexOf(e[n]),1)):this.clear():Jb(e[n],this.toBBox)}},sx=class{constructor(e){this.tree=void 0,this.idToNode=void 0,this.nodeToId=void 0,this.tree=new ox(e&&e.maxEntries?e.maxEntries:9),this.idToNode=new Map,this.nodeToId=new Map}setMaps(e,t){this.idToNode.set(e.id,t),this.nodeToId.set(t,e.id)}toBBox(e){let t=[],n=[],r;if(e.geometry.type===`Polygon`)r=e.geometry.coordinates[0];else if(e.geometry.type===`LineString`)r=e.geometry.coordinates;else{if(e.geometry.type!==`Point`)throw Error(`Not a valid feature to turn into a bounding box`);r=[e.geometry.coordinates]}for(let e=0;e<r.length;e++)n.push(r[e][1]),t.push(r[e][0]);let i=Math.min(...n),a=Math.max(...n);return{minX:Math.min(...t),minY:i,maxX:Math.max(...t),maxY:a}}insert(e){if(this.idToNode.get(String(e.id)))throw Error(`Feature already exists`);let t=this.toBBox(e);this.setMaps(e,t),this.tree.insert(t)}load(e){let t=[],n=new Set;e.forEach(e=>{let r=this.toBBox(e);if(this.setMaps(e,r),n.has(String(e.id)))throw Error(`Duplicate feature ID found ${e.id}`);n.add(String(e.id)),t.push(r)}),this.tree.load(t)}update(e){this.remove(e.id);let t=this.toBBox(e);this.setMaps(e,t),this.tree.insert(t)}remove(e){let t=this.idToNode.get(e);if(!t)throw Error(`${e} not inserted into the spatial index`);this.tree.remove(t)}clear(){this.tree.clear()}search(e){return this.tree.search(this.toBBox(e)).map(e=>this.nodeToId.get(e))}collides(e){return this.tree.collides(this.toBBox(e))}},cx={getId:()=>`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,function(e){let t=16*Math.random()|0;return(e==`x`?t:3&t|8).toString(16)}),isValidId:e=>typeof e==`string`&&e.length===36},lx={target:`geometry`},ux={target:`properties`},dx=class{constructor(e){this.idStrategy=void 0,this.tracked=void 0,this.spatialIndex=void 0,this.store=void 0,this._onChange=()=>{},this.store={},this.spatialIndex=new sx,this.tracked=!e||!1!==e.tracked,this.idStrategy=e&&e.idStrategy?e.idStrategy:cx}clone(e){return JSON.parse(JSON.stringify(e))}getId(){return this.idStrategy.getId()}has(e){return!!this.store[e]}load(e,t,n,r){if(e.length===0)return[];let i=this.clone(e),a=[],o=[];i=i.filter(e=>{e.id??=this.idStrategy.getId();let n=e.id;if(t){let r=t(e);if(!r.valid)return a.push({id:n,valid:!1,reason:r.reason}),!1}if(this.tracked){if(e.properties.createdAt){if(!ly(e.properties.createdAt))return a.push({id:e.id,valid:!1,reason:`createdAt is not a valid numeric timestamp`}),!1}else e.properties.createdAt=+new Date;if(e.properties.updatedAt){if(!ly(e.properties.updatedAt))return a.push({id:e.id,valid:!1,reason:`updatedAt is not a valid numeric timestamp`}),!1}else e.properties.updatedAt=+new Date}return this.has(n)?(a.push({id:n,valid:!1,reason:`Feature already exists with this id: ${n}`}),!1):(this.store[n]=e,o.push(e),a.push({id:n,valid:!0}),!0)}),this.spatialIndex.load(i);let s=o.map(({id:e})=>e);return s.length>0&&(this._onChange(s,`create`,r),n&&o.forEach(e=>{n(e)})),a}search(e,t){let n=this.spatialIndex.search(e).map(e=>this.store[e]);return this.clone(t?n.filter(t):n)}registerOnChange(e){this._onChange=(t,n,r)=>{e(t,n,r)}}getGeometryCopy(e){let t=this.store[e];if(!t)throw Error(`No feature with this id (${e}), can not get geometry copy`);return this.clone(t.geometry)}getPropertiesCopy(e){let t=this.store[e];if(!t)throw Error(`No feature with this id (${e}), can not get properties copy`);return this.clone(t.properties)}updateProperty(e,t){let n=new Set;e.forEach(({id:e,property:t,value:r})=>{let i=this.store[e];if(!i)throw Error(`No feature with this (${e}), can not update geometry`);i.properties[t]!==r&&(n.add(e),r===void 0?delete i.properties[t]:i.properties[t]=r,this.tracked&&(i.properties.updatedAt=+new Date))}),this._onChange&&n.size>0&&this._onChange(Array.from(n),`update`,t?Zv({},t,ux):ux)}updateGeometry(e,t){let n=new Set;e.forEach(({id:e,geometry:t})=>{n.add(e);let r=this.store[e];if(!r)throw Error(`No feature with this (${e}), can not update geometry`);r.geometry=this.clone(t),this.spatialIndex.update(r),this.tracked&&(r.properties.updatedAt=+new Date)}),this._onChange&&n.size>0&&this._onChange(Array.from(n),`update`,t?Zv({},t,lx):lx)}create(e,t){let n=[];return e.forEach(({geometry:e,properties:t})=>{let r,i=Zv({},t);this.tracked&&(r=+new Date,t?(i.createdAt=typeof t.createdAt==`number`?t.createdAt:r,i.updatedAt=typeof t.updatedAt==`number`?t.updatedAt:r):i={createdAt:r,updatedAt:r});let a=this.getId(),o={id:a,type:`Feature`,geometry:e,properties:i};this.store[a]=o,this.spatialIndex.insert(o),n.push(a)}),this._onChange&&this._onChange([...n],`create`,t),n}delete(e,t){e.forEach(e=>{if(!this.store[e])throw Error(`No feature with id ${e}, can not delete`);delete this.store[e],this.spatialIndex.remove(e)}),this._onChange&&this._onChange([...e],`delete`,t)}copy(e){return this.clone(this.store[e])}copyAll(){return this.clone(Object.keys(this.store).map(e=>this.store[e]))}copyAllWhere(e){return this.clone(Object.keys(this.store).map(e=>this.store[e]).filter(t=>t.properties&&e(t.properties)))}clear(e){let t=Object.keys(this.store);this.store={},this.spatialIndex.clear(),this._onChange(t,`delete`,e)}size(){return Object.keys(this.store).length}};Math.PI/180;var fx=class{constructor({name:e,callback:t,unregister:n,register:r}){this.name=void 0,this.callback=void 0,this.registered=!1,this.register=void 0,this.unregister=void 0,this.name=e,this.register=()=>{this.registered||(this.registered=!0,r(t))},this.unregister=()=>{this.register&&(this.registered=!1,n(t))},this.callback=t}},px={__proto__:null,GeoJSONStore:dx,TerraDrawBaseDrawMode:py,TerraDrawBaseSelectMode:my,TerraDrawBaseAdapter:class{constructor(e){this._nextKeyUpIsContextMenu=!1,this._lastPointerDownEventTarget=void 0,this._ignoreMismatchedPointerEvents=!1,this._minPixelDragDistance=void 0,this._minPixelDragDistanceDrawing=void 0,this._minPixelDragDistanceSelecting=void 0,this._lastDrawEvent=void 0,this._coordinatePrecision=void 0,this._heldKeys=new Set,this._listeners=[],this._dragState=`not-dragging`,this._currentModeCallbacks=void 0,this._ignoreMismatchedPointerEvents=typeof e.ignoreMismatchedPointerEvents==`boolean`&&e.ignoreMismatchedPointerEvents,this._minPixelDragDistance=typeof e.minPixelDragDistance==`number`?e.minPixelDragDistance:1,this._minPixelDragDistanceSelecting=typeof e.minPixelDragDistanceSelecting==`number`?e.minPixelDragDistanceSelecting:1,this._minPixelDragDistanceDrawing=typeof e.minPixelDragDistanceDrawing==`number`?e.minPixelDragDistanceDrawing:8,this._coordinatePrecision=typeof e.coordinatePrecision==`number`?e.coordinatePrecision:9}getButton(e){return e.button===-1?`neither`:e.button===0?`left`:e.button===1?`middle`:e.button===2?`right`:`neither`}getMapElementXYPosition(e){let{left:t,top:n}=this.getMapEventElement(e.type).getBoundingClientRect();return{containerX:e.clientX-t,containerY:e.clientY-n}}getDrawEventFromEvent(e,t=!1){let n=this.getLngLatFromEvent(e);if(!n)return null;let{lng:r,lat:i}=n,{containerX:a,containerY:o}=this.getMapElementXYPosition(e),s=this.getButton(e),c=Array.from(this._heldKeys);return{lng:by(r,this._coordinatePrecision),lat:by(i,this._coordinatePrecision),containerX:a,containerY:o,button:s,heldKeys:c,isContextMenu:t}}register(e){this._currentModeCallbacks=e,this._listeners=this.getAdapterListeners(),this._listeners.forEach(e=>{e.register()})}getCoordinatePrecision(){return this._coordinatePrecision}getAdapterListeners(){return[new fx({name:`pointerdown`,callback:e=>{if(!this._currentModeCallbacks||!e.isPrimary)return;let t=this.getDrawEventFromEvent(e);t&&(this._dragState=`pre-dragging`,this._lastDrawEvent=t,this._lastPointerDownEventTarget=e.target?e.target:void 0)},register:e=>{this.getMapEventElement(`pointerdown`).addEventListener(`pointerdown`,e)},unregister:e=>{this.getMapEventElement(`pointerdown`).removeEventListener(`pointerdown`,e)}}),new fx({name:`pointermove`,callback:e=>{if(!this._currentModeCallbacks||!e.isPrimary)return;e.preventDefault();let t=this.getDrawEventFromEvent(e);if(t)if(this._dragState===`not-dragging`)this._currentModeCallbacks.onMouseMove(t),this._lastDrawEvent=t;else if(this._dragState===`pre-dragging`){if(!this._lastDrawEvent)return;let e={x:this._lastDrawEvent.containerX,y:this._lastDrawEvent.containerY},n={x:t.containerX,y:t.containerY},r=this._currentModeCallbacks.getState(),i=zy(e,n),a=!1;if(a=r===`drawing`?i<this._minPixelDragDistanceDrawing:r===`selecting`?i<this._minPixelDragDistanceSelecting:i<this._minPixelDragDistance,a)return;this._nextKeyUpIsContextMenu=!1,this._dragState=`dragging`,this._currentModeCallbacks.onDragStart(t,e=>{this.setDraggability.bind(this)(e)})}else this._dragState===`dragging`&&this._currentModeCallbacks.onDrag(t,e=>{this.setDraggability.bind(this)(e)})},register:e=>{this.getMapEventElement(`pointermove`).addEventListener(`pointermove`,e)},unregister:e=>{this.getMapEventElement(`pointermove`).removeEventListener(`pointermove`,e)}}),new fx({name:`contextmenu`,callback:e=>{this._currentModeCallbacks&&(e.preventDefault(),this._nextKeyUpIsContextMenu=!0)},register:e=>{this.getMapEventElement(`contextmenu`).addEventListener(`contextmenu`,e)},unregister:e=>{this.getMapEventElement(`contextmenu`).removeEventListener(`contextmenu`,e)}}),new fx({name:`pointerup`,callback:e=>{if(!this._currentModeCallbacks||e.target!==this.getMapEventElement(`pointerup`)||this._ignoreMismatchedPointerEvents&&this._lastPointerDownEventTarget!==e.target||(this._lastPointerDownEventTarget=void 0,!e.isPrimary))return;let t=this.getDrawEventFromEvent(e);t&&(this._dragState===`dragging`?this._currentModeCallbacks.onDragEnd(t,e=>{this.setDraggability.bind(this)(e)}):this._dragState!==`not-dragging`&&this._dragState!==`pre-dragging`||(this._nextKeyUpIsContextMenu&&=(t.isContextMenu=!0,!1),this._currentModeCallbacks.onClick(t)),this._dragState=`not-dragging`,this.setDraggability(!0))},register:e=>{this.getMapEventElement(`pointerup`).addEventListener(`pointerup`,e)},unregister:e=>{this.getMapEventElement(`pointerup`).removeEventListener(`pointerup`,e)}}),new fx({name:`keyup`,callback:e=>{this._currentModeCallbacks&&(this._heldKeys.delete(e.key),this._currentModeCallbacks.onKeyUp({key:e.key,heldKeys:Array.from(this._heldKeys),preventDefault:()=>e.preventDefault()}))},register:e=>{this.getMapEventElement(`keyup`).addEventListener(`keyup`,e)},unregister:e=>{this.getMapEventElement(`keyup`).removeEventListener(`keyup`,e)}}),new fx({name:`keydown`,callback:e=>{this._currentModeCallbacks&&(this._heldKeys.add(e.key),this._currentModeCallbacks.onKeyDown({key:e.key,heldKeys:Array.from(this._heldKeys),preventDefault:()=>e.preventDefault()}))},register:e=>{this.getMapEventElement(`keydown`).addEventListener(`keydown`,e)},unregister:e=>{this.getMapEventElement(`keydown`).removeEventListener(`keydown`,e)}})]}unregister(){this._listeners.forEach(e=>{e.unregister()}),this.clear(),this._currentModeCallbacks=void 0,this._lastDrawEvent=void 0,this._lastPointerDownEventTarget=void 0,this._nextKeyUpIsContextMenu=!1}},getDefaultStyling:()=>({polygonFillColor:`#3f97e0`,polygonOutlineColor:`#3f97e0`,polygonOutlineWidth:4,polygonOutlineOpacity:1,polygonFillOpacity:.3,pointColor:`#3f97e0`,pointOpacity:1,pointOutlineColor:`#ffffff`,pointOutlineOpacity:1,pointOutlineWidth:0,pointWidth:6,lineStringColor:`#3f97e0`,lineStringWidth:4,lineStringOpacity:1,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0,lineStringDash:void 0}),SELECT_PROPERTIES:iy};function mx(e){if(e===null||typeof e==`boolean`||typeof e==`string`)return!0;if(e===void 0)return!1;if(typeof e==`number`)return Number.isFinite(e);if(typeof e==`bigint`||typeof e==`symbol`||typeof e==`function`||e instanceof RegExp||e instanceof Map||e instanceof Set||e instanceof Date)return!1;if(typeof e==`object`&&e&&!Array.isArray(e)){let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return!1}if(ArrayBuffer.isView(e)&&!(e instanceof DataView))return!1;if(Array.isArray(e)){for(let t of e)if(!mx(t))return!1}return typeof e==`object`&&Object.keys(e).every(t=>typeof t==`string`&&mx(e[t]))}var hx=`push`,gx=`mode`,_x=`session`,vx=class{constructor(e){this.modeLevel=void 0,this.sessionLevel=void 0,this.shouldPreferMode=void 0,this.onHistoryChange=void 0,this.shouldEmitHistoryChange=void 0,this.modeLevel=e.modeLevel,this.sessionLevel=e.sessionLevel,this.shouldPreferMode=e.shouldPreferMode,this.onHistoryChange=e.onHistoryChange,this.shouldEmitHistoryChange=e.shouldEmitHistoryChange??(()=>!0)}emitStackHistoryChange(e){this.shouldEmitHistoryChange()&&this.onHistoryChange&&this.onHistoryChange({cause:e.cause,stack:e.stack,undoSize:e.undoStackSize,redoSize:e.redoStackSize})}hasSessionUndo(){return!!(this.sessionLevel&&this.sessionLevel.canUndo())}hasSessionRedo(){return!!(this.sessionLevel&&this.sessionLevel.canRedo())}activeStackForUndo(){var e,t;return this.shouldPreferMode()&&(e=this.modeLevel)!=null&&e.canUndo()?gx:this.hasSessionUndo()?_x:(t=this.modeLevel)!=null&&t.canUndo()?gx:void 0}activeStackForRedo(){var e,t;return this.shouldPreferMode()&&(e=this.modeLevel)!=null&&e.canRedo()?gx:this.hasSessionRedo()?_x:(t=this.modeLevel)!=null&&t.canRedo()?gx:void 0}canUndo(){return this.activeStackForUndo()!==void 0}canRedo(){return this.activeStackForRedo()!==void 0}undo(){let e=this.activeStackForUndo();return!!e&&(e===gx?!!this.modeLevel&&this.modeLevel.undo():!(!this.sessionLevel||!this.sessionLevel.canUndo())&&this.sessionLevel.undo())}redo(){let e=this.activeStackForRedo();return!!e&&(e===gx?!!this.modeLevel&&this.modeLevel.redo():!(!this.sessionLevel||!this.sessionLevel.canRedo())&&this.sessionLevel.redo())}clearHistory(){this.modeLevel&&this.modeLevel.clearHistory(),this.sessionLevel&&this.sessionLevel.clearHistory()}emitHistoryPushForCompletedAction(){this.sessionLevel?this.emitStackHistoryChange({cause:hx,undoStackSize:this.sessionLevel.undoSize(),redoStackSize:this.sessionLevel.redoSize(),stack:_x}):this.modeLevel&&this.emitStackHistoryChange({cause:hx,undoStackSize:this.modeLevel.undoSize(),redoStackSize:this.modeLevel.redoSize(),stack:gx})}},yx=class{constructor(e){var t,n,r,i;this._modes=void 0,this._mode=void 0,this._adapter=void 0,this._enabled=!1,this._store=void 0,this._eventListeners=void 0,this._instanceSelectModes=void 0,this.sessionUndoRedoEnabled=!1,this.keyboardShortcutsMatcher=void 0,this.drawingUndoRedo=void 0,this.sessionUndoRedo=void 0,this.undoRedoCoordinator=void 0,this._adapter=e.adapter,this._instanceSelectModes=[];let a=e==null||(t=e.undoRedo)==null?void 0:t.modeLevel;a&&(this.drawingUndoRedo=a);let o=e==null||(n=e.undoRedo)==null?void 0:n.keyboardShortcuts;o&&(this.keyboardShortcutsMatcher=o),this.sessionUndoRedoEnabled=!!(!(e==null||(r=e.undoRedo)==null)&&r.sessionLevel);let s=e==null||(i=e.undoRedo)==null?void 0:i.sessionLevel;this._mode=new Gb;let c=new Set,l=e.modes.reduce((e,t)=>{if(c.has(t.mode))throw Error(`There is already a ${t.mode} mode provided`);return c.add(t.mode),e[t.mode]=t,e},{}),u=Object.keys(l);if(u.length===0)throw Error(`No modes provided`);u.forEach(e=>{l[e].type===dy.Select&&this._instanceSelectModes.push(e)}),this._modes=Zv({},l,{static:this._mode}),this._eventListeners={change:[],select:[],deselect:[],finish:[],ready:[],history:[]},this._store=new dx({tracked:!!e.tracked,idStrategy:e.idStrategy?e.idStrategy:void 0});let d=e=>{let t=[];return{changed:t,unchanged:this._store.copyAll().filter(n=>!e.includes(n.id)||(t.push(n),!1))}},f=(e,t)=>{var n;this._enabled&&(this._eventListeners.finish.forEach(n=>{n(e,t)}),(n=this.undoRedoCoordinator)==null||n.emitHistoryPushForCompletedAction())},p=(e,t,n)=>{if(!this._enabled)return;this._eventListeners.change.forEach(r=>{r(e,t,n)}),this.emitDrawingPushIfHistoryChangedFromLastSnapshot();let{changed:r,unchanged:i}=d(e);t===`create`?this._adapter.render({created:r,deletedIds:[],unchanged:i,updated:[]},this.getModeStyles()):t===`update`?this._adapter.render({created:[],deletedIds:[],unchanged:i,updated:r},this.getModeStyles()):t===`delete`?this._adapter.render({created:[],deletedIds:e,unchanged:i,updated:[]},this.getModeStyles()):t===`styling`&&this._adapter.render({created:[],deletedIds:[],unchanged:i,updated:[]},this.getModeStyles())},m=e=>{if(!this._enabled)return;this._eventListeners.select.forEach(t=>{t(e)});let{changed:t,unchanged:n}=d([e]);this._adapter.render({created:[],deletedIds:[],unchanged:n,updated:t},this.getModeStyles())},h=e=>{if(!this._enabled)return;this._eventListeners.deselect.forEach(t=>{t(e)});let{changed:t,unchanged:n}=d([e]);t&&this._adapter.render({created:[],deletedIds:[],unchanged:n,updated:t},this.getModeStyles())};Object.keys(this._modes).forEach(e=>{var t;this._modes[e].register({mode:e,store:this._store,setCursor:this._adapter.setCursor.bind(this._adapter),project:this._adapter.project.bind(this._adapter),unproject:this._adapter.unproject.bind(this._adapter),setDoubleClickToZoom:this._adapter.setDoubleClickToZoom.bind(this._adapter),onChange:p,onSelect:m,onDeselect:h,onFinish:f,coordinatePrecision:this._adapter.getCoordinatePrecision(),undoRedoMaxStackSize:(t=this.drawingUndoRedo)==null||t.getMaxStackSize==null?void 0:t.getMaxStackSize()})}),this.sessionUndoRedoEnabled&&s&&(this.sessionUndoRedo=s,s.register({draw:this,onHistoryChange:e=>{var t;(t=this.undoRedoCoordinator)==null||t.emitStackHistoryChange(e)}})),this.drawingUndoRedo&&this.drawingUndoRedo.register({getModeState:()=>this.getModeState(),getModeHistorySizes:()=>this.getDrawingHistorySizes(),undoMode:()=>{this._mode.undo&&this._mode.undo()},redoMode:()=>{this._mode.redo&&this._mode.redo()},clearModeHistory:()=>{let e=this._mode;e.clearHistory&&e.clearHistory()},onHistoryChange:e=>{var t;(t=this.undoRedoCoordinator)==null||t.emitStackHistoryChange(e)}}),this.undoRedoCoordinator=new vx({modeLevel:this.drawingUndoRedo,sessionLevel:this.sessionUndoRedo,shouldPreferMode:()=>this.getModeState()===`drawing`,onHistoryChange:e=>{this._eventListeners.history.forEach(t=>{t(e)})},shouldEmitHistoryChange:()=>this._enabled})}checkEnabled(){if(!this._enabled)throw Error(`Terra Draw is not enabled`)}handleUndoRedoKeyboardShortcut(e){if(!this.drawingUndoRedo&&!this.sessionUndoRedoEnabled||!this.keyboardShortcutsMatcher)return!1;let t=this.keyboardShortcutsMatcher.isUndoKeyboardShortcut(e),n=this.keyboardShortcutsMatcher.isRedoKeyboardShortcut(e);if(t){if(!this.canUndo())return!1;let t=this.undo();return t&&e.preventDefault(),t}if(n){if(!this.canRedo())return!1;let t=this.redo();return t&&e.preventDefault(),t}return!1}getDrawingHistorySizes(){return{undoSize:this._mode.undoSize&&typeof this._mode.undoSize==`function`?this._mode.undoSize():0,redoSize:this._mode.redoSize&&typeof this._mode.redoSize==`function`?this._mode.redoSize():0}}emitDrawingPushIfHistoryChangedFromLastSnapshot(){this.drawingUndoRedo&&this.drawingUndoRedo.emitPushIfHistoryChangedFromLastSnapshot()}emitDrawingPushIfHistoryChanged(e){this.drawingUndoRedo&&this.drawingUndoRedo.emitPushIfHistoryChanged(e)}getModeStyles(){let e={},t=this._instanceSelectModes.includes(this._mode.mode)?this._mode.mode:void 0;return Object.keys(this._modes).forEach(n=>{e[n]=e=>t&&e.properties[iy.SELECTED]?this._modes[t].styleFeature.bind(this._modes[t])(e):this._modes[n].styleFeature.bind(this._modes[n])(e)}),e}featuresAtLocation({lng:e,lat:t},n){let r=n&&n.pointerDistance!==void 0?n.pointerDistance:30,i=!n||n.ignoreSelectFeatures===void 0||n.ignoreSelectFeatures,a=!(!n||n.ignoreCoordinatePoints===void 0)&&n.ignoreCoordinatePoints,o=!(!n||n.ignoreCurrentlyDrawing===void 0)&&n.ignoreCurrentlyDrawing,s=!(!n||n.ignoreClosingPoints===void 0)&&n.ignoreClosingPoints,c=!(!n||n.ignoreSnappingPoints===void 0)&&n.ignoreSnappingPoints,l=this._adapter.unproject.bind(this._adapter),u=this._adapter.project.bind(this._adapter),d=u(e,t),f=Hy({unproject:l,point:d,pointerDistance:r});return this._store.search(f).filter(l=>{if(i&&(l.properties[iy.MID_POINT]||l.properties[iy.SELECTION_POINT])||a&&l.properties[ay.COORDINATE_POINT]||s&&l.properties[ay.CLOSING_POINT]||o&&l.properties[ay.CURRENTLY_DRAWING]||c&&l.properties[ay.SNAPPING_POINT])return!1;if(l.geometry.type===`Point`){let e=l.geometry.coordinates;return zy(d,u(e[0],e[1]))<r}if(l.geometry.type===`LineString`){let e=l.geometry.coordinates;for(let t=0;t<e.length-1;t++){let n=e[t],i=e[t+1];if(jb(d,u(n[0],n[1]),u(i[0],i[1]))<r)return!0}return!1}if(Ab([e,t],l.geometry.coordinates))return!0;if(n!=null&&n.includePolygonsWithinPointerDistance){let e=l.geometry.coordinates;for(let t of e)for(let e=0;e<t.length-1;e++){let n=t[e],i=t[e+1];if(jb(d,u(n[0],n[1]),u(i[0],i[1]))<r)return!0}}return!1}).map(r=>{if(n==null||!n.addClosestCoordinateInfoToProperties)return r;let i;if(r.geometry.type===`Polygon`)i=r.geometry.coordinates[0].slice(0,-1);else{if(r.geometry.type!==`LineString`)return r;i=r.geometry.coordinates}let a,o=-1,s=1/0;for(let e=0;e<i.length;e++){let t=i[e],n=zy(u(t[0],t[1]),d);n<s&&(o=e,s=n,a=t)}return r.properties.closestCoordinateIndexToEvent=o,r.properties.closestCoordinatePixelDistanceToEvent=s,r.properties.closestCoordinateDistanceKmToEvent=hy(a,[e,t]),r})}getSelectModeOrThrow(e=void 0){let t=this.getSelectMode({switchToSelectMode:!0,selectMode:e});if(!t)throw Error(`No select mode defined in instance`);return t}getSelectMode({switchToSelectMode:e,selectMode:t}){this.checkEnabled();let n=this.getMode();if(this._instanceSelectModes.length===0)return null;if(t!==void 0&&!this._instanceSelectModes.includes(t))throw Error(`No select mode with this name present: ${t}`);let r;return r=t===void 0?this._instanceSelectModes.includes(n)?n:this._instanceSelectModes[0]:t,e&&n!==r&&this.setMode(r),this._modes[r]}isGuidanceFeature(e){return!!(e.properties[iy.MID_POINT]||e.properties[iy.SELECTION_POINT]||e.properties[ay.COORDINATE_POINT]||e.properties[ay.SNAPPING_POINT])}setModeStyles(e,t){if(this.checkEnabled(),!this._modes[e])throw Error(`No mode with this name present`);this._modes[e].styles=t}updateModeOptions(e,t){if(this.checkEnabled(),!this._modes[e])throw Error(`No mode with this name present`);this._modes[e].updateOptions(t)}getSnapshot(){return this._store.copyAll()}getSnapshotFeature(e){if(this._store.has(e))return this._store.copy(e)}clear(){this.checkEnabled(),this._adapter.clear()}get enabled(){return this._enabled}set enabled(e){throw Error(`Enabled is read only`)}getMode(){return this._mode.mode}getModeState(){return this._mode.state}setMode(e){if(this.checkEnabled(),!this._modes[e])throw Error(`No mode with this name present`);this._mode.stop(),this._mode=this._modes[e],this._mode.start()}removeFeatures(e){this.checkEnabled();let t=[],n=[],r;e.forEach(e=>{if(!this._store.has(e))throw Error(`No feature with id ${e}, can not delete`);let i=this._store.getPropertiesCopy(e);i[iy.SELECTED]&&this.deselectFeature(e),i[ay.CURRENTLY_DRAWING]&&this._modes[i.mode]?r=i.mode:(i[ay.COORDINATE_POINT_IDS]&&t.push(...i[ay.COORDINATE_POINT_IDS]),n.push(e))}),this._store.delete([...n,...t],{origin:`api`}),r&&this._modes[r]&&this._modes[r].cleanUp()&&this._modes[r].cleanUp()}selectFeature(e,t){this.getSelectModeOrThrow(t).selectFeature(e)}deselectFeature(e){this.getSelectModeOrThrow().deselectFeature(e)}getFeatureId(){return this._store.getId()}hasFeature(e){return this._store.has(e)}checkIsReservedProperty(e){return![...Object.values(iy),...Object.values(ay)].includes(e)}updateFeatureProperties(e,t){var n;if(!this._store.has(e))throw Error(`No feature with id ${e} present in store`);let r=this._store.copy(e);if(this.isGuidanceFeature(r))throw Error(`Guidance features are not allowed to be updated directly.`);let i=r.properties.mode;if(!this._modes[i])throw Error(`No mode with name ${i} present in instance`);let a=Object.entries(t);a.forEach(([e,t])=>{if(!this.checkIsReservedProperty(e))throw Error(`You are trying to update a reserved property name: ${e}. Please choose another name.`);if(t!==void 0&&!mx(t))throw Error(`Invalid JSON value provided for property ${e}`)}),this._store.updateProperty(a.map(([e,t])=>({id:r.id,property:e,value:t})),{origin:`api`}),(n=this.undoRedoCoordinator)==null||n.emitHistoryPushForCompletedAction()}updateFeatureGeometry(e,t){var n;if(!this._store.has(e))throw Error(`No feature with id ${e} present in store`);let r=this._store.copy(e);if(this.isGuidanceFeature(r))throw Error(`Guidance features are not allowed to be updated directly.`);if(!(r&&t&&t.type&&t.coordinates))throw Error(`Invalid geometry provided`);if(t.type!==r.geometry.type)throw Error(`Geometry type mismatch: expected ${r.geometry.type}, got ${t.type}`);let i=r.properties.mode,a=this._modes[i];if(!a)throw Error(`No mode with name ${i} present in instance`);let o=Zv({},r,{geometry:t}),s=a.validateFeature(o);if(!s.valid)throw Error(`Feature validation failed: ${s.reason||`Unknown reason`}`);if(this._store.updateGeometry([{id:r.id,geometry:t}],{origin:`api`}),a.afterFeatureUpdated){a.afterFeatureUpdated(o);let e=o.properties[iy.SELECTED],t=this.getSelectMode({switchToSelectMode:!1});t&&e&&t.afterFeatureUpdated(o)}(n=this.undoRedoCoordinator)==null||n.emitHistoryPushForCompletedAction()}transformFeatureGeometry(e,t){var n;if(!this._store.has(e))throw Error(`No feature with id ${e} present in store`);let r=this._store.copy(e);if(this.isGuidanceFeature(r))throw Error(`Guidance features are not allowed to be updated directly.`);let i=r.properties.mode,a=this._modes[i];if(!a)throw Error(`No mode with name ${i} present in instance`);let o;if(r.geometry.type===`Polygon`)o=r.geometry.coordinates[0];else{if(r.geometry.type!==`LineString`)throw Error(`Feature geometry type ${r.geometry.type} is not supported for transformation`);o=r.geometry.coordinates}if(t.projection!=`web-mercator`)throw Error(`Projection ${t.projection} is not currently supported for transformation`);if(t.type===`scale`){let{x:e,y:n}=wy(t.origin[0],t.origin[1]);Bb({coordinates:o,originX:e,originY:n,xScale:t.options.xScale||1,yScale:t.options.yScale||1})}else t.type===`rotate`&&(r=Ib(r,t.options.angle||0),o=r.geometry.type===`Polygon`?r.geometry.coordinates[0]:r.geometry.coordinates);if(o=o.map(e=>[by(e[0],this._adapter.getCoordinatePrecision()),by(e[1],this._adapter.getCoordinatePrecision())]),r.geometry.coordinates=r.geometry.type===`Polygon`?[o]:o,this._store.updateGeometry([{id:r.id,geometry:r.geometry}],{origin:`api`}),a.afterFeatureUpdated){a.afterFeatureUpdated(r);let e=r.properties[iy.SELECTED],t=this.getSelectMode({switchToSelectMode:!1});t&&e&&t.afterFeatureUpdated(r)}(n=this.undoRedoCoordinator)==null||n.emitHistoryPushForCompletedAction()}undo(){return this.checkEnabled(),!!this.undoRedoCoordinator&&this.undoRedoCoordinator.undo()}canUndo(){return this.checkEnabled(),!!this.undoRedoCoordinator&&this.undoRedoCoordinator.canUndo()}canRedo(){return this.checkEnabled(),!!this.undoRedoCoordinator&&this.undoRedoCoordinator.canRedo()}redo(){return this.checkEnabled(),!!this.undoRedoCoordinator&&this.undoRedoCoordinator.redo()}clearUndoRedoHistory(){this.checkEnabled(),this.undoRedoCoordinator&&this.undoRedoCoordinator.clearHistory()}addFeatures(e){return this.checkEnabled(),e.length===0?[]:this._store.load(e,e=>{if(cy(e)){let t=e.properties.mode,n=this._modes[t];if(!n)return{id:e.id,valid:!1,reason:`${t} mode is not in the list of instantiated modes`};let r=n.validateFeature.bind(n)(e);return{id:e.id,valid:r.valid,reason:r.reason?r.reason:r.valid?void 0:`Feature is invalid`}}return{id:e.id,valid:!1,reason:`Mode property does not exist`}},e=>{if(cy(e)){let t=this._modes[e.properties.mode];t&&t.afterFeatureAdded&&t.afterFeatureAdded(e)}},{origin:`api`})}start(){this._enabled||(this._enabled=!0,this._adapter.register({onReady:()=>{this._eventListeners.ready.forEach(e=>{e()})},getState:()=>this._mode.state,onClick:e=>{let t=this.drawingUndoRedo?this.drawingUndoRedo.getHistorySizes():{undoSize:0,redoSize:0};this._mode.onClick(e),this.emitDrawingPushIfHistoryChanged(t)},onMouseMove:e=>{this._mode.onMouseMove(e)},onKeyDown:e=>{this.handleUndoRedoKeyboardShortcut(e)||this._mode.onKeyDown(e)},onKeyUp:e=>{let t=this.drawingUndoRedo?this.drawingUndoRedo.getHistorySizes():{undoSize:0,redoSize:0};this._mode.onKeyUp(e),this.emitDrawingPushIfHistoryChanged(t)},onDragStart:(e,t)=>{this._mode.onDragStart(e,t)},onDrag:(e,t)=>{this._mode.onDrag(e,t)},onDragEnd:(e,t)=>{this._mode.onDragEnd(e,t)},onClear:()=>{this._mode.cleanUp(),this._store.clear({origin:`api`})}}))}getFeaturesAtLngLat(e,t){let{lng:n,lat:r}=e;return this.featuresAtLocation({lng:n,lat:r},t)}getFeaturesAtPointerEvent(e,t){let n=this._adapter.getLngLatFromEvent.bind(this._adapter)(e);return n===null?[]:this.featuresAtLocation(n,t)}stop(){this._enabled&&(this._enabled=!1,this._adapter.unregister())}on(e,t){let n=this._eventListeners[e];n.includes(t)||n.push(t)}off(e,t){let n=this._eventListeners[e];n.includes(t)&&n.splice(n.indexOf(t),1)}};function bx(){return bx=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},bx.apply(null,arguments)}var xx=class extends px.TerraDrawBaseAdapter{constructor(e){super(e),this._renderBeforeLayerId=void 0,this._prefixId=void 0,this._initialDragPan=void 0,this._initialDragRotate=void 0,this._nextRender=void 0,this._map=void 0,this._container=void 0,this.changedIds={deletion:!1,points:!1,linestrings:!1,polygons:!1,styling:!1},this._map=e.map,this._container=this._map.getContainer(),this._initialDragRotate=this._map.dragRotate.isEnabled(),this._initialDragPan=this._map.dragPan.isEnabled(),this._renderBeforeLayerId=e.renderBelowLayerId,this._prefixId=e.prefixId||`td`}hashCode(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t)}resizeImage(e,t,n,r){let i=new Image;i.crossOrigin=`anonymous`,i.onload=()=>{let e=document.createElement(`canvas`);e.width=t,e.height=n;let a=e.getContext(`2d`);if(!a)throw Error(`Could not get canvas context`);a.drawImage(i,0,0,t,n),r(e.toDataURL())},i.src=e}toGlDashArrayFromPixels(e,t){if(!e)return null;let[n,r]=e;if(!Number.isFinite(n)||!Number.isFinite(r)||n<0||r<0)return null;let i=Math.max(1e-4,t);return[n/i,r/i]}isMapLibreAtLeast(e){let t=this._map.version;if(!t)return!1;let n=e=>{let t=e.match(/(\d+)\.(\d+)\.(\d+)/);return t?[parseInt(t[1],10),parseInt(t[2],10),parseInt(t[3],10)]:null},r=n(t),i=n(e);if(!r||!i)return!0;let[a,o,s]=r,[c,l,u]=i;return a===c?o===l?s>=u:o>l:a>c}_addGeoJSONSource(e,t){this._map.addSource(e,{type:`geojson`,data:{type:`FeatureCollection`,features:t},tolerance:0})}_addFillLayer(e){return this._map.addLayer({id:e,source:e,type:`fill`,layout:{"fill-sort-key":[`get`,`zIndex`]},paint:{"fill-color":[`get`,`polygonFillColor`],"fill-opacity":[`get`,`polygonFillOpacity`]}})}_addFillOutlineLayer(e){return this._map.addLayer({id:e+`-outline`,source:e,type:`line`,layout:{"line-sort-key":[`get`,`zIndex`]},paint:{"line-width":[`get`,`polygonOutlineWidth`],"line-color":[`get`,`polygonOutlineColor`],"line-opacity":[`get`,`polygonOutlineOpacity`]}})}_addLineLayer(e){let t={};return this.isMapLibreAtLeast(`5.8.0`)&&(t[`line-dasharray`]=[`coalesce`,[`get`,`lineStringDash`],[`literal`,[1,0]]]),this._map.addLayer({id:e,source:e,type:`line`,layout:{"line-sort-key":[`get`,`zIndex`]},paint:bx({},t,{"line-width":[`get`,`lineStringWidth`],"line-color":[`get`,`lineStringColor`],"line-opacity":[`get`,`lineStringOpacity`]})})}_addPointLayer(e){return this._map.addLayer({id:e,source:e,type:`circle`,layout:{"circle-sort-key":[`get`,`zIndex`]},paint:{"circle-stroke-color":[`get`,`pointOutlineColor`],"circle-stroke-width":[`get`,`pointOutlineWidth`],"circle-stroke-opacity":[`get`,`pointOutlineOpacity`],"circle-radius":[`get`,`pointWidth`],"circle-color":[`get`,`pointColor`],"circle-opacity":[`get`,`pointOpacity`]}})}_addMarkerLayer(e){return this._map.addLayer({id:e+`-marker`,source:e,type:`symbol`,filter:[`has`,`markerId`],layout:{"icon-image":[`image`,[`get`,`markerId`]],"icon-anchor":`bottom`,"icon-allow-overlap":!0}})}_addLayer(e,t){t===`Point`&&(this._addPointLayer(e),this._addMarkerLayer(e)),t===`LineString`&&this._addLineLayer(e),t===`Polygon`&&(this._addFillLayer(e),this._addFillOutlineLayer(e))}_addGeoJSONLayer(e,t){let n=`${this._prefixId}-${e.toLowerCase()}`;return this._addGeoJSONSource(n,t),this._addLayer(n,e),n}_setGeoJSONLayerData(e,t){let n=`${this._prefixId}-${e.toLowerCase()}`;return this._map.getSource(n).setData({type:`FeatureCollection`,features:t}),n}updateChangedIds(e){[...e.updated,...e.created].forEach(e=>{e.geometry.type===`Point`?this.changedIds.points=!0:e.geometry.type===`LineString`?this.changedIds.linestrings=!0:e.geometry.type===`Polygon`&&(this.changedIds.polygons=!0)}),e.deletedIds.length>0&&(this.changedIds.deletion=!0),e.created.length===0&&e.updated.length===0&&e.deletedIds.length===0&&(this.changedIds.styling=!0)}getLngLatFromEvent(e){let{left:t,top:n}=this._container.getBoundingClientRect();return this.unproject(e.clientX-t,e.clientY-n)}getMapEventElement(){return this._map.getCanvas()}setDraggability(e){e?(this._initialDragRotate&&this._map.dragRotate.enable(),this._initialDragPan&&this._map.dragPan.enable()):(this._initialDragRotate&&this._map.dragRotate.disable(),this._initialDragPan&&this._map.dragPan.disable())}project(e,t){let{x:n,y:r}=this._map.project({lng:e,lat:t});return{x:n,y:r}}unproject(e,t){let{lng:n,lat:r}=this._map.unproject({x:e,y:t});return{lng:n,lat:r}}setCursor(e){let t=this._map.getCanvas();e===`unset`?t.style.removeProperty(`cursor`):t.style.cursor=e}setDoubleClickToZoom(e){e?this._map.doubleClickZoom.enable():this._map.doubleClickZoom.disable()}render(e,t){this.updateChangedIds(e),this._nextRender&&cancelAnimationFrame(this._nextRender),this._nextRender=requestAnimationFrame(()=>{if(!this._currentModeCallbacks)return;let n=[...e.created,...e.updated,...e.unchanged],r=[],i=[],a=[];for(let e=0;e<n.length;e++){let o=n[e],{properties:s}=o,c=t[s.mode](o);if(s.zIndex=c.zIndex,s.zIndex=c.zIndex,o.geometry.type===`Point`){s.pointColor=c.pointColor,s.pointOutlineColor=c.pointOutlineColor,s.pointOutlineWidth=c.pointOutlineWidth;let e=c.pointOutlineOpacity;s.pointOutlineOpacity=e===void 0?1:e,s.pointWidth=c.pointWidth;let t=c.pointOpacity;if(s.pointOpacity=t===void 0?1:t,c.markerUrl&&c.markerWidth&&c.markerHeight){let e=`marker-${this.hashCode(c.markerUrl)}`;this._map.hasImage(e)||this.resizeImage(c.markerUrl,c.markerWidth,c.markerHeight,t=>{this._map.loadImage(t).then(t=>{this._map.hasImage(e)||this._map.addImage(e,t.data)})}),s.markerId=e,s.pointWidth=0}r.push(o)}else if(o.geometry.type===`LineString`){s.lineStringDash=this.toGlDashArrayFromPixels(c.lineStringDash,c.lineStringWidth),s.lineStringColor=c.lineStringColor,s.lineStringWidth=c.lineStringWidth;let e=c.lineStringOpacity;s.lineStringOpacity=e===void 0?1:e,i.push(o)}else if(o.geometry.type===`Polygon`){let e=c.polygonOutlineOpacity;s.polygonFillColor=c.polygonFillColor,s.polygonFillOpacity=c.polygonFillOpacity,s.polygonOutlineOpacity=e===void 0?1:e,s.polygonOutlineColor=c.polygonOutlineColor,s.polygonOutlineWidth=c.polygonOutlineWidth,a.push(o)}}let o=this.changedIds.deletion||this.changedIds.styling,s=o||this.changedIds.linestrings,c=o||this.changedIds.polygons;(o||this.changedIds.points)&&this._setGeoJSONLayerData(`Point`,r),s&&this._setGeoJSONLayerData(`LineString`,i),c&&this._setGeoJSONLayerData(`Polygon`,a),this.changedIds={points:!1,linestrings:!1,polygons:!1,deletion:!1,styling:!1}})}clear(){this._currentModeCallbacks&&(this._currentModeCallbacks.onClear(),this._nextRender&&=(cancelAnimationFrame(this._nextRender),void 0),this._setGeoJSONLayerData(`Point`,[]),this._setGeoJSONLayerData(`LineString`,[]),this._setGeoJSONLayerData(`Polygon`,[]))}getCoordinatePrecision(){return super.getCoordinatePrecision()}unregister(){super.unregister(),this.changedIds={points:!1,linestrings:!1,polygons:!1,deletion:!1,styling:!1},this._map.removeLayer(`${this._prefixId}-point`),this._map.removeLayer(`${this._prefixId}-point-marker`),this._map.removeSource(`${this._prefixId}-point`),this._map.removeLayer(`${this._prefixId}-linestring`),this._map.removeSource(`${this._prefixId}-linestring`),this._map.removeLayer(`${this._prefixId}-polygon`),this._map.removeLayer(`${this._prefixId}-polygon-outline`),this._map.removeSource(`${this._prefixId}-polygon`)}register(e){var t;super.register(e);let n=this._addGeoJSONLayer(`Polygon`,[]),r=this._addGeoJSONLayer(`LineString`,[]),i=this._addGeoJSONLayer(`Point`,[]);var a;this._renderBeforeLayerId&&(this._map.moveLayer(i,this._renderBeforeLayerId),this._map.moveLayer(r,i),this._map.moveLayer(`${n}-outline`,r),this._map.moveLayer(n,`${n}-outline`)),(t=this._currentModeCallbacks)!=null&&t.onReady&&((a=this._currentModeCallbacks)==null||a.onReady())}},Sx=`linestring`;function Cx(e){return sl(e).select}function wx(e){let t=e.geometry;return t.type===`LineString`?t.coordinates.filter(e=>Array.isArray(e)&&typeof e[0]==`number`&&typeof e[1]==`number`).map(e=>({position:Rs([e[0],e[1]])})):[]}function Tx(e){return{type:`Feature`,properties:{mode:Sx},geometry:{type:`LineString`,coordinates:e.waypoints.map(e=>zs(e.position))}}}function Ex(e){let t=Cx(e.theme),n=new yx({adapter:new xx({map:e.map,prefixId:`binnacle-route-draw`,renderBelowLayerId:e.beforeId}),modes:[new Sb({styles:{pointColor:t,pointWidth:6}}),new hb({styles:{lineStringColor:t,lineStringWidth:4}}),new Wb({styles:{selectionPointColor:t,midPointColor:t},flags:{linestring:{feature:{draggable:!0,coordinates:{midpoints:!0,draggable:!0,deletable:!0}}}}})]}),r=()=>{let e=n.getSnapshot().find(e=>e.properties.mode===Sx);return e?wx(e):[]};return n.on(`change`,()=>e.onChange(r())),{start(e){n.start(),e&&e.waypoints.length>0?(n.addFeatures([Tx(e)]),n.setMode(`select`)):n.setMode(Sx)},setTheme(e){let t=Cx(e);n.updateModeOptions(`point`,{styles:{pointColor:t,pointWidth:6}}),n.updateModeOptions(`linestring`,{styles:{lineStringColor:t,lineStringWidth:4}}),n.updateModeOptions(`select`,{styles:{selectionPointColor:t,midPointColor:t}})},stop(){n.stop()}}}function Dx(e,t,n){let r=[];for(let i of e)t.has(i.id)&&(i.waypoints.length<2||r.push({type:`Feature`,geometry:{type:`LineString`,coordinates:i.waypoints.map(e=>zs(e.position))},properties:{id:i.id,active:i.id===n}}));return{type:`FeatureCollection`,features:r}}function Ox(e,t){let n=[];for(let r of e)t.has(r.id)&&r.waypoints.forEach((e,t)=>{n.push({type:`Feature`,geometry:{type:`Point`,coordinates:zs(e.position)},properties:{id:r.id,index:t,name:e.name??`${t+1}`}})});return{type:`FeatureCollection`,features:n}}var kx=`binnacle-route-lines`,Ax=`binnacle-route-line`,jx=`binnacle-route-waypoints`,Mx=`binnacle-route-waypoint`,Nx=`binnacle-route-waypoint-label`,Px=`routes`,Fx=[Ax,Mx,Nx];function Ix(e){return[`case`,[`get`,`active`],e.select,e.note]}var Lx=[`case`,[`get`,`active`],3,2];function Rx(e){let t=sl(`day`),n=-1;return{id:`routes`,title:`Routes`,band:Px,supportsOpacity:!0,layerIds:Fx,add(e){n=-1;let r=e.beforeIdFor(Px);if(!e.map.getSource(kx)){let t={type:`geojson`,data:od()};e.map.addSource(kx,t)}if(!e.map.getSource(jx)){let t={type:`geojson`,data:od()};e.map.addSource(jx,t)}if(!e.map.getLayer(Ax)){let n={id:Ax,type:`line`,source:kx,layout:{"line-cap":`round`,"line-join":`round`},paint:{"line-color":Ix(t),"line-width":Lx,"line-dasharray":[2,1]}};e.map.addLayer(n,r)}if(!e.map.getLayer(Mx)){let n={id:Mx,type:`circle`,source:jx,paint:{"circle-radius":4,"circle-color":t.note,"circle-stroke-color":t.markerGlyph,"circle-stroke-width":1}};e.map.addLayer(n,r)}if(!e.map.getLayer(Nx)){let n={id:Nx,type:`symbol`,source:jx,layout:{"text-field":[`get`,`name`],"text-size":11,"text-offset":[0,1.1],"text-optional":!0},paint:{"text-color":t.label,"text-halo-color":t.background,"text-halo-width":1.5}};e.map.addLayer(n,r)}},sync(t){e.version!==n&&(n=e.version,t.map.getSource(kx)?.setData(Dx(e.routes,e.shownIds,e.activeId)),t.map.getSource(jx)?.setData(Ox(e.routes,e.shownIds)))},setVisible(e,t){let n=t?`visible`:`none`;for(let t of Fx)e.map.setLayoutProperty(t,`visibility`,n)},setOpacity(e,t){e.map.setPaintProperty(Ax,`line-opacity`,t),e.map.setPaintProperty(Mx,`circle-opacity`,t)},applyTheme(e,n){t=n,e.map.setPaintProperty(Ax,`line-color`,Ix(t)),e.map.setPaintProperty(Mx,`circle-color`,t.note),e.map.setPaintProperty(Mx,`circle-stroke-color`,t.markerGlyph),e.map.setPaintProperty(Nx,`text-color`,t.label),e.map.setPaintProperty(Nx,`text-halo-color`,t.background)},remove(e){for(let t of Fx)e.map.getLayer(t)&&e.map.removeLayer(t);for(let t of[kx,jx])e.map.getSource(t)&&e.map.removeSource(t)}}}function zx(e,t,n){let r=n.lon-t.lon,i=n.lat-t.lat,a=r*r+i*i;if(a===0)return Math.hypot(e.lon-t.lon,e.lat-t.lat);let o=((e.lon-t.lon)*r+(e.lat-t.lat)*i)/a;return Math.hypot(e.lon-(t.lon+o*r),e.lat-(t.lat+o*i))}function Bx(e,t){let n=e.length;if(n<=2)return e;let r=Array(n).fill(!1);r[0]=!0,r[n-1]=!0;let i=[[0,n-1]];for(;i.length>0;){let n=i.pop();if(!n)break;let[a,o]=n,s=0,c=-1;for(let t=a+1;t<o;t+=1){let n=zx(e[t],e[a],e[o]);n>s&&(s=n,c=t)}s>t&&c!==-1&&(r[c]=!0,i.push([a,c]),i.push([c,o]))}let a=[];for(let t=0;t<n;t+=1)r[t]&&a.push(e[t]);return a}function Vx(e,t){if(e.length<=2)return e.slice();let n=[];for(let r of rl(e))n.push(...Bx(r,t));return n}function Hx(e){let t=[];for(let n=1;n<e.length;n+=1){let r=e[n];if(r.gap)continue;let i=e[n-1];t.push({type:`Feature`,geometry:{type:`LineString`,coordinates:[nl(i),nl(r)]},properties:{sog:r.sog}})}return{type:`FeatureCollection`,features:t}}var Ux=`binnacle-track-active`,Wx=`binnacle-track-active-line`,Gx=`binnacle-track-saved`,Kx=`binnacle-track-saved-line`,qx=`track`,Jx=8e-5,Yx=2.5,Xx=5,Zx=od(),Qx={features:()=>Zx,version:()=>0};function $x(e,t){return t===`solid`?e.trackSolid:[`interpolate`,[`linear`],[`get`,`sog`],0,e.trackSlow,Yx,e.trackMid,Xx,e.trackFast]}function eS(e,t,n=Qx){let r=sl(`day`),i=-1,a,o,s=-1;function c(t){let n=Vx(e.points,Jx);t.map.getSource(Ux)?.setData(Hx(n))}return{id:`track`,title:`Track`,band:qx,supportsOpacity:!0,layerIds:[Kx,Wx],add(e){i=-1,a=void 0,o=void 0,s=-1;let n=e.beforeIdFor(qx),c={type:`geojson`,data:Zx};e.map.addSource(Ux,c),e.map.addSource(Gx,{type:`geojson`,data:Zx});let l={id:Kx,type:`line`,source:Gx,layout:{"line-cap":`round`,"line-join":`round`},paint:{"line-color":r.trackSolid,"line-width":2}};e.map.addLayer(l,n);let u={id:Wx,type:`line`,source:Ux,layout:{"line-cap":`round`,"line-join":`round`},paint:{"line-color":$x(r,t.value.colorMode),"line-width":3}};e.map.addLayer(u,n)},sync(l){let u=t.value.colorMode,d=e.points,f=d[d.length-1]?.t;(d.length!==i||f!==a)&&(i=d.length,a=f,c(l)),u!==o&&(o=u,l.map.setPaintProperty(Wx,`line-color`,$x(r,u)));let p=n.version();p!==s&&(s=p,l.map.getSource(Gx)?.setData(n.features()))},applyTheme(e,n){r=n,e.map.setPaintProperty(Wx,`line-color`,$x(r,t.value.colorMode)),e.map.setPaintProperty(Kx,`line-color`,r.trackSolid)},setVisible(e,t){let n=t?`visible`:`none`;e.map.setLayoutProperty(Wx,`visibility`,n),e.map.setLayoutProperty(Kx,`visibility`,n)},setOpacity(e,t){e.map.setPaintProperty(Wx,`line-opacity`,t),e.map.setPaintProperty(Kx,`line-opacity`,t)},remove(e){for(let t of[Wx,Kx])e.map.getLayer(t)&&e.map.removeLayer(t);for(let t of[Ux,Gx])e.map.getSource(t)&&e.map.removeSource(t)}}}var tS=`binnacle-vessel`,nS=80,rS=64;function iS(e,t=e.a){return`rgba(${e.r}, ${e.g}, ${e.b}, ${(t/255).toFixed(3)})`}function aS(e,t){return{r:Math.round(e.r*t),g:Math.round(e.g*t),b:Math.round(e.b*t),a:e.a}}function oS(e){if(typeof document<`u`){let t=document.createElement(`canvas`);t.width=nS,t.height=nS;let n=t.getContext(`2d`);if(n)return sS(n,e)}return cS(e)}function sS(e,t){let n=iS(aS(t,.5));return e.clearRect(0,0,nS,nS),e.scale(nS/rS,nS/rS),e.beginPath(),e.moveTo(32,4),e.quadraticCurveTo(44,24,43,44),e.quadraticCurveTo(42,53,38,57),e.lineTo(26,57),e.quadraticCurveTo(22,53,21,44),e.quadraticCurveTo(20,24,32,4),e.closePath(),e.fillStyle=iS(t),e.fill(),e.lineJoin=`round`,e.lineCap=`round`,e.lineWidth=2.5,e.strokeStyle=n,e.stroke(),e.getImageData(0,0,nS,nS)}function cS(e){return sd(nS,e,(e,t,n)=>{let r=t/2.4;return t>6&&Math.abs(e-n)<=r})}var lS=`binnacle-own-vessel`,uS=`binnacle-own-vessel-symbol`,dS={r:31,g:111,b:178,a:255},fS=`own-vessel`;function pS(e){let t,n,r,i=()=>vc(e.headingRad,e.cogRad);function a(){let t=e.position;return t?{type:`FeatureCollection`,features:[{type:`Feature`,geometry:{type:`Point`,coordinates:[t.longitude,t.latitude]},properties:{heading:i()}}]}:od()}function o(){let a=e.position,o=a?.longitude,s=a?.latitude,c=a?i():void 0;return o===t&&s===n&&c===r?!1:(t=o,n=s,r=c,!0)}return vd({id:fS,title:`Own vessel`,band:`vessel`,sourceId:lS,layerId:uS,iconId:tS,iconImage:oS,pixelRatio:2,defaultColor:dS,paintColor:e=>e.ownVessel,features:a,shouldRefresh:o})}var mS=K(`<div class="chart-canvas svelte-1mqhhzl"></div>`);function hS(e,t){Qe(t,!0);let n,r,i;Ln(()=>{i?.setTheme(t.theme)}),ed(),ga(()=>{r=xd({container:n,view:t.initialView,managerOptions:{saved:t.savedLayers,onChange:t.onLayersChange,savedOrder:t.savedOrder,onOrderChange:t.onOrderChange,pinned:[Ef,fS]},onView:e=>t.onViewChange?.(e),onUserPan:()=>t.onUserPan?.(),onLoad:async({map:e,ctx:n,manager:r,recolor:a,isDestroyed:o,runTick:s})=>{let c=await Gv(Vs(),t.chartsToken);if(o())return;let l=Rx(t.routeStore),u=Em(Vs(),t.chartsToken,t.onNoteSelect),d=Hv(t.aisTargets,t.store),f=kf(t.collision),p=eS(t.recorder,t.trackSettings,t.savedTracks),m=pS(t.vessel);if(await r.registerAll([...c.map(e=>ad(e,Vs())),...Xv.map(e=>Yv(e)),l,u,d,f,p,m]),o())return;i=Ex({map:e,beforeId:n.beforeIdFor(`routes`),theme:t.theme,onChange:e=>{let n=t.routeStore.working;n&&t.routeStore.setWorking({...n,waypoints:e})}});let h=new bf(r);h.refresh(),t.onReady?.(h),t.onUserChartsReady?.({register:async e=>{o()||(await r.register(ad(e,Vs(),`bathymetry`)),h.refresh())},unregister:e=>{r.unregister(fl(e)),h.refresh()}}),t.onMapReady?.(a),t.onCommandsReady?.({centerOnVessel:()=>{let n=t.vessel.position;if(!n)return;let r=e.getZoom();e.flyTo({center:[n.longitude,n.latitude],zoom:r<12?14:r})},recenterOnVessel:(t,n)=>{e.setCenter([n,t])},flyTo:(t,n)=>{let r=e.getZoom();e.flyTo({center:[n,t],zoom:r<11?12:r})},clearNoteSelection:()=>u.deselect(n),startRouteEdit:e=>i?.start(e),stopRouteEdit:()=>i?.stop()}),s([l,u,d,f,p,m])}})}),_a(()=>r?.destroy());var a=mS();da(a,e=>n=e,()=>n),q(e,a),$e()}var gS=K(`<button type="button"> </button>`),_S=K(`<span class="bar-sep svelte-qluf4r" aria-hidden="true"></span>`),vS=K(`<div class="conditions-slot svelte-qluf4r"><!></div>`),yS=K(`&middot; <b class="svelte-qluf4r"> </b> hPa`,1),bS=K(`/ <b class="svelte-qluf4r"> </b> s`,1),xS=K(`&middot; sea <b class="svelte-qluf4r"> </b> m <!>`,1),SS=K(`&middot; rain <b class="svelte-qluf4r"> </b> mm/h`,1),CS=K(`<span class="readout-source svelte-qluf4r"> </span>`),wS=K(`<div class="readout svelte-qluf4r" role="status" aria-live="polite"><span class="readout-line">Wind <b class="svelte-qluf4r"> </b> kn from <b class="svelte-qluf4r"> </b>&deg; <!> <!> <!></span> <!></div>`),TS=K(`<p class="hint svelte-qluf4r">Turn on a layer above to load weather for this area.</p>`),ES=K(`<div class="scrubber svelte-qluf4r" role="group" aria-label="Forecast time"><button type="button" class="step svelte-qluf4r" aria-label="Earlier"><span aria-hidden="true">&#9664;</span></button> <button type="button" class="step svelte-qluf4r"><!></button> <button type="button" class="step svelte-qluf4r" aria-label="Later"><span aria-hidden="true">&#9654;</span></button> <input class="track svelte-qluf4r" type="range" aria-label="Forecast time"/> <span class="time svelte-qluf4r"> </span></div>`),DS=K(`<span class="legend-scale svelte-qluf4r"><span class="legend-end svelte-qluf4r"> </span> <span class="legend-bar svelte-qluf4r"></span> <span class="legend-end svelte-qluf4r"> </span></span>`),OS=K(`<span class="legend-swatch svelte-qluf4r"><span class="legend-chip svelte-qluf4r"></span> </span>`),kS=K(`<span class="legend-swatches svelte-qluf4r"></span>`),AS=K(`<span class="legend-note svelte-qluf4r"> </span>`),jS=K(`<div class="legend-row svelte-qluf4r"><span class="legend-title caps-label svelte-qluf4r"> </span> <!> <!></div>`),MS=K(`<div class="legend svelte-qluf4r" role="group" aria-label="Weather legend"></div>`),NS=K(`<section class="weather-panel svelte-qluf4r" aria-label="Weather"><header class="panel-head svelte-qluf4r"><h2 class="panel-title">Weather</h2> <div class="layer-bar svelte-qluf4r" role="group" aria-label="Weather layers"><!> <!> <!></div> <button type="button">Here</button> <button type="button" class="panel-close" aria-label="Close weather"><!></button></header> <div class="panel-map svelte-qluf4r"><div class="map svelte-qluf4r"></div> <!> <!> <!></div> <footer class="panel-foot svelte-qluf4r"><!> <!></footer></section>`);function PS(e,t){Qe(t,!0);let n=3*hc,r=`Open-Meteo`,i,a,o,s,c=z(void 0),l=z(!1),u=z(!1),d,f,p=z(void 0),m=z(void 0),h,g=0,_=R(()=>W(c)?.items??[]),v=R(()=>W(_).filter(e=>kh.includes(e.id))),y=R(()=>W(_).filter(e=>!kh.includes(e.id))),b=R(()=>W(_).some(e=>e.visible)),x=R(()=>W(_).some(e=>e.id===Oh.waves&&e.visible)),S=R(()=>W(_).some(e=>e.id===Oh.radar&&e.visible)),C=e=>W(_).some(t=>t.id===e&&t.visible),w=R(()=>W(_).filter(e=>e.visible).map(e=>ag(e.id,t.theme)).filter(e=>e!==void 0)),T=R(()=>t.store.grid&&t.store.grid.times.length>0?{start:t.store.grid.times[0],end:t.store.grid.times[t.store.grid.times.length-1],stepMs:n}:void 0),E=R(()=>t.store.grid?new Date(t.store.selectedTime).toLocaleString([],{weekday:`short`,hour:`2-digit`,minute:`2-digit`}):``);function D(e){W(T)&&t.store.setSelectedTime(Ig(e,W(T)))}function O(){B(u,!1),d&&clearInterval(d),d=void 0}function k(){if(W(u)||!W(T)){O();return}B(u,!0),d=setInterval(()=>W(T)&&t.store.setSelectedTime(Rg(t.store.selectedTime,W(T))),700)}let A={maxCells:200,forecastDays:5};function ee(){f&&clearTimeout(f),f=setTimeout(()=>{!o||!W(b)||t.loader.load(t.store,o(),A,{waves:W(x),radar:W(S)})},400)}function te(e,t){B(p,e,!0),B(m,e?t:void 0,!0),h&&clearTimeout(h),e&&(h=setTimeout(()=>B(p,void 0),8e3))}async function ne(e,n){let i=++g;if(t.providerName){let r=await ie(n,e);if(i!==g)return;if(r){te(r,t.providerName);return}}W(b)&&t.store.grid?te(zg(t.store.grid,e,n,t.store.bracket.lo),r):te(void 0,void 0)}let re=e=>W(m)===r?C(e):!0;async function ie(e,n){let r=Vs(),i=t.store.selectedTime;if(Math.abs(i-Date.now())<54e5){let i=await kg(r,e,n,t.token),a=i&&Pg(i);if(a)return a}let a=await Ag(r,e,n,48,t.token),o=a&&Fg(a,i);return o?Pg(o):void 0}let ae=xc;function oe(e){let t=!1;Ln(()=>{e()&&!t?(t=!0,ee()):e()||(t=!1)})}oe(()=>W(x)),oe(()=>W(S)),Ln(()=>{W(b)&&!t.store.grid&&ee()}),Ln(()=>{s?.(t.theme)}),ga(()=>{a=xd({container:i,view:t.initialView??t.savedView,defaultZoom:3,minZoom:1,maxZoom:7,managerOptions:{saved:t.savedLayers,onChange:t.onLayersChange,exclusive:[kh]},onView:e=>t.onViewChange?.(e),onClick:e=>void ne(e.lng,e.lat),onLoad:async({map:e,manager:n,recolor:r,isDestroyed:i,runTick:a})=>{let l=[h_(t.store),sg(t.store),Ah(t.store),xg(t.store),Sv(t.store),fg(t.store)];for(let e of l)if(await n.register(e),i())return;let u=new bf(n);u.refresh(),B(c,u,!0),s=r,s(t.theme),o=()=>Ed(e.getBounds()),e.on(`moveend`,ee),a(l)}})}),_a(()=>{f&&clearTimeout(f),h&&clearTimeout(h),O(),a?.destroy()});var se=NS(),ce=V(se),le=H(V(ce),2),ue=V(le);vi(ue,17,()=>W(v),e=>e.id,(e,t)=>{var n=gS();let r;var i=V(n,!0);N(n),U(()=>{r=Li(n,1,`pill svelte-qluf4r`,null,r,{on:W(t).visible}),X(n,`aria-pressed`,W(t).visible),J(i,W(t).title)}),G(`click`,n,()=>W(c)?.toggle(W(t).id,!W(t).visible)),q(e,n)});var de=H(ue,2),fe=e=>{q(e,_S())};Y(de,e=>{W(v).length>0&&W(y).length>0&&e(fe)}),vi(H(de,2),17,()=>W(y),e=>e.id,(e,t)=>{var n=gS();let r;var i=V(n,!0);N(n),U(()=>{r=Li(n,1,`pill svelte-qluf4r`,null,r,{on:W(t).visible}),X(n,`aria-pressed`,W(t).visible),J(i,W(t).title)}),G(`click`,n,()=>W(c)?.toggle(W(t).id,!W(t).visible)),q(e,n)}),N(le);var pe=H(le,2);let me;var he=H(pe,2);Ko(V(he),{size:18,"aria-hidden":`true`}),N(he),N(ce);var ge=H(ce,2),_e=V(ge);da(_e,e=>i=e,()=>i);var ve=H(_e,2),ye=e=>{var n=vS(),r=V(n);{let e=R(Vs);a_(r,{get origin(){return W(e)},get token(){return t.token},get providerName(){return t.providerName},get position(){return t.position},get store(){return t.store}})}N(n),q(e,n)};Y(ve,e=>{W(l)&&e(ye)});var be=H(ve,2),xe=e=>{var t=wS(),n=V(t),r=H(V(n)),i=V(r,!0);N(r);var a=H(r,2),o=V(a,!0);N(a);var s=H(a,2),c=e=>{var t=yS(),n=H(Sn(t)),r=V(n,!0);N(n),P(),U(e=>J(r,e),[()=>ae(yc(W(p).pressurePa),0)]),q(e,t)},l=R(()=>re(Oh.pressure)&&W(p).pressurePa!==void 0);Y(s,e=>{W(l)&&e(c)});var u=H(s,2),d=e=>{var t=xS(),n=H(Sn(t)),r=V(n,!0);N(n);var i=H(n,2),a=e=>{var t=bS(),n=H(Sn(t)),r=V(n,!0);N(n),P(),U(e=>J(r,e),[()=>ae(W(p).wavePeriodS,1)]),q(e,t)};Y(i,e=>{W(p).wavePeriodS!==void 0&&e(a)}),U(e=>J(r,e),[()=>ae(W(p).waveHeightM,1)]),q(e,t)},f=R(()=>re(Oh.waves)&&W(p).waveHeightM!==void 0);Y(u,e=>{W(f)&&e(d)});var h=H(u,2),g=e=>{var t=SS(),n=H(Sn(t)),r=V(n,!0);N(n),P(),U(e=>J(r,e),[()=>ae(W(p).precipitationMm,1)]),q(e,t)},_=R(()=>(re(Oh.precip)||re(Oh.radar))&&W(p).precipitationMm!==void 0&&W(p).precipitationMm>=.1);Y(h,e=>{W(_)&&e(g)}),N(n);var v=H(n,2),y=e=>{var t=CS(),n=V(t,!0);N(t),U(()=>J(n,W(m))),q(e,t)};Y(v,e=>{W(m)&&e(y)}),N(t),U((e,t)=>{J(i,e),J(o,t)},[()=>ae(gc(W(p).speedMs),1),()=>ae(_c(W(p).fromRad),0)]),q(e,t)};Y(be,e=>{W(p)&&e(xe)});var Se=H(be,2),Ce=e=>{q(e,TS())};Y(Se,e=>{W(b)||e(Ce)}),N(ge);var we=H(ge,2),Te=V(we),Ee=e=>{var n=ES(),r=V(n),i=H(r,2),a=V(i),o=e=>{lo(e,{size:16,"aria-hidden":`true`})},s=e=>{mo(e,{size:16,"aria-hidden":`true`})};Y(a,e=>{W(u)?e(o):e(s,-1)}),N(i);var c=H(i,2),l=H(c,2);Qi(l);var d=H(l,2),f=V(d,!0);N(d),N(n),U(()=>{X(i,`aria-label`,W(u)?`Pause`:`Play`),X(l,`min`,W(T).start),X(l,`max`,W(T).end),X(l,`step`,W(T).stepMs),$i(l,t.store.selectedTime),J(f,W(E))}),G(`click`,r,()=>D(Lg(t.store.selectedTime,-1,W(T)))),G(`click`,i,k),G(`click`,c,()=>D(Lg(t.store.selectedTime,1,W(T)))),G(`input`,l,e=>D(Number(e.currentTarget.value))),q(e,n)};Y(Te,e=>{W(T)&&e(Ee)});var De=H(Te,2),Oe=e=>{var t=MS();vi(t,21,()=>W(w),e=>e.id,(e,t)=>{var n=jS(),r=V(n),i=V(r,!0);N(r);var a=H(r,2),o=e=>{var n=DS(),r=V(n),i=V(r,!0);N(r);var a=H(r,2),o=H(a,2),s=V(o,!0);N(o),N(n),U(()=>{J(i,W(t).lowLabel),zi(a,`background:${W(t).gradient??``}`),J(s,W(t).highLabel)}),q(e,n)},s=e=>{var n=kS();vi(n,21,()=>W(t).swatches,e=>e.label,(e,t)=>{var n=OS(),r=V(n),i=H(r);N(n),U(()=>{zi(r,`background:${W(t).color??``}`),J(i,` ${W(t).label??``}`)}),q(e,n)}),N(n),q(e,n)};Y(a,e=>{W(t).gradient?e(o):W(t).swatches&&e(s,1)});var c=H(a,2),l=e=>{var n=AS(),r=V(n,!0);N(n),U(()=>J(r,W(t).note)),q(e,n)};Y(c,e=>{W(t).note&&e(l)}),N(n),U(()=>J(i,W(t).title)),q(e,n)}),N(t),q(e,t)};Y(De,e=>{W(w).length>0&&e(Oe)}),N(we),N(se),Di(se,(e,t)=>Rd?.(e,t),()=>t.onClose),U(()=>{me=Li(pe,1,`pill svelte-qluf4r`,null,me,{on:W(l)}),X(pe,`aria-pressed`,W(l))}),G(`click`,pe,()=>B(l,!W(l))),G(`click`,he,function(...e){t.onClose?.apply(this,e)}),q(e,se),$e()}Xr([`click`,`input`]);var FS=K(`<!> <!>`,1),IS=K(`<button type="button" class="btn btn-primary btn-pill">Update</button>`),LS=K(`<div class="note-panel-slot svelte-1hicyxm"><!></div>`),RS=K(`<div class="layers-panel-slot svelte-1hicyxm"><!></div>`),zS=K(`<div class="routes-panel-slot svelte-1hicyxm"><!></div>`),BS=K(`<span class="readout offline svelte-1hicyxm" role="status" aria-live="polite">Offline</span>`),VS=K(`<main class="binnacle-shell svelte-1hicyxm"><header class="topbar svelte-1hicyxm"><span class="topbar-start svelte-1hicyxm"><!> <span class="brand svelte-1hicyxm">Binnacle <span class="version svelte-1hicyxm"></span></span></span> <span class="topbar-actions svelte-1hicyxm"><!> <!></span></header> <section class="chart-host svelte-1hicyxm" aria-label="Chart"><!> <div class="banner-slot svelte-1hicyxm"><!></div> <div class="nav-slot svelte-1hicyxm"><!></div> <div class="danger-slot svelte-1hicyxm"><!></div> <!> <!> <!> <!></section> <footer class="status-strip svelte-1hicyxm"><div class="forecast-center svelte-1hicyxm"><button type="button"><!> Forecast</button></div> <span role="status" aria-live="polite"> </span> <!> <span class="readout svelte-1hicyxm">SOG <b class="svelte-1hicyxm"> </b> kn</span> <span class="readout svelte-1hicyxm">COG <b class="svelte-1hicyxm"> </b>&deg;</span> <span class="spacer svelte-1hicyxm"></span> <span class="readout">Center</span> <span class="readout svelte-1hicyxm"><b class="svelte-1hicyxm"> </b></span> <span class="readout svelte-1hicyxm"><b class="svelte-1hicyxm"> </b></span> <span class="readout svelte-1hicyxm">z<b class="svelte-1hicyxm"> </b></span></footer></main>`);function HS(e,t){Qe(t,!0);let n=`vessels.*`,r=new tc,i=new Td(r),a=new nc(r),o=Is(),s=new ss(Vs()),c=new Cv,l=ts(),u=new Gc(i,a,l),d=new Rf,f=new Jo(`binnacle:alarm-muted`,!1),p=new Cf((e,t)=>void o.publish({context:Qs,updates:[{values:[{path:e,value:t}]}]})),m=$o(),h=new tl(m,G_()),g=new Zc,_=new qc(r,i),v=new Zf,y=new Jo(`binnacle:arrival-muted`,!1),b=new Md,x=ev(),S=z(!1),C=z(void 0),w=new Jo(`binnacle:weather-layers`,{[Oh.wind]:{visible:!0,opacity:1},[Oh.waves]:{visible:!0,opacity:.7}}),T=Zo(`binnacle:weather-view`),E=Xo(T.value)?T.value:void 0,D=z(dn([])),O=z(dn(new Set)),k=0,A={version:()=>k,features:()=>oh(W(D),W(O))},ee=z(void 0),te=z(!1),ne=z(!1),re,ie=z(void 0),ae=z(void 0),oe=z(void 0),se=z(void 0),ce=z(!1),le=Nv(()=>B(ce,!0)),ue=Wd(e=>re?.(e)),de=Zo(),fe=Xo(de.value)?de.value:void 0,pe=new Jo(`binnacle:layers`,{}),me=new Jo(`binnacle:layer-order`,[]),he=V_(),ge=new Jo(`binnacle:user-charts`,[]),_e=new wd(he,ge.value,e=>ge.set(e)),ve=z(void 0),ye=new Map,be;function xe(e){B(se,e,!0),be&&clearTimeout(be),be=setTimeout(()=>de.set(e),400)}let Se=z(void 0),Ce=z(!1),we=R(()=>[{id:`center-on-boat`,label:`Center on boat`,icon:to,onSelect:()=>W(Se)?.centerOnVessel()},{id:`follow-boat`,label:W(Ce)?`Stop following`:`Follow boat`,icon:so,onSelect:()=>B(Ce,!W(Ce))},{id:`mute-alarm`,label:f.value?`Unmute alarm`:`Mute alarm`,icon:f.value?Wo:Ho,onSelect:()=>f.set(!f.value)},{id:`mute-arrival`,label:y.value?`Unmute arrival`:`Mute arrival`,icon:y.value?ka:ja,onSelect:()=>y.set(!y.value)},{id:`routes`,label:`Routes`,icon:vo,disabled:!W(Se),onSelect:()=>{B(te,!1),B(ne,!0)}},{id:`layers`,label:`Layers and charts`,icon:Za,disabled:!W(ee),onSelect:()=>{B(ne,!1),B(te,!0)}}]);Ln(()=>{d.update(u.assessment.worst,u.suppressed,f.value)}),Ln(()=>{p.update(u.assessment)}),Ln(()=>{let e=i.position;e&&h.consider(e.latitude,e.longitude,i.sogMps??0)}),Ln(()=>{let e=W(Se),t=i.position;W(Ce)&&t&&e?.recenterOnVessel(t.latitude,t.longitude)}),Ln(()=>{let e=W(ve),t=_e.sources;if(!e)return;let n=new Set(t.map(e=>e.id));for(let[t,r]of ye)n.has(t)||(ye.delete(t),e.unregister(t),r&&URL.revokeObjectURL(r));for(let n of t)ye.has(n.id)||(ye.set(n.id,void 0),Te(n,e))});async function Te(e,t){let n,r;if(e.origin.type===`url`)r=e.origin.url;else{let t=await _e.resolveBlob(e.origin.storeId);if(!t||!ye.has(e.id)){ye.delete(e.id);return}n=URL.createObjectURL(t),ye.set(e.id,n),r=`pmtiles://${n}`}if(await t.register(Sd(e,r)),!ye.has(e.id)){t.unregister(e.id),n&&URL.revokeObjectURL(n);return}re?.(ue.theme)}function Ee(){k+=1}async function De(){B(D,await hh(Vs(),W(ie)),!0),Ee()}async function Oe(e){if(h.points.length<2)return;let t=cc();await gh(Vs(),W(ie),t,e,h.points)&&(h.clear(),B(O,new Set(W(O)).add(t),!0),await De())}async function ke(e){if(!await _h(Vs(),W(ie),e))return;let t=new Set(W(O));t.delete(e),B(O,t,!0),await De()}function Ae(e){let t=new Set(W(O));t.has(e)?t.delete(e):t.add(e),B(O,t,!0),Ee()}function je(e){let t=[];e.points.forEach((e,n)=>{e.forEach((e,r)=>{t.push(r===0&&n>0?{...e,gap:!0}:e)})}),ah(e.name,t)}async function Me(){let e=await Wm(Vs(),W(ie));e&&g.setRoutes(e)}let Ne=z(void 0);function Pe(e){B(Ne,e,!0)}function Fe(){B(Ne,void 0)}async function Ie(){return await Am(Vs(),W(ie))?(g.setActive(void 0),_.clear(),v.stop(),!0):!1}function Le(e){let t=g.routes.find(t=>t.id===e)?.waypoints[0]?.position;t&&W(Se)?.flyTo(t.latitude,t.longitude)}function Re(e,t){g.toggleShown(e,t),t&&Le(e)}function ze(){Fe(),g.setWorking({id:cc(),name:``,waypoints:[]}),W(Se)?.startRouteEdit()}function j(e){let t=g.routes.find(t=>t.id===e);t&&(g.setWorking(t),W(Se)?.startRouteEdit(t),Le(e))}async function Be(e){Fe();let t=g.working;if(!t||t.waypoints.length<2)return;let n={...t,name:e};if(!await Gm(Vs(),W(ie),n)){Pe(`Could not save the route. It is kept under edit so you can retry.`),g.setWorking(n);return}W(Se)?.stopRouteEdit(),g.setWorking(void 0),g.toggleShown(n.id,!0),await Me()}function Ve(){W(Se)?.stopRouteEdit(),g.setWorking(void 0)}async function M(e){if(Fe(),e===g.activeId&&!await Ie()){Pe(`Could not stop the active route, so it was not deleted.`);return}if(!await Km(Vs(),W(ie),e)){Pe(`Could not delete the route.`);return}g.toggleShown(e,!1),await Me()}async function He(e){if(Fe(),!await Om(Vs(),W(ie),`/resources/routes/${e}`)){Pe(`Could not activate the route. Check the connection.`);return}g.setActive(e),g.toggleShown(e,!0),Le(e);let{info:t,calc:n}=await jm(Vs(),W(ie));_.seed(t,n)}async function Ue(){Fe(),await Ie()||Pe(`Could not stop the active route. Check the connection.`)}let We=!1;Ln(()=>{let e=_.arrived&&g.activeId!==void 0;v.update(e,y.value),e&&!We&&!_.isLastPoint&&km(Vs(),W(ie),1).then(e=>{e||Pe(`Could not advance to the next waypoint.`)}),We=e});function Ge(){B(ae,void 0),W(Se)?.clearNoteSelection()}let Ke=()=>{d.prime(),v.prime()},qe={open:`Connected`,connecting:`Connecting`,reconnecting:`Reconnecting`,closed:`Not connected`},Je=R(()=>qe[r.connection.phase]),Ye=`${Vs()}/admin/#/security/access/requests`,Xe=!1;Ln(()=>{Xe||s.status!==`authenticated`&&s.status!==`unsecured`||(Xe=!0,F(s.token??void 0))});async function F(e){B(ie,e,!0),B(oe,fp(Vs(),e),!0),await o.connect(Hs(e),e=>r.applyFrame(e)),await o.raw.subscribe([{path:Us.headingTrue,policy:`instant`,minPeriod:200},{path:Us.position,policy:`instant`,minPeriod:1e3},{path:Us.courseOverGroundTrue,policy:`instant`,minPeriod:1e3},{path:Us.speedOverGround,policy:`instant`,minPeriod:1e3},{path:Us.courseNextPoint,policy:`instant`,minPeriod:1e3},{path:Us.coursePreviousPoint,policy:`instant`,minPeriod:1e3},{path:Us.courseActiveRoute,policy:`instant`,minPeriod:1e3},{path:Us.courseArrivalCircle,policy:`instant`,minPeriod:1e3},{path:Us.courseCalcValues,policy:`instant`,minPeriod:1e3},{path:Us.position,context:n,policy:`fixed`,period:5e3},{path:Us.courseOverGroundTrue,context:n,policy:`fixed`,period:5e3},{path:Us.speedOverGround,context:n,policy:`fixed`,period:5e3},{path:Us.headingTrue,context:n,policy:`fixed`,period:5e3},{path:Us.name,context:n,policy:`fixed`,period:5e3},{path:Us.aisShipType,context:n,policy:`fixed`,period:5e3},{path:Us.closestApproach,context:n,policy:`fixed`,period:5e3}]),await De(),await Me(),B(C,Dg(await Eg(Vs(),e)),!0)}ga(()=>{window.addEventListener(`pointerdown`,Ke,{once:!0}),s.watch(),s.probe()}),_a(()=>{be&&clearTimeout(be);for(let e of ye.values())e&&URL.revokeObjectURL(e);window.removeEventListener(`pointerdown`,Ke),d.stop(),s.stop(),c.dispose(),o.disconnect()});var Ze=VS(),et=V(Ze),I=V(et),tt=V(I);Kf(tt,{get items(){return W(we)},children:(e,t)=>{var n=FS(),r=Sn(n);Yf(r,{label:`Tracks`,get icon(){return Eo},children:(e,t)=>{th(e,{get recorder(){return h},get settings(){return m},get saved(){return W(D)},get shown(){return W(O)},onSave:Oe,onDelete:ke,onToggleSaved:Ae,onExport:je})},$$slots:{default:!0}}),Yf(H(r,2),{label:`Collision thresholds`,get icon(){return wo},children:(e,t)=>{Bf(e,{get thresholds(){return l}})},$$slots:{default:!0}}),q(e,n)},$$slots:{default:!0}});var nt=H(tt,2),rt=H(V(nt));rt.textContent=`v0.1.0`,N(nt),N(I);var it=H(I,2),at=V(it),ot=e=>{var t=IS();G(`click`,t,()=>le.update()),q(e,t)};Y(at,e=>{W(ce)&&e(ot)}),Jm(H(at,2),{get controller(){return ue}}),N(it),N(et);var st=H(et,2),ct=V(st);hS(ct,{get store(){return r},get vessel(){return i},get aisTargets(){return a},get collision(){return u},get recorder(){return h},get routeStore(){return g},get theme(){return ue.theme},get trackSettings(){return m},get savedTracks(){return A},get chartsToken(){return W(ie)},get initialView(){return fe},get savedLayers(){return pe.value},onLayersChange:e=>pe.set(e),get savedOrder(){return me.value},onOrderChange:e=>me.set(e),onReady:e=>B(ee,e,!0),onMapReady:e=>{re=e,e(ue.theme)},onCommandsReady:e=>B(Se,e,!0),onUserChartsReady:e=>B(ve,e,!0),onViewChange:xe,onNoteSelect:e=>B(ae,e,!0),onUserPan:()=>B(Ce,!1)});var lt=H(ct,2);Fd(V(lt),{get auth(){return s},get requestsUrl(){return Ye}}),N(lt);var ut=H(lt,2);tp(V(ut),{get guidance(){return _},onStop:Ue}),N(ut);var dt=H(ut,2);Pf(V(dt),{get collision(){return u}}),N(dt);var ft=H(dt,2),pt=e=>{var t=LS();Kp(V(t),{get selection(){return W(ae)},get load(){return W(oe).load},onClose:Ge}),N(t),q(e,t)};Y(ft,e=>{W(ae)&&W(oe)&&e(pt)});var mt=H(ft,2),ht=e=>{var t=RS();yf(V(t),{get view(){return W(ee)},get userCharts(){return _e},onClose:()=>B(te,!1)}),N(t),q(e,t)};Y(mt,e=>{W(te)&&W(ee)&&e(ht)});var gt=H(mt,2),_t=e=>{var t=zS();Vm(V(t),{get routes(){return g.routes},get shownIds(){return g.shownIds},get working(){return g.working},get activeId(){return g.activeId},get error(){return W(Ne)},onNew:ze,onEditRoute:j,onSave:Be,onCancelEdit:Ve,onToggleShown:Re,onLocate:Le,onActivate:He,onStop:Ue,onDelete:M,onClose:()=>{Ve(),Fe(),B(ne,!1)}}),N(t),q(e,t)};Y(gt,e=>{W(ne)&&e(_t)});var vt=H(gt,2),yt=e=>{{let t=R(()=>W(se)??fe);PS(e,{get store(){return b},get loader(){return x},get theme(){return ue.theme},get initialView(){return W(t)},get savedView(){return E},onViewChange:e=>T.set(e),get savedLayers(){return w.value},onLayersChange:e=>w.set(e),get token(){return W(ie)},get providerName(){return W(C)},get position(){return i.position},onClose:()=>B(S,!1)})}};Y(vt,e=>{W(S)&&e(yt)}),N(st);var bt=H(st,2),xt=V(bt),St=V(xt);let Ct;La(V(St),{size:16,"aria-hidden":`true`}),P(),N(St),N(xt);var wt=H(xt,2),Tt=V(wt,!0);N(wt);var Et=H(wt,2),Dt=e=>{q(e,BS())};Y(Et,e=>{c.online||e(Dt)});var Ot=H(Et,2),kt=H(V(Ot)),At=V(kt,!0);N(kt),P(),N(Ot);var jt=H(Ot,2),Mt=H(V(jt)),Nt=V(Mt,!0);N(Mt),P(),N(jt);var Pt=H(jt,6),Ft=V(Pt),It=V(Ft,!0);N(Ft),N(Pt);var Lt=H(Pt,2),Rt=V(Lt),zt=V(Rt,!0);N(Rt),N(Lt);var Bt=H(Lt,2),Vt=H(V(Bt)),Ht=V(Vt,!0);N(Vt),N(Bt),N(bt),N(Ze),U((e,t,n,r,i)=>{Ct=Li(St,1,`btn btn-pill forecast-btn svelte-1hicyxm`,null,Ct,{on:W(S)}),X(St,`aria-pressed`,W(S)),J(Tt,W(Je)),J(At,e),J(Nt,t),J(It,n),J(zt,r),J(Ht,i)},[()=>xc(gc(i.sogMps),1),()=>xc(_c(i.cogRad),0),()=>oc(W(se)?.lat),()=>sc(W(se)?.lon),()=>xc(W(se)?.zoom,1)]),G(`click`,St,()=>B(S,!W(S))),q(e,Ze),$e()}Xr([`click`]);var US=document.getElementById(`app`);if(!US)throw Error(`Missing #app mount element`);si(HS,{target:US});
830
+ }`;function dv(e,t,n){let r=e.createShader(t);if(!r)throw Error(`createShader failed`);if(e.shaderSource(r,n),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS))throw Error(e.getShaderInfoLog(r)??`shader compile failed`);return r}function fv(e,t,n){let r=e.createProgram();if(!r)throw Error(`createProgram failed`);if(e.attachShader(r,dv(e,e.VERTEX_SHADER,t)),e.attachShader(r,dv(e,e.FRAGMENT_SHADER,n)),e.linkProgram(r),!e.getProgramParameter(r,e.LINK_STATUS))throw Error(e.getProgramInfoLog(r)??`program link failed`);return r}function pv(e,t,n,r,i){let a=e.createTexture();if(!a)throw Error(`createTexture failed`);return e.bindTexture(e.TEXTURE_2D,a),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,r,i,0,e.RGBA,e.UNSIGNED_BYTE,n),e.bindTexture(e.TEXTURE_2D,null),a}function mv(e,t){let n=e.createBuffer();if(!n)throw Error(`createBuffer failed`);return e.bindBuffer(e.ARRAY_BUFFER,n),e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW),n}function hv(){try{let e=document.createElement(`canvas`),t=e.getContext(`webgl`)??e.getContext(`experimental-webgl`);return t?(fv(t,ov,cv),fv(t,lv,uv),!0):!1}catch{return!1}}var gv=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_=0;#v=0;#y;#b;#x;#S;#C;#w;#T=1;constructor(e,t={}){this.#e=e,this.#y=t.resolution??90,this.#b=this.#y*this.#y,this.#x=t.speedFactor??8e-4,this.#S=t.dropRate??.003,this.#C=t.dropRateBump??.01,this.#w=t.fadeOpacity??.96,this.#t=fv(e,ov,cv),this.#n=fv(e,lv,uv),this.#r=fv(e,ov,sv),this.#i={aPos:e.getAttribLocation(this.#r,`a_pos`),uScreen:e.getUniformLocation(this.#r,`u_screen`),uOpacity:e.getUniformLocation(this.#r,`u_opacity`)},this.#a={aPos:e.getAttribLocation(this.#t,`a_pos`),uParticles:e.getUniformLocation(this.#t,`u_particles`),uWind:e.getUniformLocation(this.#t,`u_wind`),uWindMin:e.getUniformLocation(this.#t,`u_wind_min`),uWindMax:e.getUniformLocation(this.#t,`u_wind_max`),uRandSeed:e.getUniformLocation(this.#t,`u_rand_seed`),uSpeedFactor:e.getUniformLocation(this.#t,`u_speed_factor`),uDropRate:e.getUniformLocation(this.#t,`u_drop_rate`),uDropRateBump:e.getUniformLocation(this.#t,`u_drop_rate_bump`)},this.#o={aIndex:e.getAttribLocation(this.#n,`a_index`),uParticles:e.getUniformLocation(this.#n,`u_particles`),uWind:e.getUniformLocation(this.#n,`u_wind`),uColorRamp:e.getUniformLocation(this.#n,`u_color_ramp`),uParticlesRes:e.getUniformLocation(this.#n,`u_particles_res`),uMatrix:e.getUniformLocation(this.#n,`u_matrix`),uWindMin:e.getUniformLocation(this.#n,`u_wind_min`),uWindMax:e.getUniformLocation(this.#n,`u_wind_max`),uBounds:e.getUniformLocation(this.#n,`u_bounds`)},this.#s=mv(e,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]));let n=new Float32Array(this.#b);for(let e=0;e<this.#b;e+=1)n[e]=e;this.#c=mv(e,n);let r=e.createFramebuffer();if(!r)throw Error(`createFramebuffer failed`);this.#l=r,this.#u=pv(e,e.LINEAR,null,256,1);let i=this.#E();this.#p=pv(e,e.NEAREST,i,this.#y,this.#y),this.#m=pv(e,e.NEAREST,i,this.#y,this.#y),this.#h=pv(e,e.NEAREST,null,1,1),this.#g=pv(e,e.NEAREST,null,1,1)}#E(){let e=new Uint8Array(this.#b*4);for(let t=0;t<e.length;t+=1)e[t]=Math.floor(Math.random()*256);return e}setWind(e){this.#f=e;let t=this.#e;this.#d&&t.deleteTexture(this.#d),this.#d=pv(t,t.LINEAR,e.data,e.width,e.height)}setTheme(e){let t=this.#e;t.bindTexture(t.TEXTURE_2D,this.#u),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,256,1,0,t.RGBA,t.UNSIGNED_BYTE,e),t.bindTexture(t.TEXTURE_2D,null)}setOpacity(e){this.#T=e}#D(e,t){if(e===this.#_&&t===this.#v)return;let n=this.#e;n.deleteTexture(this.#h),n.deleteTexture(this.#g);let r=new Uint8Array(e*t*4);this.#h=pv(n,n.NEAREST,r,e,t),this.#g=pv(n,n.NEAREST,r,e,t),this.#_=e,this.#v=t}#O(e,t,n){let r=this.#e;r.bindBuffer(r.ARRAY_BUFFER,e),r.enableVertexAttribArray(t),r.vertexAttribPointer(t,n,r.FLOAT,!1,0,0)}#k(e,t){let n=this.#e,r=this.#i;n.useProgram(this.#r),this.#O(this.#s,r.aPos,2),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,e),n.uniform1i(r.uScreen,0),n.uniform1f(r.uOpacity,t),n.drawArrays(n.TRIANGLES,0,6)}#A(){let e=this.#e;if(!this.#d||!this.#f)return;let t=this.#a;e.bindFramebuffer(e.FRAMEBUFFER,this.#l),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.#m,0),e.viewport(0,0,this.#y,this.#y),e.useProgram(this.#t),this.#O(this.#s,t.aPos,2),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.#p),e.uniform1i(t.uParticles,0),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,this.#d),e.uniform1i(t.uWind,1),e.uniform2f(t.uWindMin,this.#f.uMin,this.#f.vMin),e.uniform2f(t.uWindMax,this.#f.uMax,this.#f.vMax),e.uniform1f(t.uRandSeed,Math.random()),e.uniform1f(t.uSpeedFactor,this.#x),e.uniform1f(t.uDropRate,this.#S),e.uniform1f(t.uDropRateBump,this.#C),e.drawArrays(e.TRIANGLES,0,6);let n=this.#p;this.#p=this.#m,this.#m=n}#j(e){let t=this.#e;if(!this.#d||!this.#f)return;let n=this.#o;t.useProgram(this.#n),this.#O(this.#c,n.aIndex,1),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.#p),t.uniform1i(n.uParticles,0),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.#d),t.uniform1i(n.uWind,1),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.#u),t.uniform1i(n.uColorRamp,2),t.uniform1f(n.uParticlesRes,this.#y),t.uniformMatrix4fv(n.uMatrix,!1,e),t.uniform2f(n.uWindMin,this.#f.uMin,this.#f.vMin),t.uniform2f(n.uWindMax,this.#f.uMax,this.#f.vMax),t.uniform4f(n.uBounds,this.#f.west,this.#f.south,this.#f.east,this.#f.north),t.drawArrays(t.POINTS,0,this.#b)}render(e,t,n,r){let i=this.#e;if(!this.#d||!this.#f)return;this.#D(t,n),i.disable(i.DEPTH_TEST),i.disable(i.STENCIL_TEST),this.#A(),i.bindFramebuffer(i.FRAMEBUFFER,this.#l),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,this.#g,0),i.viewport(0,0,t,n),r?(i.clearColor(0,0,0,0),i.clear(i.COLOR_BUFFER_BIT)):this.#k(this.#h,this.#w),i.enable(i.BLEND),i.blendFunc(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA),this.#j(e),i.disable(i.BLEND),i.bindFramebuffer(i.FRAMEBUFFER,null),i.enable(i.BLEND),i.blendFunc(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA),this.#k(this.#g,this.#T),i.disable(i.BLEND);let a=this.#h;this.#h=this.#g,this.#g=a}dispose(){let e=this.#e;e.deleteProgram(this.#t),e.deleteProgram(this.#n),e.deleteProgram(this.#r),e.deleteBuffer(this.#s),e.deleteBuffer(this.#c),e.deleteFramebuffer(this.#l),e.deleteTexture(this.#u),e.deleteTexture(this.#p),e.deleteTexture(this.#m),e.deleteTexture(this.#h),e.deleteTexture(this.#g),this.#d&&e.deleteTexture(this.#d)}},_v=`binnacle-weather-wind`,vv=`binnacle-weather-wind-line`,yv=`binnacle-weather-wind-particles`;function bv(e){return Array.isArray(e)?e:e.defaultProjectionData?.mainMatrix??[]}function xv(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function Sv(e){let t=hv(),n=`day`,r=1,i=!1,a,o=NaN,s,c=[];function l(e){return Zh(e)}function u(e){if(!e.map.getSource(_v)){let t={type:`geojson`,data:od()};e.map.addSource(_v,t)}if(!e.map.getLayer(vv)){let t={id:vv,type:`line`,source:_v,layout:{"line-cap":`round`,visibility:i?`visible`:`none`},paint:{"line-color":l(n),"line-width":2,"line-opacity":r}};e.map.addLayer(t,e.beforeIdFor(`weather`))}}function d(t){let n=e.grid;t.map.getSource(_v)?.setData(n?rv(n,e.bracket):od())}function f(){if(!s)return;let t=e.grid,n=t?av(t,e.bracket):void 0;n&&s.setWind(n)}function p(e){let t={id:yv,type:`custom`,onAdd(t,i){try{s=new gv(i),s.setTheme(iv(n)),s.setOpacity(r),f()}catch(t){console.warn(`[wind] particle init failed, using arrows`,t),s=void 0,u(e),d(e)}},render(t,n){if(!s||!i)return;let r=bv(n);if(r.length<16)return;let a=!xv(r,c);c=r,s.render(r,t.drawingBufferWidth,t.drawingBufferHeight,a),e.map.triggerRepaint()},onRemove(){s?.dispose(),s=void 0}};e.map.addLayer(t,e.beforeIdFor(`weather`))}return{id:Oh.wind,title:`Wind`,band:`weather`,supportsOpacity:!0,defaultVisible:!1,layerIds:[yv,vv],add(e){a=void 0,o=NaN,t?p(e):u(e)},sync(t){let n=e.grid;n===a&&e.selectedTime===o||(a=n,o=e.selectedTime,f(),!s&&t.map.getLayer(vv)&&d(t))},remove(e){e.map.getLayer(yv)&&e.map.removeLayer(yv),e.map.getLayer(vv)&&e.map.removeLayer(vv),e.map.getSource(_v)&&e.map.removeSource(_v)},setVisible(e,t){i=t,e.map.getLayer(vv)&&e.map.setLayoutProperty(vv,`visibility`,t?`visible`:`none`),t&&e.map.triggerRepaint()},setOpacity(e,t){r=t,s?.setOpacity(t),e.map.getLayer(vv)&&e.map.setPaintProperty(vv,`line-opacity`,t)},applyTheme(e,t){n=t.theme,s?.setTheme(iv(n)),e.map.getLayer(vv)&&e.map.setPaintProperty(vv,`line-color`,l(n))}}}var Cv=class{#e=z(dn(typeof navigator>`u`?!0:navigator.onLine));get online(){return W(this.#e)}set online(e){B(this.#e,e,!0)}#t;constructor(){if(typeof window>`u`)return;let e=()=>{this.online=!0},t=()=>{this.online=!1};window.addEventListener(`online`,e),window.addEventListener(`offline`,t),this.#t=()=>{window.removeEventListener(`online`,e),window.removeEventListener(`offline`,t)}}dispose(){this.#t?.(),this.#t=void 0}},wv=`modulepreload`,Tv=function(e){return`/signalk-binnacle/`+e},Ev={},Dv=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}r=o(t.map(t=>{if(t=Tv(t,n),t in Ev)return;Ev[t]=!0;let r=t.endsWith(`.css`),i=r?`[rel="stylesheet"]`:``;if(n)for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${t}"]${i}`))return;let o=document.createElement(`link`);if(o.rel=r?`stylesheet`:wv,r||(o.as=`script`),o.crossOrigin=``,o.href=t,a&&o.setAttribute(`nonce`,a),document.head.appendChild(o),r)return new Promise((e,n)=>{o.addEventListener(`load`,e),o.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},Ov=`false`,kv=`false`,Av=Ov===`true`,jv=kv===`true`;function Mv(e={}){let{immediate:t=!1,onNeedReload:n,onNeedRefresh:r,onOfflineReady:i,onRegistered:a,onRegisteredSW:o,onRegisterError:s}=e,c,l,u,d=async(e=!0)=>{await l,Av||u?.()};async function f(){if(`serviceWorker`in navigator){if(c=await Dv(async()=>{let{Workbox:e}=await import(`./workbox-window.prod.es5-Bd17z0YL.js`);return{Workbox:e}},[]).then(({Workbox:e})=>new e(`/signalk-binnacle/sw.js`,{scope:`/signalk-binnacle/`,type:`classic`})).catch(e=>{s?.(e)}),!c)return;if(u=()=>{c?.messageSkipWaiting()},!jv)if(Av)c.addEventListener(`activated`,e=>{(e.isUpdate||e.isExternal)&&(n?n():window.location.reload())}),c.addEventListener(`installed`,e=>{e.isUpdate||i?.()});else{let e=!1,t=()=>{e=!0,c?.addEventListener(`controlling`,e=>{e.isUpdate&&(n?n():window.location.reload())}),r?.()};c.addEventListener(`installed`,n=>{n.isUpdate===void 0?n.isExternal===void 0?!e&&i?.():n.isExternal?t():!e&&i?.():n.isUpdate||i?.()}),c.addEventListener(`waiting`,t)}c.register({immediate:t}).then(e=>{o?o(`/signalk-binnacle/sw.js`,e):a?.(e)}).catch(e=>{s?.(e)})}}return l=f(),d}function Nv(e){let t=Mv({onNeedRefresh:()=>e?.(),onRegisterError:e=>console.warn(`[pwa] service worker registration failed`,e)});return{update:()=>void t(!0)}}var Pv=`binnacle-ais-icon`,Fv=28;function Iv(e){return sd(Fv,e,(e,t,n)=>{let r=t/2.6,i=Math.abs(e-n);return t>3&&Math.abs(i-r)<=1.4&&i<=r+1.4||t>=Fv-3&&i<=r})}var Lv=`binnacle-ais`,Rv=`binnacle-ais-symbol`,zv=36e4,Bv=5e3,Vv={r:224,g:160,b:32,a:255};function Hv(e,t){let n=-1,r=0;function i(){return{type:`FeatureCollection`,features:e.list().map(e=>({type:`Feature`,geometry:{type:`Point`,coordinates:[e.position.longitude,e.position.latitude]},properties:{id:e.id,name:e.name??``,heading:vc(e.headingRad,e.cogRad)}}))}}function a(){let e=Date.now();e-r<Bv||(r=e,t.pruneAis(e,zv))}function o(){return t.aisVersion===n?!1:(n=t.aisVersion,!0)}return vd({id:`ais`,title:`AIS targets`,band:`traffic`,sourceId:Lv,layerId:Rv,iconId:Pv,iconImage:Iv,defaultColor:Vv,paintColor:e=>e.aisTarget,features:i,shouldRefresh:o,beforeSync:a})}var Uv=`/signalk/v2/api/resources/charts`,Wv=`/signalk/v1/api/resources/charts`;async function Gv(e,t){return await Js(e,[Uv,Wv],t,(e,t)=>t,(e,t)=>console.warn(`[charts] ${e} returned ${t}`))??[]}var Kv=`streaming-`,qv=e=>`${Kv}${e}`,Jv=e=>`${Kv}${e}-layer`;function Yv(e){let t=qv(e.id),n=Jv(e.id);return{id:e.id,title:e.title,band:`bathymetry`,supportsOpacity:!0,defaultVisible:!1,layerIds:[n],add(r){if(!r.map.getSource(t)){let n={type:`raster`,tiles:[...e.tiles],tileSize:e.tileSize??256,attribution:e.attribution};e.minzoom!==void 0&&(n.minzoom=e.minzoom),e.maxzoom!==void 0&&(n.maxzoom=e.maxzoom),e.bounds&&(n.bounds=e.bounds),r.map.addSource(t,n)}if(!r.map.getLayer(n)){let e={id:n,type:`raster`,source:t};r.map.addLayer(e,r.beforeIdFor(`bathymetry`))}},remove(e){e.map.getLayer(n)&&e.map.removeLayer(n),e.map.getSource(t)&&e.map.removeSource(t)},setVisible(e,t){e.map.setLayoutProperty(n,`visibility`,t?`visible`:`none`)},setOpacity(e,t){e.map.setPaintProperty(n,`raster-opacity`,t)},applyTheme(e,t){cl(e.map,n,t)}}}var Xv=[{id:`depth-gebco`,title:`GEBCO global bathymetry`,tiles:[`https://wms.gebco.net/mapserv?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&LAYERS=GEBCO_LATEST&CRS=EPSG:3857&BBOX={bbox-epsg-3857}&WIDTH=256&HEIGHT=256&FORMAT=image/png&TRANSPARENT=true&STYLES=`],tileSize:256,minzoom:0,maxzoom:12,attribution:`GEBCO_2024 Grid, GEBCO Compilation Group (2024)`},{id:`depth-emodnet`,title:`EMODnet bathymetry (Europe)`,tiles:[`https://ows.emodnet-bathymetry.eu/wms?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&LAYERS=emodnet:mean_multicolour&CRS=EPSG:3857&BBOX={bbox-epsg-3857}&WIDTH=256&HEIGHT=256&FORMAT=image/png&TRANSPARENT=true&STYLES=`],tileSize:256,minzoom:0,maxzoom:12,bounds:[-73.125,5.625,45,90],attribution:`EMODnet Bathymetry Consortium (2022): EMODnet Digital Bathymetry (DTM)`},{id:`depth-noaa-enc`,title:`NOAA ENC chart (US)`,tiles:[`https://gis.charttools.noaa.gov/arcgis/rest/services/MCS/NOAAChartDisplay/MapServer/exts/MaritimeChartService/WMSServer?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&LAYERS=0,1,2,3,4,5,6,7,8,9,10,11,12&CRS=EPSG:3857&BBOX={bbox-epsg-3857}&WIDTH=256&HEIGHT=256&FORMAT=image/png&TRANSPARENT=true&STYLES=`],tileSize:256,minzoom:0,maxzoom:18,bounds:[-180,-15,180,75],attribution:`NOAA Office of Coast Survey, Electronic Navigational Charts (ENC)`},{id:`depth-bluetopo`,title:`NOAA BlueTopo bathymetry (US)`,tiles:[`https://nowcoast.noaa.gov/geoserver/gwc/service/wmts?SERVICE=WMTS&VERSION=1.0.0&REQUEST=GetTile&LAYER=bluetopo:bathymetry&STYLE=&TILEMATRIXSET=EPSG:3857&TILEMATRIX=EPSG:3857:{z}&TILEROW={y}&TILECOL={x}&FORMAT=image/png8`],tileSize:512,minzoom:0,maxzoom:16,bounds:[-138,-53.876,17.046,59.55],attribution:`NOAA Office of Coast Survey, BlueTopo / National Bathymetric Source`}];function Zv(){return Zv=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Zv.apply(null,arguments)}var Qv=`draw`,$v=`edit`,ey=`deleteCoordinate`,ty=`insertMidpoint`,ny;(function(e){e.Commit=`commit`,e.Provisional=`provisional`,e.Finish=`finish`})(ny||={});var ry=`https://raw.githubusercontent.com/JamesLMilner/terra-draw/refs/heads/main/assets/markers/marker-blue.png`,iy={SELECTED:`selected`,MID_POINT:`midPoint`,SELECTION_POINT_FEATURE_ID:`selectionPointFeatureId`,SELECTION_POINT:`selectionPoint`},ay={MODE:`mode`,CURRENTLY_DRAWING:`currentlyDrawing`,EDITED:`edited`,CLOSING_POINT:`closingPoint`,SNAPPING_POINT:`snappingPoint`,COORDINATE_POINT:`coordinatePoint`,COORDINATE_POINT_FEATURE_ID:`coordinatePointFeatureId`,COORDINATE_POINT_IDS:`coordinatePointIds`,PROVISIONAL_COORDINATE_COUNT:`provisionalCoordinateCount`,COMMITTED_COORDINATE_COUNT:`committedCoordinateCount`,MARKER:`marker`},oy=10;function sy(e){return!!(e&&typeof e==`object`&&e&&!Array.isArray(e))}function cy(e){return!!(e&&typeof e==`object`&&`properties`in e&&typeof e.properties==`object`&&e.properties!==null&&`mode`in e.properties)}function ly(e){return!!function(e){return typeof e==`number`&&!isNaN(new Date(e).valueOf())}(e)}var uy=`Feature mode property does not match the mode being added to`,dy;(function(e){e.Drawing=`drawing`,e.Select=`select`,e.Static=`static`,e.Render=`render`})(dy||={});var fy={rightClick:!0,contextMenu:!1,leftClick:!0,onDragStart:!0,onDrag:!0,onDragEnd:!0},py=class{get state(){return this._state}set state(e){throw Error(`Please use the modes lifecycle methods`)}get styles(){return this._styles}set styles(e){if(typeof e!=`object`)throw Error(`Styling must be an object`);this.onStyleChange&&this.onStyleChange([],`styling`),this._styles=e}registerBehaviors(e){}constructor(e,t=!1){this._state=`unregistered`,this._styles={},this.pointerEvents=fy,this.behaviors=[],this.validate=void 0,this.pointerDistance=40,this.coordinatePrecision=void 0,this.undoRedoMaxStackSize=void 0,this.onStyleChange=void 0,this.store=void 0,this.projection=`web-mercator`,this.setDoubleClickToZoom=void 0,this.unproject=void 0,this.project=void 0,this.setCursor=void 0,this.isInitialUpdate=!1,this.type=dy.Drawing,this.mode=`base`,t?this.isInitialUpdate=!0:this.updateOptions(Zv({},e))}updateOptions(e){e!=null&&e.styles&&(this.styles=Zv({},this._styles,e.styles)),e!=null&&e.pointerDistance&&(this.pointerDistance=e.pointerDistance),e!=null&&e.validation&&(this.validate=e&&e.validation),e!=null&&e.projection&&(this.projection=e.projection),e?.pointerEvents!==void 0&&(this.pointerEvents=e.pointerEvents),e!=null&&e.modeName&&!0===this.isInitialUpdate&&(this.mode=e.modeName),this.isInitialUpdate=!1}allowPointerEvent(e,t){return typeof e==`boolean`?e:typeof e!=`function`||e(t)}setDrawing(){if(this._state!==`started`)throw Error(`Mode must be unregistered or stopped to start`);this._state=`drawing`}setStarted(){if(this._state!==`stopped`&&this._state!==`registered`&&this._state!==`drawing`&&this._state!==`selecting`)throw Error(`Mode must be unregistered or stopped to start`);this._state=`started`,this.setDoubleClickToZoom(!1)}setStopped(){if(this._state!==`started`)throw Error(`Mode must be started to be stopped`);this._state=`stopped`,this.setDoubleClickToZoom(!0)}register(e){if(this._state!==`unregistered`)throw Error(`Can not register unless mode is unregistered`);this._state=`registered`,this.store=e.store,this.store.registerOnChange(e.onChange),this.setDoubleClickToZoom=e.setDoubleClickToZoom,this.project=e.project,this.unproject=e.unproject,this.onSelect=e.onSelect,this.onDeselect=e.onDeselect,this.setCursor=e.setCursor,this.onStyleChange=e.onChange,this.onFinish=e.onFinish,this.coordinatePrecision=e.coordinatePrecision,this.undoRedoMaxStackSize=e.undoRedoMaxStackSize,this.registerBehaviors({mode:e.mode,store:this.store,project:this.project,unproject:this.unproject,pointerDistance:this.pointerDistance,coordinatePrecision:e.coordinatePrecision,projection:this.projection,undoRedoMaxStackSize:e.undoRedoMaxStackSize})}validateFeature(e){return this.performFeatureValidation(e)}afterFeatureAdded(e){}afterFeatureUpdated(e){}performFeatureValidation(e){if(this._state===`unregistered`)throw Error(`Mode must be registered`);let t=function(e,t){let n;if(sy(e))if(e.id==null)n=`Feature has no id`;else if(typeof e.id!=`string`&&typeof e.id!=`number`)n=`Feature must be string or number as per GeoJSON spec`;else if(t(e.id))if(sy(e.geometry))if(sy(e.properties))if(typeof e.geometry.type==`string`&&[`Polygon`,`LineString`,`Point`].includes(e.geometry.type))if(Array.isArray(e.geometry.coordinates)){if(!e.properties.mode||typeof e.properties.mode!=`string`)return{valid:!1,reason:`Feature does not have a valid mode property`}}else n=`Feature coordinates is not an array`;else n=`Feature is not Point, LineString or Polygon`;else n=`Feature has no properties`;else n=`Feature has no geometry`;else n=`Feature must match the id strategy (default is UUID4)`;else n=`Feature is not object`;return n?{valid:!1,reason:n}:{valid:!0}}(e,this.store.idStrategy.isValidId);if(!t.valid)return t;if(this.validate){let n=this.validate(e,{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:ny.Provisional});return{valid:t.valid&&n.valid,reason:n.reason}}return{valid:t.valid,reason:t.reason}}validateModeFeature(e,t){let n=this.performFeatureValidation(e);return n.valid?e.properties.mode===this.mode?t(e):{valid:!1,reason:uy}:{valid:!1,reason:n.reason}}onFinish(e,t){}onDeselect(e){}onSelect(e){}onKeyDown(e){}onKeyUp(e){}undo(){}clearHistory(){}undoSize(){return 0}redoSize(){return 0}redo(){}onMouseMove(e){}onClick(e){}onDragStart(e,t){}onDrag(e,t){}onDragEnd(e,t){}getHexColorStylingValue(e,t,n){return this.getStylingValue(e,t,n)}getNumericStylingValue(e,t,n){return this.getStylingValue(e,t,n)}getUrlStylingValue(e,t,n){return this.getStylingValue(e,t,n)}getStylingValue(e,t,n){return e===void 0?t:typeof e==`function`?(r=e(n))??t:e;var r}},my=class extends py{constructor(...e){super(...e),this.type=dy.Select}};function hy(e,t){let n=e=>e*Math.PI/180,r=n(e[1]),i=n(e[0]),a=n(t[1]),o=a-r,s=n(t[0])-i,c=Math.sin(o/2)*Math.sin(o/2)+Math.cos(r)*Math.cos(a)*Math.sin(s/2)*Math.sin(s/2);return 2*Math.atan2(Math.sqrt(c),Math.sqrt(1-c))*6371e3/1e3}var gy=6371008.8;function _y(e){return e%360*Math.PI/180}function vy(e){return e/6371.0088}function yy(e){return e%(2*Math.PI)*180/Math.PI}function by(e,t=9){let n=10**t;return Math.round(e*n)/n}var xy=57.29577951308232,Sy=.017453292519943295,Cy=6378137,wy=(e,t)=>({x:e===0?0:e*Sy*Cy,y:t===0?0:Math.log(Math.tan(Math.PI/4+t*Sy/2))*Cy}),Ty=(e,t)=>({lng:e===0?0:e/Cy*xy,lat:t===0?0:(2*Math.atan(Math.exp(t/Cy))-Math.PI/2)*xy});function Ey(e){let t;if(e.geometry.type===`Polygon`)t=e.geometry.coordinates;else{if(e.geometry.type!==`LineString`)throw Error(`Self intersects only accepts Polygons and LineStrings`);t=[e.geometry.coordinates]}let n=[];for(let e=0;e<t.length;e++)for(let n=0;n<t[e].length-1;n++)for(let r=0;r<t.length;r++)for(let a=0;a<t[r].length-1;a++)i(e,n,r,a);return n.length>0;function r(e){return e<0||e>1}function i(e,i,a,o){let s=t[e][i],c=t[e][i+1],l=t[a][o],u=t[a][o+1],d=function(e,t,n,r){if(Dy(e,n)||Dy(e,r)||Dy(t,n)||Dy(r,n))return null;let i=e[0],a=e[1],o=t[0],s=t[1],c=n[0],l=n[1],u=r[0],d=r[1],f=(i-o)*(l-d)-(a-s)*(c-u);return f===0?null:[((i*s-a*o)*(c-u)-(i-o)*(c*d-l*u))/f,((i*s-a*o)*(l-d)-(a-s)*(c*d-l*u))/f]}(s,c,l,u);if(d===null)return;let f,p;f=c[0]===s[0]?(d[1]-s[1])/(c[1]-s[1]):(d[0]-s[0])/(c[0]-s[0]),p=u[0]===l[0]?(d[1]-l[1])/(u[1]-l[1]):(d[0]-l[0])/(u[0]-l[0]),r(f)||r(p)||(d.toString(),n.push(d))}}function Dy(e,t){return e[0]===t[0]&&e[1]===t[1]}function Oy(e,t){return Ay(e[0])<=t&&Ay(e[1])<=t}function ky(e){return e.length===2&&typeof e[0]==`number`&&typeof e[1]==`number`&&e[0]!==1/0&&e[1]!==1/0&&(n=e[0])>=-180&&n<=180&&(t=e[1])>=-90&&t<=90;var t,n}function Ay(e){let t=1,n=0;for(;Math.round(e*t)/t!==e;)t*=10,n++;return n}var jy=class{constructor({store:e,mode:t,project:n,unproject:r,pointerDistance:i,coordinatePrecision:a,projection:o,undoRedoMaxStackSize:s}){this.store=void 0,this.mode=void 0,this.project=void 0,this.unproject=void 0,this.pointerDistance=void 0,this.coordinatePrecision=void 0,this.projection=void 0,this.undoRedoMaxStackSize=void 0,this.store=e,this.mode=t,this.project=n,this.unproject=r,this.pointerDistance=i,this.coordinatePrecision=a,this.projection=o,this.undoRedoMaxStackSize=s}};function My(e){if(!function(e){let t=e.coordinates[0],n=0;for(let e=0;e<t.length-1;e++){let[r,i]=t[e],[a,o]=t[e+1];n+=(a-r)*(o+i)}return n<0}(e))return{type:`Polygon`,coordinates:[e.coordinates[0].reverse()]}}var Ny=`insert-before`,Py=`insert-after`,Fy=`update`,Iy=`delete`,Ly=`replace`,Ry=class extends jy{constructor(e,t){super(e),this.options=void 0,this.options=t}createPoint({coordinates:e,properties:t,context:n}){if(n?.updateType!==ny.Finish||this.validateGeometryWithUpdateType({geometry:{type:`Point`,coordinates:e},properties:t,updateType:ny.Finish}))return this.handleCreateFeature({geometry:{type:`Point`,coordinates:e},properties:t})}createLineString({coordinates:e,properties:t}){return this.handleCreateFeature({geometry:{type:`LineString`,coordinates:e},properties:t})}createPolygon({coordinates:e,properties:t,context:n}){let r=My({type:`Polygon`,coordinates:[e]}),i={type:`Polygon`,coordinates:r?r.coordinates:[e]};if(n?.updateType!==ny.Finish||this.validateGeometryWithUpdateType({geometry:i,properties:t,updateType:ny.Finish}))return this.handleCreateFeature({geometry:i,properties:t})}createGuidancePoint({coordinate:e,type:t}){return this.createGuidancePoints({coordinates:[e],type:t})[0]}createGuidancePoints({coordinates:e,type:t,additionalProperties:n}){let r=e.map((e,r)=>({type:`Feature`,geometry:{type:`Point`,coordinates:e},properties:Zv({mode:this.mode,[t]:!0},n?n(r):{})}));return this.createFeatures(r)}updatePoint({featureId:e,coordinateMutations:t,propertyMutations:n,context:r}){return this.handleMutateFeature({type:`Point`,featureId:e,coordinateMutations:t,propertyMutations:n,context:r})}updatePolygon({featureId:e,coordinateMutations:t,context:n,propertyMutations:r}){return this.handleMutateFeature({type:`Polygon`,featureId:e,coordinateMutations:t,propertyMutations:r,context:n})}updateLineString({featureId:e,coordinateMutations:t,context:n,propertyMutations:r}){return this.handleMutateFeature({type:`LineString`,featureId:e,coordinateMutations:t,propertyMutations:r,context:n})}deleteFeatureIfPresent(e){e&&this.store.has(e)&&this.store.delete([e])}deleteFeaturesIfPresent(e){if(e.length===0)return;let t=e.filter(e=>this.store.has(e));t.length&&this.store.delete(t)}setDeselected(e){let t=e.filter(e=>this.store.has(e)).map(e=>({featureId:e,properties:{[iy.SELECTED]:!1}}));this.updateFeatureProperties(t)}setSelected(e){let{type:t}=this.store.getGeometryCopy(e),n={featureId:e,propertyMutations:{[iy.SELECTED]:!0},context:{updateType:ny.Commit}};t===`Polygon`?this.updatePolygon(n):t===`LineString`?this.updateLineString(n):t===`Point`&&this.updatePoint(n)}updateGuidancePoints(e){this.updateFeatureGeometries(e.map(({featureId:e,coordinate:t})=>({id:e,geometry:{type:`Point`,coordinates:t}})))}handleCreateFeature({geometry:e,properties:t}){return this.createFeatureWithGeometry({geometry:e,properties:t})}handleMutateFeature({type:e,featureId:t,coordinateMutations:n,propertyMutations:r,context:i}){if(!this.mutateFeature({type:e,featureId:t,coordinateMutations:n,propertyMutations:r,context:i.updateType===ny.Finish?Zv({},i,{correctRightHandRule:!0}):Zv({},i)}))return null;let a=this.buildFeatureWithGeometry(t);return i.updateType!==ny.Finish||n||this.validateGeometryWithUpdateType({geometry:a.geometry,properties:a.properties,updateType:i.updateType})?a:null}mutateFeature({type:e,featureId:t,coordinateMutations:n,propertyMutations:r,context:i}){if(!t)return!1;let a=this.store.getGeometryCopy(t),o=this.store.getPropertiesCopy(t);if(a.type!==e)throw Error(`${e} geometries cannot be updated on features with ${a.type} geometries`);if(n){let e=this.applyCoordinateMutations(a,n);if(i.correctRightHandRule&&e.type===`Polygon`){let t=My(e);t&&(e=t)}if(!this.validateGeometryWithUpdateType({geometry:e,properties:o,updateType:i.updateType}))return!1;this.updateFeatureGeometries([{id:t,geometry:e}])}return r&&this.updateFeatureProperties([{featureId:t,properties:r}]),!0}applyCoordinateMutations(e,t){if(this.isReplaceMutation(t))return Zv({},e,{coordinates:t.coordinates});if(e.type===`Point`)throw Error(`Coordinate mutations are not supported for Point geometries`);let n=e.type===`Polygon`,r=n?e.coordinates[0].slice():e.coordinates.slice(),i=r.length,a=e=>{let t=e<0?i+e:e;if(t<0||t>=i)throw RangeError(`Index ${e} (normalized to ${t}) is out of bounds`);return t},o=Array(i).fill(void 0),s=Array.from({length:i},()=>[]),c=Array.from({length:i},()=>[]),l=[];for(let e of t){if(e.type===Ny||e.type===Py){let t=e.index,n=t<0?i+t:t;if(n<0||n>i)throw RangeError(`Index ${e.index} (normalized to ${n}) is out of bounds`);if(e.type===Ny){if(n>=i)throw RangeError(`INSERT_BEFORE index ${e.index} (normalized to ${n}) is out of bounds for length ${i}`);s[n].push(e)}else n===i?l.push(e):c[n].push(e);continue}let t=a(e.index);o[t]=Zv({},e,{index:t})}let u=[];for(let e=0;e<i;e++){let t=s[e];for(let e of t)u.push(e.coordinate);let n=o[e];n?n.type===Iy||u.push(n.coordinate):u.push(r[e]);let i=c[e];for(let e of i)u.push(e.coordinate)}for(let e of l)u.push(e.coordinate);return Zv({},e,n?{coordinates:[u,...e.coordinates.slice(1)]}:{coordinates:u})}isReplaceMutation(e){return e.type===Ly}createFeatureWithGeometry({geometry:e,properties:t}){let[n]=this.createFeatures([{type:`Feature`,geometry:e,properties:t}]);return{id:n,type:`Feature`,properties:this.store.getPropertiesCopy(n),geometry:this.store.getGeometryCopy(n)}}validateGeometryWithUpdateType({geometry:e,properties:t,updateType:n}){return!this.options.validate||this.options.validate({type:`Feature`,geometry:e,properties:t||{}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:n}).valid}buildFeatureWithGeometry(e){return{id:e,type:`Feature`,properties:this.store.getPropertiesCopy(e),geometry:this.store.getGeometryCopy(e)}}createFeatures(e){return this.store.create(e)}updateFeatureGeometries(e){this.store.updateGeometry(e)}updateFeatureProperties(e){let t=e.map(({featureId:e,properties:t})=>Object.entries(t).map(([t,n])=>({id:e,property:t,value:n}))).flat();this.store.updateProperty(t)}},zy=(e,t)=>{let{x:n,y:r}=e,{x:i,y:a}=t,o=i-n,s=a-r;return Math.sqrt(s*s+o*o)};function By(e,t){return e[0]===t[0]&&e[1]===t[1]}var Vy=class extends jy{constructor(e){super(e)}getGeometryType(e){return this.store.getGeometryCopy(e).type}coordinateAtIndexIsIdentical({featureId:e,newCoordinate:t,index:n}){let r=this.store.getGeometryCopy(e),i;if(r.type===`Polygon`)i=r.coordinates[0][n];else if(r.type===`LineString`)i=r.coordinates[n];else{if(n!==0)throw Error(`Point geometries only have one coordinate at index 0`);i=r.coordinates}return By(t,i)}getGeometry(e){return this.store.getGeometryCopy(e)}getCoordinates(e){let{type:t,coordinates:n}=this.store.getGeometryCopy(e);return t===`Polygon`?n[0]:n}getCoordinate(e,t){let n=this.getCoordinates(e),r=t<0?n.length+t:t;if(r<0||r>=n.length)throw RangeError(`Index ${t} (normalized to ${r}) is out of bounds`);return n[r]}getProperties(e){return this.store.getPropertiesCopy(e)}hasFeature(e){return this.store.has(e)}getAllFeatureIdsWhere(e){return this.store.copyAllWhere(e).map(({id:e})=>e)}};function Hy({unproject:e,point:t,pointerDistance:n}){let r=n/2,{x:i,y:a}=t;return{type:`Feature`,properties:{},geometry:{type:`Polygon`,coordinates:[[e(i-r,a-r),e(i+r,a-r),e(i+r,a+r),e(i-r,a+r),e(i-r,a-r)].map(e=>[e.lng,e.lat])]}}}var Uy=class extends jy{constructor(e){super(e)}create(e){let{containerX:t,containerY:n}=e;return Hy({unproject:this.unproject,point:{x:t,y:n},pointerDistance:this.pointerDistance})}},Wy=class extends jy{constructor(e){super(e)}measure(e,t){let{x:n,y:r}=this.project(t[0],t[1]);return zy({x:n,y:r},{x:e.containerX,y:e.containerY})}},Gy=class extends jy{constructor(e,t,n){super(e),this.config=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.getSnappableCoordinateFirstClick=e=>this.getSnappable(e,e=>!!(e.properties&&e.properties.mode===this.mode)).coordinate,this.getSnappableCoordinate=(e,t)=>this.getSnappable(e,e=>!!(e.properties&&e.properties.mode===this.mode&&e.id!==t)).coordinate,this.config=e,this.pixelDistance=t,this.clickBoundingBox=n}getSnappable(e,t){let n=this.clickBoundingBox.create(e),r=this.store.search(n,t),i={featureId:void 0,featureCoordinateIndex:void 0,coordinate:void 0,minDist:1/0};return r.forEach(t=>{let n;if(t.geometry.type===`Polygon`)n=t.geometry.coordinates[0];else{if(t.geometry.type!==`LineString`)return;n=t.geometry.coordinates}n.forEach((n,r)=>{let a=this.pixelDistance.measure(e,n);a<i.minDist&&a<this.pointerDistance&&(i.coordinate=n,i.minDist=a,i.featureId=t.id,i.featureCoordinateIndex=r)})}),i}};function Ky(e,t,n){let r=_y(e[0]),i=_y(e[1]),a=_y(n),o=vy(t),s=Math.asin(Math.sin(i)*Math.cos(o)+Math.cos(i)*Math.sin(o)*Math.cos(a));return[yy(r+Math.atan2(Math.sin(a)*Math.sin(o)*Math.cos(i),Math.cos(o)-Math.sin(i)*Math.sin(s))),yy(s)]}function qy(e,t){let n=_y(e[0]),r=_y(t[0]),i=_y(e[1]),a=_y(t[1]),o=Math.sin(r-n)*Math.cos(a),s=Math.cos(i)*Math.sin(a)-Math.sin(i)*Math.cos(a)*Math.cos(r-n);return yy(Math.atan2(o,s))}function Jy({x:e,y:t},{x:n,y:r}){let i=n-e,a=r-t;if(i===0&&a===0)return 0;let o=Math.atan2(a,i);return o*=180/Math.PI,o>180?o-=360:o<-180&&(o+=360),o}function Yy(e,t,n){let r=[],i=e.length,a,o,s,c=0;for(let i=0;i<e.length&&!(t>=c&&i===e.length-1);i++){if(c>t&&r.length===0){if(a=t-c,!a)return r.push(e[i]),r;o=qy(e[i],e[i-1])-180,s=Ky(e[i],a,o),r.push(s)}if(c>=n)return a=n-c,a?(o=qy(e[i],e[i-1])-180,s=Ky(e[i],a,o),r.push(s),r):(r.push(e[i]),r);if(c>=t&&r.push(e[i]),i===e.length-1)return r;c+=hy(e[i],e[i+1])}if(c<t&&e.length===i)throw Error(`Start position is beyond line`);let l=e[e.length-1];return[l,l]}function Xy(e){return Math.PI/180*e}function Zy(e){return 180/Math.PI*e}var Qy=class extends jy{constructor(e){super(e),this.config=void 0,this.config=e}generateInsertionCoordinates(e,t,n){let r=[e,t],i=0;for(let e=0;e<r.length-1;e++)i+=hy(r[0],r[1]);if(i<=n)return r;let a=i/n-1;Number.isInteger(a)||(a=Math.floor(a)+1);let o=[];for(let e=0;e<a;e++){let t=Yy(r,n*e,n*(e+1));o.push(t)}let s=[];for(let e=0;e<o.length;e++)s.push(o[e][1]);return this.limitCoordinates(s)}generateInsertionGeodesicCoordinates(e,t,n){let r=hy(e,t),i=function(e,t,n){let r=[],i=Xy(e[1]),a=Xy(e[0]),o=Xy(t[1]),s=Xy(t[0]);n+=1;let c=2*Math.asin(Math.sqrt(Math.sin((o-i)/2)**2+Math.cos(i)*Math.cos(o)*Math.sin((s-a)/2)**2));if(c===0||isNaN(c))return r;for(let e=0;e<=n;e++){let t=e/n,l=Math.sin((1-t)*c)/Math.sin(c),u=Math.sin(t*c)/Math.sin(c),d=l*Math.cos(i)*Math.cos(a)+u*Math.cos(o)*Math.cos(s),f=l*Math.cos(i)*Math.sin(a)+u*Math.cos(o)*Math.sin(s),p=l*Math.sin(i)+u*Math.sin(o);if(isNaN(d)||isNaN(f)||isNaN(p))continue;let m=Math.atan2(p,Math.sqrt(d**2+f**2)),h=Math.atan2(f,d);isNaN(m)||isNaN(h)||r.push([Zy(h),Zy(m)])}return r.slice(1,-1)}(e,t,Math.floor(r/n));return this.limitCoordinates(i)}limitCoordinates(e){return e.map(e=>[by(e[0],this.config.coordinatePrecision),by(e[1],this.config.coordinatePrecision)])}};function $y(e,t){if(e.geometry.type!==`LineString`)return{valid:!1,reason:`Feature is not a LineString`};if(e.geometry.coordinates.length<2)return{valid:!1,reason:`Feature has less than 2 coordinates`};for(let n=0;n<e.geometry.coordinates.length;n++){if(!ky(e.geometry.coordinates[n]))return{valid:!1,reason:`Feature has invalid coordinates`};if(!Oy(e.geometry.coordinates[n],t))return{valid:!1,reason:`Feature has coordinates with excessive precision`}}return{valid:!0}}function eb(e){return Math.sqrt(e[0]**2+e[1]**2+e[2]**2)}function tb(e,t){let n=function(e,t){let[n,r,i]=e,[a,o,s]=t;return n*a+r*o+i*s}(e,t)/(eb(e)*eb(t));return Math.acos(Math.min(Math.max(n,-1),1))}function nb(e){let t=_y(e[1]),n=_y(e[0]);return[Math.cos(t)*Math.cos(n),Math.cos(t)*Math.sin(n),Math.sin(t)]}function rb(e){let[t,n,r]=e,i=yy(Math.asin(r));return[yy(Math.atan2(n,t)),i]}function ib(e,t,n){let r=nb(e),i=nb(t),[a,o,s]=nb(n),[c,l,u]=function(e,t){let[n,r,i]=e,[a,o,s]=t;return[r*s-i*o,i*a-n*s,n*o-r*a]}(r,i),d=l*s-u*o,f=u*a-c*s,p=c*o-l*a,m=p*l-f*u,h=d*u-p*c,g=f*c-d*l,_=1/Math.sqrt(m**2+h**2+g**2),v=[m*_,h*_,g*_],y=[-1*m*_,-1*h*_,-1*g*_],b=tb(r,i),x=tb(r,v),S=tb(i,v),C=tb(r,y),w=tb(i,y),T;return T=x<C&&x<w||S<C&&S<w?v:y,tb(r,T)>b||tb(i,T)>b?hy(rb(T),rb(r))<=hy(rb(T),rb(i))?[rb(r),!0,!1]:[rb(i),!1,!0]:[rb(T),!1,!1]}function ab(e,t,n){let r=t.x-e.x,i=t.y-e.y,a=Math.max(0,Math.min(1,((n.x-e.x)*r+(n.y-e.y)*i)/(r*r+i*i)));return{x:e.x+a*r,y:e.y+a*i}}var ob=class extends jy{constructor(e,t,n){super(e),this.config=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.getSnappableCoordinateFirstClick=e=>{let t=this.getSnappable(e,e=>!!(e.properties&&e.properties.mode===this.mode));return t.coordinate?[by(t.coordinate[0],this.config.coordinatePrecision),by(t.coordinate[1],this.config.coordinatePrecision)]:void 0},this.getSnappableCoordinate=(e,t)=>{let n=this.getSnappable(e,e=>!!(e.properties&&e.properties.mode===this.mode&&e.id!==t));return n.coordinate?[by(n.coordinate[0],this.config.coordinatePrecision),by(n.coordinate[1],this.config.coordinatePrecision)]:void 0},this.config=e,this.pixelDistance=t,this.clickBoundingBox=n}getSnappable(e,t){let n=this.clickBoundingBox.create(e),r=this.store.search(n,t),i={featureId:void 0,featureCoordinateIndex:void 0,coordinate:void 0,minDistance:1/0};return r.forEach(t=>{let n;if(t.geometry.type===`Polygon`)n=t.geometry.coordinates[0];else{if(t.geometry.type!==`LineString`)return;n=t.geometry.coordinates}let r=[];for(let e=0;e<n.length-1;e++)r.push([n[e],n[e+1]]);let a,o=[e.lng,e.lat];if(this.config.projection===`web-mercator`?a=function(e,t){let n=[1/0,1/0],r=1/0,i=0;for(let a of t){let o=a[0],s=a[1],c,l=1/0,u=wy(o[0],o[1]),d=wy(s[0],s[1]),f=wy(e[0],e[1]);if(o[0]===e[0]&&o[1]===e[1])c=o;else if(s[0]===e[0]&&s[1]===e[1])c=s;else{let{x:e,y:t}=ab(u,d,f),{lng:n,lat:r}=Ty(e,t);c=[n,r]}c&&(l=zy(f,wy(c[0],c[1])),l<r&&(n=c,r=l,i=t.indexOf(a)))}return r===1/0?void 0:{coordinate:n,lineIndex:i,distance:r}}(o,r):this.config.projection===`globe`&&(a=function(e,t){let n=[1/0,1/0],r=1/0,i=0;for(let a of t){let o=a[0],s=a[1],c,l=1/0;o[0]===e[0]&&o[1]===e[1]?c=o:s[0]===e[0]&&s[1]===e[1]?c=s:[c]=ib(o,s,e),c&&(l=hy(e,c),l<r&&(n=c,r=l,i=t.indexOf(a)))}return r===1/0?void 0:{coordinate:n,distance:r,lineIndex:i}}(o,r)),!a)return;let s=this.pixelDistance.measure(e,a.coordinate);s<i.minDistance&&s<this.pointerDistance&&(i.featureId=t.id,i.coordinate=[by(a.coordinate[0],this.config.coordinatePrecision),by(a.coordinate[1],this.config.coordinatePrecision)],i.featureCoordinateIndex=a.lineIndex,i.minDistance=s)}),i}};function sb(e){return Array.isArray(e)&&e.length>0&&Array.isArray(e[0])&&Array.isArray(e[0][0])}var cb=e=>sb(e)?e[0].slice(0,-1):e,lb=e=>sb(e)?e[0]:e,ub=class extends jy{constructor(e,t,n,r){super(e),this.config=void 0,this.pixelDistance=void 0,this.mutateFeatureBehavior=void 0,this.readFeatureBehavior=void 0,this._startEndPoints=[],this.config=e,this.pixelDistance=t,this.mutateFeatureBehavior=n,this.readFeatureBehavior=r}get ids(){return this._startEndPoints.concat()}set ids(e){}create(e){if(this.ids.length)throw Error(`Opening and closing points already created`);let t=sb(e),n=lb(e);if(t){if(n.length<=3)throw Error(`Requires at least 4 coordinates`);this._startEndPoints=this.mutateFeatureBehavior.createGuidancePoints({coordinates:[n[0],n[n.length-2]],type:ay.CLOSING_POINT})}else this._startEndPoints=[this.mutateFeatureBehavior.createGuidancePoint({coordinate:n[n.length-2],type:ay.CLOSING_POINT})]}delete(){this.ids.length&&(this.mutateFeatureBehavior.deleteFeaturesIfPresent(this.ids),this._startEndPoints=[])}updateOne(e,t){this.mutateFeatureBehavior.updateGuidancePoints([{featureId:this.ids[e],coordinate:t}])}update(e){let t=lb(e);this.ids.length===1?this.mutateFeatureBehavior.updateGuidancePoints([{featureId:this.ids[0],coordinate:t[t.length-2]}]):this.ids.length===2&&this.mutateFeatureBehavior.updateGuidancePoints([{featureId:this.ids[0],coordinate:t[0]},{featureId:this.ids[1],coordinate:t[t.length-3]}])}isLineStringClosingPoint(e){if(this.ids.length!==1)return{isClosing:!1};let t=this.readFeatureBehavior.getGeometry(this.ids[0]);return{isClosing:this.pixelDistance.measure(e,t.coordinates)<this.pointerDistance}}isPolygonClosingPoints(e){if(this.ids.length!==2)return{isClosing:!1,isPreviousClosing:!1};let t=this.readFeatureBehavior.getGeometry(this.ids[0]),n=this.readFeatureBehavior.getGeometry(this.ids[1]),r=this.pixelDistance.measure(e,t.coordinates),i=this.pixelDistance.measure(e,n.coordinates);return{isClosing:r<this.pointerDistance,isPreviousClosing:i<this.pointerDistance}}},db=class extends jy{constructor(e,t,n){super(e),this.readFeature=void 0,this.mutateFeature=void 0,this.readFeature=t,this.mutateFeature=n}createOrUpdate({featureId:e,featureCoordinates:t}){if(!this.readFeature.hasFeature(e))return void this.deleteOrphanedPoints(e);let n=cb(t),r=this.readFeature.getProperties(e),i=r.coordinatePointIds;if(i)if(i&&i.every(e=>this.readFeature.hasFeature(e))){let t=r.coordinatePointIds,i=t.map(e=>this.readFeature.getGeometry(e).coordinates);if(t.length!==n.length){this.deleteCoordinatePoints(t);let i=this.createPoints(n,r.mode,e);this.setFeatureCoordinatePoints(e,i)}else{let e=[];n.forEach((n,r)=>{n[0]===i[r][0]&&n[1]===i[r][1]||e.push({featureId:t[r],coordinate:n})}),this.mutateFeature.updateGuidancePoints(e)}}else{let t=i.filter(e=>this.readFeature.hasFeature(e));t.length&&this.deleteCoordinatePoints(t);let a=this.createPoints(n,r.mode,e);this.setFeatureCoordinatePoints(e,a)}else{let t=this.createPoints(n,r.mode,e);this.setFeatureCoordinatePoints(e,t)}}deletePointsByFeatureIds(e){for(let t of e)this.deleteIfPresent(t)}updateOneAtIndex(e,t,n){let r=this.readFeature.getProperties(e).coordinatePointIds;r&&r.length!==0&&r[t]!==void 0&&this.mutateFeature.updateGuidancePoints([{featureId:r[t],coordinate:n}])}updateAllInPlace({featureId:e,featureCoordinates:t}){let n=this.readFeature.getProperties(e);if(!n.coordinatePointIds)return;let r=cb(t);r.length===n.coordinatePointIds.length&&this.mutateFeature.updateGuidancePoints(n.coordinatePointIds.map((e,t)=>({featureId:e,coordinate:r[t]})))}createPoints(e,t,n){return this.mutateFeature.createGuidancePoints({coordinates:e,type:ay.COORDINATE_POINT,additionalProperties:e=>({mode:t,[ay.COORDINATE_POINT]:!0,[ay.COORDINATE_POINT_FEATURE_ID]:n,index:e})})}setFeatureCoordinatePoints(e,t,n=ny.Commit){let r=this.readFeature.getGeometryType(e),i={featureId:e,propertyMutations:{[ay.COORDINATE_POINT_IDS]:t},context:{updateType:n}};if(r===`Polygon`)this.mutateFeature.updatePolygon(i);else{if(r!==`LineString`)throw Error(`Unsupported geometry type for coordinate points`);this.mutateFeature.updateLineString(i)}}deleteCoordinatePoints(e){this.mutateFeature.deleteFeaturesIfPresent(e)}deleteIfPresent(e){if(!this.readFeature.hasFeature(e))return;let t=this.readFeature.getProperties(e).coordinatePointIds;t&&(this.deleteCoordinatePoints(t),this.setFeatureCoordinatePoints(e,null))}deleteOrphanedPoints(e){let t=this.readFeature.getAllFeatureIdsWhere(t=>t[ay.COORDINATE_POINT_FEATURE_ID]===e);this.mutateFeature.deleteFeaturesIfPresent(t)}},fb=class{constructor(e){this.undoHistory=[],this.redoHistory=[],this.cloneCoordinatesFunction=void 0,this.maxStackSize=void 0,this.cloneCoordinatesFunction=e=>this.cloneRecursively(e);let t=e?.maxStackSize;this.maxStackSize=t!==void 0&&Number.isFinite(t)?Math.max(0,Math.floor(t)):1/0}setMaxStackSize(e){Number.isFinite(e)?(this.maxStackSize=Math.max(0,Math.floor(e)),this.trimHistoryToMax(this.undoHistory),this.trimHistoryToMax(this.redoHistory)):this.maxStackSize=1/0}trimHistoryToMax(e){if(Number.isFinite(this.maxStackSize))for(;e.length>this.maxStackSize;)e.shift()}pushUndoEntry(e){this.maxStackSize!==0&&(this.undoHistory.push(e),this.trimHistoryToMax(this.undoHistory))}pushRedoEntry(e){this.maxStackSize!==0&&(this.redoHistory.push(e),this.trimHistoryToMax(this.redoHistory))}cloneRecursively(e){return Array.isArray(e)?e.map(e=>this.cloneRecursively(e)):typeof e==`object`&&e?Zv({},e):e}cloneCoordinates(e){return this.cloneCoordinatesFunction(e)}cloneEntry(e){return{featureCoordinates:this.cloneCoordinates(e.featureCoordinates),currentCoordinate:e.currentCoordinate}}clear(){this.undoHistory=[],this.redoHistory=[]}undoSize(){return this.undoHistory.length}redoSize(){return this.redoHistory.length}recordSnapshot(e){this.pushUndoEntry(this.cloneEntry(e)),this.redoHistory=[]}beginUndo(){let e=this.undoHistory.pop();if(!e)return;let t=this.cloneEntry(e);this.pushRedoEntry(t);let n=this.undoHistory[this.undoHistory.length-1];return{undoneEntry:t,previousEntry:n?this.cloneEntry(n):void 0}}takeRedo(){let e=this.redoHistory.pop();if(e)return this.cloneEntry(e)}commitRedo(e){this.pushUndoEntry(this.cloneEntry(e))}},pb={cancel:`Escape`,finish:`Enter`},mb={start:`crosshair`,close:`pointer`,dragStart:`grabbing`,dragEnd:`crosshair`},hb=class extends py{constructor(e){super(e,!0),this.mode=`linestring`,this.currentCoordinate=0,this.currentId=void 0,this.keyEvents=pb,this.snapping=void 0,this.cursors=mb,this.mouseMove=!1,this.insertCoordinates=void 0,this.lastCommittedCoordinates=void 0,this.snappedPointId=void 0,this.lastMouseMoveEvent=void 0,this.showCoordinatePoints=!1,this.finishOnNthCoordinate=void 0,this.editable=!1,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedSnapType=void 0,this.editedInsertIndex=void 0,this.editedPointId=void 0,this.coordinateSnapping=void 0,this.insertPoint=void 0,this.lineSnapping=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.mutateFeature=void 0,this.readFeature=void 0,this.closingPoints=void 0,this.coordinatePoints=void 0,this.undoRedo=void 0,this.updateOptions(e)}updateOptions(e){if(super.updateOptions(e),e?.finishOnNthCoordinate!==void 0&&Number.isInteger(e.finishOnNthCoordinate)&&e.finishOnNthCoordinate>1&&(this.finishOnNthCoordinate=Math.floor(e.finishOnNthCoordinate)),e!=null&&e.cursors&&(this.cursors=Zv({},this.cursors,e.cursors)),e!=null&&e.snapping&&(this.snapping=e.snapping),e?.keyEvents===null?this.keyEvents={cancel:null,finish:null}:e!=null&&e.keyEvents&&(this.keyEvents=Zv({},this.keyEvents,e.keyEvents)),e!=null&&e.insertCoordinates&&(this.insertCoordinates=e.insertCoordinates),e&&e.editable&&(this.editable=e.editable),e?.showCoordinatePoints!==void 0){if(this.showCoordinatePoints=e.showCoordinatePoints,this.coordinatePoints&&!0===e.showCoordinatePoints)this.store.copyAllWhere(e=>e.mode===this.mode).forEach(e=>{this.coordinatePoints.createOrUpdate({featureId:e.id,featureCoordinates:e.geometry.coordinates})});else if(this.coordinatePoints&&!1===this.showCoordinatePoints){let e=this.store.copyAllWhere(e=>e.mode===this.mode&&!!e[ay.COORDINATE_POINT_IDS]?.length);this.coordinatePoints.deletePointsByFeatureIds(e.map(e=>e.id))}}}shouldFinishOnCommit(e){return!!this.finishOnNthCoordinate&&Math.max(0,e.coordinates.length-1)>=this.finishOnNthCoordinate}updateSnappedCoordinate(e){let t=this.snapCoordinate(e);return t?(this.snappedPointId?this.mutateFeature.updateGuidancePoints([{featureId:this.snappedPointId,coordinate:t}]):this.snappedPointId=this.mutateFeature.createGuidancePoint({coordinate:t,type:ay.SNAPPING_POINT}),e.lng=t[0],e.lat=t[1]):this.snappedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),void 0),t}close(){if(this.currentId===void 0)return;let e=this.mutateFeature.updateLineString({featureId:this.currentId,context:{updateType:ny.Finish,action:Qv},coordinateMutations:[{type:Iy,index:-1}],propertyMutations:{[ay.CURRENTLY_DRAWING]:void 0}});if(!e)return;this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:e.geometry.coordinates});let t=this.currentId;this.currentCoordinate=0,this.currentId=void 0,this.lastCommittedCoordinates=void 0,this.undoRedo.clear(),this.state===`drawing`&&this.setStarted(),this.closingPoints.delete(),this.snappedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),void 0),this.editedPointId&&(this.mutateFeature.deleteFeatureIfPresent(this.editedPointId),this.editedPointId=void 0,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedInsertIndex=void 0,this.editedSnapType=void 0),this.onFinish(t,{mode:this.mode,action:Qv})}generateInsertCoordinates(e,t){if(!this.insertCoordinates||!this.lastCommittedCoordinates)throw Error(`Not able to insert coordinates`);if(this.insertCoordinates.strategy!==`amount`)throw Error(`Strategy does not exist`);let n=hy(e,t)/(this.insertCoordinates.value+1),r=[];return this.projection===`globe`?r=this.insertPoint.generateInsertionGeodesicCoordinates(e,t,n):this.projection===`web-mercator`&&(r=this.insertPoint.generateInsertionCoordinates(e,t,n)),r}createLine(e){let t=this.mutateFeature.createLineString({coordinates:[e,e],properties:{mode:this.mode,[ay.CURRENTLY_DRAWING]:!0}});this.lastCommittedCoordinates=t.geometry.coordinates,this.currentId=t.id,this.currentCoordinate++,this.pushHistorySnapshot(this.currentId,this.currentCoordinate),this.setDrawing(),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:t.geometry.coordinates})}firstUpdateToLine(e){if(!this.currentId)return;this.setCursor(this.cursors.close);let t=this.mutateFeature.updateLineString({featureId:this.currentId,context:{updateType:ny.Commit},coordinateMutations:[{type:Py,index:-1,coordinate:e}]});t&&(this.closingPoints.create(t.geometry.coordinates),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:t.geometry.coordinates}),this.lastCommittedCoordinates=t.geometry.coordinates,this.currentCoordinate++,this.pushHistorySnapshot(this.currentId,this.currentCoordinate),this.shouldFinishOnCommit(t.geometry)&&this.close())}updateToLine(e,t){if(!this.currentId)return;let{isClosing:n}=this.closingPoints.isLineStringClosingPoint(e);if(n)return void this.close();this.setCursor(this.cursors.close);let r=this.mutateFeature.updateLineString({featureId:this.currentId,context:{updateType:ny.Commit},coordinateMutations:[{type:Py,index:-1,coordinate:t}]});r&&(this.closingPoints.update(r.geometry.coordinates),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:r.geometry.coordinates}),this.lastCommittedCoordinates=r.geometry.coordinates,this.currentCoordinate++,this.pushHistorySnapshot(this.currentId,this.currentCoordinate),this.shouldFinishOnCommit(r.geometry)&&this.close())}undoSize(){return this.undoRedo.undoSize()}clearHistory(){this.undoRedo.clear()}pushHistorySnapshot(e,t){let n=this.readFeature.getGeometry(e);this.undoRedo.recordSnapshot({featureCoordinates:n.coordinates,currentCoordinate:t})}updateSnappedGuidancePointFromLastMouseMove(){this.snapping&&this.lastMouseMoveEvent?this.updateSnappedCoordinate(this.lastMouseMoveEvent):this.snappedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),void 0)}syncClosingPoints(e){this.currentCoordinate>=2?this.closingPoints.ids.length?this.closingPoints.update(e):this.closingPoints.create(e):this.closingPoints.delete()}undo(){if(this.state!==`drawing`||!this.currentId)return;let e=this.undoRedo.beginUndo();if(!e)return;let{previousEntry:t}=e;if(!t){let e=this.currentId;this.currentId=void 0,this.currentCoordinate=0,this.lastCommittedCoordinates=void 0,this.closingPoints.delete(),this.state===`drawing`&&this.setStarted(),this.showCoordinatePoints&&this.coordinatePoints.deletePointsByFeatureIds([e]),this.mutateFeature.deleteFeatureIfPresent(e),this.updateSnappedGuidancePointFromLastMouseMove();return}let n=this.mutateFeature.updateLineString({featureId:this.currentId,coordinateMutations:{type:Ly,coordinates:t.featureCoordinates},propertyMutations:{[ay.CURRENTLY_DRAWING]:!0},context:{updateType:ny.Commit}});n&&(this.currentCoordinate=t.currentCoordinate,this.lastCommittedCoordinates=n.geometry.coordinates,this.syncClosingPoints(n.geometry.coordinates),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:n.geometry.coordinates}),this.updateSnappedGuidancePointFromLastMouseMove())}redoSize(){return this.undoRedo.redoSize()}redo(){let e=this.undoRedo.takeRedo();if(e){if(this.currentId){let t=this.mutateFeature.updateLineString({featureId:this.currentId,coordinateMutations:{type:Ly,coordinates:e.featureCoordinates},propertyMutations:{[ay.CURRENTLY_DRAWING]:!0},context:{updateType:ny.Commit}});if(!t)return;this.currentCoordinate=e.currentCoordinate,this.lastCommittedCoordinates=t.geometry.coordinates,this.syncClosingPoints(t.geometry.coordinates),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:t.geometry.coordinates})}else{let{id:t,geometry:n}=this.mutateFeature.createLineString({coordinates:e.featureCoordinates,properties:{mode:this.mode,[ay.CURRENTLY_DRAWING]:!0}});this.currentId=t,this.currentCoordinate=e.currentCoordinate,this.lastCommittedCoordinates=n.coordinates,this.state===`started`&&this.setDrawing(),this.syncClosingPoints(n.coordinates),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:t,featureCoordinates:n.coordinates})}this.undoRedo.commitRedo(e),this.updateSnappedGuidancePointFromLastMouseMove()}}registerBehaviors(e){this.insertPoint=new Qy(e),this.clickBoundingBox=new Uy(e),this.pixelDistance=new Wy(e),this.lineSnapping=new ob(e,this.pixelDistance,this.clickBoundingBox),this.coordinateSnapping=new Gy(e,this.pixelDistance,this.clickBoundingBox),this.readFeature=new Vy(e),this.mutateFeature=new Ry(e,{validate:this.validate}),this.closingPoints=new ub(e,this.pixelDistance,this.mutateFeature,this.readFeature),this.coordinatePoints=new db(e,this.readFeature,this.mutateFeature),this.undoRedo=new fb({maxStackSize:e.undoRedoMaxStackSize})}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor(`unset`)}onMouseMove(e){this.mouseMove=!0,this.setCursor(this.cursors.start),this.lastMouseMoveEvent=e;let t=this.updateSnappedCoordinate(e)||[e.lng,e.lat];if(this.currentId===void 0||this.currentCoordinate===0)return;let{isClosing:n}=this.closingPoints.isLineStringClosingPoint(e);n&&this.setCursor(this.cursors.close);let r=[{type:Fy,index:-1,coordinate:t}];if(this.insertCoordinates){let e=this.getInsertCoordinates(t);e&&(r={type:Ly,coordinates:e})}let i=this.mutateFeature.updateLineString({coordinateMutations:r,featureId:this.currentId,context:{updateType:ny.Provisional}});i&&this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:i.geometry.coordinates})}getInsertCoordinates(e){if(!this.lastCommittedCoordinates)return;let t=this.lastCommittedCoordinates[this.lastCommittedCoordinates.length-1];if(By(t,e))return;let n=this.generateInsertCoordinates(t,e);return[...this.lastCommittedCoordinates.slice(0,-1),...n,e]}onRightClick(e){if(!this.editable||this.state!==`started`)return;let{featureId:t,featureCoordinateIndex:n}=this.coordinateSnapping.getSnappable(e,e=>this.lineStringFilter(e));if(!t||n===void 0)return;let r=this.readFeature.getGeometry(t),i;if(r.type!==`LineString`||(i=r.coordinates,i.length<=2))return;let a=this.mutateFeature.updateLineString({featureId:t,coordinateMutations:[{type:Iy,index:n}],context:{updateType:ny.Finish,action:$v}});a&&this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:t,featureCoordinates:a.geometry.coordinates}),this.snappedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),void 0),this.editedPointId&&(this.mutateFeature.deleteFeatureIfPresent(this.editedPointId),this.editedPointId=void 0,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedInsertIndex=void 0,this.editedSnapType=void 0),this.closingPoints.delete(),this.onFinish(t,{mode:this.mode,action:ey})}onLeftClick(e){this.snappedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),void 0);let t=this.snapCoordinate(e)||[e.lng,e.lat];this.currentCoordinate===0?this.createLine(t):this.currentCoordinate===1&&this.currentId?this.firstUpdateToLine(t):this.currentId&&this.updateToLine(e,t)}onClick(e){this.currentId===void 0||this.readFeature.hasFeature(this.currentId)||this.cleanUp(),(e.button===`right`&&this.allowPointerEvent(this.pointerEvents.rightClick,e)||e.button===`left`&&this.allowPointerEvent(this.pointerEvents.leftClick,e)||e.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,e))&&(this.currentCoordinate>0&&!this.mouseMove&&this.onMouseMove(e),this.mouseMove=!1,e.button===`right`?this.onRightClick(e):e.button===`left`&&this.onLeftClick(e))}onKeyDown(){}onKeyUp(e){e.key===this.keyEvents.cancel&&this.cleanUp(),e.key===this.keyEvents.finish&&this.close()}onDragStart(e,t){if(!this.allowPointerEvent(this.pointerEvents.onDragStart,e)||!this.editable)return;let n;if(this.state===`started`){let t=this.lineSnapping.getSnappable(e,e=>this.lineStringFilter(e));t.coordinate&&(this.editedSnapType=`line`,this.editedFeatureCoordinateIndex=t.featureCoordinateIndex,this.editedFeatureId=t.featureId,n=t.coordinate);let r=this.coordinateSnapping.getSnappable(e,e=>this.lineStringFilter(e));r.coordinate&&(this.editedSnapType=`coordinate`,this.editedFeatureCoordinateIndex=r.featureCoordinateIndex,this.editedFeatureId=r.featureId,n=r.coordinate)}this.editedFeatureId&&n&&(this.editedPointId||=this.mutateFeature.createGuidancePoint({coordinate:n,type:ay.EDITED}),this.setCursor(this.cursors.dragStart),t(!1))}onDrag(e,t){if(this.allowPointerEvent(this.pointerEvents.onDrag,e)&&this.editedFeatureId!==void 0&&this.editedFeatureCoordinateIndex!==void 0){if(this.editedSnapType===`coordinate`||this.editedSnapType===`line`&&this.editedInsertIndex!==void 0){let t=this.mutateFeature.updateLineString({featureId:this.editedFeatureId,context:{updateType:ny.Provisional},coordinateMutations:[{type:Fy,index:this.editedFeatureCoordinateIndex,coordinate:[e.lng,e.lat]}]});if(!t)return;this.showCoordinatePoints&&(this.editedInsertIndex===void 0?this.coordinatePoints.updateOneAtIndex(this.editedFeatureId,this.editedFeatureCoordinateIndex,[e.lng,e.lat]):this.coordinatePoints.createOrUpdate({featureId:this.editedFeatureId,featureCoordinates:t.geometry.coordinates}))}else if(this.editedSnapType===`line`&&this.editedInsertIndex===void 0){this.editedInsertIndex=this.editedFeatureCoordinateIndex+1;let e=this.mutateFeature.updateLineString({featureId:this.editedFeatureId,context:{updateType:ny.Provisional}});if(!e)return;this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.editedFeatureId,featureCoordinates:e.geometry.coordinates}),this.editedFeatureCoordinateIndex++}this.snapping&&this.snappedPointId&&(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),this.snappedPointId=void 0),this.editedPointId&&this.mutateFeature.updateGuidancePoints([{featureId:this.editedPointId,coordinate:[e.lng,e.lat]}]),this.mutateFeature.updateLineString({featureId:this.editedFeatureId,context:{updateType:ny.Provisional},propertyMutations:{[ay.EDITED]:!0}})}}onDragEnd(e,t){if(!this.allowPointerEvent(this.pointerEvents.onDragEnd,e)||this.editedFeatureId===void 0||(this.setCursor(this.cursors.dragEnd),!this.mutateFeature.updateLineString({featureId:this.editedFeatureId,propertyMutations:{[ay.EDITED]:!1},context:{updateType:ny.Finish,action:$v}})))return;let n=this.editedFeatureId;t(!0),this.snappedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),void 0),this.editedPointId&&(this.mutateFeature.deleteFeatureIfPresent(this.editedPointId),this.editedPointId=void 0,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedInsertIndex=void 0,this.editedSnapType=void 0),this.closingPoints.delete(),this.onFinish(n,{mode:this.mode,action:$v})}cleanUp(){let e=this.currentId,t=this.snappedPointId;this.snappedPointId=void 0,this.currentId=void 0,this.currentCoordinate=0,this.lastCommittedCoordinates=void 0,this.undoRedo.clear(),this.state===`drawing`&&this.setStarted(),e&&this.showCoordinatePoints&&this.coordinatePoints.deletePointsByFeatureIds([e]),this.mutateFeature.deleteFeatureIfPresent(e),this.mutateFeature.deleteFeatureIfPresent(t),this.closingPoints.delete()}styleFeature(e){let t=Zv({},{polygonFillColor:`#3f97e0`,polygonOutlineColor:`#3f97e0`,polygonOutlineWidth:4,polygonOutlineOpacity:1,polygonFillOpacity:.3,pointColor:`#3f97e0`,pointOpacity:1,pointOutlineColor:`#ffffff`,pointOutlineOpacity:1,pointOutlineWidth:0,pointWidth:6,lineStringColor:`#3f97e0`,lineStringWidth:4,lineStringOpacity:1,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0,lineStringDash:void 0});if(e.type===`Feature`&&e.geometry.type===`LineString`&&e.properties.mode===this.mode)return t.lineStringDash=this.styles.lineStringDash,t.lineStringColor=this.getHexColorStylingValue(this.styles.lineStringColor,t.lineStringColor,e),t.lineStringOpacity=this.getNumericStylingValue(this.styles.lineStringOpacity,t.lineStringOpacity===void 0?1:t.lineStringOpacity,e),t.lineStringWidth=this.getNumericStylingValue(this.styles.lineStringWidth,t.lineStringWidth,e),t.zIndex=oy,t;if(e.type===`Feature`&&e.geometry.type===`Point`&&e.properties.mode===this.mode){let n=e.properties[ay.COORDINATE_POINT],r=e.properties[ay.CLOSING_POINT]?`closingPoint`:e.properties[ay.SNAPPING_POINT]?`snappingPoint`:n?`coordinatePoint`:void 0;if(!r)return t;let i={closingPoint:{width:this.styles.closingPointWidth,color:this.styles.closingPointColor,opacity:this.styles.closingPointOpacity,outlineColor:this.styles.closingPointOutlineColor,outlineWidth:this.styles.closingPointOutlineWidth,outlineOpacity:this.styles.closingPointOutlineOpacity},snappingPoint:{width:this.styles.snappingPointWidth,color:this.styles.snappingPointColor,opacity:this.styles.snappingPointOpacity,outlineColor:this.styles.snappingPointOutlineColor,outlineWidth:this.styles.snappingPointOutlineWidth,outlineOpacity:this.styles.snappingPointOutlineOpacity},coordinatePoint:{width:this.styles.coordinatePointWidth,color:this.styles.coordinatePointColor,opacity:this.styles.coordinatePointOpacity,outlineColor:this.styles.coordinatePointOutlineColor,outlineWidth:this.styles.coordinatePointOutlineWidth,outlineOpacity:this.styles.coordinatePointOutlineOpacity}};return t.pointWidth=this.getNumericStylingValue(i[r].width,t.pointWidth,e),t.pointOpacity=this.getNumericStylingValue(i[r].opacity,1,e),t.pointColor=this.getHexColorStylingValue(i[r].color,t.pointColor,e),t.pointOutlineColor=this.getHexColorStylingValue(i[r].outlineColor,`#ffffff`,e),t.pointOutlineWidth=this.getNumericStylingValue(i[r].outlineWidth,2,e),t.pointOutlineOpacity=this.getNumericStylingValue(i[r].outlineOpacity,1,e),t.zIndex=n?20:50,t}return t}validateFeature(e){return this.validateModeFeature(e,e=>$y(e,this.coordinatePrecision))}lineStringFilter(e){return!!(e.geometry.type===`LineString`&&e.properties&&e.properties.mode===this.mode)}snapCoordinate(e){var t,n,r;let i;if((t=this.snapping)!=null&&t.toLine){let t;t=this.currentId?this.lineSnapping.getSnappableCoordinate(e,this.currentId):this.lineSnapping.getSnappableCoordinateFirstClick(e),t&&(i=t)}if((n=this.snapping)!=null&&n.toCoordinate){let t;t=this.currentId?this.coordinateSnapping.getSnappableCoordinate(e,this.currentId):this.coordinateSnapping.getSnappableCoordinateFirstClick(e),t&&(i=t)}if((r=this.snapping)!=null&&r.toCustom){let t=this.snapping.toCustom(e,{currentCoordinate:this.currentCoordinate,currentId:this.currentId,getCurrentGeometrySnapshot:this.currentId?()=>this.readFeature.getGeometry(this.currentId):()=>null,project:this.project,unproject:this.unproject});t&&(i=t)}return i}afterFeatureUpdated(e){this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:e.id,featureCoordinates:e.geometry.coordinates}),this.editedFeatureId===e.id&&this.editedPointId&&(this.mutateFeature.deleteFeatureIfPresent(this.editedPointId),this.editedPointId=void 0,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedSnapType=void 0),this.snappedPointId&&this.lastMouseMoveEvent&&this.updateSnappedCoordinate(this.lastMouseMoveEvent),this.currentId===e.id&&(this.closingPoints.delete(),this.currentCoordinate=0,this.currentId=void 0,this.lastCommittedCoordinates=void 0,this.undoRedo.clear(),this.state===`drawing`&&this.setStarted())}afterFeatureAdded(e){this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:e.id,featureCoordinates:e.geometry.coordinates})}},gb=`Feature is not a Point`,_b=`Feature has invalid coordinates`,vb=`Feature has coordinates with excessive precision`;function yb(e,t){return e.geometry.type===`Point`?ky(e.geometry.coordinates)?Oy(e.geometry.coordinates,t)?{valid:!0}:{valid:!1,reason:vb}:{valid:!1,reason:_b}:{valid:!1,reason:gb}}var bb=class extends jy{constructor(e,t,n){super(e),this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.pixelDistance=t,this.clickBoundingBox=n}getNearestPointFeature(e){let t=this.clickBoundingBox.create(e),n=this.store.search(t),r,i=1/0;for(let t=0;t<n.length;t++){let a=n[t];if(a.geometry.type!==`Point`||a.properties.mode!==this.mode)continue;let o=this.pixelDistance.measure(e,a.geometry.coordinates);o>i||o>this.pointerDistance||(i=o,r=a)}return r}},xb={create:`crosshair`,dragStart:`grabbing`,dragEnd:`crosshair`},Sb=class extends py{constructor(e){super(e,!0),this.mode=`point`,this.cursors=xb,this.editable=!1,this.editedFeatureId=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.pointSearch=void 0,this.mutateFeature=void 0,this.updateOptions(e)}updateOptions(e){super.updateOptions(e),e!=null&&e.cursors&&(this.cursors=Zv({},this.cursors,e.cursors)),e!=null&&e.editable&&(this.editable=e.editable)}start(){this.setStarted(),this.setCursor(this.cursors.create)}stop(){this.cleanUp(),this.setStopped(),this.setCursor(`unset`)}onClick(e){e.button===`right`&&this.allowPointerEvent(this.pointerEvents.rightClick,e)||e.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,e)?this.onRightClick(e):e.button===`left`&&this.allowPointerEvent(this.pointerEvents.leftClick,e)&&this.onLeftClick(e)}onMouseMove(){}onKeyDown(){}onKeyUp(){}cleanUp(){this.editedFeatureId=void 0}onDragStart(e,t){if(this.allowPointerEvent(this.pointerEvents.onDragStart,e)){if(this.editable){let t=this.pointSearch.getNearestPointFeature(e);this.editedFeatureId=t?.id}this.editedFeatureId&&(this.setCursor(this.cursors.dragStart),t(!1))}}onDrag(e,t){this.allowPointerEvent(this.pointerEvents.onDrag,e)&&this.editedFeatureId!==void 0&&this.mutateFeature.updatePoint({featureId:this.editedFeatureId,coordinateMutations:{type:Ly,coordinates:[e.lng,e.lat]},propertyMutations:{[ay.EDITED]:!0},context:{updateType:ny.Provisional}})}onDragEnd(e,t){if(!this.allowPointerEvent(this.pointerEvents.onDragEnd,e)||this.editedFeatureId===void 0||!this.mutateFeature.updatePoint({featureId:this.editedFeatureId,propertyMutations:{mode:this.mode,[ay.EDITED]:!1},context:{updateType:ny.Finish,action:`edit`}}))return;let n=this.editedFeatureId;this.setCursor(this.cursors.dragEnd),this.editedFeatureId=void 0,t(!0),this.onFinish(n,{mode:this.mode,action:Qv})}registerBehaviors(e){this.pixelDistance=new Wy(e),this.clickBoundingBox=new Uy(e),this.pointSearch=new bb(e,this.pixelDistance,this.clickBoundingBox),this.mutateFeature=new Ry(e,{validate:this.validate})}styleFeature(e){let t=Zv({},{polygonFillColor:`#3f97e0`,polygonOutlineColor:`#3f97e0`,polygonOutlineWidth:4,polygonOutlineOpacity:1,polygonFillOpacity:.3,pointColor:`#3f97e0`,pointOpacity:1,pointOutlineColor:`#ffffff`,pointOutlineOpacity:1,pointOutlineWidth:0,pointWidth:6,lineStringColor:`#3f97e0`,lineStringWidth:4,lineStringOpacity:1,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0,lineStringDash:void 0});if(e.type===`Feature`&&e.geometry.type===`Point`&&e.properties.mode===this.mode){let n=!!(e.id&&this.editedFeatureId===e.id);t.pointWidth=this.getNumericStylingValue(n?this.styles.editedPointWidth:this.styles.pointWidth,t.pointWidth,e),t.pointOpacity=this.getNumericStylingValue(this.styles.pointOpacity,t.pointOpacity===void 0?1:t.pointOpacity,e),t.pointColor=this.getHexColorStylingValue(n?this.styles.editedPointColor:this.styles.pointColor,t.pointColor,e),t.pointOutlineColor=this.getHexColorStylingValue(n?this.styles.editedPointOutlineColor:this.styles.pointOutlineColor,t.pointOutlineColor,e),t.pointOutlineOpacity=this.getNumericStylingValue(this.styles.pointOutlineOpacity,t.pointOutlineOpacity===void 0?1:t.pointOutlineOpacity,e),t.pointOutlineWidth=this.getNumericStylingValue(n?this.styles.editedPointOutlineWidth:this.styles.pointOutlineWidth,2,e),t.zIndex=30}return t}validateFeature(e){return this.validateModeFeature(e,e=>yb(e,this.coordinatePrecision))}onLeftClick(e){let t=this.mutateFeature.createPoint({coordinates:[e.lng,e.lat],properties:{mode:this.mode},context:{updateType:ny.Finish,action:Qv}});t&&this.onFinish(t.id,{mode:this.mode,action:Qv})}onRightClick(e){if(!this.editable)return;let t=this.pointSearch.getNearestPointFeature(e);t&&this.mutateFeature.deleteFeatureIfPresent(t.id)}afterFeatureUpdated(e){this.editedFeatureId===e.id&&(this.editedFeatureId=void 0,this.setCursor(this.cursors.create))}};function Cb(e,t){let n=e,r=t,i=_y(n[1]),a=_y(r[1]),o=_y(r[0]-n[0]);o>Math.PI&&(o-=2*Math.PI),o<-Math.PI&&(o+=2*Math.PI);let s=Math.log(Math.tan(a/2+Math.PI/4)/Math.tan(i/2+Math.PI/4)),c=(yy(Math.atan2(o,s))+360)%360;return c>180?-(360-c):c}function wb(e,t,n){let r=t;t<0&&(r=-Math.abs(r));let i=r/gy,a=e[0]*Math.PI/180,o=_y(e[1]),s=_y(n),c=i*Math.cos(s),l=o+c;Math.abs(l)>Math.PI/2&&(l=l>0?Math.PI-l:-Math.PI-l);let u=Math.log(Math.tan(l/2+Math.PI/4)/Math.tan(o/2+Math.PI/4)),d=Math.abs(u)>1e-11?c/u:Math.cos(o),f=[(180*(a+i*Math.sin(s)/d)/Math.PI+540)%360-180,180*l/Math.PI];return f[0]+=f[0]-e[0]>180?-360:e[0]-f[0]>180?360:0,f}function Tb(e,t,n,r,i){let a=r(e[0],e[1]),o=r(t[0],t[1]),{lng:s,lat:c}=i((a.x+o.x)/2,(a.y+o.y)/2);return[by(s,n),by(c,n)]}function Eb(e,t,n){let r=wb(e,1e3*hy(e,t)/2,Cb(e,t));return[by(r[0],n),by(r[1],n)]}function Db({featureCoords:e,precision:t,unproject:n,project:r,projection:i}){let a=[];for(let o=0;o<e.length-1;o++){let s;if(i===`web-mercator`)s=Tb(e[o],e[o+1],t,r,n);else{if(i!==`globe`)throw Error(`Invalid projection`);s=Eb(e[o],e[o+1],t)}a.push(s)}return a}var Ob=class extends jy{constructor(e,t,n,r,i,a){super(e),this.config=void 0,this.selectionPointBehavior=void 0,this.coordinatePointBehavior=void 0,this.mutateFeature=void 0,this.readFeature=void 0,this.pixelDistance=void 0,this._midPoints=[],this.config=e,this.selectionPointBehavior=t,this.coordinatePointBehavior=n,this.mutateFeature=r,this.readFeature=i,this.pixelDistance=a}getMidpointConfig(e){return{featureCoords:e,precision:this.coordinatePrecision,project:this.config.project,unproject:this.config.unproject,projection:this.config.projection}}get ids(){return this._midPoints.concat()}set ids(e){}getNearestMidPoint(e){let t,n=1/0;return this.ids.forEach(r=>{let i=this.readFeature.getGeometry(r),a=this.pixelDistance.measure(e,i.coordinates);a<this.pointerDistance&&a<n&&(n=a,t=r)}),t}insert({featureId:e,midPointId:t}){let n=this.readFeature.getGeometry(t),{midPointFeatureId:r,midPointSegment:i}=this.readFeature.getProperties(t),a=this.readFeature.getGeometry(r),o={featureId:r,coordinateMutations:[{type:Py,index:i,coordinate:n.coordinates}],context:{updateType:ny.Commit}},s=null;if(a.type===`Polygon`)s=this.mutateFeature.updatePolygon(o);else{if(a.type!==`LineString`)throw Error(`Midpoints can only be added to polygons or linestrings`);s=this.mutateFeature.updateLineString(o)}if(!s)throw Error(`Failed to insert midpoint coordinate`);let c=s.geometry.coordinates;this.readFeature.getProperties(e)[ay.COORDINATE_POINT_IDS]&&this.coordinatePointBehavior.createOrUpdate({featureId:e,featureCoordinates:c}),this.mutateFeature.deleteFeaturesIfPresent([...this.selectionPointBehavior.ids,...this._midPoints]),this.create({featureCoordinates:c,featureId:r}),this.selectionPointBehavior.create({featureCoordinates:c,featureId:e})}create({featureCoordinates:e,featureId:t}){if(!this.readFeature.hasFeature(t))throw Error(`Store does not have feature with this id`);let n=lb(e),r=Db(this.getMidpointConfig(n));this._midPoints=this.mutateFeature.createGuidancePoints({additionalProperties:e=>({mode:this.mode,midPointSegment:e,midPointFeatureId:t,[iy.MID_POINT]:!0}),coordinates:r,type:iy.MID_POINT})}delete(){this._midPoints.length&&(this.mutateFeature.deleteFeaturesIfPresent(this._midPoints),this._midPoints=[])}updateAllInPlace({featureCoordinates:e}){if(this._midPoints.length===0)return;let t=lb(e),n=Db(this.getMidpointConfig(t));this.mutateFeature.updateGuidancePoints(this._midPoints.map((e,t)=>({featureId:e,coordinate:n[t]})))}updateOneAtIndex(e,t){if(e<0&&(e=this._midPoints.length+e),this._midPoints[e]===void 0)return;let n=lb(t),r=Db(this.getMidpointConfig(n));this.mutateFeature.updateGuidancePoints([{featureId:this._midPoints[e],coordinate:r[e]}])}},kb=class extends jy{constructor(e,t){super(e),this.mutateFeature=void 0,this._selectionPoints=[],this.mutateFeature=t}get ids(){return this._selectionPoints.concat()}set ids(e){}create({featureId:e,featureCoordinates:t}){let n=cb(t);this._selectionPoints=this.mutateFeature.createGuidancePoints({coordinates:n,type:iy.SELECTION_POINT,additionalProperties:t=>({[iy.SELECTION_POINT_FEATURE_ID]:e,index:t})})}delete(){this.ids.length&&(this.mutateFeature.deleteFeaturesIfPresent(this.ids),this._selectionPoints=[])}updateAllInPlace({featureCoordinates:e}){if(this._selectionPoints.length===0)return;let t=cb(e);t.length===this._selectionPoints.length&&this.mutateFeature.updateGuidancePoints(this._selectionPoints.map((e,n)=>({featureId:e,coordinate:t[n]})))}updateOneAtIndex(e,t){this._selectionPoints[e]!==void 0&&this.mutateFeature.updateGuidancePoints([{featureId:this._selectionPoints[e],coordinate:t}])}};function Ab(e,t){let n=!1;for(let o=0,s=t.length;o<s;o++){let s=t[o];for(let t=0,o=s.length,c=o-1;t<o;c=t++)(i=s[t])[1]>(r=e)[1]!=(a=s[c])[1]>r[1]&&r[0]<(a[0]-i[0])*(r[1]-i[1])/(a[1]-i[1])+i[0]&&(n=!n)}var r,i,a;return n}var jb=(e,t,n)=>{let r=e=>e*e,i=(e,t)=>r(e.x-t.x)+r(e.y-t.y);return Math.sqrt(((e,t,n)=>{let r=i(t,n);if(r===0)return i(e,t);let a=((e.x-t.x)*(n.x-t.x)+(e.y-t.y)*(n.y-t.y))/r;return a=Math.max(0,Math.min(1,a)),i(e,{x:t.x+a*(n.x-t.x),y:t.y+a*(n.y-t.y)})})(e,t,n))},Mb=class extends jy{constructor(e,t,n){super(e),this.config=void 0,this.createClickBoundingBox=void 0,this.pixelDistance=void 0,this.config=e,this.createClickBoundingBox=t,this.pixelDistance=n}find(e,t){let n,r,i,a=1/0,o=1/0,s=this.createClickBoundingBox.create(e),c=this.store.search(s);for(let s=0;s<c.length;s++){let l=c[s],u=l.geometry;if(u.type===`Point`){if(l.properties.selectionPoint||l.properties.coordinatePoint||!t&&l.properties[iy.MID_POINT])continue;let r=this.pixelDistance.measure(e,u.coordinates);!l.properties[iy.MID_POINT]&&r<this.pointerDistance&&r<a&&(a=r,n=l)}else if(u.type===`LineString`){if(n)continue;for(let t=0;t<u.coordinates.length-1;t++){let n=u.coordinates[t],i=u.coordinates[t+1],a=jb({x:e.containerX,y:e.containerY},this.project(n[0],n[1]),this.project(i[0],i[1]));a<this.pointerDistance&&a<o&&(o=a,r=l)}}else if(u.type===`Polygon`){if(n||r)continue;Ab([e.lng,e.lat],u.coordinates)&&(i=l)}}return{clickedFeature:n||r||i}}},Nb=class extends jy{constructor(e,t,n,r,i,a,o){super(e),this.config=void 0,this.featuresAtCursorEvent=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.coordinatePoints=void 0,this.readFeature=void 0,this.mutateFeature=void 0,this.draggedFeatureId=null,this.dragPosition=void 0,this.config=e,this.featuresAtCursorEvent=t,this.selectionPoints=n,this.midPoints=r,this.coordinatePoints=i,this.readFeature=a,this.mutateFeature=o}startDragging(e,t){this.draggedFeatureId=t,this.dragPosition=[e.lng,e.lat]}stopDragging(){this.draggedFeatureId=null,this.dragPosition=void 0}isDragging(){return this.draggedFeatureId!==null}canDrag(e,t){let{clickedFeature:n}=this.featuresAtCursorEvent.find(e,!0);return!(!n||n.id!==t)}drag(e){if(!this.draggedFeatureId)return;let t=this.readFeature.getGeometry(this.draggedFeatureId),n=[e.lng,e.lat];if(t.type===`Polygon`||t.type===`LineString`){let r,i;if(t.type===`Polygon`?(r=t.coordinates[0],i=r.length-1):(r=t.coordinates,i=r.length),!this.dragPosition)return!1;for(let e=0;e<i;e++){let t=r[e],i,a;if(this.config.projection===`web-mercator`){let e=wy(this.dragPosition[0],this.dragPosition[1]),r=wy(n[0],n[1]),o=wy(t[0],t[1]),s={x:e.x-r.x,y:e.y-r.y},{lng:c,lat:l}=Ty(o.x-s.x,o.y-s.y);i=c,a=l}else{let e=[this.dragPosition[0]-n[0],this.dragPosition[1]-n[1]];i=t[0]-e[0],a=t[1]-e[1]}if(i=by(i,this.config.coordinatePrecision),a=by(a,this.config.coordinatePrecision),i>180||i<-180||a>90||a<-90)return!1;r[e]=[i,a]}t.type===`Polygon`&&(r[r.length-1]=[r[0][0],r[0][1]]);let a=this.draggedFeatureId,o=null;if(t.type===`Polygon`)o=this.mutateFeature.updatePolygon({featureId:a,coordinateMutations:{type:Ly,coordinates:[r]},context:{updateType:ny.Provisional}});else{if(t.type!==`LineString`)return;o=this.mutateFeature.updateLineString({featureId:a,coordinateMutations:{type:Ly,coordinates:r},context:{updateType:ny.Provisional}})}if(!o)return!1;let s=o.geometry.coordinates;this.midPoints.updateAllInPlace({featureCoordinates:s}),this.selectionPoints.updateAllInPlace({featureCoordinates:s}),this.coordinatePoints.updateAllInPlace({featureId:a,featureCoordinates:s}),this.dragPosition=[e.lng,e.lat]}else t.type===`Point`&&(this.mutateFeature.updatePoint({featureId:this.draggedFeatureId,coordinateMutations:{type:Ly,coordinates:n},context:{updateType:ny.Provisional}}),this.dragPosition=[e.lng,e.lat])}},Pb=class extends jy{constructor(e,t,n,r,i,a,o,s,c){super(e),this.config=void 0,this.pixelDistance=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.coordinatePoints=void 0,this.coordinateSnapping=void 0,this.lineSnapping=void 0,this.readFeature=void 0,this.mutateFeature=void 0,this.draggedCoordinate={id:null,index:-1},this.config=e,this.pixelDistance=t,this.selectionPoints=n,this.midPoints=r,this.coordinatePoints=i,this.coordinateSnapping=a,this.lineSnapping=o,this.readFeature=s,this.mutateFeature=c}getClosestCoordinate(e,t){let n={dist:1/0,index:-1,isFirstOrLastPolygonCoord:!1},r;if(t.type===`LineString`)r=t.coordinates;else{if(t.type!==`Polygon`)return n;r=t.coordinates[0]}for(let i=0;i<r.length;i++){let a=this.pixelDistance.measure(e,r[i]);if(a<this.pointerDistance&&a<n.dist){let e=t.type===`Polygon`&&(i===r.length-1||i===0);n.dist=a,n.index=e?0:i,n.isFirstOrLastPolygonCoord=e}}return n}getDraggable(e,t){let n=this.readFeature.getGeometry(t);return this.getClosestCoordinate(e,n)}getDraggableIndex(e,t){let n=this.readFeature.getGeometry(t),r=this.getClosestCoordinate(e,n);return r.index===-1?-1:r.index}snapCoordinate(e,t,n){let r=[e.lng,e.lat],i=e=>!!(e.properties&&e.properties.mode===n.properties.mode&&e.id!==this.draggedCoordinate.id);if(t!=null&&t.toLine){let t;t=this.lineSnapping.getSnappable(e,i).coordinate,t&&(r=t)}if(t.toCoordinate){let t;t=this.coordinateSnapping.getSnappable(e,i).coordinate,t&&(r=t)}if(t!=null&&t.toCustom){let i;i=t.toCustom(e,{currentCoordinate:this.draggedCoordinate.index,currentId:n.id,getCurrentGeometrySnapshot:n.id?()=>this.readFeature.getGeometry(n.id):()=>null,project:this.project,unproject:this.unproject}),i&&(r=i)}return r}drag(e,t,n){let r=this.draggedCoordinate.id;if(r===null)return!1;let i=this.draggedCoordinate.index,a=this.readFeature.getGeometry(r),o=this.readFeature.getProperties(r),s=a.type===`LineString`?a.coordinates:a.coordinates[0],c=a.type===`Polygon`&&(i===s.length-1||i===0),l=this.snapCoordinate(e,n,{type:`Feature`,id:r,geometry:a,properties:o});if(e.lng>180||e.lng<-180||e.lat>90||e.lat<-90)return!1;if(c){let e=s.length-1;s[0]=l,s[e]=l}else s[i]=l;if(a.type!==`Point`&&!t&&Ey({type:`Feature`,geometry:a,properties:{}}))return!1;let u=r,d=null;return a.type===`Polygon`?d=this.mutateFeature.updatePolygon({featureId:u,coordinateMutations:{type:Ly,coordinates:[s]},context:{updateType:ny.Provisional}}):a.type===`LineString`&&(d=this.mutateFeature.updateLineString({featureId:u,coordinateMutations:{type:Ly,coordinates:s},context:{updateType:ny.Provisional}})),!!d&&(this.midPoints.updateOneAtIndex(i>0?i-1:-1,s),this.midPoints.updateOneAtIndex(i,s),this.selectionPoints.updateOneAtIndex(i,l),this.coordinatePoints.updateOneAtIndex(u,i,l),!0)}isDragging(){return this.draggedCoordinate.id!==null}startDragging(e,t){this.draggedCoordinate={id:e,index:t}}stopDragging(){this.draggedCoordinate={id:null,index:-1}}};function Fb(e){let t=0,n=0,r=0;return(e.geometry.type===`Polygon`?e.geometry.coordinates[0].slice(0,-1):e.geometry.coordinates).forEach(e=>{t+=e[0],n+=e[1],r++},!0),[t/r,n/r]}var Ib=(e,t)=>{if(t===0||t===360||t===-360)return e;let n=.017453292519943295*t,r=(e.geometry.type===`Polygon`?e.geometry.coordinates[0]:e.geometry.coordinates).map(([e,t])=>wy(e,t)),i=r.reduce((e,t)=>({x:e.x+t.x,y:e.y+t.y}),{x:0,y:0});i.x/=r.length,i.y/=r.length;let a=r.map(e=>({x:i.x+(e.x-i.x)*Math.cos(n)-(e.y-i.y)*Math.sin(n),y:i.y+(e.x-i.x)*Math.sin(n)+(e.y-i.y)*Math.cos(n)})).map(({x:e,y:t})=>[Ty(e,t).lng,Ty(e,t).lat]);return e.geometry.type===`Polygon`?e.geometry.coordinates[0]=a:e.geometry.coordinates=a,e};function Lb(e){let t=(e.geometry.type===`Polygon`?e.geometry.coordinates[0]:e.geometry.coordinates).map(e=>{let{x:t,y:n}=wy(e[0],e[1]);return[t,n]});return e.geometry.type===`Polygon`?function(e){let t=0,n=0,r=0,i=e.length;for(let a=0;a<i-1;a++){let[i,o]=e[a],[s,c]=e[a+1],l=i*c-s*o;t+=l,n+=(i+s)*l,r+=(o+c)*l}return t/=2,n/=6*t,r/=6*t,{x:n,y:r}}(t):function(e){let t=e.length,n=0,r=0;for(let i=0;i<t;i++){let[t,a]=e[i];n+=t,r+=a}return{x:n/t,y:r/t}}(t)}var Rb=class extends jy{constructor(e,t,n,r,i,a){super(e),this.config=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.coordinatePoints=void 0,this.readFeature=void 0,this.mutateFeature=void 0,this.lastBearing=void 0,this.selectedGeometry=void 0,this.selectedGeometryCentroid=void 0,this.selectedGeometryWebMercatorCentroid=void 0,this.config=e,this.selectionPoints=t,this.midPoints=n,this.coordinatePoints=r,this.readFeature=i,this.mutateFeature=a}reset(){this.lastBearing=void 0,this.selectedGeometry=void 0,this.selectedGeometryWebMercatorCentroid=void 0,this.selectedGeometryCentroid=void 0}rotate(e,t){this.selectedGeometry||=this.readFeature.getGeometry(t);let n=this.selectedGeometry;if(n.type!==`Polygon`&&n.type!==`LineString`)return;let r=[e.lng,e.lat],i,a={type:`Feature`,geometry:n,properties:{}};if(this.config.projection===`web-mercator`){this.selectedGeometryWebMercatorCentroid||=Lb(a);let t=wy(e.lng,e.lat);if(i=Jy(this.selectedGeometryWebMercatorCentroid,t),i===0)return;if(!this.lastBearing)return void(this.lastBearing=i);Ib(a,-(this.lastBearing-i))}else{if(this.config.projection!==`globe`)throw Error(`Unsupported projection`);if(this.selectedGeometryCentroid||=Fb({type:`Feature`,geometry:n,properties:{}}),i=Cb(this.selectedGeometryCentroid,r),!this.lastBearing)return void(this.lastBearing=i+180);(function(e,t){if(t===0||t===360||t===-360)return e;let n=Fb(e);(e.geometry.type===`Polygon`?e.geometry.coordinates[0]:e.geometry.coordinates).forEach(e=>{let r=Cb(n,e)+t,i=wb(n,function(e,t){e[0]+=e[0]-t[0]>180?-360:t[0]-e[0]>180?360:0;let n=gy,r=t[1]*Math.PI/180,i=e[1]*Math.PI/180,a=i-r,o=Math.abs(e[0]-t[0])*Math.PI/180;o>Math.PI&&(o-=2*Math.PI);let s=Math.log(Math.tan(i/2+Math.PI/4)/Math.tan(r/2+Math.PI/4)),c=Math.abs(s)>1e-11?a/s:Math.cos(r);return Math.sqrt(a*a+c*c*o*o)*n}(n,e),r);e[0]=i[0],e[1]=i[1]})})(a,-(this.lastBearing-(i+180)))}let o=n.type===`Polygon`?n.coordinates[0]:n.coordinates;o.forEach(e=>{e[0]=by(e[0],this.coordinatePrecision),e[1]=by(e[1],this.coordinatePrecision)});let s={featureId:t,coordinateMutations:{type:Ly,coordinates:n.type===`Polygon`?[o]:o},context:{updateType:ny.Provisional}},c=null;if(a.geometry.type===`Polygon`)c=this.mutateFeature.updatePolygon(s);else{if(a.geometry.type!==`LineString`)return;c=this.mutateFeature.updateLineString(s)}if(!c)return!1;let l=c.geometry.coordinates;this.midPoints.updateAllInPlace({featureCoordinates:l}),this.selectionPoints.updateAllInPlace({featureCoordinates:l}),this.coordinatePoints.updateAllInPlace({featureId:t,featureCoordinates:l}),this.projection===`web-mercator`?this.lastBearing=i:this.projection===`globe`&&(this.lastBearing=i+180)}},zb=class extends jy{constructor(e,t){super(e),this.config=void 0,this.dragCoordinateResizeBehavior=void 0,this.config=e,this.dragCoordinateResizeBehavior=t}scale(e,t){if(!this.dragCoordinateResizeBehavior.isDragging()){let n=this.dragCoordinateResizeBehavior.getDraggableIndex(e,t);this.dragCoordinateResizeBehavior.startDragging(t,n)}this.dragCoordinateResizeBehavior.drag(e,`center-fixed`)}reset(){this.dragCoordinateResizeBehavior.stopDragging()}};function Bb({coordinates:e,originX:t,originY:n,xScale:r,yScale:i}){r===1&&i===1||e.forEach(e=>{let{x:a,y:o}=wy(e[0],e[1]),{lng:s,lat:c}=Ty(t+(a-t)*r,n+(o-n)*i);e[0]=s,e[1]=c})}var Vb=class extends jy{constructor(e,t,n,r,i,a,o){super(e),this.config=void 0,this.pixelDistance=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.coordinatePoints=void 0,this.readFeature=void 0,this.mutateFeature=void 0,this.minimumScale=1e-4,this.draggedCoordinate={id:null,index:-1},this.boundingBoxMaps={opposite:{0:4,1:5,2:6,3:7,4:0,5:1,6:2,7:3}},this.config=e,this.pixelDistance=t,this.selectionPoints=n,this.midPoints=r,this.coordinatePoints=i,this.readFeature=a,this.mutateFeature=o}getClosestCoordinate(e,t){let n={dist:1/0,index:-1,isFirstOrLastPolygonCoord:!1},r;if(t.type===`LineString`)r=t.coordinates;else{if(t.type!==`Polygon`)return n;r=t.coordinates[0]}for(let i=0;i<r.length;i++){let a=this.pixelDistance.measure(e,r[i]);if(a<this.pointerDistance&&a<n.dist){let e=t.type===`Polygon`&&(i===r.length-1||i===0);n.dist=a,n.index=e?0:i,n.isFirstOrLastPolygonCoord=e}}return n}isValidDragWebMercator(e,t,n){switch(e){case 0:if(t<=0||n>=0)return!1;break;case 1:if(n>=0)return!1;break;case 2:if(t>=0||n>=0)return!1;break;case 3:if(t>=0)return!1;break;case 4:if(t>=0||n<=0)return!1;break;case 5:if(n<=0)return!1;break;case 6:if(t<=0||n<=0)return!1;break;case 7:if(t<=0)return!1}return!0}getSelectedFeatureDataWebMercator(){if(!this.draggedCoordinate.id||this.draggedCoordinate.index===-1)return null;let e=this.getFeature(this.draggedCoordinate.id);if(!e)return null;let t=this.getNormalisedCoordinates(e.geometry);return{boundingBox:this.getBBoxWebMercator(t),feature:e,updatedCoords:t,selectedCoordinate:t[this.draggedCoordinate.index]}}centerWebMercatorDrag(e){let t=this.getSelectedFeatureDataWebMercator();if(!t)return null;let{feature:n,boundingBox:r,updatedCoords:i,selectedCoordinate:a}=t,o=Lb(n);if(!o)return null;let s=wy(a[0],a[1]),{closestBBoxIndex:c}=this.getIndexesWebMercator(r,s),l=wy(e.lng,e.lat);return this.scaleWebMercator({closestBBoxIndex:c,updatedCoords:i,webMercatorCursor:l,webMercatorSelected:s,webMercatorOrigin:o}),i}centerFixedWebMercatorDrag(e){let t=this.getSelectedFeatureDataWebMercator();if(!t)return null;let{feature:n,boundingBox:r,updatedCoords:i,selectedCoordinate:a}=t,o=Lb(n);if(!o)return null;let s=wy(a[0],a[1]),{closestBBoxIndex:c}=this.getIndexesWebMercator(r,s),l=wy(e.lng,e.lat);return this.scaleFixedWebMercator({closestBBoxIndex:c,updatedCoords:i,webMercatorCursor:l,webMercatorSelected:s,webMercatorOrigin:o}),i}scaleFixedWebMercator({closestBBoxIndex:e,webMercatorOrigin:t,webMercatorSelected:n,webMercatorCursor:r,updatedCoords:i}){if(!this.isValidDragWebMercator(e,t.x-r.x,t.y-r.y))return null;let a=zy(t,r)/zy(t,n);return a<0&&(a=this.minimumScale),Bb({coordinates:i,originX:t.x,originY:t.y,xScale:a,yScale:a}),i}oppositeFixedWebMercatorDrag(e){let t=this.getSelectedFeatureDataWebMercator();if(!t)return null;let{boundingBox:n,updatedCoords:r,selectedCoordinate:i}=t,a=wy(i[0],i[1]),{oppositeBboxIndex:o,closestBBoxIndex:s}=this.getIndexesWebMercator(n,a),c={x:n[o][0],y:n[o][1]},l=wy(e.lng,e.lat);return this.scaleFixedWebMercator({closestBBoxIndex:s,updatedCoords:r,webMercatorCursor:l,webMercatorSelected:a,webMercatorOrigin:c}),r}oppositeWebMercatorDrag(e){let t=this.getSelectedFeatureDataWebMercator();if(!t)return null;let{boundingBox:n,updatedCoords:r,selectedCoordinate:i}=t,a=wy(i[0],i[1]),{oppositeBboxIndex:o,closestBBoxIndex:s}=this.getIndexesWebMercator(n,a),c={x:n[o][0],y:n[o][1]},l=wy(e.lng,e.lat);return this.scaleWebMercator({closestBBoxIndex:s,updatedCoords:r,webMercatorCursor:l,webMercatorSelected:a,webMercatorOrigin:c}),r}scaleWebMercator({closestBBoxIndex:e,webMercatorOrigin:t,webMercatorSelected:n,webMercatorCursor:r,updatedCoords:i}){let a=t.x-r.x,o=t.y-r.y;if(!this.isValidDragWebMercator(e,a,o))return null;let s=1;a!==0&&e!==1&&e!==5&&(s=1-(t.x-n.x-a)/a);let c=1;return o!==0&&e!==3&&e!==7&&(c=1-(t.y-n.y-o)/o),this.validateScale(s,c)?(s<0&&(s=this.minimumScale),c<0&&(c=this.minimumScale),this.performWebMercatorScale(i,t.x,t.y,s,c),i):null}getFeature(e){if(this.draggedCoordinate.id===null)return null;let t=this.readFeature.getGeometry(e);return t.type!==`Polygon`&&t.type!==`LineString`?null:{id:e,type:`Feature`,geometry:t,properties:{}}}getNormalisedCoordinates(e){return e.type===`Polygon`?e.coordinates[0]:e.coordinates}validateScale(e,t){return!isNaN(e)&&t<2**53-1&&!isNaN(t)&&t<2**53-1}performWebMercatorScale(e,t,n,r,i){e.forEach(e=>{let{x:a,y:o}=wy(e[0],e[1]),{lng:s,lat:c}=Ty(t+(a-t)*r,n+(o-n)*i);e[0]=s,e[1]=c})}getBBoxWebMercator(e){let t=[1/0,1/0,-1/0,-1/0];(e=e.map(e=>{let{x:t,y:n}=wy(e[0],e[1]);return[t,n]})).forEach(([e,n])=>{e<t[0]&&(t[0]=e),n<t[1]&&(t[1]=n),e>t[2]&&(t[2]=e),n>t[3]&&(t[3]=n)});let[n,r,i,a]=t;return[[n,a],[(n+i)/2,a],[i,a],[i,a+(r-a)/2],[i,r],[(n+i)/2,r],[n,r],[n,a+(r-a)/2]]}getIndexesWebMercator(e,t){let n,r=1/0;for(let i=0;i<e.length;i++){let a=zy({x:t.x,y:t.y},{x:e[i][0],y:e[i][1]});a<r&&(n=i,r=a)}if(n===void 0)throw Error(`No closest coordinate found`);return{oppositeBboxIndex:this.boundingBoxMaps.opposite[n],closestBBoxIndex:n}}isDragging(){return this.draggedCoordinate.id!==null}startDragging(e,t){this.draggedCoordinate={id:e,index:t}}stopDragging(){this.draggedCoordinate={id:null,index:-1}}getDraggableIndex(e,t){let n=this.readFeature.getGeometry(t),r=this.getClosestCoordinate(e,n);return r.index===-1?-1:r.index}drag(e,t){if(!this.draggedCoordinate.id)return!1;let n=this.getFeature(this.draggedCoordinate.id);if(!n)return!1;let r=null;if(t===`center`?r=this.centerWebMercatorDrag(e):t===`opposite`?r=this.oppositeWebMercatorDrag(e):t===`center-fixed`?r=this.centerFixedWebMercatorDrag(e):t===`opposite-fixed`&&(r=this.oppositeFixedWebMercatorDrag(e)),!r)return!1;for(let e=0;e<r.length;e++){let t=r[e];if(t[0]=by(t[0],this.coordinatePrecision),t[1]=by(t[1],this.coordinatePrecision),!Oy(t,this.coordinatePrecision))return!1}let i=n.id,a=null;if(n.geometry.type===`Polygon`?a=this.mutateFeature.updatePolygon({featureId:i,coordinateMutations:{type:Ly,coordinates:[r]},context:{updateType:ny.Provisional}}):n.geometry.type===`LineString`&&(a=this.mutateFeature.updateLineString({featureId:i,coordinateMutations:{type:Ly,coordinates:r},context:{updateType:ny.Provisional}})),!a)return!1;let o=a.geometry.coordinates;return this.midPoints.updateAllInPlace({featureCoordinates:o}),this.selectionPoints.updateAllInPlace({featureCoordinates:o}),this.coordinatePoints.updateAllInPlace({featureId:i,featureCoordinates:o}),!0}},Hb={deselect:`Escape`,delete:`Delete`,rotate:[`Control`,`r`],scale:[`Control`,`s`]},Ub={pointerOver:`move`,dragStart:`move`,dragEnd:`move`,insertMidpoint:`crosshair`},Wb=class extends my{getPointerOverFeatureCursor(){return this.cursors.pointerOverFeature??this.cursors.pointerOver}getPointerOverCoordinateCursor(){return this.cursors.pointerOverCoordinate??this.cursors.pointerOver}getPointerOverResizeHandleCursor(){return this.cursors.pointerOverResizeHandle??this.cursors.pointerOver}constructor(e){super(e,!0),this.mode=`select`,this.allowManualDeselection=!0,this.allowManualSelection=!0,this.dragEventThrottle=5,this.dragEventCount=0,this.selected=[],this.flags={},this.keyEvents=Hb,this.cursors=Ub,this.validations={},this.dragTarget={type:`none`},this.selectionPoints=void 0,this.midPoints=void 0,this.coordinateSnap=void 0,this.featuresAtMouseEvent=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.dragFeature=void 0,this.dragCoordinate=void 0,this.rotateFeature=void 0,this.scaleFeature=void 0,this.dragCoordinateResizeFeature=void 0,this.coordinatePoints=void 0,this.lineSnap=void 0,this.mutateFeature=void 0,this.readFeature=void 0,this.updateOptions(e)}updateOptions(e){if(super.updateOptions(e),this.cursors=e&&e.cursors?Zv({},this.cursors,e.cursors):Ub,e?.keyEvents===null?this.keyEvents={deselect:null,delete:null,rotate:null,scale:null}:e!=null&&e.keyEvents&&(this.keyEvents=Zv({},this.keyEvents,e.keyEvents)),e?.dragEventThrottle!==void 0&&(this.dragEventThrottle=e.dragEventThrottle),e?.allowManualDeselection!==void 0&&(this.allowManualDeselection=e.allowManualDeselection),e?.allowManualSelection!==void 0&&(this.allowManualSelection=e.allowManualSelection),e!=null&&e.flags){this.flags=Zv({},this.flags,e.flags),this.validations={};for(let e in this.flags){let t=this.flags[e].feature;t&&t.validation&&(this.validations[e]=t.validation)}}}selectFeature(e){this.select(e,!1)}setSelecting(){if(this._state!==`started`)throw Error(`Mode must be started to move to selecting state`);this._state=`selecting`}registerBehaviors(e){this.readFeature=new Vy(e),this.mutateFeature=new Ry(e,{validate:(e,t)=>{let n=e.properties.mode;return this.validations&&this.validations[n]?this.validations[n](e,t):{valid:!0}}}),this.pixelDistance=new Wy(e),this.clickBoundingBox=new Uy(e),this.featuresAtMouseEvent=new Mb(e,this.clickBoundingBox,this.pixelDistance),this.selectionPoints=new kb(e,this.mutateFeature),this.coordinatePoints=new db(e,this.readFeature,this.mutateFeature),this.midPoints=new Ob(e,this.selectionPoints,this.coordinatePoints,this.mutateFeature,this.readFeature,this.pixelDistance),this.coordinateSnap=new Gy(e,this.pixelDistance,this.clickBoundingBox),this.lineSnap=new ob(e,this.pixelDistance,this.clickBoundingBox),this.rotateFeature=new Rb(e,this.selectionPoints,this.midPoints,this.coordinatePoints,this.readFeature,this.mutateFeature),this.dragFeature=new Nb(e,this.featuresAtMouseEvent,this.selectionPoints,this.midPoints,this.coordinatePoints,this.readFeature,this.mutateFeature),this.dragCoordinate=new Pb(e,this.pixelDistance,this.selectionPoints,this.midPoints,this.coordinatePoints,this.coordinateSnap,this.lineSnap,this.readFeature,this.mutateFeature),this.dragCoordinateResizeFeature=new Vb(e,this.pixelDistance,this.selectionPoints,this.midPoints,this.coordinatePoints,this.readFeature,this.mutateFeature),this.scaleFeature=new zb(e,this.dragCoordinateResizeFeature)}deselectFeature(e){this.deselect(e)}deselect(e){this.selected.includes(e)&&(this.mutateFeature.setDeselected(this.selected),this.onDeselect(this.selected[0]),this.selected=[],this.selectionPoints.delete(),this.midPoints.delete(),this.dragTarget={type:`none`})}deleteSelected(){this.selected.length&&this.mutateFeature.deleteFeaturesIfPresent(this.selected),this.selected=[],this.dragTarget={type:`none`}}clearDragTargetAndCursor(){this.dragTarget={type:`none`},this.setCursor(`unset`)}getSelectedFlags(e){let t=this.readFeature.getProperties(e),n=this.flags[t.mode]?.feature,r=n?.coordinates;return{featureFlags:n,coordinatesFlags:r,hasDraggableFlags:n&&(n.draggable||r?.draggable||r?.resizable||typeof r?.midpoints==`object`&&r.midpoints.draggable)}}onRightClick(e){if(!this.selectionPoints.ids.length)return;let t,n=1/0;if(this.selectionPoints.ids.forEach(r=>{let i=this.readFeature.getGeometry(r),a=this.pixelDistance.measure(e,i.coordinates);a<this.pointerDistance&&a<n&&(n=a,t=this.readFeature.getProperties(r))}),!t)return;let r=t.selectionPointFeatureId,i=t.index,a=this.readFeature.getProperties(r),o=this.flags[a.mode];if(!(o&&o.feature&&o.feature.coordinates&&o.feature.coordinates.deletable))return;let s=this.readFeature.getGeometry(r),c;if(s.type===`Polygon`){if(c=s.coordinates[0],c.length<=4)return}else if(s.type!==`LineString`||(c=s.coordinates,c.length<=2))return;s.type!==`Polygon`||i!==0&&i!==c.length-1?c.splice(i,1):(c.shift(),c.pop(),c.push([c[0][0],c[0][1]]));let l=null;if(s.type===`Polygon`?l=this.mutateFeature.updatePolygon({featureId:r,coordinateMutations:{type:Ly,coordinates:[c]},context:{updateType:ny.Commit}}):s.type===`LineString`&&(l=this.mutateFeature.updateLineString({featureId:r,coordinateMutations:{type:Ly,coordinates:c},context:{updateType:ny.Commit}})),!l)return;let u=l.geometry.coordinates;this.mutateFeature.deleteFeaturesIfPresent([...this.midPoints.ids,...this.selectionPoints.ids]),a.coordinatePointIds&&this.coordinatePoints.createOrUpdate({featureId:r,featureCoordinates:u}),this.selectionPoints.create({featureCoordinates:u,featureId:r}),o&&o.feature&&o.feature.coordinates&&o.feature.coordinates.midpoints&&this.midPoints.create({featureCoordinates:u,featureId:r}),this.onFinish(r,{action:ey,mode:this.mode})}select(e,t=!0){if(this.selected[0]===e)return;let{mode:n}=this.readFeature.getProperties(e),r=this.flags[n];if(!r||!r.feature)return;let i=this.selected[0];if(i){if(i===e)return;this.deselect(i)}t&&this.setCursor(this.getPointerOverFeatureCursor()),this.selected=[e],this.mutateFeature.setSelected(e),this.onSelect(e);let{type:a,coordinates:o}=this.readFeature.getGeometry(e);a!==`LineString`&&a!==`Polygon`||o&&r&&r.feature.coordinates&&(this.selectionPoints.create({featureCoordinates:o,featureId:e}),r.feature.coordinates.midpoints&&this.midPoints.create({featureCoordinates:o,featureId:e}))}onLeftClick(e){let{clickedFeature:t}=this.featuresAtMouseEvent.find(e,this.selected.length>0),n=this.midPoints.getNearestMidPoint(e),r=this.selected[0];if(r){var i;let{featureFlags:t}=this.getSelectedFlags(r);if(t!=null&&(i=t.coordinates)!=null&&i.midpoints&&n){if(t.coordinates.draggable){let t=this.pixelDistance.measure(e,this.readFeature.getGeometry(n).coordinates),{dist:i}=this.dragCoordinate.getDraggable(e,r);if(i!==void 0&&t>i)return}this.midPoints.insert({featureId:r,midPointId:n}),this.onFinish(this.selected[0],{action:ty,mode:this.mode});return}}if(t!=null&&t.id)this.allowManualSelection&&this.select(t.id,!0);else if(this.selected.length&&this.allowManualDeselection)return void this.deselect(this.selected[0])}start(){this.setStarted(),this.setSelecting()}stop(){this.cleanUp(),this.setStarted(),this.setStopped()}onClick(e){e.button===`right`&&this.allowPointerEvent(this.pointerEvents.rightClick,e)||e.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,e)?this.onRightClick(e):e.button===`left`&&this.allowPointerEvent(this.pointerEvents.leftClick,e)&&this.onLeftClick(e)}canScale(e){return this.keyEvents.scale&&this.keyEvents.scale.every(t=>e.heldKeys.includes(t))}canRotate(e){return this.keyEvents.rotate&&this.keyEvents.rotate.every(t=>e.heldKeys.includes(t))}preventDefaultKeyEvent(e){let t=this.canRotate(e),n=this.canScale(e);(t||n)&&e.preventDefault()}onKeyDown(e){this.preventDefaultKeyEvent(e)}onKeyUp(e){if(this.preventDefaultKeyEvent(e),this.keyEvents.delete&&e.key===this.keyEvents.delete){if(!this.selected.length)return;let e=this.selected[0];this.onDeselect(this.selected[0]),this.coordinatePoints.deletePointsByFeatureIds([e]),this.deleteSelected(),this.selectionPoints.delete(),this.midPoints.delete()}else this.keyEvents.deselect&&e.key===this.keyEvents.deselect&&this.cleanUp()}cleanUp(){this.selected.length&&this.deselect(this.selected[0])}onDragStart(e,t){if(!this.allowPointerEvent(this.pointerEvents.onDragStart,e))return;let n=this.selected[0];if(!n)return;let{featureFlags:r,coordinatesFlags:i,hasDraggableFlags:a}=this.getSelectedFlags(n);if(!a)return;this.dragEventCount=0;let o=this.dragTarget.type!==`none`&&this.dragTarget.featureId===n?this.dragTarget:{type:`none`},s=o.type===`coordinate`?o.coordinateIndex:this.dragCoordinate.getDraggableIndex(e,n),c=o.type===`resize`?o.coordinateIndex:this.dragCoordinateResizeFeature.getDraggableIndex(e,n),l=i?.resizable&&c!==-1,u=i?.draggable&&s!==-1,d=i&&typeof i.midpoints==`object`&&i.midpoints.draggable,f=r?.draggable&&(o.type===`feature`||this.dragFeature.canDrag(e,n));if(l)return this.setCursor(this.cursors.dragStart),this.dragCoordinateResizeFeature.startDragging(n,c),void t(!1);if(u)return this.setCursor(this.cursors.dragStart),this.dragCoordinate.startDragging(n,s),void t(!1);if(d){let r=o.type===`midpoint`?o.midPointId:this.midPoints.getNearestMidPoint(e);if(this.selected.length&&r){this.midPoints.insert({featureId:n,midPointId:r}),this.onFinish(this.selected[0],{action:ty,mode:this.mode});let i=this.dragCoordinate.getDraggableIndex(e,n);this.dragCoordinate.startDragging(n,i),t(!1);return}}if(f)return this.setCursor(this.cursors.dragStart),this.dragFeature.startDragging(e,n),void t(!1);this.setCursor(`unset`)}onDrag(e,t){if(!this.allowPointerEvent(this.pointerEvents.onDrag,e))return;let n=this.selected[0];if(!n)return;let r=this.readFeature.getProperties(n),i=this.flags[r.mode],a=!0===(i&&i.feature&&i.feature.selfIntersectable);if(this.dragEventCount++,this.dragEventCount%this.dragEventThrottle!=0){if(i&&i.feature&&i.feature.rotateable&&this.canRotate(e))return t(!1),void this.rotateFeature.rotate(e,n);if(i&&i.feature&&i.feature.scaleable&&this.canScale(e))return t(!1),void this.scaleFeature.scale(e,n);if(this.dragCoordinateResizeFeature.isDragging()&&i.feature&&i.feature.coordinates&&i.feature.coordinates.resizable){if(this.projection===`globe`)throw Error(`Globe is currently unsupported projection for resizable`);t(!1),this.dragCoordinateResizeFeature.drag(e,i.feature.coordinates.resizable);return}if(this.dragCoordinate.isDragging()){var o;let t=(o=i.feature)==null||(o=o.coordinates)==null?void 0:o.snappable,n={toCoordinate:!1};!0===t?n={toCoordinate:!0}:typeof t==`object`&&(n=t),this.dragCoordinate.drag(e,a,n);return}this.dragFeature.isDragging()?this.dragFeature.drag(e):t(!0)}}onDragEnd(e,t){this.allowPointerEvent(this.pointerEvents.onDragEnd,e)&&(this.setCursor(this.cursors.dragEnd),this.dragCoordinate.isDragging()?this.onFinish(this.selected[0],{mode:this.mode,action:`dragCoordinate`}):this.dragFeature.isDragging()?this.onFinish(this.selected[0],{mode:this.mode,action:`dragFeature`}):this.dragCoordinateResizeFeature.isDragging()&&this.onFinish(this.selected[0],{mode:this.mode,action:`dragCoordinateResize`}),this.dragCoordinate.stopDragging(),this.dragFeature.stopDragging(),this.dragCoordinateResizeFeature.stopDragging(),this.rotateFeature.reset(),this.scaleFeature.reset(),t(!0))}onMouseMove(e){let t=this.selected[0];if(!t)return void this.clearDragTargetAndCursor();if(this.dragFeature.isDragging()||this.dragCoordinate.isDragging()||this.dragCoordinateResizeFeature.isDragging())return;let{featureFlags:n}=this.getSelectedFlags(t);if(!n)return void this.clearDragTargetAndCursor();let r,i=n.coordinates;if(i!=null&&i.midpoints&&(r=this.midPoints.getNearestMidPoint(e),r&&(this.dragTarget={type:`midpoint`,featureId:t,midPointId:r},this.setCursor(this.cursors.insertMidpoint))),i&&i.draggable){let{index:n,dist:i}=this.dragCoordinate.getDraggable(e,t);if(n>-1){if(r&&this.pixelDistance.measure(e,this.readFeature.getGeometry(r).coordinates)<i)return;this.dragTarget={type:`coordinate`,featureId:t,coordinateIndex:n},this.setCursor(this.getPointerOverCoordinateCursor());return}}if(i&&i.resizable){let n=this.dragCoordinateResizeFeature.getDraggableIndex(e,t);if(n>-1)return this.dragTarget={type:`resize`,featureId:t,coordinateIndex:n},void this.setCursor(this.getPointerOverResizeHandleCursor())}if(n.draggable&&this.dragFeature.canDrag(e,t)){if(r)return;this.dragTarget={type:`feature`,featureId:t},this.setCursor(this.getPointerOverFeatureCursor());return}r||this.clearDragTargetAndCursor()}styleFeature(e){let t=Zv({},{polygonFillColor:`#3f97e0`,polygonOutlineColor:`#3f97e0`,polygonOutlineWidth:4,polygonOutlineOpacity:1,polygonFillOpacity:.3,pointColor:`#3f97e0`,pointOpacity:1,pointOutlineColor:`#ffffff`,pointOutlineOpacity:1,pointOutlineWidth:0,pointWidth:6,lineStringColor:`#3f97e0`,lineStringWidth:4,lineStringOpacity:1,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0,lineStringDash:void 0});if(e.properties.mode===this.mode&&e.geometry.type===`Point`){if(e.properties[iy.SELECTION_POINT])return t.pointColor=this.getHexColorStylingValue(this.styles.selectionPointColor,t.pointColor,e),t.pointOpacity=this.getNumericStylingValue(this.styles.selectionPointOpacity,1,e),t.pointOutlineColor=this.getHexColorStylingValue(this.styles.selectionPointOutlineColor,t.pointOutlineColor,e),t.pointWidth=this.getNumericStylingValue(this.styles.selectionPointWidth,t.pointWidth,e),t.pointOutlineOpacity=this.getNumericStylingValue(this.styles.selectionPointOutlineOpacity,1,e),t.pointOutlineWidth=this.getNumericStylingValue(this.styles.selectionPointOutlineWidth,2,e),t.zIndex=30,t;if(e.properties[iy.MID_POINT])return t.pointColor=this.getHexColorStylingValue(this.styles.midPointColor,t.pointColor,e),t.pointOpacity=this.getNumericStylingValue(this.styles.midPointOpacity,1,e),t.pointOutlineColor=this.getHexColorStylingValue(this.styles.midPointOutlineColor,t.pointOutlineColor,e),t.pointWidth=this.getNumericStylingValue(this.styles.midPointWidth,4,e),t.pointOutlineOpacity=this.getNumericStylingValue(this.styles.midPointOutlineOpacity,1,e),t.pointOutlineWidth=this.getNumericStylingValue(this.styles.midPointOutlineWidth,2,e),t.zIndex=50,t}else if(e.properties[iy.SELECTED]){if(e.geometry.type===`Point`&&e.properties[ay.MARKER])return t.markerUrl=this.getUrlStylingValue(this.styles.selectedMarkerUrl,ry,e),t.markerHeight=this.getNumericStylingValue(this.styles.selectedMarkerHeight,40,e),t.markerWidth=this.getNumericStylingValue(this.styles.selectedMarkerWidth,32,e),t;if(e.geometry.type===`Polygon`)return t.polygonFillColor=this.getHexColorStylingValue(this.styles.selectedPolygonColor,t.polygonFillColor,e),t.polygonOutlineWidth=this.getNumericStylingValue(this.styles.selectedPolygonOutlineWidth,t.polygonOutlineWidth,e),t.polygonOutlineColor=this.getHexColorStylingValue(this.styles.selectedPolygonOutlineColor,t.polygonOutlineColor,e),t.polygonOutlineOpacity=this.getNumericStylingValue(this.styles.selectedPolygonOutlineOpacity,1,e),t.polygonFillOpacity=this.getNumericStylingValue(this.styles.selectedPolygonFillOpacity,t.polygonFillOpacity,e),t.zIndex=oy,t;if(e.geometry.type===`LineString`)return t.lineStringColor=this.getHexColorStylingValue(this.styles.selectedLineStringColor,t.lineStringColor,e),t.lineStringWidth=this.getNumericStylingValue(this.styles.selectedLineStringWidth,t.lineStringWidth,e),t.zIndex=oy,t;if(e.geometry.type===`Point`)return t.pointWidth=this.getNumericStylingValue(this.styles.selectedPointWidth,t.pointWidth,e),t.pointColor=this.getHexColorStylingValue(this.styles.selectedPointColor,t.pointColor,e),t.pointOpacity=this.getNumericStylingValue(this.styles.selectedPointOpacity,1,e),t.pointOutlineColor=this.getHexColorStylingValue(this.styles.selectedPointOutlineColor,t.pointOutlineColor,e),t.pointOutlineOpacity=this.getNumericStylingValue(this.styles.selectedPointOutlineOpacity,1,e),t.pointOutlineWidth=this.getNumericStylingValue(this.styles.selectedPointOutlineWidth,t.pointOutlineWidth,e),t.zIndex=oy,t}return t}afterFeatureUpdated(e){if(this.selected.length&&e.id===this.selected[0]){var t,n;let r=this.flags[e.properties.mode];if(r==null||(t=r.feature)==null||!t.coordinates)return;let i=e.geometry.type,a=e.id;if(this.selectionPoints.delete(),this.midPoints.delete(),i!==`LineString`&&i!==`Polygon`)return;let o=e.geometry.coordinates;this.selectionPoints.create({featureCoordinates:o,featureId:a}),r!=null&&(n=r.feature)!=null&&(n=n.coordinates)!=null&&n.midpoints&&this.midPoints.create({featureCoordinates:o,featureId:a})}}},Gb=class extends py{constructor(...e){super(...e),this.type=dy.Static,this.mode=`static`}start(){}stop(){}onKeyUp(){}onKeyDown(){}onClick(){}onDragStart(){}onDrag(){}onDragEnd(){}onMouseMove(){}cleanUp(){}styleFeature(){return Zv({},{polygonFillColor:`#3f97e0`,polygonOutlineColor:`#3f97e0`,polygonOutlineWidth:4,polygonOutlineOpacity:1,polygonFillOpacity:.3,pointColor:`#3f97e0`,pointOpacity:1,pointOutlineColor:`#ffffff`,pointOutlineOpacity:1,pointOutlineWidth:0,pointWidth:6,lineStringColor:`#3f97e0`,lineStringWidth:4,lineStringOpacity:1,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0,lineStringDash:void 0})}};function Kb(e,t,n,r,i){for(;r>n;){if(r-n>600){let a=r-n+1,o=t-n+1,s=Math.log(a),c=.5*Math.exp(2*s/3),l=.5*Math.sqrt(s*c*(a-c)/a)*(o-a/2<0?-1:1);Kb(e,t,Math.max(n,Math.floor(t-o*c/a+l)),Math.min(r,Math.floor(t+(a-o)*c/a+l)),i)}let a=e[t],o=n,s=r;for(qb(e,n,t),i(e[r],a)>0&&qb(e,n,r);o<s;){for(qb(e,o,s),o++,s--;i(e[o],a)<0;)o++;for(;i(e[s],a)>0;)s--}i(e[n],a)===0?qb(e,n,s):(s++,qb(e,s,r)),s<=t&&(n=s+1),t<=s&&(r=s-1)}}function qb(e,t,n){let r=e[t];e[t]=e[n],e[n]=r}function Jb(e,t){Yb(e,0,e.children.length,t,e)}function Yb(e,t,n,r,i){i||=ix([]),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(let a=t;a<n;a++){let t=e.children[a];Xb(i,e.leaf?r(t):t)}return i}function Xb(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function Zb(e,t){return e.minX-t.minX}function Qb(e,t){return e.minY-t.minY}function $b(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function ex(e){return e.maxX-e.minX+(e.maxY-e.minY)}function tx(e,t){let n=Math.max(e.minX,t.minX),r=Math.max(e.minY,t.minY),i=Math.min(e.maxX,t.maxX),a=Math.min(e.maxY,t.maxY);return Math.max(0,i-n)*Math.max(0,a-r)}function nx(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function rx(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function ix(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function ax(e,t,n,r,i){let a=[t,n];for(;a.length;){if((n=a.pop())-(t=a.pop())<=r)continue;let o=t+Math.ceil((n-t)/r/2)*r;Kb(e,o,t,n,i),a.push(t,o,o,n)}}var ox=class{constructor(e){this._maxEntries=void 0,this._minEntries=void 0,this.data=void 0,this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}search(e){let t=this.data,n=[];if(!rx(e,t))return n;let r=this.toBBox,i=[];for(;t;){for(let a=0;a<t.children.length;a++){let o=t.children[a],s=t.leaf?r(o):o;rx(e,s)&&(t.leaf?n.push(o):nx(e,s)?this._all(o,n):i.push(o))}t=i.pop()}return n}collides(e){let t=this.data;if(rx(e,t)){let n=[];for(;t;){for(let r=0;r<t.children.length;r++){let i=t.children[r],a=t.leaf?this.toBBox(i):i;if(rx(e,a)){if(t.leaf||nx(e,a))return!0;n.push(i)}}t=n.pop()}}return!1}load(e){if(e.length<this._minEntries){for(let t=0;t<e.length;t++)this.insert(e[t]);return}let t=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===t.height)this._splitRoot(this.data,t);else{if(this.data.height<t.height){let e=this.data;this.data=t,t=e}this._insert(t,this.data.height-t.height-1,!0)}else this.data=t}insert(e){this._insert(e,this.data.height-1)}clear(){this.data=ix([])}remove(e){let t=this.data,n=this.toBBox(e),r=[],i=[],a,o,s=!1;for(;t||r.length;){if(t||(t=r.pop(),o=r[r.length-1],a=i.pop(),s=!0),t.leaf){let n=t.children.indexOf(e);n!==-1&&(t.children.splice(n,1),r.push(t),this._condense(r))}s||t.leaf||!nx(t,n)?o?(a++,t=o.children[a],s=!1):t=null:(r.push(t),i.push(a),a=0,o=t,t=t.children[0])}}toBBox(e){return e}compareMinX(e,t){return e.minX-t.minX}compareMinY(e,t){return e.minY-t.minY}_all(e,t){let n=[];for(;e;)e.leaf?t.push(...e.children):n.push(...e.children),e=n.pop();return t}_build(e,t,n,r){let i=n-t+1,a,o=this._maxEntries;if(i<=o)return a=ix(e.slice(t,n+1)),Jb(a,this.toBBox),a;r||(r=Math.ceil(Math.log(i)/Math.log(o)),o=Math.ceil(i/o**(r-1))),a=ix([]),a.leaf=!1,a.height=r;let s=Math.ceil(i/o),c=s*Math.ceil(Math.sqrt(o));ax(e,t,n,c,this.compareMinX);for(let i=t;i<=n;i+=c){let t=Math.min(i+c-1,n);ax(e,i,t,s,this.compareMinY);for(let n=i;n<=t;n+=s){let i=Math.min(n+s-1,t);a.children.push(this._build(e,n,i,r-1))}}return Jb(a,this.toBBox),a}_chooseSubtree(e,t,n,r){for(;r.push(t),!t.leaf&&r.length-1!==n;){let n,r=1/0,o=1/0;for(let s=0;s<t.children.length;s++){let c=t.children[s],l=$b(c),u=(i=e,a=c,(Math.max(a.maxX,i.maxX)-Math.min(a.minX,i.minX))*(Math.max(a.maxY,i.maxY)-Math.min(a.minY,i.minY))-l);u<o?(o=u,r=l<r?l:r,n=c):u===o&&l<r&&(r=l,n=c)}t=n||t.children[0]}var i,a;return t}_insert(e,t,n){let r=n?e:this.toBBox(e),i=[],a=this._chooseSubtree(r,this.data,t,i);for(a.children.push(e),Xb(a,r);t>=0&&i[t].children.length>this._maxEntries;)this._split(i,t),t--;this._adjustParentBBoxes(r,i,t)}_split(e,t){let n=e[t],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);let a=this._chooseSplitIndex(n,i,r),o=ix(n.children.splice(a,n.children.length-a));o.height=n.height,o.leaf=n.leaf,Jb(n,this.toBBox),Jb(o,this.toBBox),t?e[t-1].children.push(o):this._splitRoot(n,o)}_splitRoot(e,t){this.data=ix([e,t]),this.data.height=e.height+1,this.data.leaf=!1,Jb(this.data,this.toBBox)}_chooseSplitIndex(e,t,n){let r,i=1/0,a=1/0;for(let o=t;o<=n-t;o++){let t=Yb(e,0,o,this.toBBox),s=Yb(e,o,n,this.toBBox),c=tx(t,s),l=$b(t)+$b(s);c<i?(i=c,r=o,a=l<a?l:a):c===i&&l<a&&(a=l,r=o)}return r||n-t}_chooseSplitAxis(e,t,n){let r=e.leaf?this.compareMinX:Zb,i=e.leaf?this.compareMinY:Qb;this._allDistMargin(e,t,n,r)<this._allDistMargin(e,t,n,i)&&e.children.sort(r)}_allDistMargin(e,t,n,r){e.children.sort(r);let i=this.toBBox,a=Yb(e,0,t,i),o=Yb(e,n-t,n,i),s=ex(a)+ex(o);for(let r=t;r<n-t;r++){let t=e.children[r];Xb(a,e.leaf?i(t):t),s+=ex(a)}for(let r=n-t-1;r>=t;r--){let t=e.children[r];Xb(o,e.leaf?i(t):t),s+=ex(o)}return s}_adjustParentBBoxes(e,t,n){for(let r=n;r>=0;r--)Xb(t[r],e)}_condense(e){for(let t,n=e.length-1;n>=0;n--)e[n].children.length===0?n>0?(t=e[n-1].children,t.splice(t.indexOf(e[n]),1)):this.clear():Jb(e[n],this.toBBox)}},sx=class{constructor(e){this.tree=void 0,this.idToNode=void 0,this.nodeToId=void 0,this.tree=new ox(e&&e.maxEntries?e.maxEntries:9),this.idToNode=new Map,this.nodeToId=new Map}setMaps(e,t){this.idToNode.set(e.id,t),this.nodeToId.set(t,e.id)}toBBox(e){let t=[],n=[],r;if(e.geometry.type===`Polygon`)r=e.geometry.coordinates[0];else if(e.geometry.type===`LineString`)r=e.geometry.coordinates;else{if(e.geometry.type!==`Point`)throw Error(`Not a valid feature to turn into a bounding box`);r=[e.geometry.coordinates]}for(let e=0;e<r.length;e++)n.push(r[e][1]),t.push(r[e][0]);let i=Math.min(...n),a=Math.max(...n);return{minX:Math.min(...t),minY:i,maxX:Math.max(...t),maxY:a}}insert(e){if(this.idToNode.get(String(e.id)))throw Error(`Feature already exists`);let t=this.toBBox(e);this.setMaps(e,t),this.tree.insert(t)}load(e){let t=[],n=new Set;e.forEach(e=>{let r=this.toBBox(e);if(this.setMaps(e,r),n.has(String(e.id)))throw Error(`Duplicate feature ID found ${e.id}`);n.add(String(e.id)),t.push(r)}),this.tree.load(t)}update(e){this.remove(e.id);let t=this.toBBox(e);this.setMaps(e,t),this.tree.insert(t)}remove(e){let t=this.idToNode.get(e);if(!t)throw Error(`${e} not inserted into the spatial index`);this.tree.remove(t)}clear(){this.tree.clear()}search(e){return this.tree.search(this.toBBox(e)).map(e=>this.nodeToId.get(e))}collides(e){return this.tree.collides(this.toBBox(e))}},cx={getId:()=>`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,function(e){let t=16*Math.random()|0;return(e==`x`?t:3&t|8).toString(16)}),isValidId:e=>typeof e==`string`&&e.length===36},lx={target:`geometry`},ux={target:`properties`},dx=class{constructor(e){this.idStrategy=void 0,this.tracked=void 0,this.spatialIndex=void 0,this.store=void 0,this._onChange=()=>{},this.store={},this.spatialIndex=new sx,this.tracked=!e||!1!==e.tracked,this.idStrategy=e&&e.idStrategy?e.idStrategy:cx}clone(e){return JSON.parse(JSON.stringify(e))}getId(){return this.idStrategy.getId()}has(e){return!!this.store[e]}load(e,t,n,r){if(e.length===0)return[];let i=this.clone(e),a=[],o=[];i=i.filter(e=>{e.id??=this.idStrategy.getId();let n=e.id;if(t){let r=t(e);if(!r.valid)return a.push({id:n,valid:!1,reason:r.reason}),!1}if(this.tracked){if(e.properties.createdAt){if(!ly(e.properties.createdAt))return a.push({id:e.id,valid:!1,reason:`createdAt is not a valid numeric timestamp`}),!1}else e.properties.createdAt=+new Date;if(e.properties.updatedAt){if(!ly(e.properties.updatedAt))return a.push({id:e.id,valid:!1,reason:`updatedAt is not a valid numeric timestamp`}),!1}else e.properties.updatedAt=+new Date}return this.has(n)?(a.push({id:n,valid:!1,reason:`Feature already exists with this id: ${n}`}),!1):(this.store[n]=e,o.push(e),a.push({id:n,valid:!0}),!0)}),this.spatialIndex.load(i);let s=o.map(({id:e})=>e);return s.length>0&&(this._onChange(s,`create`,r),n&&o.forEach(e=>{n(e)})),a}search(e,t){let n=this.spatialIndex.search(e).map(e=>this.store[e]);return this.clone(t?n.filter(t):n)}registerOnChange(e){this._onChange=(t,n,r)=>{e(t,n,r)}}getGeometryCopy(e){let t=this.store[e];if(!t)throw Error(`No feature with this id (${e}), can not get geometry copy`);return this.clone(t.geometry)}getPropertiesCopy(e){let t=this.store[e];if(!t)throw Error(`No feature with this id (${e}), can not get properties copy`);return this.clone(t.properties)}updateProperty(e,t){let n=new Set;e.forEach(({id:e,property:t,value:r})=>{let i=this.store[e];if(!i)throw Error(`No feature with this (${e}), can not update geometry`);i.properties[t]!==r&&(n.add(e),r===void 0?delete i.properties[t]:i.properties[t]=r,this.tracked&&(i.properties.updatedAt=+new Date))}),this._onChange&&n.size>0&&this._onChange(Array.from(n),`update`,t?Zv({},t,ux):ux)}updateGeometry(e,t){let n=new Set;e.forEach(({id:e,geometry:t})=>{n.add(e);let r=this.store[e];if(!r)throw Error(`No feature with this (${e}), can not update geometry`);r.geometry=this.clone(t),this.spatialIndex.update(r),this.tracked&&(r.properties.updatedAt=+new Date)}),this._onChange&&n.size>0&&this._onChange(Array.from(n),`update`,t?Zv({},t,lx):lx)}create(e,t){let n=[];return e.forEach(({geometry:e,properties:t})=>{let r,i=Zv({},t);this.tracked&&(r=+new Date,t?(i.createdAt=typeof t.createdAt==`number`?t.createdAt:r,i.updatedAt=typeof t.updatedAt==`number`?t.updatedAt:r):i={createdAt:r,updatedAt:r});let a=this.getId(),o={id:a,type:`Feature`,geometry:e,properties:i};this.store[a]=o,this.spatialIndex.insert(o),n.push(a)}),this._onChange&&this._onChange([...n],`create`,t),n}delete(e,t){e.forEach(e=>{if(!this.store[e])throw Error(`No feature with id ${e}, can not delete`);delete this.store[e],this.spatialIndex.remove(e)}),this._onChange&&this._onChange([...e],`delete`,t)}copy(e){return this.clone(this.store[e])}copyAll(){return this.clone(Object.keys(this.store).map(e=>this.store[e]))}copyAllWhere(e){return this.clone(Object.keys(this.store).map(e=>this.store[e]).filter(t=>t.properties&&e(t.properties)))}clear(e){let t=Object.keys(this.store);this.store={},this.spatialIndex.clear(),this._onChange(t,`delete`,e)}size(){return Object.keys(this.store).length}};Math.PI/180;var fx=class{constructor({name:e,callback:t,unregister:n,register:r}){this.name=void 0,this.callback=void 0,this.registered=!1,this.register=void 0,this.unregister=void 0,this.name=e,this.register=()=>{this.registered||(this.registered=!0,r(t))},this.unregister=()=>{this.register&&(this.registered=!1,n(t))},this.callback=t}},px={__proto__:null,GeoJSONStore:dx,TerraDrawBaseDrawMode:py,TerraDrawBaseSelectMode:my,TerraDrawBaseAdapter:class{constructor(e){this._nextKeyUpIsContextMenu=!1,this._lastPointerDownEventTarget=void 0,this._ignoreMismatchedPointerEvents=!1,this._minPixelDragDistance=void 0,this._minPixelDragDistanceDrawing=void 0,this._minPixelDragDistanceSelecting=void 0,this._lastDrawEvent=void 0,this._coordinatePrecision=void 0,this._heldKeys=new Set,this._listeners=[],this._dragState=`not-dragging`,this._currentModeCallbacks=void 0,this._ignoreMismatchedPointerEvents=typeof e.ignoreMismatchedPointerEvents==`boolean`&&e.ignoreMismatchedPointerEvents,this._minPixelDragDistance=typeof e.minPixelDragDistance==`number`?e.minPixelDragDistance:1,this._minPixelDragDistanceSelecting=typeof e.minPixelDragDistanceSelecting==`number`?e.minPixelDragDistanceSelecting:1,this._minPixelDragDistanceDrawing=typeof e.minPixelDragDistanceDrawing==`number`?e.minPixelDragDistanceDrawing:8,this._coordinatePrecision=typeof e.coordinatePrecision==`number`?e.coordinatePrecision:9}getButton(e){return e.button===-1?`neither`:e.button===0?`left`:e.button===1?`middle`:e.button===2?`right`:`neither`}getMapElementXYPosition(e){let{left:t,top:n}=this.getMapEventElement(e.type).getBoundingClientRect();return{containerX:e.clientX-t,containerY:e.clientY-n}}getDrawEventFromEvent(e,t=!1){let n=this.getLngLatFromEvent(e);if(!n)return null;let{lng:r,lat:i}=n,{containerX:a,containerY:o}=this.getMapElementXYPosition(e),s=this.getButton(e),c=Array.from(this._heldKeys);return{lng:by(r,this._coordinatePrecision),lat:by(i,this._coordinatePrecision),containerX:a,containerY:o,button:s,heldKeys:c,isContextMenu:t}}register(e){this._currentModeCallbacks=e,this._listeners=this.getAdapterListeners(),this._listeners.forEach(e=>{e.register()})}getCoordinatePrecision(){return this._coordinatePrecision}getAdapterListeners(){return[new fx({name:`pointerdown`,callback:e=>{if(!this._currentModeCallbacks||!e.isPrimary)return;let t=this.getDrawEventFromEvent(e);t&&(this._dragState=`pre-dragging`,this._lastDrawEvent=t,this._lastPointerDownEventTarget=e.target?e.target:void 0)},register:e=>{this.getMapEventElement(`pointerdown`).addEventListener(`pointerdown`,e)},unregister:e=>{this.getMapEventElement(`pointerdown`).removeEventListener(`pointerdown`,e)}}),new fx({name:`pointermove`,callback:e=>{if(!this._currentModeCallbacks||!e.isPrimary)return;e.preventDefault();let t=this.getDrawEventFromEvent(e);if(t)if(this._dragState===`not-dragging`)this._currentModeCallbacks.onMouseMove(t),this._lastDrawEvent=t;else if(this._dragState===`pre-dragging`){if(!this._lastDrawEvent)return;let e={x:this._lastDrawEvent.containerX,y:this._lastDrawEvent.containerY},n={x:t.containerX,y:t.containerY},r=this._currentModeCallbacks.getState(),i=zy(e,n),a=!1;if(a=r===`drawing`?i<this._minPixelDragDistanceDrawing:r===`selecting`?i<this._minPixelDragDistanceSelecting:i<this._minPixelDragDistance,a)return;this._nextKeyUpIsContextMenu=!1,this._dragState=`dragging`,this._currentModeCallbacks.onDragStart(t,e=>{this.setDraggability.bind(this)(e)})}else this._dragState===`dragging`&&this._currentModeCallbacks.onDrag(t,e=>{this.setDraggability.bind(this)(e)})},register:e=>{this.getMapEventElement(`pointermove`).addEventListener(`pointermove`,e)},unregister:e=>{this.getMapEventElement(`pointermove`).removeEventListener(`pointermove`,e)}}),new fx({name:`contextmenu`,callback:e=>{this._currentModeCallbacks&&(e.preventDefault(),this._nextKeyUpIsContextMenu=!0)},register:e=>{this.getMapEventElement(`contextmenu`).addEventListener(`contextmenu`,e)},unregister:e=>{this.getMapEventElement(`contextmenu`).removeEventListener(`contextmenu`,e)}}),new fx({name:`pointerup`,callback:e=>{if(!this._currentModeCallbacks||e.target!==this.getMapEventElement(`pointerup`)||this._ignoreMismatchedPointerEvents&&this._lastPointerDownEventTarget!==e.target||(this._lastPointerDownEventTarget=void 0,!e.isPrimary))return;let t=this.getDrawEventFromEvent(e);t&&(this._dragState===`dragging`?this._currentModeCallbacks.onDragEnd(t,e=>{this.setDraggability.bind(this)(e)}):this._dragState!==`not-dragging`&&this._dragState!==`pre-dragging`||(this._nextKeyUpIsContextMenu&&=(t.isContextMenu=!0,!1),this._currentModeCallbacks.onClick(t)),this._dragState=`not-dragging`,this.setDraggability(!0))},register:e=>{this.getMapEventElement(`pointerup`).addEventListener(`pointerup`,e)},unregister:e=>{this.getMapEventElement(`pointerup`).removeEventListener(`pointerup`,e)}}),new fx({name:`keyup`,callback:e=>{this._currentModeCallbacks&&(this._heldKeys.delete(e.key),this._currentModeCallbacks.onKeyUp({key:e.key,heldKeys:Array.from(this._heldKeys),preventDefault:()=>e.preventDefault()}))},register:e=>{this.getMapEventElement(`keyup`).addEventListener(`keyup`,e)},unregister:e=>{this.getMapEventElement(`keyup`).removeEventListener(`keyup`,e)}}),new fx({name:`keydown`,callback:e=>{this._currentModeCallbacks&&(this._heldKeys.add(e.key),this._currentModeCallbacks.onKeyDown({key:e.key,heldKeys:Array.from(this._heldKeys),preventDefault:()=>e.preventDefault()}))},register:e=>{this.getMapEventElement(`keydown`).addEventListener(`keydown`,e)},unregister:e=>{this.getMapEventElement(`keydown`).removeEventListener(`keydown`,e)}})]}unregister(){this._listeners.forEach(e=>{e.unregister()}),this.clear(),this._currentModeCallbacks=void 0,this._lastDrawEvent=void 0,this._lastPointerDownEventTarget=void 0,this._nextKeyUpIsContextMenu=!1}},getDefaultStyling:()=>({polygonFillColor:`#3f97e0`,polygonOutlineColor:`#3f97e0`,polygonOutlineWidth:4,polygonOutlineOpacity:1,polygonFillOpacity:.3,pointColor:`#3f97e0`,pointOpacity:1,pointOutlineColor:`#ffffff`,pointOutlineOpacity:1,pointOutlineWidth:0,pointWidth:6,lineStringColor:`#3f97e0`,lineStringWidth:4,lineStringOpacity:1,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0,lineStringDash:void 0}),SELECT_PROPERTIES:iy};function mx(e){if(e===null||typeof e==`boolean`||typeof e==`string`)return!0;if(e===void 0)return!1;if(typeof e==`number`)return Number.isFinite(e);if(typeof e==`bigint`||typeof e==`symbol`||typeof e==`function`||e instanceof RegExp||e instanceof Map||e instanceof Set||e instanceof Date)return!1;if(typeof e==`object`&&e&&!Array.isArray(e)){let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return!1}if(ArrayBuffer.isView(e)&&!(e instanceof DataView))return!1;if(Array.isArray(e)){for(let t of e)if(!mx(t))return!1}return typeof e==`object`&&Object.keys(e).every(t=>typeof t==`string`&&mx(e[t]))}var hx=`push`,gx=`mode`,_x=`session`,vx=class{constructor(e){this.modeLevel=void 0,this.sessionLevel=void 0,this.shouldPreferMode=void 0,this.onHistoryChange=void 0,this.shouldEmitHistoryChange=void 0,this.modeLevel=e.modeLevel,this.sessionLevel=e.sessionLevel,this.shouldPreferMode=e.shouldPreferMode,this.onHistoryChange=e.onHistoryChange,this.shouldEmitHistoryChange=e.shouldEmitHistoryChange??(()=>!0)}emitStackHistoryChange(e){this.shouldEmitHistoryChange()&&this.onHistoryChange&&this.onHistoryChange({cause:e.cause,stack:e.stack,undoSize:e.undoStackSize,redoSize:e.redoStackSize})}hasSessionUndo(){return!!(this.sessionLevel&&this.sessionLevel.canUndo())}hasSessionRedo(){return!!(this.sessionLevel&&this.sessionLevel.canRedo())}activeStackForUndo(){var e,t;return this.shouldPreferMode()&&(e=this.modeLevel)!=null&&e.canUndo()?gx:this.hasSessionUndo()?_x:(t=this.modeLevel)!=null&&t.canUndo()?gx:void 0}activeStackForRedo(){var e,t;return this.shouldPreferMode()&&(e=this.modeLevel)!=null&&e.canRedo()?gx:this.hasSessionRedo()?_x:(t=this.modeLevel)!=null&&t.canRedo()?gx:void 0}canUndo(){return this.activeStackForUndo()!==void 0}canRedo(){return this.activeStackForRedo()!==void 0}undo(){let e=this.activeStackForUndo();return!!e&&(e===gx?!!this.modeLevel&&this.modeLevel.undo():!(!this.sessionLevel||!this.sessionLevel.canUndo())&&this.sessionLevel.undo())}redo(){let e=this.activeStackForRedo();return!!e&&(e===gx?!!this.modeLevel&&this.modeLevel.redo():!(!this.sessionLevel||!this.sessionLevel.canRedo())&&this.sessionLevel.redo())}clearHistory(){this.modeLevel&&this.modeLevel.clearHistory(),this.sessionLevel&&this.sessionLevel.clearHistory()}emitHistoryPushForCompletedAction(){this.sessionLevel?this.emitStackHistoryChange({cause:hx,undoStackSize:this.sessionLevel.undoSize(),redoStackSize:this.sessionLevel.redoSize(),stack:_x}):this.modeLevel&&this.emitStackHistoryChange({cause:hx,undoStackSize:this.modeLevel.undoSize(),redoStackSize:this.modeLevel.redoSize(),stack:gx})}},yx=class{constructor(e){var t,n,r,i;this._modes=void 0,this._mode=void 0,this._adapter=void 0,this._enabled=!1,this._store=void 0,this._eventListeners=void 0,this._instanceSelectModes=void 0,this.sessionUndoRedoEnabled=!1,this.keyboardShortcutsMatcher=void 0,this.drawingUndoRedo=void 0,this.sessionUndoRedo=void 0,this.undoRedoCoordinator=void 0,this._adapter=e.adapter,this._instanceSelectModes=[];let a=e==null||(t=e.undoRedo)==null?void 0:t.modeLevel;a&&(this.drawingUndoRedo=a);let o=e==null||(n=e.undoRedo)==null?void 0:n.keyboardShortcuts;o&&(this.keyboardShortcutsMatcher=o),this.sessionUndoRedoEnabled=!!(!(e==null||(r=e.undoRedo)==null)&&r.sessionLevel);let s=e==null||(i=e.undoRedo)==null?void 0:i.sessionLevel;this._mode=new Gb;let c=new Set,l=e.modes.reduce((e,t)=>{if(c.has(t.mode))throw Error(`There is already a ${t.mode} mode provided`);return c.add(t.mode),e[t.mode]=t,e},{}),u=Object.keys(l);if(u.length===0)throw Error(`No modes provided`);u.forEach(e=>{l[e].type===dy.Select&&this._instanceSelectModes.push(e)}),this._modes=Zv({},l,{static:this._mode}),this._eventListeners={change:[],select:[],deselect:[],finish:[],ready:[],history:[]},this._store=new dx({tracked:!!e.tracked,idStrategy:e.idStrategy?e.idStrategy:void 0});let d=e=>{let t=[];return{changed:t,unchanged:this._store.copyAll().filter(n=>!e.includes(n.id)||(t.push(n),!1))}},f=(e,t)=>{var n;this._enabled&&(this._eventListeners.finish.forEach(n=>{n(e,t)}),(n=this.undoRedoCoordinator)==null||n.emitHistoryPushForCompletedAction())},p=(e,t,n)=>{if(!this._enabled)return;this._eventListeners.change.forEach(r=>{r(e,t,n)}),this.emitDrawingPushIfHistoryChangedFromLastSnapshot();let{changed:r,unchanged:i}=d(e);t===`create`?this._adapter.render({created:r,deletedIds:[],unchanged:i,updated:[]},this.getModeStyles()):t===`update`?this._adapter.render({created:[],deletedIds:[],unchanged:i,updated:r},this.getModeStyles()):t===`delete`?this._adapter.render({created:[],deletedIds:e,unchanged:i,updated:[]},this.getModeStyles()):t===`styling`&&this._adapter.render({created:[],deletedIds:[],unchanged:i,updated:[]},this.getModeStyles())},m=e=>{if(!this._enabled)return;this._eventListeners.select.forEach(t=>{t(e)});let{changed:t,unchanged:n}=d([e]);this._adapter.render({created:[],deletedIds:[],unchanged:n,updated:t},this.getModeStyles())},h=e=>{if(!this._enabled)return;this._eventListeners.deselect.forEach(t=>{t(e)});let{changed:t,unchanged:n}=d([e]);t&&this._adapter.render({created:[],deletedIds:[],unchanged:n,updated:t},this.getModeStyles())};Object.keys(this._modes).forEach(e=>{var t;this._modes[e].register({mode:e,store:this._store,setCursor:this._adapter.setCursor.bind(this._adapter),project:this._adapter.project.bind(this._adapter),unproject:this._adapter.unproject.bind(this._adapter),setDoubleClickToZoom:this._adapter.setDoubleClickToZoom.bind(this._adapter),onChange:p,onSelect:m,onDeselect:h,onFinish:f,coordinatePrecision:this._adapter.getCoordinatePrecision(),undoRedoMaxStackSize:(t=this.drawingUndoRedo)==null||t.getMaxStackSize==null?void 0:t.getMaxStackSize()})}),this.sessionUndoRedoEnabled&&s&&(this.sessionUndoRedo=s,s.register({draw:this,onHistoryChange:e=>{var t;(t=this.undoRedoCoordinator)==null||t.emitStackHistoryChange(e)}})),this.drawingUndoRedo&&this.drawingUndoRedo.register({getModeState:()=>this.getModeState(),getModeHistorySizes:()=>this.getDrawingHistorySizes(),undoMode:()=>{this._mode.undo&&this._mode.undo()},redoMode:()=>{this._mode.redo&&this._mode.redo()},clearModeHistory:()=>{let e=this._mode;e.clearHistory&&e.clearHistory()},onHistoryChange:e=>{var t;(t=this.undoRedoCoordinator)==null||t.emitStackHistoryChange(e)}}),this.undoRedoCoordinator=new vx({modeLevel:this.drawingUndoRedo,sessionLevel:this.sessionUndoRedo,shouldPreferMode:()=>this.getModeState()===`drawing`,onHistoryChange:e=>{this._eventListeners.history.forEach(t=>{t(e)})},shouldEmitHistoryChange:()=>this._enabled})}checkEnabled(){if(!this._enabled)throw Error(`Terra Draw is not enabled`)}handleUndoRedoKeyboardShortcut(e){if(!this.drawingUndoRedo&&!this.sessionUndoRedoEnabled||!this.keyboardShortcutsMatcher)return!1;let t=this.keyboardShortcutsMatcher.isUndoKeyboardShortcut(e),n=this.keyboardShortcutsMatcher.isRedoKeyboardShortcut(e);if(t){if(!this.canUndo())return!1;let t=this.undo();return t&&e.preventDefault(),t}if(n){if(!this.canRedo())return!1;let t=this.redo();return t&&e.preventDefault(),t}return!1}getDrawingHistorySizes(){return{undoSize:this._mode.undoSize&&typeof this._mode.undoSize==`function`?this._mode.undoSize():0,redoSize:this._mode.redoSize&&typeof this._mode.redoSize==`function`?this._mode.redoSize():0}}emitDrawingPushIfHistoryChangedFromLastSnapshot(){this.drawingUndoRedo&&this.drawingUndoRedo.emitPushIfHistoryChangedFromLastSnapshot()}emitDrawingPushIfHistoryChanged(e){this.drawingUndoRedo&&this.drawingUndoRedo.emitPushIfHistoryChanged(e)}getModeStyles(){let e={},t=this._instanceSelectModes.includes(this._mode.mode)?this._mode.mode:void 0;return Object.keys(this._modes).forEach(n=>{e[n]=e=>t&&e.properties[iy.SELECTED]?this._modes[t].styleFeature.bind(this._modes[t])(e):this._modes[n].styleFeature.bind(this._modes[n])(e)}),e}featuresAtLocation({lng:e,lat:t},n){let r=n&&n.pointerDistance!==void 0?n.pointerDistance:30,i=!n||n.ignoreSelectFeatures===void 0||n.ignoreSelectFeatures,a=!(!n||n.ignoreCoordinatePoints===void 0)&&n.ignoreCoordinatePoints,o=!(!n||n.ignoreCurrentlyDrawing===void 0)&&n.ignoreCurrentlyDrawing,s=!(!n||n.ignoreClosingPoints===void 0)&&n.ignoreClosingPoints,c=!(!n||n.ignoreSnappingPoints===void 0)&&n.ignoreSnappingPoints,l=this._adapter.unproject.bind(this._adapter),u=this._adapter.project.bind(this._adapter),d=u(e,t),f=Hy({unproject:l,point:d,pointerDistance:r});return this._store.search(f).filter(l=>{if(i&&(l.properties[iy.MID_POINT]||l.properties[iy.SELECTION_POINT])||a&&l.properties[ay.COORDINATE_POINT]||s&&l.properties[ay.CLOSING_POINT]||o&&l.properties[ay.CURRENTLY_DRAWING]||c&&l.properties[ay.SNAPPING_POINT])return!1;if(l.geometry.type===`Point`){let e=l.geometry.coordinates;return zy(d,u(e[0],e[1]))<r}if(l.geometry.type===`LineString`){let e=l.geometry.coordinates;for(let t=0;t<e.length-1;t++){let n=e[t],i=e[t+1];if(jb(d,u(n[0],n[1]),u(i[0],i[1]))<r)return!0}return!1}if(Ab([e,t],l.geometry.coordinates))return!0;if(n!=null&&n.includePolygonsWithinPointerDistance){let e=l.geometry.coordinates;for(let t of e)for(let e=0;e<t.length-1;e++){let n=t[e],i=t[e+1];if(jb(d,u(n[0],n[1]),u(i[0],i[1]))<r)return!0}}return!1}).map(r=>{if(n==null||!n.addClosestCoordinateInfoToProperties)return r;let i;if(r.geometry.type===`Polygon`)i=r.geometry.coordinates[0].slice(0,-1);else{if(r.geometry.type!==`LineString`)return r;i=r.geometry.coordinates}let a,o=-1,s=1/0;for(let e=0;e<i.length;e++){let t=i[e],n=zy(u(t[0],t[1]),d);n<s&&(o=e,s=n,a=t)}return r.properties.closestCoordinateIndexToEvent=o,r.properties.closestCoordinatePixelDistanceToEvent=s,r.properties.closestCoordinateDistanceKmToEvent=hy(a,[e,t]),r})}getSelectModeOrThrow(e=void 0){let t=this.getSelectMode({switchToSelectMode:!0,selectMode:e});if(!t)throw Error(`No select mode defined in instance`);return t}getSelectMode({switchToSelectMode:e,selectMode:t}){this.checkEnabled();let n=this.getMode();if(this._instanceSelectModes.length===0)return null;if(t!==void 0&&!this._instanceSelectModes.includes(t))throw Error(`No select mode with this name present: ${t}`);let r;return r=t===void 0?this._instanceSelectModes.includes(n)?n:this._instanceSelectModes[0]:t,e&&n!==r&&this.setMode(r),this._modes[r]}isGuidanceFeature(e){return!!(e.properties[iy.MID_POINT]||e.properties[iy.SELECTION_POINT]||e.properties[ay.COORDINATE_POINT]||e.properties[ay.SNAPPING_POINT])}setModeStyles(e,t){if(this.checkEnabled(),!this._modes[e])throw Error(`No mode with this name present`);this._modes[e].styles=t}updateModeOptions(e,t){if(this.checkEnabled(),!this._modes[e])throw Error(`No mode with this name present`);this._modes[e].updateOptions(t)}getSnapshot(){return this._store.copyAll()}getSnapshotFeature(e){if(this._store.has(e))return this._store.copy(e)}clear(){this.checkEnabled(),this._adapter.clear()}get enabled(){return this._enabled}set enabled(e){throw Error(`Enabled is read only`)}getMode(){return this._mode.mode}getModeState(){return this._mode.state}setMode(e){if(this.checkEnabled(),!this._modes[e])throw Error(`No mode with this name present`);this._mode.stop(),this._mode=this._modes[e],this._mode.start()}removeFeatures(e){this.checkEnabled();let t=[],n=[],r;e.forEach(e=>{if(!this._store.has(e))throw Error(`No feature with id ${e}, can not delete`);let i=this._store.getPropertiesCopy(e);i[iy.SELECTED]&&this.deselectFeature(e),i[ay.CURRENTLY_DRAWING]&&this._modes[i.mode]?r=i.mode:(i[ay.COORDINATE_POINT_IDS]&&t.push(...i[ay.COORDINATE_POINT_IDS]),n.push(e))}),this._store.delete([...n,...t],{origin:`api`}),r&&this._modes[r]&&this._modes[r].cleanUp()&&this._modes[r].cleanUp()}selectFeature(e,t){this.getSelectModeOrThrow(t).selectFeature(e)}deselectFeature(e){this.getSelectModeOrThrow().deselectFeature(e)}getFeatureId(){return this._store.getId()}hasFeature(e){return this._store.has(e)}checkIsReservedProperty(e){return![...Object.values(iy),...Object.values(ay)].includes(e)}updateFeatureProperties(e,t){var n;if(!this._store.has(e))throw Error(`No feature with id ${e} present in store`);let r=this._store.copy(e);if(this.isGuidanceFeature(r))throw Error(`Guidance features are not allowed to be updated directly.`);let i=r.properties.mode;if(!this._modes[i])throw Error(`No mode with name ${i} present in instance`);let a=Object.entries(t);a.forEach(([e,t])=>{if(!this.checkIsReservedProperty(e))throw Error(`You are trying to update a reserved property name: ${e}. Please choose another name.`);if(t!==void 0&&!mx(t))throw Error(`Invalid JSON value provided for property ${e}`)}),this._store.updateProperty(a.map(([e,t])=>({id:r.id,property:e,value:t})),{origin:`api`}),(n=this.undoRedoCoordinator)==null||n.emitHistoryPushForCompletedAction()}updateFeatureGeometry(e,t){var n;if(!this._store.has(e))throw Error(`No feature with id ${e} present in store`);let r=this._store.copy(e);if(this.isGuidanceFeature(r))throw Error(`Guidance features are not allowed to be updated directly.`);if(!(r&&t&&t.type&&t.coordinates))throw Error(`Invalid geometry provided`);if(t.type!==r.geometry.type)throw Error(`Geometry type mismatch: expected ${r.geometry.type}, got ${t.type}`);let i=r.properties.mode,a=this._modes[i];if(!a)throw Error(`No mode with name ${i} present in instance`);let o=Zv({},r,{geometry:t}),s=a.validateFeature(o);if(!s.valid)throw Error(`Feature validation failed: ${s.reason||`Unknown reason`}`);if(this._store.updateGeometry([{id:r.id,geometry:t}],{origin:`api`}),a.afterFeatureUpdated){a.afterFeatureUpdated(o);let e=o.properties[iy.SELECTED],t=this.getSelectMode({switchToSelectMode:!1});t&&e&&t.afterFeatureUpdated(o)}(n=this.undoRedoCoordinator)==null||n.emitHistoryPushForCompletedAction()}transformFeatureGeometry(e,t){var n;if(!this._store.has(e))throw Error(`No feature with id ${e} present in store`);let r=this._store.copy(e);if(this.isGuidanceFeature(r))throw Error(`Guidance features are not allowed to be updated directly.`);let i=r.properties.mode,a=this._modes[i];if(!a)throw Error(`No mode with name ${i} present in instance`);let o;if(r.geometry.type===`Polygon`)o=r.geometry.coordinates[0];else{if(r.geometry.type!==`LineString`)throw Error(`Feature geometry type ${r.geometry.type} is not supported for transformation`);o=r.geometry.coordinates}if(t.projection!=`web-mercator`)throw Error(`Projection ${t.projection} is not currently supported for transformation`);if(t.type===`scale`){let{x:e,y:n}=wy(t.origin[0],t.origin[1]);Bb({coordinates:o,originX:e,originY:n,xScale:t.options.xScale||1,yScale:t.options.yScale||1})}else t.type===`rotate`&&(r=Ib(r,t.options.angle||0),o=r.geometry.type===`Polygon`?r.geometry.coordinates[0]:r.geometry.coordinates);if(o=o.map(e=>[by(e[0],this._adapter.getCoordinatePrecision()),by(e[1],this._adapter.getCoordinatePrecision())]),r.geometry.coordinates=r.geometry.type===`Polygon`?[o]:o,this._store.updateGeometry([{id:r.id,geometry:r.geometry}],{origin:`api`}),a.afterFeatureUpdated){a.afterFeatureUpdated(r);let e=r.properties[iy.SELECTED],t=this.getSelectMode({switchToSelectMode:!1});t&&e&&t.afterFeatureUpdated(r)}(n=this.undoRedoCoordinator)==null||n.emitHistoryPushForCompletedAction()}undo(){return this.checkEnabled(),!!this.undoRedoCoordinator&&this.undoRedoCoordinator.undo()}canUndo(){return this.checkEnabled(),!!this.undoRedoCoordinator&&this.undoRedoCoordinator.canUndo()}canRedo(){return this.checkEnabled(),!!this.undoRedoCoordinator&&this.undoRedoCoordinator.canRedo()}redo(){return this.checkEnabled(),!!this.undoRedoCoordinator&&this.undoRedoCoordinator.redo()}clearUndoRedoHistory(){this.checkEnabled(),this.undoRedoCoordinator&&this.undoRedoCoordinator.clearHistory()}addFeatures(e){return this.checkEnabled(),e.length===0?[]:this._store.load(e,e=>{if(cy(e)){let t=e.properties.mode,n=this._modes[t];if(!n)return{id:e.id,valid:!1,reason:`${t} mode is not in the list of instantiated modes`};let r=n.validateFeature.bind(n)(e);return{id:e.id,valid:r.valid,reason:r.reason?r.reason:r.valid?void 0:`Feature is invalid`}}return{id:e.id,valid:!1,reason:`Mode property does not exist`}},e=>{if(cy(e)){let t=this._modes[e.properties.mode];t&&t.afterFeatureAdded&&t.afterFeatureAdded(e)}},{origin:`api`})}start(){this._enabled||(this._enabled=!0,this._adapter.register({onReady:()=>{this._eventListeners.ready.forEach(e=>{e()})},getState:()=>this._mode.state,onClick:e=>{let t=this.drawingUndoRedo?this.drawingUndoRedo.getHistorySizes():{undoSize:0,redoSize:0};this._mode.onClick(e),this.emitDrawingPushIfHistoryChanged(t)},onMouseMove:e=>{this._mode.onMouseMove(e)},onKeyDown:e=>{this.handleUndoRedoKeyboardShortcut(e)||this._mode.onKeyDown(e)},onKeyUp:e=>{let t=this.drawingUndoRedo?this.drawingUndoRedo.getHistorySizes():{undoSize:0,redoSize:0};this._mode.onKeyUp(e),this.emitDrawingPushIfHistoryChanged(t)},onDragStart:(e,t)=>{this._mode.onDragStart(e,t)},onDrag:(e,t)=>{this._mode.onDrag(e,t)},onDragEnd:(e,t)=>{this._mode.onDragEnd(e,t)},onClear:()=>{this._mode.cleanUp(),this._store.clear({origin:`api`})}}))}getFeaturesAtLngLat(e,t){let{lng:n,lat:r}=e;return this.featuresAtLocation({lng:n,lat:r},t)}getFeaturesAtPointerEvent(e,t){let n=this._adapter.getLngLatFromEvent.bind(this._adapter)(e);return n===null?[]:this.featuresAtLocation(n,t)}stop(){this._enabled&&(this._enabled=!1,this._adapter.unregister())}on(e,t){let n=this._eventListeners[e];n.includes(t)||n.push(t)}off(e,t){let n=this._eventListeners[e];n.includes(t)&&n.splice(n.indexOf(t),1)}};function bx(){return bx=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},bx.apply(null,arguments)}var xx=class extends px.TerraDrawBaseAdapter{constructor(e){super(e),this._renderBeforeLayerId=void 0,this._prefixId=void 0,this._initialDragPan=void 0,this._initialDragRotate=void 0,this._nextRender=void 0,this._map=void 0,this._container=void 0,this.changedIds={deletion:!1,points:!1,linestrings:!1,polygons:!1,styling:!1},this._map=e.map,this._container=this._map.getContainer(),this._initialDragRotate=this._map.dragRotate.isEnabled(),this._initialDragPan=this._map.dragPan.isEnabled(),this._renderBeforeLayerId=e.renderBelowLayerId,this._prefixId=e.prefixId||`td`}hashCode(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t)}resizeImage(e,t,n,r){let i=new Image;i.crossOrigin=`anonymous`,i.onload=()=>{let e=document.createElement(`canvas`);e.width=t,e.height=n;let a=e.getContext(`2d`);if(!a)throw Error(`Could not get canvas context`);a.drawImage(i,0,0,t,n),r(e.toDataURL())},i.src=e}toGlDashArrayFromPixels(e,t){if(!e)return null;let[n,r]=e;if(!Number.isFinite(n)||!Number.isFinite(r)||n<0||r<0)return null;let i=Math.max(1e-4,t);return[n/i,r/i]}isMapLibreAtLeast(e){let t=this._map.version;if(!t)return!1;let n=e=>{let t=e.match(/(\d+)\.(\d+)\.(\d+)/);return t?[parseInt(t[1],10),parseInt(t[2],10),parseInt(t[3],10)]:null},r=n(t),i=n(e);if(!r||!i)return!0;let[a,o,s]=r,[c,l,u]=i;return a===c?o===l?s>=u:o>l:a>c}_addGeoJSONSource(e,t){this._map.addSource(e,{type:`geojson`,data:{type:`FeatureCollection`,features:t},tolerance:0})}_addFillLayer(e){return this._map.addLayer({id:e,source:e,type:`fill`,layout:{"fill-sort-key":[`get`,`zIndex`]},paint:{"fill-color":[`get`,`polygonFillColor`],"fill-opacity":[`get`,`polygonFillOpacity`]}})}_addFillOutlineLayer(e){return this._map.addLayer({id:e+`-outline`,source:e,type:`line`,layout:{"line-sort-key":[`get`,`zIndex`]},paint:{"line-width":[`get`,`polygonOutlineWidth`],"line-color":[`get`,`polygonOutlineColor`],"line-opacity":[`get`,`polygonOutlineOpacity`]}})}_addLineLayer(e){let t={};return this.isMapLibreAtLeast(`5.8.0`)&&(t[`line-dasharray`]=[`coalesce`,[`get`,`lineStringDash`],[`literal`,[1,0]]]),this._map.addLayer({id:e,source:e,type:`line`,layout:{"line-sort-key":[`get`,`zIndex`]},paint:bx({},t,{"line-width":[`get`,`lineStringWidth`],"line-color":[`get`,`lineStringColor`],"line-opacity":[`get`,`lineStringOpacity`]})})}_addPointLayer(e){return this._map.addLayer({id:e,source:e,type:`circle`,layout:{"circle-sort-key":[`get`,`zIndex`]},paint:{"circle-stroke-color":[`get`,`pointOutlineColor`],"circle-stroke-width":[`get`,`pointOutlineWidth`],"circle-stroke-opacity":[`get`,`pointOutlineOpacity`],"circle-radius":[`get`,`pointWidth`],"circle-color":[`get`,`pointColor`],"circle-opacity":[`get`,`pointOpacity`]}})}_addMarkerLayer(e){return this._map.addLayer({id:e+`-marker`,source:e,type:`symbol`,filter:[`has`,`markerId`],layout:{"icon-image":[`image`,[`get`,`markerId`]],"icon-anchor":`bottom`,"icon-allow-overlap":!0}})}_addLayer(e,t){t===`Point`&&(this._addPointLayer(e),this._addMarkerLayer(e)),t===`LineString`&&this._addLineLayer(e),t===`Polygon`&&(this._addFillLayer(e),this._addFillOutlineLayer(e))}_addGeoJSONLayer(e,t){let n=`${this._prefixId}-${e.toLowerCase()}`;return this._addGeoJSONSource(n,t),this._addLayer(n,e),n}_setGeoJSONLayerData(e,t){let n=`${this._prefixId}-${e.toLowerCase()}`;return this._map.getSource(n).setData({type:`FeatureCollection`,features:t}),n}updateChangedIds(e){[...e.updated,...e.created].forEach(e=>{e.geometry.type===`Point`?this.changedIds.points=!0:e.geometry.type===`LineString`?this.changedIds.linestrings=!0:e.geometry.type===`Polygon`&&(this.changedIds.polygons=!0)}),e.deletedIds.length>0&&(this.changedIds.deletion=!0),e.created.length===0&&e.updated.length===0&&e.deletedIds.length===0&&(this.changedIds.styling=!0)}getLngLatFromEvent(e){let{left:t,top:n}=this._container.getBoundingClientRect();return this.unproject(e.clientX-t,e.clientY-n)}getMapEventElement(){return this._map.getCanvas()}setDraggability(e){e?(this._initialDragRotate&&this._map.dragRotate.enable(),this._initialDragPan&&this._map.dragPan.enable()):(this._initialDragRotate&&this._map.dragRotate.disable(),this._initialDragPan&&this._map.dragPan.disable())}project(e,t){let{x:n,y:r}=this._map.project({lng:e,lat:t});return{x:n,y:r}}unproject(e,t){let{lng:n,lat:r}=this._map.unproject({x:e,y:t});return{lng:n,lat:r}}setCursor(e){let t=this._map.getCanvas();e===`unset`?t.style.removeProperty(`cursor`):t.style.cursor=e}setDoubleClickToZoom(e){e?this._map.doubleClickZoom.enable():this._map.doubleClickZoom.disable()}render(e,t){this.updateChangedIds(e),this._nextRender&&cancelAnimationFrame(this._nextRender),this._nextRender=requestAnimationFrame(()=>{if(!this._currentModeCallbacks)return;let n=[...e.created,...e.updated,...e.unchanged],r=[],i=[],a=[];for(let e=0;e<n.length;e++){let o=n[e],{properties:s}=o,c=t[s.mode](o);if(s.zIndex=c.zIndex,s.zIndex=c.zIndex,o.geometry.type===`Point`){s.pointColor=c.pointColor,s.pointOutlineColor=c.pointOutlineColor,s.pointOutlineWidth=c.pointOutlineWidth;let e=c.pointOutlineOpacity;s.pointOutlineOpacity=e===void 0?1:e,s.pointWidth=c.pointWidth;let t=c.pointOpacity;if(s.pointOpacity=t===void 0?1:t,c.markerUrl&&c.markerWidth&&c.markerHeight){let e=`marker-${this.hashCode(c.markerUrl)}`;this._map.hasImage(e)||this.resizeImage(c.markerUrl,c.markerWidth,c.markerHeight,t=>{this._map.loadImage(t).then(t=>{this._map.hasImage(e)||this._map.addImage(e,t.data)})}),s.markerId=e,s.pointWidth=0}r.push(o)}else if(o.geometry.type===`LineString`){s.lineStringDash=this.toGlDashArrayFromPixels(c.lineStringDash,c.lineStringWidth),s.lineStringColor=c.lineStringColor,s.lineStringWidth=c.lineStringWidth;let e=c.lineStringOpacity;s.lineStringOpacity=e===void 0?1:e,i.push(o)}else if(o.geometry.type===`Polygon`){let e=c.polygonOutlineOpacity;s.polygonFillColor=c.polygonFillColor,s.polygonFillOpacity=c.polygonFillOpacity,s.polygonOutlineOpacity=e===void 0?1:e,s.polygonOutlineColor=c.polygonOutlineColor,s.polygonOutlineWidth=c.polygonOutlineWidth,a.push(o)}}let o=this.changedIds.deletion||this.changedIds.styling,s=o||this.changedIds.linestrings,c=o||this.changedIds.polygons;(o||this.changedIds.points)&&this._setGeoJSONLayerData(`Point`,r),s&&this._setGeoJSONLayerData(`LineString`,i),c&&this._setGeoJSONLayerData(`Polygon`,a),this.changedIds={points:!1,linestrings:!1,polygons:!1,deletion:!1,styling:!1}})}clear(){this._currentModeCallbacks&&(this._currentModeCallbacks.onClear(),this._nextRender&&=(cancelAnimationFrame(this._nextRender),void 0),this._setGeoJSONLayerData(`Point`,[]),this._setGeoJSONLayerData(`LineString`,[]),this._setGeoJSONLayerData(`Polygon`,[]))}getCoordinatePrecision(){return super.getCoordinatePrecision()}unregister(){super.unregister(),this.changedIds={points:!1,linestrings:!1,polygons:!1,deletion:!1,styling:!1},this._map.removeLayer(`${this._prefixId}-point`),this._map.removeLayer(`${this._prefixId}-point-marker`),this._map.removeSource(`${this._prefixId}-point`),this._map.removeLayer(`${this._prefixId}-linestring`),this._map.removeSource(`${this._prefixId}-linestring`),this._map.removeLayer(`${this._prefixId}-polygon`),this._map.removeLayer(`${this._prefixId}-polygon-outline`),this._map.removeSource(`${this._prefixId}-polygon`)}register(e){var t;super.register(e);let n=this._addGeoJSONLayer(`Polygon`,[]),r=this._addGeoJSONLayer(`LineString`,[]),i=this._addGeoJSONLayer(`Point`,[]);var a;this._renderBeforeLayerId&&(this._map.moveLayer(i,this._renderBeforeLayerId),this._map.moveLayer(r,i),this._map.moveLayer(`${n}-outline`,r),this._map.moveLayer(n,`${n}-outline`)),(t=this._currentModeCallbacks)!=null&&t.onReady&&((a=this._currentModeCallbacks)==null||a.onReady())}},Sx=`linestring`;function Cx(e){return sl(e).select}function wx(e){let t=e.geometry;return t.type===`LineString`?t.coordinates.filter(e=>Array.isArray(e)&&typeof e[0]==`number`&&typeof e[1]==`number`).map(e=>({position:Rs([e[0],e[1]])})):[]}function Tx(e){return{type:`Feature`,properties:{mode:Sx},geometry:{type:`LineString`,coordinates:e.waypoints.map(e=>zs(e.position))}}}function Ex(e){let t=Cx(e.theme),n=new yx({adapter:new xx({map:e.map,prefixId:`binnacle-route-draw`,renderBelowLayerId:e.beforeId}),modes:[new Sb({styles:{pointColor:t,pointWidth:6}}),new hb({styles:{lineStringColor:t,lineStringWidth:4}}),new Wb({styles:{selectionPointColor:t,midPointColor:t},flags:{linestring:{feature:{draggable:!0,coordinates:{midpoints:!0,draggable:!0,deletable:!0}}}}})]}),r=()=>{let e=n.getSnapshot().find(e=>e.properties.mode===Sx);return e?wx(e):[]};return n.on(`change`,()=>e.onChange(r())),{start(e){n.start(),e&&e.waypoints.length>0?(n.addFeatures([Tx(e)]),n.setMode(`select`)):n.setMode(Sx)},setTheme(e){let t=Cx(e);n.updateModeOptions(`point`,{styles:{pointColor:t,pointWidth:6}}),n.updateModeOptions(`linestring`,{styles:{lineStringColor:t,lineStringWidth:4}}),n.updateModeOptions(`select`,{styles:{selectionPointColor:t,midPointColor:t}})},stop(){n.stop()}}}function Dx(e,t,n){let r=[];for(let i of e)t.has(i.id)&&(i.waypoints.length<2||r.push({type:`Feature`,geometry:{type:`LineString`,coordinates:i.waypoints.map(e=>zs(e.position))},properties:{id:i.id,active:i.id===n}}));return{type:`FeatureCollection`,features:r}}function Ox(e,t){let n=[];for(let r of e)t.has(r.id)&&r.waypoints.forEach((e,t)=>{n.push({type:`Feature`,geometry:{type:`Point`,coordinates:zs(e.position)},properties:{id:r.id,index:t,name:e.name??`${t+1}`}})});return{type:`FeatureCollection`,features:n}}var kx=`binnacle-route-lines`,Ax=`binnacle-route-line`,jx=`binnacle-route-waypoints`,Mx=`binnacle-route-waypoint`,Nx=`binnacle-route-waypoint-label`,Px=`routes`,Fx=[Ax,Mx,Nx];function Ix(e){return[`case`,[`get`,`active`],e.select,e.note]}var Lx=[`case`,[`get`,`active`],3,2];function Rx(e){let t=sl(`day`),n=-1;return{id:`routes`,title:`Routes`,band:Px,supportsOpacity:!0,layerIds:Fx,add(e){n=-1;let r=e.beforeIdFor(Px);if(!e.map.getSource(kx)){let t={type:`geojson`,data:od()};e.map.addSource(kx,t)}if(!e.map.getSource(jx)){let t={type:`geojson`,data:od()};e.map.addSource(jx,t)}if(!e.map.getLayer(Ax)){let n={id:Ax,type:`line`,source:kx,layout:{"line-cap":`round`,"line-join":`round`},paint:{"line-color":Ix(t),"line-width":Lx,"line-dasharray":[2,1]}};e.map.addLayer(n,r)}if(!e.map.getLayer(Mx)){let n={id:Mx,type:`circle`,source:jx,paint:{"circle-radius":4,"circle-color":t.note,"circle-stroke-color":t.markerGlyph,"circle-stroke-width":1}};e.map.addLayer(n,r)}if(!e.map.getLayer(Nx)){let n={id:Nx,type:`symbol`,source:jx,layout:{"text-field":[`get`,`name`],"text-size":11,"text-offset":[0,1.1],"text-optional":!0},paint:{"text-color":t.label,"text-halo-color":t.background,"text-halo-width":1.5}};e.map.addLayer(n,r)}},sync(t){e.version!==n&&(n=e.version,t.map.getSource(kx)?.setData(Dx(e.routes,e.shownIds,e.activeId)),t.map.getSource(jx)?.setData(Ox(e.routes,e.shownIds)))},setVisible(e,t){let n=t?`visible`:`none`;for(let t of Fx)e.map.setLayoutProperty(t,`visibility`,n)},setOpacity(e,t){e.map.setPaintProperty(Ax,`line-opacity`,t),e.map.setPaintProperty(Mx,`circle-opacity`,t)},applyTheme(e,n){t=n,e.map.setPaintProperty(Ax,`line-color`,Ix(t)),e.map.setPaintProperty(Mx,`circle-color`,t.note),e.map.setPaintProperty(Mx,`circle-stroke-color`,t.markerGlyph),e.map.setPaintProperty(Nx,`text-color`,t.label),e.map.setPaintProperty(Nx,`text-halo-color`,t.background)},remove(e){for(let t of Fx)e.map.getLayer(t)&&e.map.removeLayer(t);for(let t of[kx,jx])e.map.getSource(t)&&e.map.removeSource(t)}}}function zx(e,t,n){let r=n.lon-t.lon,i=n.lat-t.lat,a=r*r+i*i;if(a===0)return Math.hypot(e.lon-t.lon,e.lat-t.lat);let o=((e.lon-t.lon)*r+(e.lat-t.lat)*i)/a;return Math.hypot(e.lon-(t.lon+o*r),e.lat-(t.lat+o*i))}function Bx(e,t){let n=e.length;if(n<=2)return e;let r=Array(n).fill(!1);r[0]=!0,r[n-1]=!0;let i=[[0,n-1]];for(;i.length>0;){let n=i.pop();if(!n)break;let[a,o]=n,s=0,c=-1;for(let t=a+1;t<o;t+=1){let n=zx(e[t],e[a],e[o]);n>s&&(s=n,c=t)}s>t&&c!==-1&&(r[c]=!0,i.push([a,c]),i.push([c,o]))}let a=[];for(let t=0;t<n;t+=1)r[t]&&a.push(e[t]);return a}function Vx(e,t){if(e.length<=2)return e.slice();let n=[];for(let r of rl(e))n.push(...Bx(r,t));return n}function Hx(e){let t=[];for(let n=1;n<e.length;n+=1){let r=e[n];if(r.gap)continue;let i=e[n-1];t.push({type:`Feature`,geometry:{type:`LineString`,coordinates:[nl(i),nl(r)]},properties:{sog:r.sog}})}return{type:`FeatureCollection`,features:t}}var Ux=`binnacle-track-active`,Wx=`binnacle-track-active-line`,Gx=`binnacle-track-saved`,Kx=`binnacle-track-saved-line`,qx=`track`,Jx=8e-5,Yx=2.5,Xx=5,Zx=od(),Qx={features:()=>Zx,version:()=>0};function $x(e,t){return t===`solid`?e.trackSolid:[`interpolate`,[`linear`],[`get`,`sog`],0,e.trackSlow,Yx,e.trackMid,Xx,e.trackFast]}function eS(e,t,n=Qx){let r=sl(`day`),i=-1,a,o,s=-1;function c(t){let n=Vx(e.points,Jx);t.map.getSource(Ux)?.setData(Hx(n))}return{id:`track`,title:`Track`,band:qx,supportsOpacity:!0,layerIds:[Kx,Wx],add(e){i=-1,a=void 0,o=void 0,s=-1;let n=e.beforeIdFor(qx),c={type:`geojson`,data:Zx};e.map.addSource(Ux,c),e.map.addSource(Gx,{type:`geojson`,data:Zx});let l={id:Kx,type:`line`,source:Gx,layout:{"line-cap":`round`,"line-join":`round`},paint:{"line-color":r.trackSolid,"line-width":2}};e.map.addLayer(l,n);let u={id:Wx,type:`line`,source:Ux,layout:{"line-cap":`round`,"line-join":`round`},paint:{"line-color":$x(r,t.value.colorMode),"line-width":3}};e.map.addLayer(u,n)},sync(l){let u=t.value.colorMode,d=e.points,f=d[d.length-1]?.t;(d.length!==i||f!==a)&&(i=d.length,a=f,c(l)),u!==o&&(o=u,l.map.setPaintProperty(Wx,`line-color`,$x(r,u)));let p=n.version();p!==s&&(s=p,l.map.getSource(Gx)?.setData(n.features()))},applyTheme(e,n){r=n,e.map.setPaintProperty(Wx,`line-color`,$x(r,t.value.colorMode)),e.map.setPaintProperty(Kx,`line-color`,r.trackSolid)},setVisible(e,t){let n=t?`visible`:`none`;e.map.setLayoutProperty(Wx,`visibility`,n),e.map.setLayoutProperty(Kx,`visibility`,n)},setOpacity(e,t){e.map.setPaintProperty(Wx,`line-opacity`,t),e.map.setPaintProperty(Kx,`line-opacity`,t)},remove(e){for(let t of[Wx,Kx])e.map.getLayer(t)&&e.map.removeLayer(t);for(let t of[Ux,Gx])e.map.getSource(t)&&e.map.removeSource(t)}}}var tS=`binnacle-vessel`,nS=80,rS=64;function iS(e,t=e.a){return`rgba(${e.r}, ${e.g}, ${e.b}, ${(t/255).toFixed(3)})`}function aS(e,t){return{r:Math.round(e.r*t),g:Math.round(e.g*t),b:Math.round(e.b*t),a:e.a}}function oS(e){if(typeof document<`u`){let t=document.createElement(`canvas`);t.width=nS,t.height=nS;let n=t.getContext(`2d`);if(n)return sS(n,e)}return cS(e)}function sS(e,t){let n=iS(aS(t,.5));return e.clearRect(0,0,nS,nS),e.scale(nS/rS,nS/rS),e.beginPath(),e.moveTo(32,4),e.quadraticCurveTo(44,24,43,44),e.quadraticCurveTo(42,53,38,57),e.lineTo(26,57),e.quadraticCurveTo(22,53,21,44),e.quadraticCurveTo(20,24,32,4),e.closePath(),e.fillStyle=iS(t),e.fill(),e.lineJoin=`round`,e.lineCap=`round`,e.lineWidth=2.5,e.strokeStyle=n,e.stroke(),e.getImageData(0,0,nS,nS)}function cS(e){return sd(nS,e,(e,t,n)=>{let r=t/2.4;return t>6&&Math.abs(e-n)<=r})}var lS=`binnacle-own-vessel`,uS=`binnacle-own-vessel-symbol`,dS={r:31,g:111,b:178,a:255},fS=`own-vessel`;function pS(e){let t,n,r,i=()=>vc(e.headingRad,e.cogRad);function a(){let t=e.position;return t?{type:`FeatureCollection`,features:[{type:`Feature`,geometry:{type:`Point`,coordinates:[t.longitude,t.latitude]},properties:{heading:i()}}]}:od()}function o(){let a=e.position,o=a?.longitude,s=a?.latitude,c=a?i():void 0;return o===t&&s===n&&c===r?!1:(t=o,n=s,r=c,!0)}return vd({id:fS,title:`Own vessel`,band:`vessel`,sourceId:lS,layerId:uS,iconId:tS,iconImage:oS,pixelRatio:2,defaultColor:dS,paintColor:e=>e.ownVessel,features:a,shouldRefresh:o})}var mS=K(`<div class="chart-canvas svelte-1mqhhzl"></div>`);function hS(e,t){Qe(t,!0);let n,r,i;Ln(()=>{i?.setTheme(t.theme)}),ed(),ga(()=>{r=xd({container:n,view:t.initialView,managerOptions:{saved:t.savedLayers,onChange:t.onLayersChange,savedOrder:t.savedOrder,onOrderChange:t.onOrderChange,pinned:[Ef,fS]},onView:e=>t.onViewChange?.(e),onUserPan:()=>t.onUserPan?.(),onLoad:async({map:e,ctx:n,manager:r,recolor:a,isDestroyed:o,runTick:s})=>{let c=await Gv(Vs(),t.chartsToken);if(o())return;let l=Rx(t.routeStore),u=Em(Vs(),t.chartsToken,t.onNoteSelect),d=Hv(t.aisTargets,t.store),f=kf(t.collision),p=eS(t.recorder,t.trackSettings,t.savedTracks),m=pS(t.vessel);if(await r.registerAll([...c.map(e=>ad(e,Vs())),...Xv.map(e=>Yv(e)),l,u,d,f,p,m]),o())return;i=Ex({map:e,beforeId:n.beforeIdFor(`routes`),theme:t.theme,onChange:e=>{let n=t.routeStore.working;n&&t.routeStore.setWorking({...n,waypoints:e})}});let h=new bf(r);h.refresh(),t.onReady?.(h),t.onUserChartsReady?.({register:async e=>{o()||(await r.register(ad(e,Vs(),`bathymetry`)),h.refresh())},unregister:e=>{r.unregister(fl(e)),h.refresh()}}),t.onMapReady?.(a),t.onCommandsReady?.({centerOnVessel:()=>{let n=t.vessel.position;if(!n)return;let r=e.getZoom();e.flyTo({center:[n.longitude,n.latitude],zoom:r<12?14:r})},recenterOnVessel:(t,n)=>{e.setCenter([n,t])},flyTo:(t,n)=>{let r=e.getZoom();e.flyTo({center:[n,t],zoom:r<11?12:r})},fitBounds:([t,n,r,i])=>{e.fitBounds([[t,n],[r,i]],{padding:40,maxZoom:16,duration:800})},clearNoteSelection:()=>u.deselect(n),startRouteEdit:e=>i?.start(e),stopRouteEdit:()=>i?.stop()}),s([l,u,d,f,p,m])}})}),_a(()=>r?.destroy());var a=mS();da(a,e=>n=e,()=>n),q(e,a),$e()}var gS=K(`<button type="button"> </button>`),_S=K(`<span class="bar-sep svelte-qluf4r" aria-hidden="true"></span>`),vS=K(`<div class="conditions-slot svelte-qluf4r"><!></div>`),yS=K(`&middot; <b class="svelte-qluf4r"> </b> hPa`,1),bS=K(`/ <b class="svelte-qluf4r"> </b> s`,1),xS=K(`&middot; sea <b class="svelte-qluf4r"> </b> m <!>`,1),SS=K(`&middot; rain <b class="svelte-qluf4r"> </b> mm/h`,1),CS=K(`<span class="readout-source svelte-qluf4r"> </span>`),wS=K(`<div class="readout svelte-qluf4r" role="status" aria-live="polite"><span class="readout-line">Wind <b class="svelte-qluf4r"> </b> kn from <b class="svelte-qluf4r"> </b>&deg; <!> <!> <!></span> <!></div>`),TS=K(`<p class="hint svelte-qluf4r">Turn on a layer above to load weather for this area.</p>`),ES=K(`<div class="scrubber svelte-qluf4r" role="group" aria-label="Forecast time"><button type="button" class="step svelte-qluf4r" aria-label="Earlier"><span aria-hidden="true">&#9664;</span></button> <button type="button" class="step svelte-qluf4r"><!></button> <button type="button" class="step svelte-qluf4r" aria-label="Later"><span aria-hidden="true">&#9654;</span></button> <input class="track svelte-qluf4r" type="range" aria-label="Forecast time"/> <span class="time svelte-qluf4r"> </span></div>`),DS=K(`<span class="legend-scale svelte-qluf4r"><span class="legend-end svelte-qluf4r"> </span> <span class="legend-bar svelte-qluf4r"></span> <span class="legend-end svelte-qluf4r"> </span></span>`),OS=K(`<span class="legend-swatch svelte-qluf4r"><span class="legend-chip svelte-qluf4r"></span> </span>`),kS=K(`<span class="legend-swatches svelte-qluf4r"></span>`),AS=K(`<span class="legend-note svelte-qluf4r"> </span>`),jS=K(`<div class="legend-row svelte-qluf4r"><span class="legend-title caps-label svelte-qluf4r"> </span> <!> <!></div>`),MS=K(`<div class="legend svelte-qluf4r" role="group" aria-label="Weather legend"></div>`),NS=K(`<section class="weather-panel svelte-qluf4r" aria-label="Weather"><header class="panel-head svelte-qluf4r"><h2 class="panel-title">Weather</h2> <div class="layer-bar svelte-qluf4r" role="group" aria-label="Weather layers"><!> <!> <!></div> <button type="button">Here</button> <button type="button" class="panel-close" aria-label="Close weather"><!></button></header> <div class="panel-map svelte-qluf4r"><div class="map svelte-qluf4r"></div> <!> <!> <!></div> <footer class="panel-foot svelte-qluf4r"><!> <!></footer></section>`);function PS(e,t){Qe(t,!0);let n=3*hc,r=`Open-Meteo`,i,a,o,s,c=z(void 0),l=z(!1),u=z(!1),d,f,p=z(void 0),m=z(void 0),h,g=0,_=R(()=>W(c)?.items??[]),v=R(()=>W(_).filter(e=>kh.includes(e.id))),y=R(()=>W(_).filter(e=>!kh.includes(e.id))),b=R(()=>W(_).some(e=>e.visible)),x=R(()=>W(_).some(e=>e.id===Oh.waves&&e.visible)),S=R(()=>W(_).some(e=>e.id===Oh.radar&&e.visible)),C=e=>W(_).some(t=>t.id===e&&t.visible),w=R(()=>W(_).filter(e=>e.visible).map(e=>ag(e.id,t.theme)).filter(e=>e!==void 0)),T=R(()=>t.store.grid&&t.store.grid.times.length>0?{start:t.store.grid.times[0],end:t.store.grid.times[t.store.grid.times.length-1],stepMs:n}:void 0),E=R(()=>t.store.grid?new Date(t.store.selectedTime).toLocaleString([],{weekday:`short`,hour:`2-digit`,minute:`2-digit`}):``);function D(e){W(T)&&t.store.setSelectedTime(Ig(e,W(T)))}function O(){B(u,!1),d&&clearInterval(d),d=void 0}function k(){if(W(u)||!W(T)){O();return}B(u,!0),d=setInterval(()=>W(T)&&t.store.setSelectedTime(Rg(t.store.selectedTime,W(T))),700)}let A={maxCells:200,forecastDays:5};function ee(){f&&clearTimeout(f),f=setTimeout(()=>{!o||!W(b)||t.loader.load(t.store,o(),A,{waves:W(x),radar:W(S)})},400)}function te(e,t){B(p,e,!0),B(m,e?t:void 0,!0),h&&clearTimeout(h),e&&(h=setTimeout(()=>B(p,void 0),8e3))}async function ne(e,n){let i=++g;if(t.providerName){let r=await ie(n,e);if(i!==g)return;if(r){te(r,t.providerName);return}}W(b)&&t.store.grid?te(zg(t.store.grid,e,n,t.store.bracket.lo),r):te(void 0,void 0)}let re=e=>W(m)===r?C(e):!0;async function ie(e,n){let r=Vs(),i=t.store.selectedTime;if(Math.abs(i-Date.now())<54e5){let i=await kg(r,e,n,t.token),a=i&&Pg(i);if(a)return a}let a=await Ag(r,e,n,48,t.token),o=a&&Fg(a,i);return o?Pg(o):void 0}let ae=xc;function oe(e){let t=!1;Ln(()=>{e()&&!t?(t=!0,ee()):e()||(t=!1)})}oe(()=>W(x)),oe(()=>W(S)),Ln(()=>{W(b)&&!t.store.grid&&ee()}),Ln(()=>{s?.(t.theme)}),ga(()=>{a=xd({container:i,view:t.initialView??t.savedView,defaultZoom:3,minZoom:1,maxZoom:7,managerOptions:{saved:t.savedLayers,onChange:t.onLayersChange,exclusive:[kh]},onView:e=>t.onViewChange?.(e),onClick:e=>void ne(e.lng,e.lat),onLoad:async({map:e,manager:n,recolor:r,isDestroyed:i,runTick:a})=>{let l=[h_(t.store),sg(t.store),Ah(t.store),xg(t.store),Sv(t.store),fg(t.store)];for(let e of l)if(await n.register(e),i())return;let u=new bf(n);u.refresh(),B(c,u,!0),s=r,s(t.theme),o=()=>Ed(e.getBounds()),e.on(`moveend`,ee),a(l)}})}),_a(()=>{f&&clearTimeout(f),h&&clearTimeout(h),O(),a?.destroy()});var se=NS(),ce=V(se),le=H(V(ce),2),ue=V(le);vi(ue,17,()=>W(v),e=>e.id,(e,t)=>{var n=gS();let r;var i=V(n,!0);N(n),U(()=>{r=Li(n,1,`pill svelte-qluf4r`,null,r,{on:W(t).visible}),X(n,`aria-pressed`,W(t).visible),J(i,W(t).title)}),G(`click`,n,()=>W(c)?.toggle(W(t).id,!W(t).visible)),q(e,n)});var de=H(ue,2),fe=e=>{q(e,_S())};Y(de,e=>{W(v).length>0&&W(y).length>0&&e(fe)}),vi(H(de,2),17,()=>W(y),e=>e.id,(e,t)=>{var n=gS();let r;var i=V(n,!0);N(n),U(()=>{r=Li(n,1,`pill svelte-qluf4r`,null,r,{on:W(t).visible}),X(n,`aria-pressed`,W(t).visible),J(i,W(t).title)}),G(`click`,n,()=>W(c)?.toggle(W(t).id,!W(t).visible)),q(e,n)}),N(le);var pe=H(le,2);let me;var he=H(pe,2);Ko(V(he),{size:18,"aria-hidden":`true`}),N(he),N(ce);var ge=H(ce,2),_e=V(ge);da(_e,e=>i=e,()=>i);var ve=H(_e,2),ye=e=>{var n=vS(),r=V(n);{let e=R(Vs);a_(r,{get origin(){return W(e)},get token(){return t.token},get providerName(){return t.providerName},get position(){return t.position},get store(){return t.store}})}N(n),q(e,n)};Y(ve,e=>{W(l)&&e(ye)});var be=H(ve,2),xe=e=>{var t=wS(),n=V(t),r=H(V(n)),i=V(r,!0);N(r);var a=H(r,2),o=V(a,!0);N(a);var s=H(a,2),c=e=>{var t=yS(),n=H(Sn(t)),r=V(n,!0);N(n),P(),U(e=>J(r,e),[()=>ae(yc(W(p).pressurePa),0)]),q(e,t)},l=R(()=>re(Oh.pressure)&&W(p).pressurePa!==void 0);Y(s,e=>{W(l)&&e(c)});var u=H(s,2),d=e=>{var t=xS(),n=H(Sn(t)),r=V(n,!0);N(n);var i=H(n,2),a=e=>{var t=bS(),n=H(Sn(t)),r=V(n,!0);N(n),P(),U(e=>J(r,e),[()=>ae(W(p).wavePeriodS,1)]),q(e,t)};Y(i,e=>{W(p).wavePeriodS!==void 0&&e(a)}),U(e=>J(r,e),[()=>ae(W(p).waveHeightM,1)]),q(e,t)},f=R(()=>re(Oh.waves)&&W(p).waveHeightM!==void 0);Y(u,e=>{W(f)&&e(d)});var h=H(u,2),g=e=>{var t=SS(),n=H(Sn(t)),r=V(n,!0);N(n),P(),U(e=>J(r,e),[()=>ae(W(p).precipitationMm,1)]),q(e,t)},_=R(()=>(re(Oh.precip)||re(Oh.radar))&&W(p).precipitationMm!==void 0&&W(p).precipitationMm>=.1);Y(h,e=>{W(_)&&e(g)}),N(n);var v=H(n,2),y=e=>{var t=CS(),n=V(t,!0);N(t),U(()=>J(n,W(m))),q(e,t)};Y(v,e=>{W(m)&&e(y)}),N(t),U((e,t)=>{J(i,e),J(o,t)},[()=>ae(gc(W(p).speedMs),1),()=>ae(_c(W(p).fromRad),0)]),q(e,t)};Y(be,e=>{W(p)&&e(xe)});var Se=H(be,2),Ce=e=>{q(e,TS())};Y(Se,e=>{W(b)||e(Ce)}),N(ge);var we=H(ge,2),Te=V(we),Ee=e=>{var n=ES(),r=V(n),i=H(r,2),a=V(i),o=e=>{lo(e,{size:16,"aria-hidden":`true`})},s=e=>{mo(e,{size:16,"aria-hidden":`true`})};Y(a,e=>{W(u)?e(o):e(s,-1)}),N(i);var c=H(i,2),l=H(c,2);Qi(l);var d=H(l,2),f=V(d,!0);N(d),N(n),U(()=>{X(i,`aria-label`,W(u)?`Pause`:`Play`),X(l,`min`,W(T).start),X(l,`max`,W(T).end),X(l,`step`,W(T).stepMs),$i(l,t.store.selectedTime),J(f,W(E))}),G(`click`,r,()=>D(Lg(t.store.selectedTime,-1,W(T)))),G(`click`,i,k),G(`click`,c,()=>D(Lg(t.store.selectedTime,1,W(T)))),G(`input`,l,e=>D(Number(e.currentTarget.value))),q(e,n)};Y(Te,e=>{W(T)&&e(Ee)});var De=H(Te,2),Oe=e=>{var t=MS();vi(t,21,()=>W(w),e=>e.id,(e,t)=>{var n=jS(),r=V(n),i=V(r,!0);N(r);var a=H(r,2),o=e=>{var n=DS(),r=V(n),i=V(r,!0);N(r);var a=H(r,2),o=H(a,2),s=V(o,!0);N(o),N(n),U(()=>{J(i,W(t).lowLabel),zi(a,`background:${W(t).gradient??``}`),J(s,W(t).highLabel)}),q(e,n)},s=e=>{var n=kS();vi(n,21,()=>W(t).swatches,e=>e.label,(e,t)=>{var n=OS(),r=V(n),i=H(r);N(n),U(()=>{zi(r,`background:${W(t).color??``}`),J(i,` ${W(t).label??``}`)}),q(e,n)}),N(n),q(e,n)};Y(a,e=>{W(t).gradient?e(o):W(t).swatches&&e(s,1)});var c=H(a,2),l=e=>{var n=AS(),r=V(n,!0);N(n),U(()=>J(r,W(t).note)),q(e,n)};Y(c,e=>{W(t).note&&e(l)}),N(n),U(()=>J(i,W(t).title)),q(e,n)}),N(t),q(e,t)};Y(De,e=>{W(w).length>0&&e(Oe)}),N(we),N(se),Di(se,(e,t)=>Rd?.(e,t),()=>t.onClose),U(()=>{me=Li(pe,1,`pill svelte-qluf4r`,null,me,{on:W(l)}),X(pe,`aria-pressed`,W(l))}),G(`click`,pe,()=>B(l,!W(l))),G(`click`,he,function(...e){t.onClose?.apply(this,e)}),q(e,se),$e()}Xr([`click`,`input`]);var FS=K(`<!> <!>`,1),IS=K(`<button type="button" class="btn btn-primary btn-pill">Update</button>`),LS=K(`<div class="note-panel-slot svelte-1hicyxm"><!></div>`),RS=K(`<div class="layers-panel-slot svelte-1hicyxm"><!></div>`),zS=K(`<div class="routes-panel-slot svelte-1hicyxm"><!></div>`),BS=K(`<span class="readout offline svelte-1hicyxm" role="status" aria-live="polite">Offline</span>`),VS=K(`<main class="binnacle-shell svelte-1hicyxm"><header class="topbar svelte-1hicyxm"><span class="topbar-start svelte-1hicyxm"><!> <span class="brand svelte-1hicyxm">Binnacle <span class="version svelte-1hicyxm"></span></span></span> <span class="topbar-actions svelte-1hicyxm"><!> <!></span></header> <section class="chart-host svelte-1hicyxm" aria-label="Chart"><!> <div class="banner-slot svelte-1hicyxm"><!></div> <div class="nav-slot svelte-1hicyxm"><!></div> <div class="danger-slot svelte-1hicyxm"><!></div> <!> <!> <!> <!></section> <footer class="status-strip svelte-1hicyxm"><div class="forecast-center svelte-1hicyxm"><button type="button"><!> Forecast</button></div> <span role="status" aria-live="polite"> </span> <!> <span class="readout svelte-1hicyxm">SOG <b class="svelte-1hicyxm"> </b> kn</span> <span class="readout svelte-1hicyxm">COG <b class="svelte-1hicyxm"> </b>&deg;</span> <span class="spacer svelte-1hicyxm"></span> <span class="readout">Center</span> <span class="readout svelte-1hicyxm"><b class="svelte-1hicyxm"> </b></span> <span class="readout svelte-1hicyxm"><b class="svelte-1hicyxm"> </b></span> <span class="readout svelte-1hicyxm">z<b class="svelte-1hicyxm"> </b></span></footer></main>`);function HS(e,t){Qe(t,!0);let n=`vessels.*`,r=new tc,i=new Td(r),a=new nc(r),o=Is(),s=new ss(Vs()),c=new Cv,l=ts(),u=new Gc(i,a,l),d=new Rf,f=new Jo(`binnacle:alarm-muted`,!1),p=new Cf((e,t)=>void o.publish({context:Qs,updates:[{values:[{path:e,value:t}]}]})),m=$o(),h=new tl(m,G_()),g=new Zc,_=new qc(r,i),v=new Zf,y=new Jo(`binnacle:arrival-muted`,!1),b=new Md,x=ev(),S=z(!1),C=z(void 0),w=new Jo(`binnacle:weather-layers`,{[Oh.wind]:{visible:!0,opacity:1},[Oh.waves]:{visible:!0,opacity:.7}}),T=Zo(`binnacle:weather-view`),E=Xo(T.value)?T.value:void 0,D=z(dn([])),O=z(dn(new Set)),k=0,A={version:()=>k,features:()=>oh(W(D),W(O))},ee=z(void 0),te=z(!1),ne=z(!1),re,ie=z(void 0),ae=z(void 0),oe=z(void 0),se=z(void 0),ce=z(!1),le=Nv(()=>B(ce,!0)),ue=Wd(e=>re?.(e)),de=Zo(),fe=Xo(de.value)?de.value:void 0,pe=new Jo(`binnacle:layers`,{}),me=new Jo(`binnacle:layer-order`,[]),he=V_(),ge=new Jo(`binnacle:user-charts`,[]),_e=new wd(he,ge.value,e=>ge.set(e),e=>{e.bounds&&W(Se)?.fitBounds(e.bounds)}),ve=z(void 0),ye=new Map,be;function xe(e){B(se,e,!0),be&&clearTimeout(be),be=setTimeout(()=>de.set(e),400)}let Se=z(void 0),Ce=z(!1),we=R(()=>[{id:`center-on-boat`,label:`Center on boat`,icon:to,onSelect:()=>W(Se)?.centerOnVessel()},{id:`follow-boat`,label:W(Ce)?`Stop following`:`Follow boat`,icon:so,onSelect:()=>B(Ce,!W(Ce))},{id:`mute-alarm`,label:f.value?`Unmute alarm`:`Mute alarm`,icon:f.value?Wo:Ho,onSelect:()=>f.set(!f.value)},{id:`mute-arrival`,label:y.value?`Unmute arrival`:`Mute arrival`,icon:y.value?ka:ja,onSelect:()=>y.set(!y.value)},{id:`routes`,label:`Routes`,icon:vo,disabled:!W(Se),onSelect:()=>{B(te,!1),B(ne,!0)}},{id:`layers`,label:`Layers and charts`,icon:Za,disabled:!W(ee),onSelect:()=>{B(ne,!1),B(te,!0)}}]);Ln(()=>{d.update(u.assessment.worst,u.suppressed,f.value)}),Ln(()=>{p.update(u.assessment)}),Ln(()=>{let e=i.position;e&&h.consider(e.latitude,e.longitude,i.sogMps??0)}),Ln(()=>{let e=W(Se),t=i.position;W(Ce)&&t&&e?.recenterOnVessel(t.latitude,t.longitude)}),Ln(()=>{let e=W(ve),t=_e.sources;if(!e)return;let n=new Set(t.map(e=>e.id));for(let[t,r]of ye)n.has(t)||(ye.delete(t),e.unregister(t),r&&URL.revokeObjectURL(r));for(let n of t)ye.has(n.id)||(ye.set(n.id,void 0),Te(n,e))});async function Te(e,t){let n,r;if(e.origin.type===`url`)r=e.origin.url;else{let t=await _e.resolveBlob(e.origin.storeId);if(!t||!ye.has(e.id)){ye.delete(e.id);return}n=URL.createObjectURL(t),ye.set(e.id,n),r=`pmtiles://${n}`}if(await t.register(Sd(e,r)),!ye.has(e.id)){t.unregister(e.id),n&&URL.revokeObjectURL(n);return}re?.(ue.theme)}function Ee(){k+=1}async function De(){B(D,await hh(Vs(),W(ie)),!0),Ee()}async function Oe(e){if(h.points.length<2)return;let t=cc();await gh(Vs(),W(ie),t,e,h.points)&&(h.clear(),B(O,new Set(W(O)).add(t),!0),await De())}async function ke(e){if(!await _h(Vs(),W(ie),e))return;let t=new Set(W(O));t.delete(e),B(O,t,!0),await De()}function Ae(e){let t=new Set(W(O));t.has(e)?t.delete(e):t.add(e),B(O,t,!0),Ee()}function je(e){let t=[];e.points.forEach((e,n)=>{e.forEach((e,r)=>{t.push(r===0&&n>0?{...e,gap:!0}:e)})}),ah(e.name,t)}async function Me(){let e=await Wm(Vs(),W(ie));e&&g.setRoutes(e)}let Ne=z(void 0);function Pe(e){B(Ne,e,!0)}function Fe(){B(Ne,void 0)}async function Ie(){return await Am(Vs(),W(ie))?(g.setActive(void 0),_.clear(),v.stop(),!0):!1}function Le(e){let t=g.routes.find(t=>t.id===e)?.waypoints[0]?.position;t&&W(Se)?.flyTo(t.latitude,t.longitude)}function Re(e,t){g.toggleShown(e,t),t&&Le(e)}function ze(){Fe(),g.setWorking({id:cc(),name:``,waypoints:[]}),W(Se)?.startRouteEdit()}function j(e){let t=g.routes.find(t=>t.id===e);t&&(g.setWorking(t),W(Se)?.startRouteEdit(t),Le(e))}async function Be(e){Fe();let t=g.working;if(!t||t.waypoints.length<2)return;let n={...t,name:e};if(!await Gm(Vs(),W(ie),n)){Pe(`Could not save the route. It is kept under edit so you can retry.`),g.setWorking(n);return}W(Se)?.stopRouteEdit(),g.setWorking(void 0),g.toggleShown(n.id,!0),await Me()}function Ve(){W(Se)?.stopRouteEdit(),g.setWorking(void 0)}async function M(e){if(Fe(),e===g.activeId&&!await Ie()){Pe(`Could not stop the active route, so it was not deleted.`);return}if(!await Km(Vs(),W(ie),e)){Pe(`Could not delete the route.`);return}g.toggleShown(e,!1),await Me()}async function He(e){if(Fe(),!await Om(Vs(),W(ie),`/resources/routes/${e}`)){Pe(`Could not activate the route. Check the connection.`);return}g.setActive(e),g.toggleShown(e,!0),Le(e);let{info:t,calc:n}=await jm(Vs(),W(ie));_.seed(t,n)}async function Ue(){Fe(),await Ie()||Pe(`Could not stop the active route. Check the connection.`)}let We=!1;Ln(()=>{let e=_.arrived&&g.activeId!==void 0;v.update(e,y.value),e&&!We&&!_.isLastPoint&&km(Vs(),W(ie),1).then(e=>{e||Pe(`Could not advance to the next waypoint.`)}),We=e});function Ge(){B(ae,void 0),W(Se)?.clearNoteSelection()}let Ke=()=>{d.prime(),v.prime()},qe={open:`Connected`,connecting:`Connecting`,reconnecting:`Reconnecting`,closed:`Not connected`},Je=R(()=>qe[r.connection.phase]),Ye=`${Vs()}/admin/#/security/access/requests`,Xe=!1;Ln(()=>{Xe||s.status!==`authenticated`&&s.status!==`unsecured`||(Xe=!0,F(s.token??void 0))});async function F(e){B(ie,e,!0),B(oe,fp(Vs(),e),!0),await o.connect(Hs(e),e=>r.applyFrame(e)),await o.raw.subscribe([{path:Us.headingTrue,policy:`instant`,minPeriod:200},{path:Us.position,policy:`instant`,minPeriod:1e3},{path:Us.courseOverGroundTrue,policy:`instant`,minPeriod:1e3},{path:Us.speedOverGround,policy:`instant`,minPeriod:1e3},{path:Us.courseNextPoint,policy:`instant`,minPeriod:1e3},{path:Us.coursePreviousPoint,policy:`instant`,minPeriod:1e3},{path:Us.courseActiveRoute,policy:`instant`,minPeriod:1e3},{path:Us.courseArrivalCircle,policy:`instant`,minPeriod:1e3},{path:Us.courseCalcValues,policy:`instant`,minPeriod:1e3},{path:Us.position,context:n,policy:`fixed`,period:5e3},{path:Us.courseOverGroundTrue,context:n,policy:`fixed`,period:5e3},{path:Us.speedOverGround,context:n,policy:`fixed`,period:5e3},{path:Us.headingTrue,context:n,policy:`fixed`,period:5e3},{path:Us.name,context:n,policy:`fixed`,period:5e3},{path:Us.aisShipType,context:n,policy:`fixed`,period:5e3},{path:Us.closestApproach,context:n,policy:`fixed`,period:5e3}]),await De(),await Me(),B(C,Dg(await Eg(Vs(),e)),!0)}ga(()=>{window.addEventListener(`pointerdown`,Ke,{once:!0}),s.watch(),s.probe()}),_a(()=>{be&&clearTimeout(be);for(let e of ye.values())e&&URL.revokeObjectURL(e);window.removeEventListener(`pointerdown`,Ke),d.stop(),s.stop(),c.dispose(),o.disconnect()});var Ze=VS(),et=V(Ze),I=V(et),tt=V(I);Kf(tt,{get items(){return W(we)},children:(e,t)=>{var n=FS(),r=Sn(n);Yf(r,{label:`Tracks`,get icon(){return Eo},children:(e,t)=>{th(e,{get recorder(){return h},get settings(){return m},get saved(){return W(D)},get shown(){return W(O)},onSave:Oe,onDelete:ke,onToggleSaved:Ae,onExport:je})},$$slots:{default:!0}}),Yf(H(r,2),{label:`Collision thresholds`,get icon(){return wo},children:(e,t)=>{Bf(e,{get thresholds(){return l}})},$$slots:{default:!0}}),q(e,n)},$$slots:{default:!0}});var nt=H(tt,2),rt=H(V(nt));rt.textContent=`v0.1.2`,N(nt),N(I);var it=H(I,2),at=V(it),ot=e=>{var t=IS();G(`click`,t,()=>le.update()),q(e,t)};Y(at,e=>{W(ce)&&e(ot)}),Jm(H(at,2),{get controller(){return ue}}),N(it),N(et);var st=H(et,2),ct=V(st);hS(ct,{get store(){return r},get vessel(){return i},get aisTargets(){return a},get collision(){return u},get recorder(){return h},get routeStore(){return g},get theme(){return ue.theme},get trackSettings(){return m},get savedTracks(){return A},get chartsToken(){return W(ie)},get initialView(){return fe},get savedLayers(){return pe.value},onLayersChange:e=>pe.set(e),get savedOrder(){return me.value},onOrderChange:e=>me.set(e),onReady:e=>B(ee,e,!0),onMapReady:e=>{re=e,e(ue.theme)},onCommandsReady:e=>B(Se,e,!0),onUserChartsReady:e=>B(ve,e,!0),onViewChange:xe,onNoteSelect:e=>B(ae,e,!0),onUserPan:()=>B(Ce,!1)});var lt=H(ct,2);Fd(V(lt),{get auth(){return s},get requestsUrl(){return Ye}}),N(lt);var ut=H(lt,2);tp(V(ut),{get guidance(){return _},onStop:Ue}),N(ut);var dt=H(ut,2);Pf(V(dt),{get collision(){return u}}),N(dt);var ft=H(dt,2),pt=e=>{var t=LS();Kp(V(t),{get selection(){return W(ae)},get load(){return W(oe).load},onClose:Ge}),N(t),q(e,t)};Y(ft,e=>{W(ae)&&W(oe)&&e(pt)});var mt=H(ft,2),ht=e=>{var t=RS();yf(V(t),{get view(){return W(ee)},get userCharts(){return _e},onClose:()=>B(te,!1)}),N(t),q(e,t)};Y(mt,e=>{W(te)&&W(ee)&&e(ht)});var gt=H(mt,2),_t=e=>{var t=zS();Vm(V(t),{get routes(){return g.routes},get shownIds(){return g.shownIds},get working(){return g.working},get activeId(){return g.activeId},get error(){return W(Ne)},onNew:ze,onEditRoute:j,onSave:Be,onCancelEdit:Ve,onToggleShown:Re,onLocate:Le,onActivate:He,onStop:Ue,onDelete:M,onClose:()=>{Ve(),Fe(),B(ne,!1)}}),N(t),q(e,t)};Y(gt,e=>{W(ne)&&e(_t)});var vt=H(gt,2),yt=e=>{{let t=R(()=>W(se)??fe);PS(e,{get store(){return b},get loader(){return x},get theme(){return ue.theme},get initialView(){return W(t)},get savedView(){return E},onViewChange:e=>T.set(e),get savedLayers(){return w.value},onLayersChange:e=>w.set(e),get token(){return W(ie)},get providerName(){return W(C)},get position(){return i.position},onClose:()=>B(S,!1)})}};Y(vt,e=>{W(S)&&e(yt)}),N(st);var bt=H(st,2),xt=V(bt),St=V(xt);let Ct;La(V(St),{size:16,"aria-hidden":`true`}),P(),N(St),N(xt);var wt=H(xt,2),Tt=V(wt,!0);N(wt);var Et=H(wt,2),Dt=e=>{q(e,BS())};Y(Et,e=>{c.online||e(Dt)});var Ot=H(Et,2),kt=H(V(Ot)),At=V(kt,!0);N(kt),P(),N(Ot);var jt=H(Ot,2),Mt=H(V(jt)),Nt=V(Mt,!0);N(Mt),P(),N(jt);var Pt=H(jt,6),Ft=V(Pt),It=V(Ft,!0);N(Ft),N(Pt);var Lt=H(Pt,2),Rt=V(Lt),zt=V(Rt,!0);N(Rt),N(Lt);var Bt=H(Lt,2),Vt=H(V(Bt)),Ht=V(Vt,!0);N(Vt),N(Bt),N(bt),N(Ze),U((e,t,n,r,i)=>{Ct=Li(St,1,`btn btn-pill forecast-btn svelte-1hicyxm`,null,Ct,{on:W(S)}),X(St,`aria-pressed`,W(S)),J(Tt,W(Je)),J(At,e),J(Nt,t),J(It,n),J(zt,r),J(Ht,i)},[()=>xc(gc(i.sogMps),1),()=>xc(_c(i.cogRad),0),()=>oc(W(se)?.lat),()=>sc(W(se)?.lon),()=>xc(W(se)?.zoom,1)]),G(`click`,St,()=>B(S,!W(S))),q(e,Ze),$e()}Xr([`click`]);var US=document.getElementById(`app`);if(!US)throw Error(`Missing #app mount element`);si(HS,{target:US});