maplibre-gl-components 0.22.2 → 0.22.3

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.
@@ -75,7 +75,7 @@ var iO=Object.create;var Gw=Object.defineProperty;var sO=Object.getOwnPropertyDe
75
75
  <p class="maplibre-gl-vector-dataset-loading-text">Loading...</p>
76
76
  <p class="maplibre-gl-vector-dataset-loading-progress"></p>
77
77
  </div>
78
- `,this._loadingOverlay.style.display="none",this._loadingText=this._loadingOverlay.querySelector(".maplibre-gl-vector-dataset-loading-text"),this._loadingProgress=this._loadingOverlay.querySelector(".maplibre-gl-vector-dataset-loading-progress"),e.appendChild(this._loadingOverlay),this._boundDragOver=n=>this._handleDragOver(n),this._boundDragLeave=n=>this._handleDragLeave(n),this._boundDrop=n=>this._handleDrop(n),e.addEventListener("dragover",this._boundDragOver),e.addEventListener("dragleave",this._boundDragLeave),e.addEventListener("drop",this._boundDrop)}_removeDragAndDrop(){if(!this._map)return;const e=this._map.getContainer();this._boundDragOver&&e.removeEventListener("dragover",this._boundDragOver),this._boundDragLeave&&e.removeEventListener("dragleave",this._boundDragLeave),this._boundDrop&&e.removeEventListener("drop",this._boundDrop),this._dropZone&&this._dropZone.parentNode&&this._dropZone.parentNode.removeChild(this._dropZone),this._loadingOverlay&&this._loadingOverlay.parentNode&&this._loadingOverlay.parentNode.removeChild(this._loadingOverlay)}_handleDragOver(e){e.preventDefault(),e.stopPropagation(),this._state.isDragging||(this._state.isDragging=!0,this._dropZone&&(this._dropZone.style.display="flex"),this._emit("dragenter"))}_handleDragLeave(e){e.preventDefault(),e.stopPropagation();const t=this._map?.getContainer();t&&!t.contains(e.relatedTarget)&&(this._state.isDragging=!1,this._dropZone&&(this._dropZone.style.display="none"),this._emit("dragleave"))}_handleDrop(e){e.preventDefault(),e.stopPropagation(),this._state.isDragging=!1,this._dropZone&&(this._dropZone.style.display="none");const t=e.dataTransfer?.files;t&&t.length>0&&this._processFiles(Array.from(t))}_handleFileSelect(e){const t=e.target,n=t.files;n&&n.length>0&&this._processFiles(Array.from(n)),t.value=""}async _processFiles(e){this._state.isLoading=!0,this._state.error=null,this._updateButtonState();for(const t of e){if(!JB(t.name,this._options.enableAdvancedFormats)){this._state.error=`Invalid file type: ${t.name}. Accepted: ${this._options.acceptedExtensions.join(", ")}`,this._emit("error",void 0,this._state.error,t.name);continue}if(t.size>this._options.maxFileSize){const i=(this._options.maxFileSize/1048576).toFixed(1);this._state.error=`File too large: ${t.name}. Maximum size: ${i}MB`,this._emit("error",void 0,this._state.error,t.name);continue}const n=YB(t.name);try{if(XB(n)){if(!this._options.enableAdvancedFormats){this._state.error=`${KB(n)} files require enableAdvancedFormats: true`,this._emit("error",void 0,this._state.error,t.name);continue}this._showLoading(`Loading ${t.name}...`),await this._processAdvancedFormat(t,n),this._hideLoading()}else{this._showLoading(`Loading ${t.name}...`);const i=await t.text(),s=JSON.parse(i);await this._processGeoJSON(s,t.name,"geojson"),this._hideLoading()}}catch(i){this._hideLoading(),this._state.error=`Failed to process ${t.name}: ${i instanceof Error?i.message:"Unknown error"}`,this._emit("error",void 0,this._state.error,t.name)}}this._state.isLoading=!1,this._updateButtonState()}async _processAdvancedFormat(e,t){const n=s=>{const r=s.message||`Processing ${e.name}...`,a=s.percent!==void 0?`${s.percent}%`:"";this._updateLoading(r,a),this._options.onConversionProgress?.(s)};this._updateLoading(`Reading ${e.name}...`);const i=await ZB(e);if(t==="shapefile"){if(!this._shapefileConverter){this._updateLoading("Loading Shapefile converter...");const{getShapefileConverter:r}=await Promise.resolve().then(()=>require("./ShapefileConverter-BD3T53jT.cjs")).then(a=>a.ShapefileConverter_exports);this._shapefileConverter=r()}const s=await this._shapefileConverter.convert(i,e.name,n);s.geojson&&(this._updateLoading("Adding to map..."),await this._processGeoJSON(s.geojson,e.name,t))}else if(jB(t)){if(!this._duckdbConverter){this._updateLoading("Loading DuckDB converter...");const{getDuckDBConverter:r}=await Promise.resolve().then(()=>require("./DuckDBConverter-D4z5GfYH.cjs")).then(a=>a.DuckDBConverter_exports);if(this._duckdbConverter=r(),this._options.duckdbBundleUrl){const{DuckDBConverter:a}=await Promise.resolve().then(()=>require("./DuckDBConverter-D4z5GfYH.cjs")).then(o=>o.DuckDBConverter_exports);this._duckdbConverter=new a(this._options.duckdbBundleUrl)}}const s=await this._duckdbConverter.convert(i,e.name,n);s.geojson&&(this._updateLoading("Adding to map..."),await this._processGeoJSON(s.geojson,e.name,t))}}async _processGeoJSON(e,t,n="geojson"){if(!this._map)return null;if(!e.type)return this._state.error=`Invalid GeoJSON: missing type property in ${t}`,this._emit("error",void 0,this._state.error,t),null;let i;e.type==="FeatureCollection"?i=e:e.type==="Feature"?i={type:"FeatureCollection",features:[e]}:i={type:"FeatureCollection",features:[{type:"Feature",properties:{},geometry:e}]};const s=Qa("vds"),r=`${s}-source`,a=new Set;for(const o of i.features)o.geometry&&a.add(o.geometry.type);try{this._map.addSource(r,{type:"geojson",data:i,generateId:!0});const o=[],l=this._options.defaultStyle;if(a.has("Polygon")||a.has("MultiPolygon")){const h=`${s}-fill`;this._map.addLayer({id:h,type:"fill",source:r,filter:["any",["==",["geometry-type"],"Polygon"],["==",["geometry-type"],"MultiPolygon"]],paint:{"fill-color":l.fillColor,"fill-opacity":l.fillOpacity}}),o.push(h);const d=`${s}-outline`;this._map.addLayer({id:d,type:"line",source:r,filter:["any",["==",["geometry-type"],"Polygon"],["==",["geometry-type"],"MultiPolygon"]],paint:{"line-color":l.strokeColor,"line-width":l.strokeWidth,"line-opacity":l.strokeOpacity}}),o.push(d)}if(a.has("LineString")||a.has("MultiLineString")){const h=`${s}-line`;this._map.addLayer({id:h,type:"line",source:r,filter:["any",["==",["geometry-type"],"LineString"],["==",["geometry-type"],"MultiLineString"]],paint:{"line-color":l.strokeColor,"line-width":l.strokeWidth,"line-opacity":l.strokeOpacity}}),o.push(h)}if(a.has("Point")||a.has("MultiPoint")){const h=`${s}-point`;this._map.addLayer({id:h,type:"circle",source:r,filter:["any",["==",["geometry-type"],"Point"],["==",["geometry-type"],"MultiPoint"]],paint:{"circle-radius":l.circleRadius,"circle-color":l.circleColor,"circle-stroke-color":l.circleStrokeColor,"circle-stroke-width":l.circleStrokeWidth}}),o.push(h)}const c={id:s,filename:t,sourceId:r,layerIds:o,featureCount:i.features.length,geometryTypes:Array.from(a),loadedAt:new Date,originalFormat:n};return this._state.loadedDatasets.push(c),this._options.fitBounds&&i.features.length>0&&this._fitToData(i),this._emit("load",c),this._emit("update"),c}catch(o){return this._state.error=`Failed to add ${t} to map: ${o instanceof Error?o.message:"Unknown error"}`,this._emit("error",void 0,this._state.error,t),null}}_fitToData(e){if(!this._map)return;let t=1/0,n=1/0,i=-1/0,s=-1/0;const r=o=>{t=Math.min(t,o[0]),i=Math.max(i,o[0]),n=Math.min(n,o[1]),s=Math.max(s,o[1])},a=o=>{for(const l of o)typeof l[0]=="number"?r(l):a(l)};for(const o of e.features){if(!o.geometry)continue;const l=o.geometry;l.type==="Point"?r(l.coordinates):(l.type==="MultiPoint"||l.type==="LineString"||l.type==="MultiLineString"||l.type==="Polygon"||l.type==="MultiPolygon")&&a(l.coordinates)}t!==1/0&&this._map.fitBounds([[t,n],[i,s]],{padding:this._options.fitBoundsPadding})}_removeAllDatasets(){for(const e of this._state.loadedDatasets)if(this._map){for(const t of e.layerIds)this._map.getLayer(t)&&this._map.removeLayer(t);this._map.getSource(e.sourceId)&&this._map.removeSource(e.sourceId)}this._state.loadedDatasets=[]}_checkZoomVisibility(){if(!this._map)return;const e=this._map.getZoom(),{minzoom:t,maxzoom:n}=this._options,i=e>=t&&e<=n;i!==this._zoomVisible&&(this._zoomVisible=i,this._updateDisplayState())}_updateDisplayState(){if(!this._container)return;const e=this._state.visible&&this._zoomVisible;this._container.style.display=e?"flex":"none"}_updateButtonState(){this._button&&(this._state.isLoading?(this._button.classList.add("maplibre-gl-vector-dataset-button--loading"),this._button.disabled=!0):(this._button.classList.remove("maplibre-gl-vector-dataset-button--loading"),this._button.disabled=!1))}_showLoading(e,t){this._loadingOverlay&&(this._loadingOverlay.style.display="flex",this._loadingText&&(this._loadingText.textContent=e),this._loadingProgress&&(this._loadingProgress.textContent=t||""))}_updateLoading(e,t){this._loadingText&&(this._loadingText.textContent=e),this._loadingProgress&&(this._loadingProgress.textContent=t||"")}_hideLoading(){this._loadingOverlay&&(this._loadingOverlay.style.display="none")}},Y0={fillColor:"#ffff00",fillOpacity:.3,strokeColor:"#ffff00",strokeWidth:3,circleRadius:10,circleStrokeWidth:3},DO={position:"top-right",className:"",visible:!0,enabled:!1,maxFeatures:10,includeLayers:[],excludeLayers:[],highlightStyle:Y0,excludeProperties:[],showGeometryType:!0,showLayerName:!0,maxWidth:320,maxHeight:300,backgroundColor:"rgba(255, 255, 255, 0.95)",borderRadius:4,opacity:1,fontSize:13,fontColor:"#333",minzoom:0,maxzoom:24},FO='<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>',n2=class{_container;_button;_options;_state;_eventHandlers=new Map;_map;_handleZoom;_zoomVisible=!0;_popup;_highlightSourceId="";_highlightLayerIds=[];_boundClickHandler;constructor(e){this._options={...DO,...e,highlightStyle:{...Y0,...e?.highlightStyle}},this._state={visible:this._options.visible,enabled:this._options.enabled,inspectedFeatures:[],selectedIndex:0,error:null},this._highlightSourceId=`inspect-highlight-${Qa()}`}onAdd(e){return this._map=e,this._container=this._createContainer(),this._handleZoom=()=>this._checkZoomVisibility(),this._map.on("zoom",this._handleZoom),this._checkZoomVisibility(),this._state.enabled&&this._setupMapListeners(),this._container}onRemove(){this._map&&this._handleZoom&&(this._map.off("zoom",this._handleZoom),this._handleZoom=void 0),this._removeMapListeners(),this._removeHighlight(),this._hidePopup(),this._map=void 0,this._container?.parentNode?.removeChild(this._container),this._container=void 0,this._button=void 0,this._eventHandlers.clear()}enable(){this._state.enabled||(this._state.enabled=!0,this._updateButtonState(),this._setupMapListeners(),this._updateCursor(!0),this._emit("enable"))}disable(){this._state.enabled&&(this._state.enabled=!1,this._updateButtonState(),this._removeMapListeners(),this._updateCursor(!1),this.clear(),this._emit("disable"))}toggle(){this._state.enabled?this.disable():this.enable()}isEnabled(){return this._state.enabled}show(){this._state.visible||(this._state.visible=!0,this._updateDisplayState(),this._emit("show"))}hide(){this._state.visible&&(this._state.visible=!0,this._updateDisplayState(),this._emit("hide"))}clear(){this._state.inspectedFeatures=[],this._state.selectedIndex=0,this._removeHighlight(),this._hidePopup(),this._emit("clear")}getState(){return{...this._state}}getInspectedFeatures(){return[...this._state.inspectedFeatures]}getSelectedFeature(){return this._state.inspectedFeatures[this._state.selectedIndex]||null}selectFeature(e){if(e>=0&&e<this._state.inspectedFeatures.length){this._state.selectedIndex=e;const t=this._state.inspectedFeatures[e];this._addHighlight(t),this._updatePopupContent(),this._emit("featureselect",t)}}nextFeature(){if(this._state.inspectedFeatures.length>1){const e=(this._state.selectedIndex+1)%this._state.inspectedFeatures.length;this.selectFeature(e)}}previousFeature(){if(this._state.inspectedFeatures.length>1){const e=this._state.selectedIndex===0?this._state.inspectedFeatures.length-1:this._state.selectedIndex-1;this.selectFeature(e)}}update(e){Object.assign(this._options,e),e.highlightStyle&&(this._options.highlightStyle={...Y0,...e.highlightStyle}),e.visible!==void 0&&(this._state.visible=e.visible,this._updateDisplayState()),e.enabled!==void 0&&(e.enabled?this.enable():this.disable()),this._emit("update")}on(e,t){this._eventHandlers.has(e)||this._eventHandlers.set(e,new Set),this._eventHandlers.get(e).add(t)}off(e,t){this._eventHandlers.get(e)?.delete(t)}_emit(e,t){const n=this._eventHandlers.get(e);n&&n.forEach(i=>i({type:e,state:this.getState(),feature:t,features:this._state.inspectedFeatures}))}_createContainer(){const e=document.createElement("div");return e.className=`maplibregl-ctrl maplibregl-ctrl-group maplibre-gl-inspect ${this._options.className}`.trim(),this._options.backgroundColor&&(e.style.backgroundColor=this._options.backgroundColor),this._options.borderRadius&&(e.style.borderRadius=`${this._options.borderRadius}px`),this._options.opacity!==void 0&&this._options.opacity!==1&&(e.style.opacity=String(this._options.opacity)),this._button=document.createElement("button"),this._button.type="button",this._button.className="maplibre-gl-inspect-button",this._button.title="Inspect features",this._button.innerHTML=FO,this._button.addEventListener("click",()=>this.toggle()),e.appendChild(this._button),e.style.display=this._state.visible?"block":"none",e}_updateButtonState(){this._button&&(this._state.enabled?(this._button.classList.add("maplibre-gl-inspect-button--active"),this._button.title="Disable inspect mode"):(this._button.classList.remove("maplibre-gl-inspect-button--active"),this._button.title="Inspect features"))}_updateCursor(e){if(this._map){const t=this._map.getCanvas();e?t.style.cursor="crosshair":t.style.cursor=""}}_setupMapListeners(){!this._map||this._boundClickHandler||(this._boundClickHandler=e=>this._handleMapClick(e),this._map.on("click",this._boundClickHandler))}_removeMapListeners(){this._map&&this._boundClickHandler&&(this._map.off("click",this._boundClickHandler),this._boundClickHandler=void 0)}_handleMapClick(e){if(!this._map)return;const t=e.point,n=[e.lngLat.lng,e.lngLat.lat],i=this._queryFeatures(t);if(i.length===0){this.clear();return}const s=i.slice(0,this._options.maxFeatures).map(a=>{const o=a.id,l={type:"Feature",geometry:a.geometry,properties:a.properties||{}};return o!==void 0&&(l.id=o),{id:Qa("inspect"),feature:l,layerId:a.layer?.id||"unknown",sourceId:a.source||"unknown",sourceLayer:a.sourceLayer,featureId:o===void 0?void 0:o,lngLat:n}});this._state.inspectedFeatures=s,this._state.selectedIndex=0;const r=s[0];this._addHighlight(r),this._showPopup(r,n),this._emit("featureselect",r)}_queryFeatures(e){if(!this._map)return[];const t={};this._options.includeLayers.length>0&&(t.layers=this._options.includeLayers);let n=this._map.queryRenderedFeatures(e,t);return this._options.excludeLayers.length>0&&(n=n.filter(i=>i.layer&&!this._options.excludeLayers.includes(i.layer.id))),n=n.filter(i=>i.layer&&!i.layer.id.startsWith("inspect-highlight-")),n}_addHighlight(e){if(!this._map)return;const t=this._map;this._removeHighlight();const n=e.feature,i=n.geometry.type,s=this._options.highlightStyle,r=this._getHighlightTarget(e),a=o=>{if(i==="Point"||i==="MultiPoint"){const l=`${this._highlightSourceId}-circle`;t.addLayer({id:l,type:"circle",...o,paint:{"circle-radius":s.circleRadius,"circle-color":s.fillColor,"circle-opacity":s.fillOpacity,"circle-stroke-color":s.strokeColor,"circle-stroke-width":s.circleStrokeWidth}}),this._highlightLayerIds.push(l)}else if(i==="LineString"||i==="MultiLineString"){const l=`${this._highlightSourceId}-line`;t.addLayer({id:l,type:"line",...o,paint:{"line-color":s.strokeColor,"line-width":s.strokeWidth,"line-opacity":1}}),this._highlightLayerIds.push(l)}else if(i==="Polygon"||i==="MultiPolygon"){const l=`${this._highlightSourceId}-fill`;t.addLayer({id:l,type:"fill",...o,paint:{"fill-color":s.fillColor,"fill-opacity":s.fillOpacity}}),this._highlightLayerIds.push(l);const c=`${this._highlightSourceId}-outline`;t.addLayer({id:c,type:"line",...o,paint:{"line-color":s.strokeColor,"line-width":s.strokeWidth}}),this._highlightLayerIds.push(c)}};if(r){const o={source:r.sourceId};r.sourceLayer&&(o["source-layer"]=r.sourceLayer),o.filter=r.filter;try{a(o);return}catch{this._removeHighlight()}}t.addSource(this._highlightSourceId,{type:"geojson",data:n}),a({source:this._highlightSourceId})}_getHighlightTarget(e){if(!this._map)return null;const{sourceId:t,sourceLayer:n,featureId:i}=e;if(!t||t==="unknown"||i==null)return null;const s=this._map.getSource(t);return!s||s.type==="vector"&&!n?null:{sourceId:t,sourceLayer:n,filter:["==","$id",i]}}_removeHighlight(){if(this._map){for(const e of this._highlightLayerIds)this._map.getLayer(e)&&this._map.removeLayer(e);this._highlightLayerIds=[],this._map.getSource(this._highlightSourceId)&&this._map.removeSource(this._highlightSourceId)}}_showPopup(e,t){if(!this._map)return;this._hidePopup();const n=this._renderPopupContent();this._popup=new fi.Popup({closeButton:!0,closeOnClick:!1,maxWidth:`${this._options.maxWidth}px`,className:"maplibre-gl-inspect-popup"}).setLngLat(t).setHTML(n).addTo(this._map),requestAnimationFrame(()=>{this._attachPopupListeners()})}_hidePopup(){this._popup&&(this._popup.remove(),this._popup=void 0)}_updatePopupContent(){if(this._popup){const e=this._renderPopupContent();this._popup.setHTML(e),this._attachPopupListeners()}}_attachPopupListeners(){if(!this._popup)return;const e=this._popup.getElement();if(!e)return;const t=e.querySelector(".maplibre-gl-inspect-nav-prev"),n=e.querySelector(".maplibre-gl-inspect-nav-next");t&&(t.onclick=i=>{i.stopPropagation(),i.preventDefault(),this.previousFeature()}),n&&(n.onclick=i=>{i.stopPropagation(),i.preventDefault(),this.nextFeature()})}_renderPopupContent(){const e=this._state.inspectedFeatures,t=this._state.selectedIndex,n=e[t];if(!n)return'<div class="maplibre-gl-inspect-empty">No feature selected</div>';const i=n.feature.geometry.type,s=n.layerId,r=n.feature.properties||{};let a='<div class="maplibre-gl-inspect-header">';if(this._options.showGeometryType&&(a+=`<span class="maplibre-gl-inspect-geometry">${this._formatGeometryType(i)}</span>`),this._options.showLayerName&&(a+=`<span class="maplibre-gl-inspect-layer" title="${s}">${s}</span>`),e.length>1){const l=e.length<=1?"disabled":"",c=e.length<=1?"disabled":"";a+=`
78
+ `,this._loadingOverlay.style.display="none",this._loadingText=this._loadingOverlay.querySelector(".maplibre-gl-vector-dataset-loading-text"),this._loadingProgress=this._loadingOverlay.querySelector(".maplibre-gl-vector-dataset-loading-progress"),e.appendChild(this._loadingOverlay),this._boundDragOver=n=>this._handleDragOver(n),this._boundDragLeave=n=>this._handleDragLeave(n),this._boundDrop=n=>this._handleDrop(n),e.addEventListener("dragover",this._boundDragOver),e.addEventListener("dragleave",this._boundDragLeave),e.addEventListener("drop",this._boundDrop)}_removeDragAndDrop(){if(!this._map)return;const e=this._map.getContainer();this._boundDragOver&&e.removeEventListener("dragover",this._boundDragOver),this._boundDragLeave&&e.removeEventListener("dragleave",this._boundDragLeave),this._boundDrop&&e.removeEventListener("drop",this._boundDrop),this._dropZone&&this._dropZone.parentNode&&this._dropZone.parentNode.removeChild(this._dropZone),this._loadingOverlay&&this._loadingOverlay.parentNode&&this._loadingOverlay.parentNode.removeChild(this._loadingOverlay)}_handleDragOver(e){e.preventDefault(),e.stopPropagation(),this._state.isDragging||(this._state.isDragging=!0,this._dropZone&&(this._dropZone.style.display="flex"),this._emit("dragenter"))}_handleDragLeave(e){e.preventDefault(),e.stopPropagation();const t=this._map?.getContainer();t&&!t.contains(e.relatedTarget)&&(this._state.isDragging=!1,this._dropZone&&(this._dropZone.style.display="none"),this._emit("dragleave"))}_handleDrop(e){e.preventDefault(),e.stopPropagation(),this._state.isDragging=!1,this._dropZone&&(this._dropZone.style.display="none");const t=e.dataTransfer?.files;t&&t.length>0&&this._processFiles(Array.from(t))}_handleFileSelect(e){const t=e.target,n=t.files;n&&n.length>0&&this._processFiles(Array.from(n)),t.value=""}async _processFiles(e){this._state.isLoading=!0,this._state.error=null,this._updateButtonState();for(const t of e){if(!JB(t.name,this._options.enableAdvancedFormats)){this._state.error=`Invalid file type: ${t.name}. Accepted: ${this._options.acceptedExtensions.join(", ")}`,this._emit("error",void 0,this._state.error,t.name);continue}if(t.size>this._options.maxFileSize){const i=(this._options.maxFileSize/1048576).toFixed(1);this._state.error=`File too large: ${t.name}. Maximum size: ${i}MB`,this._emit("error",void 0,this._state.error,t.name);continue}const n=YB(t.name);try{if(XB(n)){if(!this._options.enableAdvancedFormats){this._state.error=`${KB(n)} files require enableAdvancedFormats: true`,this._emit("error",void 0,this._state.error,t.name);continue}this._showLoading(`Loading ${t.name}...`),await this._processAdvancedFormat(t,n),this._hideLoading()}else{this._showLoading(`Loading ${t.name}...`);const i=await t.text(),s=JSON.parse(i);await this._processGeoJSON(s,t.name,"geojson"),this._hideLoading()}}catch(i){this._hideLoading(),this._state.error=`Failed to process ${t.name}: ${i instanceof Error?i.message:"Unknown error"}`,this._emit("error",void 0,this._state.error,t.name)}}this._state.isLoading=!1,this._updateButtonState()}async _processAdvancedFormat(e,t){const n=s=>{const r=s.message||`Processing ${e.name}...`,a=s.percent!==void 0?`${s.percent}%`:"";this._updateLoading(r,a),this._options.onConversionProgress?.(s)};this._updateLoading(`Reading ${e.name}...`);const i=await ZB(e);if(t==="shapefile"){if(!this._shapefileConverter){this._updateLoading("Loading Shapefile converter...");const{getShapefileConverter:r}=await Promise.resolve().then(()=>require("./ShapefileConverter-b2TR_8Ow.cjs")).then(a=>a.ShapefileConverter_exports);this._shapefileConverter=r()}const s=await this._shapefileConverter.convert(i,e.name,n);s.geojson&&(this._updateLoading("Adding to map..."),await this._processGeoJSON(s.geojson,e.name,t))}else if(jB(t)){if(!this._duckdbConverter){this._updateLoading("Loading DuckDB converter...");const{getDuckDBConverter:r}=await Promise.resolve().then(()=>require("./DuckDBConverter-BtujCPmE.cjs")).then(a=>a.DuckDBConverter_exports);if(this._duckdbConverter=r(),this._options.duckdbBundleUrl){const{DuckDBConverter:a}=await Promise.resolve().then(()=>require("./DuckDBConverter-BtujCPmE.cjs")).then(o=>o.DuckDBConverter_exports);this._duckdbConverter=new a(this._options.duckdbBundleUrl)}}const s=await this._duckdbConverter.convert(i,e.name,n);s.geojson&&(this._updateLoading("Adding to map..."),await this._processGeoJSON(s.geojson,e.name,t))}}async _processGeoJSON(e,t,n="geojson"){if(!this._map)return null;if(!e.type)return this._state.error=`Invalid GeoJSON: missing type property in ${t}`,this._emit("error",void 0,this._state.error,t),null;let i;e.type==="FeatureCollection"?i=e:e.type==="Feature"?i={type:"FeatureCollection",features:[e]}:i={type:"FeatureCollection",features:[{type:"Feature",properties:{},geometry:e}]};const s=Qa("vds"),r=`${s}-source`,a=new Set;for(const o of i.features)o.geometry&&a.add(o.geometry.type);try{this._map.addSource(r,{type:"geojson",data:i,generateId:!0});const o=[],l=this._options.defaultStyle;if(a.has("Polygon")||a.has("MultiPolygon")){const h=`${s}-fill`;this._map.addLayer({id:h,type:"fill",source:r,filter:["any",["==",["geometry-type"],"Polygon"],["==",["geometry-type"],"MultiPolygon"]],paint:{"fill-color":l.fillColor,"fill-opacity":l.fillOpacity}}),o.push(h);const d=`${s}-outline`;this._map.addLayer({id:d,type:"line",source:r,filter:["any",["==",["geometry-type"],"Polygon"],["==",["geometry-type"],"MultiPolygon"]],paint:{"line-color":l.strokeColor,"line-width":l.strokeWidth,"line-opacity":l.strokeOpacity}}),o.push(d)}if(a.has("LineString")||a.has("MultiLineString")){const h=`${s}-line`;this._map.addLayer({id:h,type:"line",source:r,filter:["any",["==",["geometry-type"],"LineString"],["==",["geometry-type"],"MultiLineString"]],paint:{"line-color":l.strokeColor,"line-width":l.strokeWidth,"line-opacity":l.strokeOpacity}}),o.push(h)}if(a.has("Point")||a.has("MultiPoint")){const h=`${s}-point`;this._map.addLayer({id:h,type:"circle",source:r,filter:["any",["==",["geometry-type"],"Point"],["==",["geometry-type"],"MultiPoint"]],paint:{"circle-radius":l.circleRadius,"circle-color":l.circleColor,"circle-stroke-color":l.circleStrokeColor,"circle-stroke-width":l.circleStrokeWidth}}),o.push(h)}const c={id:s,filename:t,sourceId:r,layerIds:o,featureCount:i.features.length,geometryTypes:Array.from(a),loadedAt:new Date,originalFormat:n};return this._state.loadedDatasets.push(c),this._options.fitBounds&&i.features.length>0&&this._fitToData(i),this._emit("load",c),this._emit("update"),c}catch(o){return this._state.error=`Failed to add ${t} to map: ${o instanceof Error?o.message:"Unknown error"}`,this._emit("error",void 0,this._state.error,t),null}}_fitToData(e){if(!this._map)return;let t=1/0,n=1/0,i=-1/0,s=-1/0;const r=o=>{t=Math.min(t,o[0]),i=Math.max(i,o[0]),n=Math.min(n,o[1]),s=Math.max(s,o[1])},a=o=>{for(const l of o)typeof l[0]=="number"?r(l):a(l)};for(const o of e.features){if(!o.geometry)continue;const l=o.geometry;l.type==="Point"?r(l.coordinates):(l.type==="MultiPoint"||l.type==="LineString"||l.type==="MultiLineString"||l.type==="Polygon"||l.type==="MultiPolygon")&&a(l.coordinates)}t!==1/0&&this._map.fitBounds([[t,n],[i,s]],{padding:this._options.fitBoundsPadding})}_removeAllDatasets(){for(const e of this._state.loadedDatasets)if(this._map){for(const t of e.layerIds)this._map.getLayer(t)&&this._map.removeLayer(t);this._map.getSource(e.sourceId)&&this._map.removeSource(e.sourceId)}this._state.loadedDatasets=[]}_checkZoomVisibility(){if(!this._map)return;const e=this._map.getZoom(),{minzoom:t,maxzoom:n}=this._options,i=e>=t&&e<=n;i!==this._zoomVisible&&(this._zoomVisible=i,this._updateDisplayState())}_updateDisplayState(){if(!this._container)return;const e=this._state.visible&&this._zoomVisible;this._container.style.display=e?"flex":"none"}_updateButtonState(){this._button&&(this._state.isLoading?(this._button.classList.add("maplibre-gl-vector-dataset-button--loading"),this._button.disabled=!0):(this._button.classList.remove("maplibre-gl-vector-dataset-button--loading"),this._button.disabled=!1))}_showLoading(e,t){this._loadingOverlay&&(this._loadingOverlay.style.display="flex",this._loadingText&&(this._loadingText.textContent=e),this._loadingProgress&&(this._loadingProgress.textContent=t||""))}_updateLoading(e,t){this._loadingText&&(this._loadingText.textContent=e),this._loadingProgress&&(this._loadingProgress.textContent=t||"")}_hideLoading(){this._loadingOverlay&&(this._loadingOverlay.style.display="none")}},Y0={fillColor:"#ffff00",fillOpacity:.3,strokeColor:"#ffff00",strokeWidth:3,circleRadius:10,circleStrokeWidth:3},DO={position:"top-right",className:"",visible:!0,enabled:!1,maxFeatures:10,includeLayers:[],excludeLayers:[],highlightStyle:Y0,excludeProperties:[],showGeometryType:!0,showLayerName:!0,maxWidth:320,maxHeight:300,backgroundColor:"rgba(255, 255, 255, 0.95)",borderRadius:4,opacity:1,fontSize:13,fontColor:"#333",minzoom:0,maxzoom:24},FO='<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>',n2=class{_container;_button;_options;_state;_eventHandlers=new Map;_map;_handleZoom;_zoomVisible=!0;_popup;_highlightSourceId="";_highlightLayerIds=[];_boundClickHandler;constructor(e){this._options={...DO,...e,highlightStyle:{...Y0,...e?.highlightStyle}},this._state={visible:this._options.visible,enabled:this._options.enabled,inspectedFeatures:[],selectedIndex:0,error:null},this._highlightSourceId=`inspect-highlight-${Qa()}`}onAdd(e){return this._map=e,this._container=this._createContainer(),this._handleZoom=()=>this._checkZoomVisibility(),this._map.on("zoom",this._handleZoom),this._checkZoomVisibility(),this._state.enabled&&this._setupMapListeners(),this._container}onRemove(){this._map&&this._handleZoom&&(this._map.off("zoom",this._handleZoom),this._handleZoom=void 0),this._removeMapListeners(),this._removeHighlight(),this._hidePopup(),this._map=void 0,this._container?.parentNode?.removeChild(this._container),this._container=void 0,this._button=void 0,this._eventHandlers.clear()}enable(){this._state.enabled||(this._state.enabled=!0,this._updateButtonState(),this._setupMapListeners(),this._updateCursor(!0),this._emit("enable"))}disable(){this._state.enabled&&(this._state.enabled=!1,this._updateButtonState(),this._removeMapListeners(),this._updateCursor(!1),this.clear(),this._emit("disable"))}toggle(){this._state.enabled?this.disable():this.enable()}isEnabled(){return this._state.enabled}show(){this._state.visible||(this._state.visible=!0,this._updateDisplayState(),this._emit("show"))}hide(){this._state.visible&&(this._state.visible=!0,this._updateDisplayState(),this._emit("hide"))}clear(){this._state.inspectedFeatures=[],this._state.selectedIndex=0,this._removeHighlight(),this._hidePopup(),this._emit("clear")}getState(){return{...this._state}}getInspectedFeatures(){return[...this._state.inspectedFeatures]}getSelectedFeature(){return this._state.inspectedFeatures[this._state.selectedIndex]||null}selectFeature(e){if(e>=0&&e<this._state.inspectedFeatures.length){this._state.selectedIndex=e;const t=this._state.inspectedFeatures[e];this._addHighlight(t),this._updatePopupContent(),this._emit("featureselect",t)}}nextFeature(){if(this._state.inspectedFeatures.length>1){const e=(this._state.selectedIndex+1)%this._state.inspectedFeatures.length;this.selectFeature(e)}}previousFeature(){if(this._state.inspectedFeatures.length>1){const e=this._state.selectedIndex===0?this._state.inspectedFeatures.length-1:this._state.selectedIndex-1;this.selectFeature(e)}}update(e){Object.assign(this._options,e),e.highlightStyle&&(this._options.highlightStyle={...Y0,...e.highlightStyle}),e.visible!==void 0&&(this._state.visible=e.visible,this._updateDisplayState()),e.enabled!==void 0&&(e.enabled?this.enable():this.disable()),this._emit("update")}on(e,t){this._eventHandlers.has(e)||this._eventHandlers.set(e,new Set),this._eventHandlers.get(e).add(t)}off(e,t){this._eventHandlers.get(e)?.delete(t)}_emit(e,t){const n=this._eventHandlers.get(e);n&&n.forEach(i=>i({type:e,state:this.getState(),feature:t,features:this._state.inspectedFeatures}))}_createContainer(){const e=document.createElement("div");return e.className=`maplibregl-ctrl maplibregl-ctrl-group maplibre-gl-inspect ${this._options.className}`.trim(),this._options.backgroundColor&&(e.style.backgroundColor=this._options.backgroundColor),this._options.borderRadius&&(e.style.borderRadius=`${this._options.borderRadius}px`),this._options.opacity!==void 0&&this._options.opacity!==1&&(e.style.opacity=String(this._options.opacity)),this._button=document.createElement("button"),this._button.type="button",this._button.className="maplibre-gl-inspect-button",this._button.title="Inspect features",this._button.innerHTML=FO,this._button.addEventListener("click",()=>this.toggle()),e.appendChild(this._button),e.style.display=this._state.visible?"block":"none",e}_updateButtonState(){this._button&&(this._state.enabled?(this._button.classList.add("maplibre-gl-inspect-button--active"),this._button.title="Disable inspect mode"):(this._button.classList.remove("maplibre-gl-inspect-button--active"),this._button.title="Inspect features"))}_updateCursor(e){if(this._map){const t=this._map.getCanvas();e?t.style.cursor="crosshair":t.style.cursor=""}}_setupMapListeners(){!this._map||this._boundClickHandler||(this._boundClickHandler=e=>this._handleMapClick(e),this._map.on("click",this._boundClickHandler))}_removeMapListeners(){this._map&&this._boundClickHandler&&(this._map.off("click",this._boundClickHandler),this._boundClickHandler=void 0)}_handleMapClick(e){if(!this._map)return;const t=e.point,n=[e.lngLat.lng,e.lngLat.lat],i=this._queryFeatures(t);if(i.length===0){this.clear();return}const s=i.slice(0,this._options.maxFeatures).map(a=>{const o=a.id,l={type:"Feature",geometry:a.geometry,properties:a.properties||{}};return o!==void 0&&(l.id=o),{id:Qa("inspect"),feature:l,layerId:a.layer?.id||"unknown",sourceId:a.source||"unknown",sourceLayer:a.sourceLayer,featureId:o===void 0?void 0:o,lngLat:n}});this._state.inspectedFeatures=s,this._state.selectedIndex=0;const r=s[0];this._addHighlight(r),this._showPopup(r,n),this._emit("featureselect",r)}_queryFeatures(e){if(!this._map)return[];const t={};this._options.includeLayers.length>0&&(t.layers=this._options.includeLayers);let n=this._map.queryRenderedFeatures(e,t);return this._options.excludeLayers.length>0&&(n=n.filter(i=>i.layer&&!this._options.excludeLayers.includes(i.layer.id))),n=n.filter(i=>i.layer&&!i.layer.id.startsWith("inspect-highlight-")),n}_addHighlight(e){if(!this._map)return;const t=this._map;this._removeHighlight();const n=e.feature,i=n.geometry.type,s=this._options.highlightStyle,r=this._getHighlightTarget(e),a=o=>{if(i==="Point"||i==="MultiPoint"){const l=`${this._highlightSourceId}-circle`;t.addLayer({id:l,type:"circle",...o,paint:{"circle-radius":s.circleRadius,"circle-color":s.fillColor,"circle-opacity":s.fillOpacity,"circle-stroke-color":s.strokeColor,"circle-stroke-width":s.circleStrokeWidth}}),this._highlightLayerIds.push(l)}else if(i==="LineString"||i==="MultiLineString"){const l=`${this._highlightSourceId}-line`;t.addLayer({id:l,type:"line",...o,paint:{"line-color":s.strokeColor,"line-width":s.strokeWidth,"line-opacity":1}}),this._highlightLayerIds.push(l)}else if(i==="Polygon"||i==="MultiPolygon"){const l=`${this._highlightSourceId}-fill`;t.addLayer({id:l,type:"fill",...o,paint:{"fill-color":s.fillColor,"fill-opacity":s.fillOpacity}}),this._highlightLayerIds.push(l);const c=`${this._highlightSourceId}-outline`;t.addLayer({id:c,type:"line",...o,paint:{"line-color":s.strokeColor,"line-width":s.strokeWidth}}),this._highlightLayerIds.push(c)}};if(r){const o={source:r.sourceId};r.sourceLayer&&(o["source-layer"]=r.sourceLayer),o.filter=r.filter;try{a(o);return}catch{this._removeHighlight()}}t.addSource(this._highlightSourceId,{type:"geojson",data:n}),a({source:this._highlightSourceId})}_getHighlightTarget(e){if(!this._map)return null;const{sourceId:t,sourceLayer:n,featureId:i}=e;if(!t||t==="unknown"||i==null)return null;const s=this._map.getSource(t);return!s||s.type==="vector"&&!n?null:{sourceId:t,sourceLayer:n,filter:["==","$id",i]}}_removeHighlight(){if(this._map){for(const e of this._highlightLayerIds)this._map.getLayer(e)&&this._map.removeLayer(e);this._highlightLayerIds=[],this._map.getSource(this._highlightSourceId)&&this._map.removeSource(this._highlightSourceId)}}_showPopup(e,t){if(!this._map)return;this._hidePopup();const n=this._renderPopupContent();this._popup=new fi.Popup({closeButton:!0,closeOnClick:!1,maxWidth:`${this._options.maxWidth}px`,className:"maplibre-gl-inspect-popup"}).setLngLat(t).setHTML(n).addTo(this._map),requestAnimationFrame(()=>{this._attachPopupListeners()})}_hidePopup(){this._popup&&(this._popup.remove(),this._popup=void 0)}_updatePopupContent(){if(this._popup){const e=this._renderPopupContent();this._popup.setHTML(e),this._attachPopupListeners()}}_attachPopupListeners(){if(!this._popup)return;const e=this._popup.getElement();if(!e)return;const t=e.querySelector(".maplibre-gl-inspect-nav-prev"),n=e.querySelector(".maplibre-gl-inspect-nav-next");t&&(t.onclick=i=>{i.stopPropagation(),i.preventDefault(),this.previousFeature()}),n&&(n.onclick=i=>{i.stopPropagation(),i.preventDefault(),this.nextFeature()})}_renderPopupContent(){const e=this._state.inspectedFeatures,t=this._state.selectedIndex,n=e[t];if(!n)return'<div class="maplibre-gl-inspect-empty">No feature selected</div>';const i=n.feature.geometry.type,s=n.layerId,r=n.feature.properties||{};let a='<div class="maplibre-gl-inspect-header">';if(this._options.showGeometryType&&(a+=`<span class="maplibre-gl-inspect-geometry">${this._formatGeometryType(i)}</span>`),this._options.showLayerName&&(a+=`<span class="maplibre-gl-inspect-layer" title="${s}">${s}</span>`),e.length>1){const l=e.length<=1?"disabled":"",c=e.length<=1?"disabled":"";a+=`
79
79
  <span class="maplibre-gl-inspect-nav">
80
80
  <button class="maplibre-gl-inspect-nav-prev" ${l} title="Previous feature">&lt;</button>
81
81
  <span class="maplibre-gl-inspect-nav-count">${t+1}/${e.length}</span>
@@ -103,7 +103,7 @@ var iO=Object.create;var Gw=Object.defineProperty;var sO=Object.getOwnPropertyDe
103
103
  color.b = clamp((color.b - rescaleFloat.minVal) / range, 0.0, 1.0);
104
104
  }
105
105
  }
106
- `},uniformTypes:{minVal:"f32",maxVal:"f32",isSingleBand:"f32"},getUniforms:e=>({minVal:e.minVal,maxVal:e.maxVal,isSingleBand:e.isSingleBand})};function s2(e,t){return e&&(Array.isArray(e)?e.map(n=>s2(n,t)):typeof e.clone=="function"?e.clone({opacity:t}):e)}function QO(e,t){return Array.isArray(e)?t(e):e&&Array.isArray(e.renderPipeline)?{...e,renderPipeline:t(e.renderPipeline)}:e}function GO(e){let t=e.replace("#","");return t.length===3&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]}function HO(e){const n=new Uint8ClampedArray(1024),i=e.map(s=>({pos:s.position,rgb:GO(s.color)}));for(let s=0;s<256;s++){const r=s/255;let a=i[0],o=i[i.length-1];for(let h=0;h<i.length-1;h++)if(r>=i[h].pos&&r<=i[h+1].pos){a=i[h],o=i[h+1];break}const l=o.pos-a.pos,c=l>0?(r-a.pos)/l:0;n[s*4]=a.rgb[0]+(o.rgb[0]-a.rgb[0])*c,n[s*4+1]=a.rgb[1]+(o.rgb[1]-a.rgb[1])*c,n[s*4+2]=a.rgb[2]+(o.rgb[2]-a.rgb[2])*c,n[s*4+3]=255}return new ImageData(n,256,1)}function $O(e){return e?.[0]===1}function cc(e){return typeof e=="number"}function VO(e,t){return Number.isNaN(t)?Number.isNaN(e):e===t}function Ww(e,t,n){const i=Math.floor(e.length/t),s=new Uint8Array(i);s.fill(255);let r=!1;const a=cc(n);for(let o=0;o<i;o++){const l=o*t;let c=!1,h=a;for(let d=0;d<t;d++){const f=e[l+d];Number.isFinite(f)||(c=!0),a&&h&&!VO(f,n)&&(h=!1)}(c||h)&&(s[o]=0,r=!0)}return r?s:null}function Yw(e,t,n){if(!t||!("set"in e))return;const i=e;for(let s=0;s<t.length;s++){if(t[s]!==0)continue;const r=s*n;for(let a=0;a<n;a++)i[r+a]=0}}function qO(e,t){if(!e)return t;if(!t)return e;const n=new Uint8Array(e.length);for(let i=0;i<e.length;i++)n[i]=e[i]===0||t[i]===0?0:255;return n}function jw(e,t){const n=HO(nr(t));return e.createTexture({data:n.data,dimension:"2d-array",format:"rgba8unorm",width:n.width,height:n.height,depth:1,mipLevels:1,sampler:{minFilter:"linear",magFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",addressModeW:"clamp-to-edge"}})}var WO=["none","bone","bwr","cividis","cool","coolwarm","gray","hot","inferno","jet","magma","ocean","plasma","rainbow","RdBu","RdYlBu","RdYlGn","seismic","spectral","terrain","turbo","viridis"],YO={position:"top-right",className:"",visible:!0,collapsed:!0,beforeId:"",defaultUrl:"",loadDefaultUrl:!1,defaultBands:"1",defaultColormap:"none",defaultRescaleMin:0,defaultRescaleMax:255,defaultNodata:void 0,defaultLayerName:"",defaultOpacity:1,defaultPickable:!0,panelWidth:300,maxHeight:500,backgroundColor:"rgba(255, 255, 255, 0.95)",borderRadius:4,opacity:1,fontSize:13,fontColor:"#333",minzoom:0,maxzoom:24},jO='<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>',j0=class{_container;_button;_panel;_options;_state;_eventHandlers=new Map;_map;_handleZoom;_zoomVisible=!0;_deckOverlay;_cogLayers=new Map;_cogLayerPropsMap=new Map;_layerCounter=0;_activePopup;_mapClickHandler;constructor(e){this._options={...YO,...e},this._state={visible:this._options.visible,collapsed:this._options.collapsed,url:this._options.defaultUrl,bands:this._options.defaultBands,colormap:this._options.defaultColormap,rescaleMin:this._options.defaultRescaleMin,rescaleMax:this._options.defaultRescaleMax,nodata:this._options.defaultNodata,layerName:this._options.defaultLayerName,layerOpacity:this._options.defaultOpacity,pickable:this._options.defaultPickable,hasLayer:!1,layerCount:0,layers:[],loading:!1,error:null,status:null}}onAdd(e){if(this._map=e,this._container=this._createContainer(),this._render(),this._handleZoom=()=>this._checkZoomVisibility(),this._map.on("zoom",this._handleZoom),this._checkZoomVisibility(),this._setupClickHandler(),this._options.loadDefaultUrl&&this._options.defaultUrl){const t=()=>{this._addLayer()};this._map.isStyleLoaded()?setTimeout(t,100):this._map.once("idle",t)}return this._container}onRemove(){if(this._removeLayer(),this._map&&this._handleZoom&&(this._map.off("zoom",this._handleZoom),this._handleZoom=void 0),this._map&&this._mapClickHandler&&(this._map.off("click",this._mapClickHandler),this._mapClickHandler=void 0),this._activePopup&&(this._activePopup.remove(),this._activePopup=void 0),this._deckOverlay&&this._map){try{this._map.removeControl(this._deckOverlay)}catch{}this._deckOverlay=void 0}this._map=void 0,this._container?.parentNode?.removeChild(this._container),this._container=void 0,this._button=void 0,this._panel=void 0,this._eventHandlers.clear()}show(){this._state.visible||(this._state.visible=!0,this._updateDisplayState(),this._emit("show"))}hide(){this._state.visible&&(this._state.visible=!1,this._updateDisplayState(),this._emit("hide"))}expand(){this._state.collapsed&&(this._state.collapsed=!1,this._render(),this._emit("expand"))}collapse(){this._state.collapsed||(this._state.collapsed=!0,this._render(),this._emit("collapse"))}toggle(){this._state.collapsed?this.expand():this.collapse()}getState(){return{...this._state}}update(e){this._options={...this._options,...e},e.visible!==void 0&&(this._state.visible=e.visible),e.collapsed!==void 0&&(this._state.collapsed=e.collapsed),this._render(),this._emit("update")}on(e,t){this._eventHandlers.has(e)||this._eventHandlers.set(e,new Set),this._eventHandlers.get(e).add(t)}off(e,t){this._eventHandlers.get(e)?.delete(t)}async addLayer(e){e&&(this._state.url=e),await this._addLayer()}removeLayer(e){this._removeLayer(e),this._render()}getLayerIds(){return Array.from(this._cogLayers.keys())}getLayerOpacity(e){const t=this._cogLayers.get(e);return!t||!t.props?null:t.props.opacity??1}setLayerOpacity(e,t){const n=this._cogLayers.get(e);if(!n||typeof n.clone!="function")return;const i=Math.max(0,Math.min(1,t)),s=n.clone({opacity:i});this._cogLayers.set(e,s),this._deckOverlay&&this._deckOverlay.setProps({layers:Array.from(this._cogLayers.values())}),this._map&&this._map.triggerRepaint()}getLayerVisibility(e){const t=this.getLayerOpacity(e);return t!==null&&t>0}setLayerVisibility(e,t,n=1){t?this.setLayerOpacity(e,n):this.setLayerOpacity(e,0)}getLayerUrl(e){const t=this._cogLayerPropsMap.get(e);return t?t._sourceUrl??(typeof t.geotiff=="string"?t.geotiff:null):null}_emit(e,t){const n=this._eventHandlers.get(e);if(n){const i={type:e,state:this.getState(),...t};n.forEach(s=>s(i))}}_checkZoomVisibility(){if(!this._map)return;const e=this._map.getZoom(),{minzoom:t,maxzoom:n}=this._options,i=e>=t&&e<=n;i!==this._zoomVisible&&(this._zoomVisible=i,this._updateDisplayState())}_updateDisplayState(){if(!this._container)return;const e=this._state.visible&&this._zoomVisible;this._container.style.display=e?"block":"none"}_createContainer(){const e=document.createElement("div");return e.className=`maplibregl-ctrl maplibre-gl-cog-layer${this._options.className?` ${this._options.className}`:""}`,this._state.visible&&this._zoomVisible||(e.style.display="none"),Object.assign(e.style,{backgroundColor:this._options.backgroundColor,borderRadius:`${this._options.borderRadius}px`,boxShadow:"0 0 0 2px rgba(0, 0, 0, 0.1)"}),this._options.opacity!==1&&(e.style.opacity=String(this._options.opacity)),e}_render(){if(!this._container)return;const e=this._container.querySelector(".maplibre-gl-cog-layer-panel"),t=e?e.scrollTop:0;if(this._container.innerHTML="",this._state.collapsed?this._renderCollapsed():this._renderExpanded(),this._updateDisplayState(),t>0){const n=this._container.querySelector(".maplibre-gl-cog-layer-panel");n&&(n.scrollTop=t)}}_renderCollapsed(){this._container&&(this._button=document.createElement("button"),this._button.type="button",this._button.className=`maplibre-gl-cog-layer-button${this._state.hasLayer?" maplibre-gl-cog-layer-button--active":""}`,this._button.title="COG Layer",this._button.setAttribute("aria-label","COG Layer"),this._button.innerHTML=jO,this._button.addEventListener("click",()=>this.expand()),this._container.appendChild(this._button),this._panel=void 0)}_renderExpanded(){if(!this._container)return;const e=document.createElement("div");e.className="maplibre-gl-cog-layer-panel",e.style.width=`${this._options.panelWidth}px`,this._options.maxHeight&&this._options.maxHeight>0&&(e.style.maxHeight=`${this._options.maxHeight}px`,e.style.overflowY="auto"),this._panel=e;const t=document.createElement("div");t.className="maplibre-gl-cog-layer-header";const n=document.createElement("span");n.className="maplibre-gl-cog-layer-title",n.textContent="COG Layer",t.appendChild(n);const i=document.createElement("button");i.className="maplibre-gl-cog-layer-close",i.innerHTML="&times;",i.title="Close",i.addEventListener("click",()=>this.collapse()),t.appendChild(i),e.appendChild(t);const s=this._createFormGroup("COG URL","url"),r=document.createElement("input");r.type="text",r.className="maplibre-gl-cog-layer-input",r.style.color="#000",r.placeholder="https://example.com/cog.tif",r.value=this._state.url,r.addEventListener("input",()=>{this._state.url=r.value}),s.appendChild(r),e.appendChild(s);const a=this._createFormGroup("Bands (comma-separated)","bands"),o=document.createElement("input");o.type="text",o.className="maplibre-gl-cog-layer-input",o.style.color="#000",o.placeholder="1 or 1,2,3",o.value=this._state.bands,o.addEventListener("input",()=>{this._state.bands=o.value}),a.appendChild(o),e.appendChild(a);const l=this._createFormGroup("Colormap","colormap"),c=document.createElement("select");c.className="maplibre-gl-cog-layer-select",c.style.color="#000";for(const U of WO){const Q=document.createElement("option");Q.value=U,Q.textContent=U,U===this._state.colormap&&(Q.selected=!0),c.appendChild(Q)}c.addEventListener("change",()=>{this._state.colormap=c.value,this._updateColormapPreview()}),l.appendChild(c);const h=document.createElement("div");h.className="maplibre-gl-cog-layer-colormap-preview",h.id="cog-colormap-preview",this._updateColormapPreviewElement(h),l.appendChild(h),e.appendChild(l);const d=document.createElement("div");d.className="maplibre-gl-cog-layer-row";const f=this._createFormGroup("Rescale Min","rescale-min"),m=document.createElement("input");m.type="number",m.className="maplibre-gl-cog-layer-input",m.style.color="#000",m.value=String(this._state.rescaleMin),m.addEventListener("input",()=>{this._state.rescaleMin=Number(m.value)||0}),f.appendChild(m),d.appendChild(f);const A=this._createFormGroup("Rescale Max","rescale-max"),y=document.createElement("input");y.type="number",y.className="maplibre-gl-cog-layer-input",y.style.color="#000",y.value=String(this._state.rescaleMax),y.addEventListener("input",()=>{this._state.rescaleMax=Number(y.value)||0}),A.appendChild(y),d.appendChild(A),e.appendChild(d);const x=this._createFormGroup("Nodata","nodata"),v=document.createElement("input");v.type="number",v.className="maplibre-gl-cog-layer-input",v.style.color="#000",v.placeholder="e.g. 0 or -9999",v.value=this._state.nodata!==void 0?String(this._state.nodata):"",v.addEventListener("input",()=>{this._state.nodata=v.value!==""?Number(v.value):void 0}),x.appendChild(v),e.appendChild(x);const b=this._createFormGroup("Opacity","opacity"),w=document.createElement("div");w.className="maplibre-gl-cog-layer-slider-row";const S=document.createElement("input");S.type="range",S.className="maplibre-gl-cog-layer-slider",S.min="0",S.max="100",S.value=String(Math.round(this._state.layerOpacity*100));const R=document.createElement("span");R.className="maplibre-gl-cog-layer-slider-value",R.textContent=`${Math.round(this._state.layerOpacity*100)}%`,S.addEventListener("input",()=>{const U=Number(S.value);this._state.layerOpacity=U/100,R.textContent=`${U}%`,this._updateOpacity()}),w.appendChild(S),w.appendChild(R),b.appendChild(w),e.appendChild(b);const k=document.createElement("div");k.className="maplibre-gl-cog-layer-form-group maplibre-gl-cog-layer-checkbox-group";const L=document.createElement("label");L.className="maplibre-gl-cog-layer-checkbox-label";const T=document.createElement("input");T.type="checkbox",T.className="maplibre-gl-cog-layer-checkbox",T.checked=this._state.pickable,T.addEventListener("change",()=>{this._state.pickable=T.checked,this._updatePickable()}),L.appendChild(T);const C=document.createElement("span");C.textContent="Pickable (click to show pixel value)",L.appendChild(C),k.appendChild(L),e.appendChild(k);const I=this._createFormGroup("Layer Name","layer-name"),M=document.createElement("input");M.type="text",M.className="maplibre-gl-cog-layer-input",M.style.color="#000",M.placeholder="Optional custom layer name",M.value=this._state.layerName,M.addEventListener("input",()=>{this._state.layerName=M.value}),I.appendChild(M),e.appendChild(I);const O=this._createFormGroup("Before Layer ID (optional)","before-id"),N=document.createElement("input");N.type="text",N.className="maplibre-gl-cog-layer-input",N.style.color="#000",N.placeholder="e.g. labels or water",N.value=this._options.beforeId||"",N.addEventListener("input",()=>{this._options.beforeId=N.value||""}),O.appendChild(N),e.appendChild(O);const D=document.createElement("div");D.className="maplibre-gl-cog-layer-buttons";const P=document.createElement("button");if(P.className="maplibre-gl-cog-layer-btn maplibre-gl-cog-layer-btn--primary",P.textContent="Add Layer",P.disabled=this._state.loading,P.addEventListener("click",()=>this._addLayer()),D.appendChild(P),e.appendChild(D),this._state.loading?this._appendStatus("Loading COG...","info"):this._state.error?this._appendStatus(this._state.error,"error"):this._state.status&&this._appendStatus(this._state.status,"success"),this._cogLayers.size>0){const U=document.createElement("div");U.className="maplibre-gl-cog-layer-list";const Q=document.createElement("div");Q.className="maplibre-gl-cog-layer-list-header",Q.textContent=`Layers (${this._cogLayers.size})`,U.appendChild(Q);for(const[z]of this._cogLayers){const H=this._cogLayerPropsMap.get(z);if(!H)continue;const W=document.createElement("div");W.className="maplibre-gl-cog-layer-list-item";const te=document.createElement("span");te.className="maplibre-gl-cog-layer-list-label";const J=H._sourceUrl??(typeof H.geotiff=="string"?H.geotiff:""),K=H._layerName;let re;if(K)re=K;else try{re=new URL(J).pathname.split("/").pop()||J}catch{re=J}te.textContent=re,te.title=J,W.appendChild(te);const ce=document.createElement("button");ce.className="maplibre-gl-cog-layer-list-remove",ce.innerHTML="&times;",ce.title="Remove layer",ce.addEventListener("click",()=>{this._removeLayer(z),this._render()}),W.appendChild(ce),U.appendChild(W)}e.appendChild(U)}this._container.appendChild(e),this._button=void 0}_createFormGroup(e,t){const n=document.createElement("div");n.className="maplibre-gl-cog-layer-form-group";const i=document.createElement("label");return i.textContent=e,i.htmlFor=`cog-layer-${t}`,n.appendChild(i),n}_appendStatus(e,t){if(!this._panel)return;const n=document.createElement("div");n.className=`maplibre-gl-cog-layer-status maplibre-gl-cog-layer-status--${t}`,n.textContent=e,this._panel.appendChild(n)}_updateColormapPreview(){const e=document.getElementById("cog-colormap-preview");e&&this._updateColormapPreviewElement(e)}_updateColormapPreviewElement(e){if(this._state.colormap==="none")e.style.background="linear-gradient(to right, #888, #888)",e.style.display="none";else{const t=nr(this._state.colormap).map(n=>n.color).join(", ");e.style.background=`linear-gradient(to right, ${t})`,e.style.display="block"}}async _ensureOverlay(){if(this._deckOverlay||!this._map)return;const{MapboxOverlay:e}=await import("@deck.gl/mapbox");this._deckOverlay=new e({interleaved:!!this._options.beforeId,layers:[]}),this._map.addControl(this._deckOverlay)}_setupClickHandler(){if(!this._map||this._mapClickHandler)return;const e=this._map;this._mapClickHandler=t=>{if(!this._state.pickable||this._cogLayers.size===0)return;this._activePopup&&this._activePopup.remove();const{lngLat:n}=t,i=Array.from(this._cogLayers.keys()),s=this._cogLayerPropsMap.get(i[0]);let r='<div class="maplibre-gl-cog-layer-popup">';r+='<table class="maplibre-gl-cog-layer-popup-table">',r+=`<tr><td><strong>Layers</strong></td><td>${i.length} COG layer(s)</td></tr>`,r+=`<tr><td><strong>Lng</strong></td><td>${n.lng.toFixed(6)}</td></tr>`,r+=`<tr><td><strong>Lat</strong></td><td>${n.lat.toFixed(6)}</td></tr>`,s&&(r+=`<tr><td><strong>Rescale</strong></td><td>${s._rescaleMin} - ${s._rescaleMax}</td></tr>`,s._colormap&&s._colormap!=="none"&&(r+=`<tr><td><strong>Colormap</strong></td><td>${s._colormap}</td></tr>`)),r+="</table>",r+="</div>",this._activePopup=new fi.default.Popup({closeButton:!0,maxWidth:"280px"}).setLngLat(n).setHTML(r).addTo(e);const a=this._activePopup.getElement();a&&(a.style.zIndex="1000")},e.on("click",this._mapClickHandler)}_updatePickable(){if(this._deckOverlay){for(const[,e]of this._cogLayerPropsMap)e.pickable=this._state.pickable;this._rebuildLayers()}}async _rebuildLayers(){if(this._deckOverlay)try{const{COGLayer:e}=await import("@developmentseed/deck.gl-geotiff");this._patchCOGLayerForFloat(e),this._patchCOGLayerForOpacity(e);const t=[];for(const[n,i]of this._cogLayerPropsMap){const s=new e(i);this._cogLayers.set(n,s),t.push(s)}this._deckOverlay.setProps({layers:t})}catch(e){console.error("Failed to rebuild layers:",e)}}async _registerCommonProjections(e){e.defs("EPSG:3978","+proj=lcc +lat_0=49 +lon_0=-95 +lat_1=49 +lat_2=77 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs +type=crs"),e.defs("EPSG:3979","+proj=lcc +lat_0=49 +lon_0=-95 +lat_1=49 +lat_2=77 +x_0=0 +y_0=0 +ellps=GRS80 +towgs84=-0.991,1.9072,0.5129,-1.25033e-07,-4.6785e-08,-5.6529e-08,0 +units=m +no_defs +type=crs")}_buildGeoKeysParser(e){let t=null;return Promise.resolve().then(()=>require("./lib-B4jvG7hB.cjs")).then(n=>{t=n.default||n,typeof t=="function"&&this._registerCommonProjections(t)}),async n=>{try{const i=e.toProj4(n);if(i&&i.proj4){let s=i.proj4;if(s=s.replace(/\+axis=\w+\s*/g,""),!t){const a=await Promise.resolve().then(()=>require("./lib-B4jvG7hB.cjs"));t=a.default||a,typeof t=="function"&&await this._registerCommonProjections(t)}let r={};if(typeof t=="function")try{t.defs("custom",s),r=t.defs("custom")||{}}catch{}return{def:s,parsed:r,coordinatesUnits:i.coordinatesUnits||"metre"}}}catch{}return null}}_patchCOGLayerForFloat(e){if(e.__floatPatched)return;e.__floatPatched=!0;const t=e.prototype._parseGeoTIFF;e.prototype._parseGeoTIFF=async function(){try{await t.call(this);const n=this.props._nodata;if(n!=null&&!isNaN(n)){const{FilterNoDataVal:i}=await import("@developmentseed/deck.gl-raster/gpu-modules"),s=this.state.defaultRenderTile;if(typeof s=="function"){const r=a=>QO(s(a),o=>{const l=o.filter(c=>c.module!==i);return l.splice(1,0,{module:i,props:{value:n}}),l});this.setState({defaultRenderTile:r})}}}catch(n){if(!(n instanceof Error?n.message:String(n)).includes("non-unsigned integers not yet supported"))throw n;const{parseCOGTileMatrixSet:i,texture:s}=await import("@developmentseed/deck.gl-geotiff");if(typeof i!="function"||typeof s?.inferTextureFormat!="function")throw n;const{fromUrl:r}=await Promise.resolve().then(()=>require("./geotiff-B55EjXJz.cjs")),{CreateTexture:a,FilterNoDataVal:o,MaskTexture:l}=await import("@developmentseed/deck.gl-raster/gpu-modules"),c=await Promise.resolve().then(()=>require("./lib-B4jvG7hB.cjs")),h=c.default||c,d=this.props.geotiff,f=typeof d=="string"?await r(d):d,m=this.props.geoKeysParser,A=await i(f,m),y=await f.getImage(),x=await f.getImageCount(),v=[];for(let Q=0;Q<x;Q++)v.push(await f.getImage(Q));const b=await m(y.getGeoKeys());if(!b)throw new Error("Could not determine source projection from GeoTIFF geo keys");const w=h(b.def,"EPSG:4326"),S=(Q,z)=>w.forward([Q,z],!1),R=(Q,z)=>w.inverse([Q,z],!1);if(this.props.onGeoTIFFLoad){const Q=y.getBoundingBox(),z=[w.forward([Q[0],Q[1]]),w.forward([Q[2],Q[1]]),w.forward([Q[2],Q[3]]),w.forward([Q[0],Q[3]])],H=z.map(J=>J[0]),W=z.map(J=>J[1]),te={west:Math.min(...H),south:Math.min(...W),east:Math.max(...H),north:Math.max(...W)};this.props.onGeoTIFFLoad(f,{projection:b,geographicBounds:te})}const{BitsPerSample:k,SampleFormat:L,SamplesPerPixel:T,GDAL_NODATA:C}=y.getFileDirectory();let I=null;if(C){const Q=C[C.length-1]==="\0"?C.slice(0,-1):C;Q.length>0&&(I=parseFloat(Q))}const M=this,O=async(Q,z)=>{const{device:H}=z,W=await Q.readRasters({...z,interleave:!0});let te=W,J=T;const K=cc(M.props._nodata)?M.props._nodata:I,re=Ww(te,J,cc(K)?K:void 0);if(Yw(te,re,J),T===3){const ie=W.width*W.height,fe=new Float32Array(ie*4);for(let ye=0;ye<ie;ye++)fe[ye*4]=W[ye*3],fe[ye*4+1]=W[ye*3+1],fe[ye*4+2]=W[ye*3+2],fe[ye*4+3]=1;te=fe,te.width=W.width,te.height=W.height,J=4}const ce=s.inferTextureFormat(J,k,L),oe=H.createTexture({data:te,format:ce,width:W.width,height:W.height,sampler:{magFilter:"nearest",minFilter:"nearest"}});let ge;return re&&(ge=H.createTexture({data:re,format:"r8unorm",width:W.width,height:W.height,sampler:{magFilter:"nearest",minFilter:"nearest"}})),{texture:oe,height:W.height,mask:ge,width:W.width}};let N=null,D=null;const{Colormap:P}=await import("@developmentseed/deck.gl-raster/gpu-modules"),U=Q=>{const z=[{module:a,props:{textureName:Q.texture}}];Q.mask&&z.push({module:l,props:{maskTexture:Q.mask}});const H=M.props._nodata!==void 0&&M.props._nodata!==null&&!isNaN(M.props._nodata)?M.props._nodata:I;cc(H)&&!Number.isNaN(H)&&z.push({module:o,props:{value:H}});const W=M.props._rescaleMin??0,te=M.props._rescaleMax??255;z.push({module:qw,props:{minVal:W,maxVal:te,isSingleBand:T===1?1:0}});const J=M.props._colormap;return J&&J!=="none"&&(J!==N&&(D=jw(M.context.device,J),N=J),z.push({module:P,props:{colormapTexture:D}})),{renderPipeline:z}};this.setState({metadata:A,forwardReproject:S,inverseReproject:R,images:v,defaultGetTileData:O,defaultRenderTile:U})}}}_patchCOGLayerForOpacity(e){if(e.__opacityPatched)return;e.__opacityPatched=!0;const t=e.prototype._renderSubLayers;e.prototype._renderSubLayers=function(...n){const i=t.apply(this,n),s=this.props.opacity;return s==null?i:s2(i,Math.max(0,Math.min(1,s)))}}async _createFloatCogLayerProps(e){const{GeoTIFF:t}=await import("@developmentseed/geotiff"),n=await t.fromUrl(e);if($O(n.cachedTags.sampleFormat))return{geotiff:n};const{texture:i}=await import("@developmentseed/deck.gl-geotiff"),{CreateTexture:s,FilterNoDataVal:r,MaskTexture:a,Colormap:o}=await import("@developmentseed/deck.gl-raster/gpu-modules"),l=this._state.colormap,c=this._state.nodata,h=this._state.rescaleMax,d=this._state.rescaleMin,f=async(x,v)=>{const{device:b,pool:w,signal:S,x:R,y:k}=v,{array:L}=await x.fetchTile(R,k,{boundless:!1,pool:w,signal:S});if(L.layout==="band-separate")throw new Error("Band-separate images are not yet implemented.");const T=x.cachedTags;let C=L.data,I=T.samplesPerPixel,M=T.bitsPerSample,O=T.sampleFormat;const N=cc(c)?c:T.nodata;C instanceof Float64Array&&(C=new Float32Array(C),M=Array.from({length:I},()=>32));const D=Ww(C,I,cc(N)?N:void 0);if(Yw(C,D,I),I===3){const W=L.width*L.height,te=new Float32Array(W*4);for(let J=0;J<W;J++)te[J*4]=C[J*3],te[J*4+1]=C[J*3+1],te[J*4+2]=C[J*3+2],te[J*4+3]=1;C=te,I=4,M=[32,32,32,32],O=[3,3,3,3]}const P=i.inferTextureFormat(I,M,O);let U=C.byteLength;const Q=b.createTexture({data:C,format:P,width:L.width,height:L.height,sampler:{magFilter:"nearest",minFilter:"nearest"}});let z;const H=qO(L.mask,D);return H&&(z=b.createTexture({data:H,format:"r8unorm",width:L.width,height:L.height,sampler:{magFilter:"nearest",minFilter:"nearest"}}),U+=H.byteLength),{byteLength:U,device:b,height:L.height,mask:z,nodata:N,samplesPerPixel:I,texture:Q,width:L.width}};let m=null,A=null;return{geotiff:n,getTileData:f,renderTile:x=>{const v=[{module:s,props:{textureName:x.texture}}];x.mask&&v.push({module:a,props:{maskTexture:x.mask}});const b=x.nodata;return cc(b)&&!Number.isNaN(b)&&v.push({module:r,props:{value:b}}),v.push({module:qw,props:{minVal:d,maxVal:h,isSingleBand:x.samplesPerPixel===1?1:0}}),l&&l!=="none"&&(m!==l&&(A=jw(x.device,l),m=l),v.push({module:o,props:{colormapTexture:A}})),{renderPipeline:v}}}}async _addLayer(){if(!this._map||!this._state.url){this._state.error="Please enter a COG URL.",this._render();return}this._state.loading=!0,this._state.error=null,this._state.status=null,this._render();try{await this._ensureOverlay();const{COGLayer:e}=await import("@developmentseed/deck.gl-geotiff");this._patchCOGLayerForFloat(e),this._patchCOGLayerForOpacity(e);const t=this._map,n=await this._createFloatCogLayerProps(this._state.url),i={geotiff:this._state.url,_sourceUrl:this._state.url,opacity:this._state.layerOpacity,pickable:this._state.pickable,_rescaleMin:this._state.rescaleMin,_rescaleMax:this._state.rescaleMax,_colormap:this._state.colormap,_nodata:this._state.nodata,...n??{},...(()=>{if(this._options.beforeId){if(t.getLayer(this._options.beforeId))return{beforeId:this._options.beforeId};console.warn(`[CogLayerControl] beforeId "${this._options.beforeId}" not found in map layers, adding layer on top`)}return{}})(),onGeoTIFFLoad:(o,l)=>{try{if(l&&l.geographicBounds){const{west:c,south:h,east:d,north:f}=l.geographicBounds;t.fitBounds([[c,h],[d,f]],{padding:50,duration:1e3})}}catch{}}};try{const o=await Promise.resolve().then(()=>require("./main-dist-DOx_Axbx.cjs")),l=o.default||o;l&&typeof l.toProj4=="function"&&(i.geoKeysParser=this._buildGeoKeysParser(l))}catch{}const s=`cog-layer-${this._layerCounter++}`;i.id=s;const r=this._state.layerName?.trim();r&&(i._layerName=r),this._cogLayerPropsMap.set(s,i);const a=new e(i);this._cogLayers.set(s,a),this._deckOverlay.setProps({layers:Array.from(this._cogLayers.values())}),this._state.hasLayer=this._cogLayers.size>0,this._state.layerCount=this._cogLayers.size,this._state.layers=this._buildLayerInfoList(),this._state.loading=!1,this._state.status="COG layer added successfully.",this._state.layerName="",this._render(),this._emit("layeradd",{url:this._state.url,layerId:s})}catch(e){this._state.loading=!1,this._state.error=`Failed to load COG: ${e instanceof Error?e.message:String(e)}`,this._render(),this._emit("error",{error:this._state.error})}}_removeLayer(e){e?(this._cogLayers.delete(e),this._cogLayerPropsMap.delete(e),this._deckOverlay&&this._deckOverlay.setProps({layers:Array.from(this._cogLayers.values())}),this._state.hasLayer=this._cogLayers.size>0,this._state.layerCount=this._cogLayers.size,this._state.layers=this._buildLayerInfoList(),this._state.status=null,this._state.error=null,this._emit("layerremove",{layerId:e})):(this._deckOverlay&&this._deckOverlay.setProps({layers:[]}),this._cogLayers.clear(),this._cogLayerPropsMap.clear(),this._state.hasLayer=!1,this._state.layerCount=0,this._state.layers=[],this._state.status=null,this._state.error=null,this._emit("layerremove"))}_updateOpacity(){if(!this._deckOverlay||this._cogLayers.size===0)return;const e=this._state.layerOpacity;for(const[t,n]of this._cogLayers)typeof n.clone=="function"&&this._cogLayers.set(t,n.clone({opacity:e}));this._deckOverlay.setProps({layers:Array.from(this._cogLayers.values())}),this._map&&this._map.triggerRepaint()}_buildLayerInfoList(){const e=[];for(const[t,n]of this._cogLayerPropsMap)e.push({id:t,name:n._layerName||void 0,url:n._sourceUrl??(typeof n.geotiff=="string"?n.geotiff:""),bands:"1",colormap:n._colormap||"none",rescaleMin:n._rescaleMin??0,rescaleMax:n._rescaleMax??255,nodata:n._nodata,opacity:n.opacity??1});return e}},XO={position:"bottom-left",className:"",visible:!0,collapsed:!1,width:250,height:180,zoomOffset:-5,style:"https://basemaps.cartocdn.com/gl/positron-gl-style/style.json",viewportRectColor:"#0078d7",viewportRectOpacity:.2,toggleable:!0,interactive:!1,minzoom:0,maxzoom:24},ZO='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><rect x="7" y="7" width="10" height="10" rx="1" stroke-dasharray="2 2"/></svg>',jf="maplibre-minimap-viewport",JO="maplibre-minimap-viewport-fill",KO="maplibre-minimap-viewport-line",r2=class{_container;_button;_panel;_options;_state;_eventHandlers=new Map;_map;_minimapMap;_handleMove;_handleZoom;_zoomVisible=!0;_isDragging=!1;_dragStartLngLat;_dragCleanup;constructor(e){this._options={...XO,...e},this._state={visible:this._options.visible,collapsed:this._options.collapsed}}getDefaultPosition(){return this._options.position}onAdd(e){return this._map=e,this._container=this._createContainer(),this._handleZoom=()=>this._checkZoomVisibility(),this._map.on("zoom",this._handleZoom),this._state.collapsed||this._showPanel(),this._state.visible||(this._container.style.display="none"),this._container}onRemove(){this._dragCleanup&&(this._dragCleanup(),this._dragCleanup=void 0),this._isDragging=!1,this._dragStartLngLat=void 0,this._minimapMap&&(this._minimapMap.remove(),this._minimapMap=void 0),this._map&&this._handleMove&&this._map.off("move",this._handleMove),this._map&&this._handleZoom&&this._map.off("zoom",this._handleZoom),this._container?.parentNode&&this._container.parentNode.removeChild(this._container),this._container=void 0,this._button=void 0,this._panel=void 0,this._map=void 0}on(e,t){return this._eventHandlers.has(e)||this._eventHandlers.set(e,new Set),this._eventHandlers.get(e).add(t),this}off(e,t){return this._eventHandlers.get(e)?.delete(t),this}_emit(e){const t=this._eventHandlers.get(e);if(t){const n={type:e,state:this.getState()};t.forEach(i=>i(n))}}_createContainer(){const e=document.createElement("div");return e.classList.add("maplibregl-ctrl","maplibre-gl-minimap-control"),this._options.className&&e.classList.add(this._options.className),this._options.toggleable&&(this._button=document.createElement("button"),this._button.type="button",this._button.className="minimap-button",this._button.title="Toggle minimap",this._button.innerHTML=ZO,this._button.addEventListener("click",()=>this.toggle()),e.appendChild(this._button)),e}_showPanel(){if(!this._container||!this._map||this._panel)return;this._panel=document.createElement("div"),this._panel.className="minimap-panel",this._panel.style.width=`${this._options.width}px`,this._panel.style.height=`${this._options.height}px`;const e=document.createElement("div");e.className="minimap-map",this._panel.appendChild(e),this._container.appendChild(this._panel);const t=this._map.getCenter(),n=this._map.getZoom(),i=Math.max(0,n+this._options.zoomOffset);if(this._minimapMap=new fi.default.Map({container:e,style:this._options.style,center:t,zoom:i,interactive:!1,attributionControl:!1}),this._minimapMap.on("load",()=>{this._addViewportRect(),this._updateViewportRect()}),this._handleMove=()=>{this._isDragging||(this._syncMinimap(),this._updateViewportRect())},this._map.on("move",this._handleMove),this._options.interactive&&this._minimapMap){const s=this._minimapMap._canvas;s.style.cursor="pointer";let r=null,a=!1,o=null;const l=d=>{if(!this._minimapMap||!this._map)return;d.preventDefault(),this._isDragging=!0,a=!1,r={x:d.clientX,y:d.clientY},s.style.cursor="grabbing";const f=s.getBoundingClientRect(),m=d.clientX-f.left,A=d.clientY-f.top;this._dragStartLngLat=this._minimapMap.unproject([m,A]),o=this._map.getCenter()},c=d=>{if(!this._isDragging||!this._minimapMap||!this._map||!this._dragStartLngLat||!o)return;if(r&&!a){const b=d.clientX-r.x,w=d.clientY-r.y;(Math.abs(b)>3||Math.abs(w)>3)&&(a=!0)}if(!a)return;const f=s.getBoundingClientRect(),m=d.clientX-f.left,A=d.clientY-f.top,y=this._minimapMap.unproject([m,A]),x=y.lng-this._dragStartLngLat.lng,v=y.lat-this._dragStartLngLat.lat;this._map.setCenter([o.lng+x,o.lat+v]),this._updateViewportRect()},h=d=>{if(this._isDragging&&!a&&this._minimapMap&&this._map){const f=s.getBoundingClientRect(),m=d.clientX-f.left,A=d.clientY-f.top,y=this._minimapMap.unproject([m,A]);this._map.flyTo({center:y})}this._isDragging=!1,a=!1,r=null,o=null,this._dragStartLngLat=void 0,s.style.cursor="pointer",this._syncMinimap(),this._updateViewportRect()};s.addEventListener("mousedown",l),document.addEventListener("mousemove",c),document.addEventListener("mouseup",h),this._dragCleanup=()=>{s.removeEventListener("mousedown",l),document.removeEventListener("mousemove",c),document.removeEventListener("mouseup",h)}}}_hidePanel(){this._dragCleanup&&(this._dragCleanup(),this._dragCleanup=void 0),this._isDragging=!1,this._dragStartLngLat=void 0,this._minimapMap&&(this._minimapMap.remove(),this._minimapMap=void 0),this._map&&this._handleMove&&(this._map.off("move",this._handleMove),this._handleMove=void 0),this._panel&&(this._panel.remove(),this._panel=void 0)}_syncMinimap(){if(!this._minimapMap||!this._map)return;const e=this._map.getCenter(),t=Math.max(0,this._map.getZoom()+this._options.zoomOffset);this._minimapMap.jumpTo({center:e,zoom:t})}_addViewportRect(){this._minimapMap&&(this._minimapMap.addSource(jf,{type:"geojson",data:{type:"Feature",geometry:{type:"Polygon",coordinates:[[]]},properties:{}}}),this._minimapMap.addLayer({id:JO,type:"fill",source:jf,paint:{"fill-color":this._options.viewportRectColor,"fill-opacity":this._options.viewportRectOpacity}}),this._minimapMap.addLayer({id:KO,type:"line",source:jf,paint:{"line-color":this._options.viewportRectColor,"line-width":2}}))}_updateViewportRect(){if(!this._minimapMap||!this._map)return;const e=this._minimapMap.getSource(jf);if(!e||!("setData"in e))return;const t=this._map.getBounds(),n=t.getSouthWest(),i=t.getNorthEast(),s=t.getNorthWest(),r=t.getSouthEast(),a=[[n.lng,n.lat],[r.lng,r.lat],[i.lng,i.lat],[s.lng,s.lat],[n.lng,n.lat]];e.setData({type:"Feature",geometry:{type:"Polygon",coordinates:[a]},properties:{}})}_checkZoomVisibility(){if(!this._map||!this._container)return;const e=this._map.getZoom(),t=this._zoomVisible;this._zoomVisible=e>=this._options.minzoom&&e<=this._options.maxzoom,t!==this._zoomVisible&&(this._container.style.display=this._zoomVisible&&this._state.visible?"":"none")}show(){return this._state.visible=!0,this._container&&(this._container.style.display=this._zoomVisible?"":"none"),this._emit("show"),this}hide(){return this._state.visible=!1,this._container&&(this._container.style.display="none"),this._emit("hide"),this}expand(){return this._state.collapsed?(this._state.collapsed=!1,this._showPanel(),this._emit("expand"),this):this}collapse(){return this._state.collapsed?this:(this._state.collapsed=!0,this._hidePanel(),this._emit("collapse"),this)}toggle(){return this._state.collapsed?this.expand():this.collapse()}getState(){return{...this._state}}},eU={position:"top-right",className:"",visible:!0,collapsed:!0,defaultMode:"distance",distanceUnit:"kilometers",areaUnit:"square-kilometers",lineColor:"#3b82f6",lineWidth:3,fillColor:"rgba(59, 130, 246, 0.2)",pointColor:"#ef4444",pointRadius:6,showSegments:!0,showTotal:!0,precision:2,panelWidth:240,maxHeight:500,backgroundColor:"",borderRadius:4,opacity:1,fontSize:12,fontColor:"",minzoom:0,maxzoom:24},Xw='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21.3 15.3a2.4 2.4 0 0 1 0 3.4l-2.6 2.6a2.4 2.4 0 0 1-3.4 0L2.7 8.7a2.41 2.41 0 0 1 0-3.4l2.6-2.6a2.41 2.41 0 0 1 3.4 0Z"/><path d="m14.5 12.5 2-2"/><path d="m11.5 9.5 2-2"/><path d="m8.5 6.5 2-2"/><path d="m17.5 15.5 2-2"/></svg>',Zw='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 3v4l-4 0"/><path d="M4 7l16 14"/><path d="M16 21v-4l4 0"/></svg>',Jw='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/></svg>',Kw='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',tU='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>',Xl={meters:{label:"Meters",factor:1},kilometers:{label:"Kilometers",factor:.001},miles:{label:"Miles",factor:621371e-9},feet:{label:"Feet",factor:3.28084},yards:{label:"Yards",factor:1.09361},"nautical-miles":{label:"Nautical Miles",factor:539957e-9}},th={"square-meters":{label:"Square Meters",factor:1},"square-kilometers":{label:"Square Kilometers",factor:1e-6},"square-miles":{label:"Square Miles",factor:3861e-10},hectares:{label:"Hectares",factor:1e-4},acres:{label:"Acres",factor:247105e-9},"square-feet":{label:"Square Feet",factor:10.7639}};function nU(e,t){const i=e.lat*Math.PI/180,s=t.lat*Math.PI/180,r=(t.lat-e.lat)*Math.PI/180,a=(t.lng-e.lng)*Math.PI/180,o=Math.sin(r/2)*Math.sin(r/2)+Math.cos(i)*Math.cos(s)*Math.sin(a/2)*Math.sin(a/2);return 6371e3*(2*Math.atan2(Math.sqrt(o),Math.sqrt(1-o)))}function iU(e){if(e.length<3)return 0;const t=6371e3;let n=0;for(let i=0;i<e.length;i++){const s=(i+1)%e.length,r=e[i].lat*Math.PI/180,a=e[s].lat*Math.PI/180,o=e[i].lng*Math.PI/180,l=e[s].lng*Math.PI/180;n+=(l-o)*(2+Math.sin(r)+Math.sin(a))}return n=Math.abs(n*t*t/2),n}var a2=class{_container;_button;_panel;_options;_state;_eventHandlers=new Map;_map;_handleZoom;_zoomVisible=!0;_sourceId;_lineLayerId;_fillLayerId;_resultValueEl;_resultUnitEl;_segmentListEl;_instructionsEl;_measurementsListEl;_boundClickHandler;_boundMoveHandler;_boundDblClickHandler;_boundKeyHandler;_markers=[];constructor(e){this._options={...eU,...e},this._state={visible:this._options.visible,collapsed:this._options.collapsed,mode:this._options.defaultMode,distanceUnit:this._options.distanceUnit,areaUnit:this._options.areaUnit,isDrawing:!1,currentPoints:[],currentValue:0,currentSegments:[],measurements:[]};const t=Qa("measure");this._sourceId=`${t}-source`,this._lineLayerId=`${t}-line`,this._fillLayerId=`${t}-fill`}onAdd(e){return this._map=e,this._container=this._createContainer(),e.isStyleLoaded()?this._setupMapSources():e.once("styledata",()=>this._setupMapSources()),this._setupZoomHandler(),this._state.collapsed||this._showPanel(),this._container}onRemove(){this._stopDrawing(),this._cleanupMapSources(),this._clearMarkers(),this._handleZoom&&this._map&&this._map.off("zoom",this._handleZoom),this._container?.remove(),this._container=void 0,this._map=void 0}getDefaultPosition(){return this._options.position}on(e,t){return this._eventHandlers.has(e)||this._eventHandlers.set(e,new Set),this._eventHandlers.get(e).add(t),this}off(e,t){return this._eventHandlers.get(e)?.delete(t),this}_emit(e,t){const n=this._eventHandlers.get(e);if(n){const i={type:e,state:{...this._state},...t};n.forEach(s=>s(i))}}_createContainer(){const e=document.createElement("div");return e.className=`maplibregl-ctrl maplibre-gl-measure-control ${this._options.className}`,e.style.opacity=String(this._options.opacity),this._state.visible||(e.style.display="none"),this._button=document.createElement("button"),this._button.type="button",this._button.className="measure-button",this._button.title="Measure distances and areas",this._button.innerHTML=Xw,this._button.addEventListener("click",()=>this._togglePanel()),e.appendChild(this._button),e}_createPanel(){const e=document.createElement("div");e.className=`measure-panel ${this._options.position.includes("left")?"right":"left"}`,e.style.width=`${this._options.panelWidth}px`,this._options.maxHeight&&this._options.maxHeight>0&&(e.style.maxHeight=`${this._options.maxHeight}px`,e.style.overflowY="auto"),this._options.backgroundColor&&(e.style.background=this._options.backgroundColor),e.style.borderRadius=`${this._options.borderRadius}px`,e.style.fontSize=`${this._options.fontSize}px`,this._options.fontColor&&(e.style.color=this._options.fontColor);const t=document.createElement("div");t.className="measure-header",t.innerHTML=`
106
+ `},uniformTypes:{minVal:"f32",maxVal:"f32",isSingleBand:"f32"},getUniforms:e=>({minVal:e.minVal,maxVal:e.maxVal,isSingleBand:e.isSingleBand})};function s2(e,t){return e&&(Array.isArray(e)?e.map(n=>s2(n,t)):typeof e.clone=="function"?e.clone({opacity:t}):e)}function QO(e,t){return Array.isArray(e)?t(e):e&&Array.isArray(e.renderPipeline)?{...e,renderPipeline:t(e.renderPipeline)}:e}function GO(e){let t=e.replace("#","");return t.length===3&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]}function HO(e){const n=new Uint8ClampedArray(1024),i=e.map(s=>({pos:s.position,rgb:GO(s.color)}));for(let s=0;s<256;s++){const r=s/255;let a=i[0],o=i[i.length-1];for(let h=0;h<i.length-1;h++)if(r>=i[h].pos&&r<=i[h+1].pos){a=i[h],o=i[h+1];break}const l=o.pos-a.pos,c=l>0?(r-a.pos)/l:0;n[s*4]=a.rgb[0]+(o.rgb[0]-a.rgb[0])*c,n[s*4+1]=a.rgb[1]+(o.rgb[1]-a.rgb[1])*c,n[s*4+2]=a.rgb[2]+(o.rgb[2]-a.rgb[2])*c,n[s*4+3]=255}return new ImageData(n,256,1)}function $O(e){return e?.[0]===1}function cc(e){return typeof e=="number"}function VO(e,t){return Number.isNaN(t)?Number.isNaN(e):e===t}function Ww(e,t,n){const i=Math.floor(e.length/t),s=new Uint8Array(i);s.fill(255);let r=!1;const a=cc(n);for(let o=0;o<i;o++){const l=o*t;let c=!1,h=a;for(let d=0;d<t;d++){const f=e[l+d];Number.isFinite(f)||(c=!0),a&&h&&!VO(f,n)&&(h=!1)}(c||h)&&(s[o]=0,r=!0)}return r?s:null}function Yw(e,t,n){if(!t||!("set"in e))return;const i=e;for(let s=0;s<t.length;s++){if(t[s]!==0)continue;const r=s*n;for(let a=0;a<n;a++)i[r+a]=0}}function qO(e,t){if(!e)return t;if(!t)return e;const n=new Uint8Array(e.length);for(let i=0;i<e.length;i++)n[i]=e[i]===0||t[i]===0?0:255;return n}function jw(e,t){const n=HO(nr(t));return e.createTexture({data:n.data,dimension:"2d-array",format:"rgba8unorm",width:n.width,height:n.height,depth:1,mipLevels:1,sampler:{minFilter:"linear",magFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",addressModeW:"clamp-to-edge"}})}var WO=["none","bone","bwr","cividis","cool","coolwarm","gray","hot","inferno","jet","magma","ocean","plasma","rainbow","RdBu","RdYlBu","RdYlGn","seismic","spectral","terrain","turbo","viridis"],YO={position:"top-right",className:"",visible:!0,collapsed:!0,beforeId:"",defaultUrl:"",loadDefaultUrl:!1,defaultBands:"1",defaultColormap:"none",defaultRescaleMin:0,defaultRescaleMax:255,defaultNodata:void 0,defaultLayerName:"",defaultOpacity:1,defaultPickable:!0,panelWidth:300,maxHeight:500,backgroundColor:"rgba(255, 255, 255, 0.95)",borderRadius:4,opacity:1,fontSize:13,fontColor:"#333",minzoom:0,maxzoom:24},jO='<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>',j0=class{_container;_button;_panel;_options;_state;_eventHandlers=new Map;_map;_handleZoom;_zoomVisible=!0;_deckOverlay;_cogLayers=new Map;_cogLayerPropsMap=new Map;_layerCounter=0;_activePopup;_mapClickHandler;constructor(e){this._options={...YO,...e},this._state={visible:this._options.visible,collapsed:this._options.collapsed,url:this._options.defaultUrl,bands:this._options.defaultBands,colormap:this._options.defaultColormap,rescaleMin:this._options.defaultRescaleMin,rescaleMax:this._options.defaultRescaleMax,nodata:this._options.defaultNodata,layerName:this._options.defaultLayerName,layerOpacity:this._options.defaultOpacity,pickable:this._options.defaultPickable,hasLayer:!1,layerCount:0,layers:[],loading:!1,error:null,status:null}}onAdd(e){if(this._map=e,this._container=this._createContainer(),this._render(),this._handleZoom=()=>this._checkZoomVisibility(),this._map.on("zoom",this._handleZoom),this._checkZoomVisibility(),this._setupClickHandler(),this._options.loadDefaultUrl&&this._options.defaultUrl){const t=()=>{this._addLayer()};this._map.isStyleLoaded()?setTimeout(t,100):this._map.once("idle",t)}return this._container}onRemove(){if(this._removeLayer(),this._map&&this._handleZoom&&(this._map.off("zoom",this._handleZoom),this._handleZoom=void 0),this._map&&this._mapClickHandler&&(this._map.off("click",this._mapClickHandler),this._mapClickHandler=void 0),this._activePopup&&(this._activePopup.remove(),this._activePopup=void 0),this._deckOverlay&&this._map){try{this._map.removeControl(this._deckOverlay)}catch{}this._deckOverlay=void 0}this._map=void 0,this._container?.parentNode?.removeChild(this._container),this._container=void 0,this._button=void 0,this._panel=void 0,this._eventHandlers.clear()}show(){this._state.visible||(this._state.visible=!0,this._updateDisplayState(),this._emit("show"))}hide(){this._state.visible&&(this._state.visible=!1,this._updateDisplayState(),this._emit("hide"))}expand(){this._state.collapsed&&(this._state.collapsed=!1,this._render(),this._emit("expand"))}collapse(){this._state.collapsed||(this._state.collapsed=!0,this._render(),this._emit("collapse"))}toggle(){this._state.collapsed?this.expand():this.collapse()}getState(){return{...this._state}}update(e){this._options={...this._options,...e},e.visible!==void 0&&(this._state.visible=e.visible),e.collapsed!==void 0&&(this._state.collapsed=e.collapsed),this._render(),this._emit("update")}on(e,t){this._eventHandlers.has(e)||this._eventHandlers.set(e,new Set),this._eventHandlers.get(e).add(t)}off(e,t){this._eventHandlers.get(e)?.delete(t)}async addLayer(e){e&&(this._state.url=e),await this._addLayer()}removeLayer(e){this._removeLayer(e),this._render()}getLayerIds(){return Array.from(this._cogLayers.keys())}getLayerOpacity(e){const t=this._cogLayers.get(e);return!t||!t.props?null:t.props.opacity??1}setLayerOpacity(e,t){const n=this._cogLayers.get(e);if(!n||typeof n.clone!="function")return;const i=Math.max(0,Math.min(1,t)),s=n.clone({opacity:i});this._cogLayers.set(e,s),this._deckOverlay&&this._deckOverlay.setProps({layers:Array.from(this._cogLayers.values())}),this._map&&this._map.triggerRepaint()}getLayerVisibility(e){const t=this.getLayerOpacity(e);return t!==null&&t>0}setLayerVisibility(e,t,n=1){t?this.setLayerOpacity(e,n):this.setLayerOpacity(e,0)}getLayerUrl(e){const t=this._cogLayerPropsMap.get(e);return t?t._sourceUrl??(typeof t.geotiff=="string"?t.geotiff:null):null}_emit(e,t){const n=this._eventHandlers.get(e);if(n){const i={type:e,state:this.getState(),...t};n.forEach(s=>s(i))}}_checkZoomVisibility(){if(!this._map)return;const e=this._map.getZoom(),{minzoom:t,maxzoom:n}=this._options,i=e>=t&&e<=n;i!==this._zoomVisible&&(this._zoomVisible=i,this._updateDisplayState())}_updateDisplayState(){if(!this._container)return;const e=this._state.visible&&this._zoomVisible;this._container.style.display=e?"block":"none"}_createContainer(){const e=document.createElement("div");return e.className=`maplibregl-ctrl maplibre-gl-cog-layer${this._options.className?` ${this._options.className}`:""}`,this._state.visible&&this._zoomVisible||(e.style.display="none"),Object.assign(e.style,{backgroundColor:this._options.backgroundColor,borderRadius:`${this._options.borderRadius}px`,boxShadow:"0 0 0 2px rgba(0, 0, 0, 0.1)"}),this._options.opacity!==1&&(e.style.opacity=String(this._options.opacity)),e}_render(){if(!this._container)return;const e=this._container.querySelector(".maplibre-gl-cog-layer-panel"),t=e?e.scrollTop:0;if(this._container.innerHTML="",this._state.collapsed?this._renderCollapsed():this._renderExpanded(),this._updateDisplayState(),t>0){const n=this._container.querySelector(".maplibre-gl-cog-layer-panel");n&&(n.scrollTop=t)}}_renderCollapsed(){this._container&&(this._button=document.createElement("button"),this._button.type="button",this._button.className=`maplibre-gl-cog-layer-button${this._state.hasLayer?" maplibre-gl-cog-layer-button--active":""}`,this._button.title="COG Layer",this._button.setAttribute("aria-label","COG Layer"),this._button.innerHTML=jO,this._button.addEventListener("click",()=>this.expand()),this._container.appendChild(this._button),this._panel=void 0)}_renderExpanded(){if(!this._container)return;const e=document.createElement("div");e.className="maplibre-gl-cog-layer-panel",e.style.width=`${this._options.panelWidth}px`,this._options.maxHeight&&this._options.maxHeight>0&&(e.style.maxHeight=`${this._options.maxHeight}px`,e.style.overflowY="auto"),this._panel=e;const t=document.createElement("div");t.className="maplibre-gl-cog-layer-header";const n=document.createElement("span");n.className="maplibre-gl-cog-layer-title",n.textContent="COG Layer",t.appendChild(n);const i=document.createElement("button");i.className="maplibre-gl-cog-layer-close",i.innerHTML="&times;",i.title="Close",i.addEventListener("click",()=>this.collapse()),t.appendChild(i),e.appendChild(t);const s=this._createFormGroup("COG URL","url"),r=document.createElement("input");r.type="text",r.className="maplibre-gl-cog-layer-input",r.style.color="#000",r.placeholder="https://example.com/cog.tif",r.value=this._state.url,r.addEventListener("input",()=>{this._state.url=r.value}),s.appendChild(r),e.appendChild(s);const a=this._createFormGroup("Bands (comma-separated)","bands"),o=document.createElement("input");o.type="text",o.className="maplibre-gl-cog-layer-input",o.style.color="#000",o.placeholder="1 or 1,2,3",o.value=this._state.bands,o.addEventListener("input",()=>{this._state.bands=o.value}),a.appendChild(o),e.appendChild(a);const l=this._createFormGroup("Colormap","colormap"),c=document.createElement("select");c.className="maplibre-gl-cog-layer-select",c.style.color="#000";for(const U of WO){const Q=document.createElement("option");Q.value=U,Q.textContent=U,U===this._state.colormap&&(Q.selected=!0),c.appendChild(Q)}c.addEventListener("change",()=>{this._state.colormap=c.value,this._updateColormapPreview()}),l.appendChild(c);const h=document.createElement("div");h.className="maplibre-gl-cog-layer-colormap-preview",h.id="cog-colormap-preview",this._updateColormapPreviewElement(h),l.appendChild(h),e.appendChild(l);const d=document.createElement("div");d.className="maplibre-gl-cog-layer-row";const f=this._createFormGroup("Rescale Min","rescale-min"),m=document.createElement("input");m.type="number",m.className="maplibre-gl-cog-layer-input",m.style.color="#000",m.value=String(this._state.rescaleMin),m.addEventListener("input",()=>{this._state.rescaleMin=Number(m.value)||0}),f.appendChild(m),d.appendChild(f);const A=this._createFormGroup("Rescale Max","rescale-max"),y=document.createElement("input");y.type="number",y.className="maplibre-gl-cog-layer-input",y.style.color="#000",y.value=String(this._state.rescaleMax),y.addEventListener("input",()=>{this._state.rescaleMax=Number(y.value)||0}),A.appendChild(y),d.appendChild(A),e.appendChild(d);const x=this._createFormGroup("Nodata","nodata"),v=document.createElement("input");v.type="number",v.className="maplibre-gl-cog-layer-input",v.style.color="#000",v.placeholder="e.g. 0 or -9999",v.value=this._state.nodata!==void 0?String(this._state.nodata):"",v.addEventListener("input",()=>{this._state.nodata=v.value!==""?Number(v.value):void 0}),x.appendChild(v),e.appendChild(x);const b=this._createFormGroup("Opacity","opacity"),w=document.createElement("div");w.className="maplibre-gl-cog-layer-slider-row";const S=document.createElement("input");S.type="range",S.className="maplibre-gl-cog-layer-slider",S.min="0",S.max="100",S.value=String(Math.round(this._state.layerOpacity*100));const R=document.createElement("span");R.className="maplibre-gl-cog-layer-slider-value",R.textContent=`${Math.round(this._state.layerOpacity*100)}%`,S.addEventListener("input",()=>{const U=Number(S.value);this._state.layerOpacity=U/100,R.textContent=`${U}%`,this._updateOpacity()}),w.appendChild(S),w.appendChild(R),b.appendChild(w),e.appendChild(b);const k=document.createElement("div");k.className="maplibre-gl-cog-layer-form-group maplibre-gl-cog-layer-checkbox-group";const L=document.createElement("label");L.className="maplibre-gl-cog-layer-checkbox-label";const T=document.createElement("input");T.type="checkbox",T.className="maplibre-gl-cog-layer-checkbox",T.checked=this._state.pickable,T.addEventListener("change",()=>{this._state.pickable=T.checked,this._updatePickable()}),L.appendChild(T);const C=document.createElement("span");C.textContent="Pickable (click to show pixel value)",L.appendChild(C),k.appendChild(L),e.appendChild(k);const I=this._createFormGroup("Layer Name","layer-name"),M=document.createElement("input");M.type="text",M.className="maplibre-gl-cog-layer-input",M.style.color="#000",M.placeholder="Optional custom layer name",M.value=this._state.layerName,M.addEventListener("input",()=>{this._state.layerName=M.value}),I.appendChild(M),e.appendChild(I);const O=this._createFormGroup("Before Layer ID (optional)","before-id"),N=document.createElement("input");N.type="text",N.className="maplibre-gl-cog-layer-input",N.style.color="#000",N.placeholder="e.g. labels or water",N.value=this._options.beforeId||"",N.addEventListener("input",()=>{this._options.beforeId=N.value||""}),O.appendChild(N),e.appendChild(O);const D=document.createElement("div");D.className="maplibre-gl-cog-layer-buttons";const P=document.createElement("button");if(P.className="maplibre-gl-cog-layer-btn maplibre-gl-cog-layer-btn--primary",P.textContent="Add Layer",P.disabled=this._state.loading,P.addEventListener("click",()=>this._addLayer()),D.appendChild(P),e.appendChild(D),this._state.loading?this._appendStatus("Loading COG...","info"):this._state.error?this._appendStatus(this._state.error,"error"):this._state.status&&this._appendStatus(this._state.status,"success"),this._cogLayers.size>0){const U=document.createElement("div");U.className="maplibre-gl-cog-layer-list";const Q=document.createElement("div");Q.className="maplibre-gl-cog-layer-list-header",Q.textContent=`Layers (${this._cogLayers.size})`,U.appendChild(Q);for(const[z]of this._cogLayers){const H=this._cogLayerPropsMap.get(z);if(!H)continue;const W=document.createElement("div");W.className="maplibre-gl-cog-layer-list-item";const te=document.createElement("span");te.className="maplibre-gl-cog-layer-list-label";const J=H._sourceUrl??(typeof H.geotiff=="string"?H.geotiff:""),K=H._layerName;let re;if(K)re=K;else try{re=new URL(J).pathname.split("/").pop()||J}catch{re=J}te.textContent=re,te.title=J,W.appendChild(te);const ce=document.createElement("button");ce.className="maplibre-gl-cog-layer-list-remove",ce.innerHTML="&times;",ce.title="Remove layer",ce.addEventListener("click",()=>{this._removeLayer(z),this._render()}),W.appendChild(ce),U.appendChild(W)}e.appendChild(U)}this._container.appendChild(e),this._button=void 0}_createFormGroup(e,t){const n=document.createElement("div");n.className="maplibre-gl-cog-layer-form-group";const i=document.createElement("label");return i.textContent=e,i.htmlFor=`cog-layer-${t}`,n.appendChild(i),n}_appendStatus(e,t){if(!this._panel)return;const n=document.createElement("div");n.className=`maplibre-gl-cog-layer-status maplibre-gl-cog-layer-status--${t}`,n.textContent=e,this._panel.appendChild(n)}_updateColormapPreview(){const e=document.getElementById("cog-colormap-preview");e&&this._updateColormapPreviewElement(e)}_updateColormapPreviewElement(e){if(this._state.colormap==="none")e.style.background="linear-gradient(to right, #888, #888)",e.style.display="none";else{const t=nr(this._state.colormap).map(n=>n.color).join(", ");e.style.background=`linear-gradient(to right, ${t})`,e.style.display="block"}}async _ensureOverlay(){if(this._deckOverlay||!this._map)return;const{MapboxOverlay:e}=await import("@deck.gl/mapbox");this._deckOverlay=new e({interleaved:!!this._options.beforeId,layers:[]}),this._map.addControl(this._deckOverlay)}_setupClickHandler(){if(!this._map||this._mapClickHandler)return;const e=this._map;this._mapClickHandler=t=>{if(!this._state.pickable||this._cogLayers.size===0)return;this._activePopup&&this._activePopup.remove();const{lngLat:n}=t,i=Array.from(this._cogLayers.keys()),s=this._cogLayerPropsMap.get(i[0]);let r='<div class="maplibre-gl-cog-layer-popup">';r+='<table class="maplibre-gl-cog-layer-popup-table">',r+=`<tr><td><strong>Layers</strong></td><td>${i.length} COG layer(s)</td></tr>`,r+=`<tr><td><strong>Lng</strong></td><td>${n.lng.toFixed(6)}</td></tr>`,r+=`<tr><td><strong>Lat</strong></td><td>${n.lat.toFixed(6)}</td></tr>`,s&&(r+=`<tr><td><strong>Rescale</strong></td><td>${s._rescaleMin} - ${s._rescaleMax}</td></tr>`,s._colormap&&s._colormap!=="none"&&(r+=`<tr><td><strong>Colormap</strong></td><td>${s._colormap}</td></tr>`)),r+="</table>",r+="</div>",this._activePopup=new fi.default.Popup({closeButton:!0,maxWidth:"280px"}).setLngLat(n).setHTML(r).addTo(e);const a=this._activePopup.getElement();a&&(a.style.zIndex="1000")},e.on("click",this._mapClickHandler)}_updatePickable(){if(this._deckOverlay){for(const[,e]of this._cogLayerPropsMap)e.pickable=this._state.pickable;this._rebuildLayers()}}async _rebuildLayers(){if(this._deckOverlay)try{const{COGLayer:e}=await import("@developmentseed/deck.gl-geotiff");this._patchCOGLayerForFloat(e),this._patchCOGLayerForOpacity(e);const t=[];for(const[n,i]of this._cogLayerPropsMap){const s=new e(i);this._cogLayers.set(n,s),t.push(s)}this._deckOverlay.setProps({layers:t})}catch(e){console.error("Failed to rebuild layers:",e)}}async _registerCommonProjections(e){e.defs("EPSG:3978","+proj=lcc +lat_0=49 +lon_0=-95 +lat_1=49 +lat_2=77 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs +type=crs"),e.defs("EPSG:3979","+proj=lcc +lat_0=49 +lon_0=-95 +lat_1=49 +lat_2=77 +x_0=0 +y_0=0 +ellps=GRS80 +towgs84=-0.991,1.9072,0.5129,-1.25033e-07,-4.6785e-08,-5.6529e-08,0 +units=m +no_defs +type=crs")}_buildGeoKeysParser(e){let t=null;return Promise.resolve().then(()=>require("./lib-B4jvG7hB.cjs")).then(n=>{t=n.default||n,typeof t=="function"&&this._registerCommonProjections(t)}),async n=>{try{const i=e.toProj4(n);if(i&&i.proj4){let s=i.proj4;if(s=s.replace(/\+axis=\w+\s*/g,""),!t){const a=await Promise.resolve().then(()=>require("./lib-B4jvG7hB.cjs"));t=a.default||a,typeof t=="function"&&await this._registerCommonProjections(t)}let r={};if(typeof t=="function")try{t.defs("custom",s),r=t.defs("custom")||{}}catch{}return{def:s,parsed:r,coordinatesUnits:i.coordinatesUnits||"metre"}}}catch{}return null}}_patchCOGLayerForFloat(e){if(e.__floatPatched)return;e.__floatPatched=!0;const t=e.prototype._parseGeoTIFF;e.prototype._parseGeoTIFF=async function(){try{await t.call(this);const n=this.props._nodata;if(n!=null&&!isNaN(n)){const{FilterNoDataVal:i}=await import("@developmentseed/deck.gl-raster/gpu-modules"),s=this.state.defaultRenderTile;if(typeof s=="function"){const r=a=>QO(s(a),o=>{const l=o.filter(c=>c.module!==i);return l.splice(1,0,{module:i,props:{value:n}}),l});this.setState({defaultRenderTile:r})}}}catch(n){if(!(n instanceof Error?n.message:String(n)).includes("non-unsigned integers not yet supported"))throw n;const{parseCOGTileMatrixSet:i,texture:s}=await import("@developmentseed/deck.gl-geotiff");if(typeof i!="function"||typeof s?.inferTextureFormat!="function")throw n;const{fromUrl:r}=await Promise.resolve().then(()=>require("./geotiff-DnbYMY3e.cjs")),{CreateTexture:a,FilterNoDataVal:o,MaskTexture:l}=await import("@developmentseed/deck.gl-raster/gpu-modules"),c=await Promise.resolve().then(()=>require("./lib-B4jvG7hB.cjs")),h=c.default||c,d=this.props.geotiff,f=typeof d=="string"?await r(d):d,m=this.props.geoKeysParser,A=await i(f,m),y=await f.getImage(),x=await f.getImageCount(),v=[];for(let Q=0;Q<x;Q++)v.push(await f.getImage(Q));const b=await m(y.getGeoKeys());if(!b)throw new Error("Could not determine source projection from GeoTIFF geo keys");const w=h(b.def,"EPSG:4326"),S=(Q,z)=>w.forward([Q,z],!1),R=(Q,z)=>w.inverse([Q,z],!1);if(this.props.onGeoTIFFLoad){const Q=y.getBoundingBox(),z=[w.forward([Q[0],Q[1]]),w.forward([Q[2],Q[1]]),w.forward([Q[2],Q[3]]),w.forward([Q[0],Q[3]])],H=z.map(J=>J[0]),W=z.map(J=>J[1]),te={west:Math.min(...H),south:Math.min(...W),east:Math.max(...H),north:Math.max(...W)};this.props.onGeoTIFFLoad(f,{projection:b,geographicBounds:te})}const{BitsPerSample:k,SampleFormat:L,SamplesPerPixel:T,GDAL_NODATA:C}=y.getFileDirectory();let I=null;if(C){const Q=C[C.length-1]==="\0"?C.slice(0,-1):C;Q.length>0&&(I=parseFloat(Q))}const M=this,O=async(Q,z)=>{const{device:H}=z,W=await Q.readRasters({...z,interleave:!0});let te=W,J=T;const K=cc(M.props._nodata)?M.props._nodata:I,re=Ww(te,J,cc(K)?K:void 0);if(Yw(te,re,J),T===3){const ie=W.width*W.height,fe=new Float32Array(ie*4);for(let ye=0;ye<ie;ye++)fe[ye*4]=W[ye*3],fe[ye*4+1]=W[ye*3+1],fe[ye*4+2]=W[ye*3+2],fe[ye*4+3]=1;te=fe,te.width=W.width,te.height=W.height,J=4}const ce=s.inferTextureFormat(J,k,L),oe=H.createTexture({data:te,format:ce,width:W.width,height:W.height,sampler:{magFilter:"nearest",minFilter:"nearest"}});let ge;return re&&(ge=H.createTexture({data:re,format:"r8unorm",width:W.width,height:W.height,sampler:{magFilter:"nearest",minFilter:"nearest"}})),{texture:oe,height:W.height,mask:ge,width:W.width}};let N=null,D=null;const{Colormap:P}=await import("@developmentseed/deck.gl-raster/gpu-modules"),U=Q=>{const z=[{module:a,props:{textureName:Q.texture}}];Q.mask&&z.push({module:l,props:{maskTexture:Q.mask}});const H=M.props._nodata!==void 0&&M.props._nodata!==null&&!isNaN(M.props._nodata)?M.props._nodata:I;cc(H)&&!Number.isNaN(H)&&z.push({module:o,props:{value:H}});const W=M.props._rescaleMin??0,te=M.props._rescaleMax??255;z.push({module:qw,props:{minVal:W,maxVal:te,isSingleBand:T===1?1:0}});const J=M.props._colormap;return J&&J!=="none"&&(J!==N&&(D=jw(M.context.device,J),N=J),z.push({module:P,props:{colormapTexture:D}})),{renderPipeline:z}};this.setState({metadata:A,forwardReproject:S,inverseReproject:R,images:v,defaultGetTileData:O,defaultRenderTile:U})}}}_patchCOGLayerForOpacity(e){if(e.__opacityPatched)return;e.__opacityPatched=!0;const t=e.prototype._renderSubLayers;e.prototype._renderSubLayers=function(...n){const i=t.apply(this,n),s=this.props.opacity;return s==null?i:s2(i,Math.max(0,Math.min(1,s)))}}async _createFloatCogLayerProps(e){const{GeoTIFF:t}=await import("@developmentseed/geotiff"),n=await t.fromUrl(e);if($O(n.cachedTags.sampleFormat))return{geotiff:n};const{texture:i}=await import("@developmentseed/deck.gl-geotiff"),{CreateTexture:s,FilterNoDataVal:r,MaskTexture:a,Colormap:o}=await import("@developmentseed/deck.gl-raster/gpu-modules"),l=this._state.colormap,c=this._state.nodata,h=this._state.rescaleMax,d=this._state.rescaleMin,f=async(x,v)=>{const{device:b,pool:w,signal:S,x:R,y:k}=v,{array:L}=await x.fetchTile(R,k,{boundless:!1,pool:w,signal:S});if(L.layout==="band-separate")throw new Error("Band-separate images are not yet implemented.");const T=x.cachedTags;let C=L.data,I=T.samplesPerPixel,M=T.bitsPerSample,O=T.sampleFormat;const N=cc(c)?c:T.nodata;C instanceof Float64Array&&(C=new Float32Array(C),M=Array.from({length:I},()=>32));const D=Ww(C,I,cc(N)?N:void 0);if(Yw(C,D,I),I===3){const W=L.width*L.height,te=new Float32Array(W*4);for(let J=0;J<W;J++)te[J*4]=C[J*3],te[J*4+1]=C[J*3+1],te[J*4+2]=C[J*3+2],te[J*4+3]=1;C=te,I=4,M=[32,32,32,32],O=[3,3,3,3]}const P=i.inferTextureFormat(I,M,O);let U=C.byteLength;const Q=b.createTexture({data:C,format:P,width:L.width,height:L.height,sampler:{magFilter:"nearest",minFilter:"nearest"}});let z;const H=qO(L.mask,D);return H&&(z=b.createTexture({data:H,format:"r8unorm",width:L.width,height:L.height,sampler:{magFilter:"nearest",minFilter:"nearest"}}),U+=H.byteLength),{byteLength:U,device:b,height:L.height,mask:z,nodata:N,samplesPerPixel:I,texture:Q,width:L.width}};let m=null,A=null;return{geotiff:n,getTileData:f,renderTile:x=>{const v=[{module:s,props:{textureName:x.texture}}];x.mask&&v.push({module:a,props:{maskTexture:x.mask}});const b=x.nodata;return cc(b)&&!Number.isNaN(b)&&v.push({module:r,props:{value:b}}),v.push({module:qw,props:{minVal:d,maxVal:h,isSingleBand:x.samplesPerPixel===1?1:0}}),l&&l!=="none"&&(m!==l&&(A=jw(x.device,l),m=l),v.push({module:o,props:{colormapTexture:A}})),{renderPipeline:v}}}}async _addLayer(){if(!this._map||!this._state.url){this._state.error="Please enter a COG URL.",this._render();return}this._state.loading=!0,this._state.error=null,this._state.status=null,this._render();try{await this._ensureOverlay();const{COGLayer:e}=await import("@developmentseed/deck.gl-geotiff");this._patchCOGLayerForFloat(e),this._patchCOGLayerForOpacity(e);const t=this._map,n=await this._createFloatCogLayerProps(this._state.url),i={geotiff:this._state.url,_sourceUrl:this._state.url,opacity:this._state.layerOpacity,pickable:this._state.pickable,_rescaleMin:this._state.rescaleMin,_rescaleMax:this._state.rescaleMax,_colormap:this._state.colormap,_nodata:this._state.nodata,...n??{},...(()=>{if(this._options.beforeId){if(t.getLayer(this._options.beforeId))return{beforeId:this._options.beforeId};console.warn(`[CogLayerControl] beforeId "${this._options.beforeId}" not found in map layers, adding layer on top`)}return{}})(),onGeoTIFFLoad:(o,l)=>{try{if(l&&l.geographicBounds){const{west:c,south:h,east:d,north:f}=l.geographicBounds;t.fitBounds([[c,h],[d,f]],{padding:50,duration:1e3})}}catch{}}};try{const o=await Promise.resolve().then(()=>require("./main-dist-DOx_Axbx.cjs")),l=o.default||o;l&&typeof l.toProj4=="function"&&(i.geoKeysParser=this._buildGeoKeysParser(l))}catch{}const s=`cog-layer-${this._layerCounter++}`;i.id=s;const r=this._state.layerName?.trim();r&&(i._layerName=r),this._cogLayerPropsMap.set(s,i);const a=new e(i);this._cogLayers.set(s,a),this._deckOverlay.setProps({layers:Array.from(this._cogLayers.values())}),this._state.hasLayer=this._cogLayers.size>0,this._state.layerCount=this._cogLayers.size,this._state.layers=this._buildLayerInfoList(),this._state.loading=!1,this._state.status="COG layer added successfully.",this._state.layerName="",this._render(),this._emit("layeradd",{url:this._state.url,layerId:s})}catch(e){this._state.loading=!1,this._state.error=`Failed to load COG: ${e instanceof Error?e.message:String(e)}`,this._render(),this._emit("error",{error:this._state.error})}}_removeLayer(e){e?(this._cogLayers.delete(e),this._cogLayerPropsMap.delete(e),this._deckOverlay&&this._deckOverlay.setProps({layers:Array.from(this._cogLayers.values())}),this._state.hasLayer=this._cogLayers.size>0,this._state.layerCount=this._cogLayers.size,this._state.layers=this._buildLayerInfoList(),this._state.status=null,this._state.error=null,this._emit("layerremove",{layerId:e})):(this._deckOverlay&&this._deckOverlay.setProps({layers:[]}),this._cogLayers.clear(),this._cogLayerPropsMap.clear(),this._state.hasLayer=!1,this._state.layerCount=0,this._state.layers=[],this._state.status=null,this._state.error=null,this._emit("layerremove"))}_updateOpacity(){if(!this._deckOverlay||this._cogLayers.size===0)return;const e=this._state.layerOpacity;for(const[t,n]of this._cogLayers)typeof n.clone=="function"&&this._cogLayers.set(t,n.clone({opacity:e}));this._deckOverlay.setProps({layers:Array.from(this._cogLayers.values())}),this._map&&this._map.triggerRepaint()}_buildLayerInfoList(){const e=[];for(const[t,n]of this._cogLayerPropsMap)e.push({id:t,name:n._layerName||void 0,url:n._sourceUrl??(typeof n.geotiff=="string"?n.geotiff:""),bands:"1",colormap:n._colormap||"none",rescaleMin:n._rescaleMin??0,rescaleMax:n._rescaleMax??255,nodata:n._nodata,opacity:n.opacity??1});return e}},XO={position:"bottom-left",className:"",visible:!0,collapsed:!1,width:250,height:180,zoomOffset:-5,style:"https://basemaps.cartocdn.com/gl/positron-gl-style/style.json",viewportRectColor:"#0078d7",viewportRectOpacity:.2,toggleable:!0,interactive:!1,minzoom:0,maxzoom:24},ZO='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><rect x="7" y="7" width="10" height="10" rx="1" stroke-dasharray="2 2"/></svg>',jf="maplibre-minimap-viewport",JO="maplibre-minimap-viewport-fill",KO="maplibre-minimap-viewport-line",r2=class{_container;_button;_panel;_options;_state;_eventHandlers=new Map;_map;_minimapMap;_handleMove;_handleZoom;_zoomVisible=!0;_isDragging=!1;_dragStartLngLat;_dragCleanup;constructor(e){this._options={...XO,...e},this._state={visible:this._options.visible,collapsed:this._options.collapsed}}getDefaultPosition(){return this._options.position}onAdd(e){return this._map=e,this._container=this._createContainer(),this._handleZoom=()=>this._checkZoomVisibility(),this._map.on("zoom",this._handleZoom),this._state.collapsed||this._showPanel(),this._state.visible||(this._container.style.display="none"),this._container}onRemove(){this._dragCleanup&&(this._dragCleanup(),this._dragCleanup=void 0),this._isDragging=!1,this._dragStartLngLat=void 0,this._minimapMap&&(this._minimapMap.remove(),this._minimapMap=void 0),this._map&&this._handleMove&&this._map.off("move",this._handleMove),this._map&&this._handleZoom&&this._map.off("zoom",this._handleZoom),this._container?.parentNode&&this._container.parentNode.removeChild(this._container),this._container=void 0,this._button=void 0,this._panel=void 0,this._map=void 0}on(e,t){return this._eventHandlers.has(e)||this._eventHandlers.set(e,new Set),this._eventHandlers.get(e).add(t),this}off(e,t){return this._eventHandlers.get(e)?.delete(t),this}_emit(e){const t=this._eventHandlers.get(e);if(t){const n={type:e,state:this.getState()};t.forEach(i=>i(n))}}_createContainer(){const e=document.createElement("div");return e.classList.add("maplibregl-ctrl","maplibre-gl-minimap-control"),this._options.className&&e.classList.add(this._options.className),this._options.toggleable&&(this._button=document.createElement("button"),this._button.type="button",this._button.className="minimap-button",this._button.title="Toggle minimap",this._button.innerHTML=ZO,this._button.addEventListener("click",()=>this.toggle()),e.appendChild(this._button)),e}_showPanel(){if(!this._container||!this._map||this._panel)return;this._panel=document.createElement("div"),this._panel.className="minimap-panel",this._panel.style.width=`${this._options.width}px`,this._panel.style.height=`${this._options.height}px`;const e=document.createElement("div");e.className="minimap-map",this._panel.appendChild(e),this._container.appendChild(this._panel);const t=this._map.getCenter(),n=this._map.getZoom(),i=Math.max(0,n+this._options.zoomOffset);if(this._minimapMap=new fi.default.Map({container:e,style:this._options.style,center:t,zoom:i,interactive:!1,attributionControl:!1}),this._minimapMap.on("load",()=>{this._addViewportRect(),this._updateViewportRect()}),this._handleMove=()=>{this._isDragging||(this._syncMinimap(),this._updateViewportRect())},this._map.on("move",this._handleMove),this._options.interactive&&this._minimapMap){const s=this._minimapMap._canvas;s.style.cursor="pointer";let r=null,a=!1,o=null;const l=d=>{if(!this._minimapMap||!this._map)return;d.preventDefault(),this._isDragging=!0,a=!1,r={x:d.clientX,y:d.clientY},s.style.cursor="grabbing";const f=s.getBoundingClientRect(),m=d.clientX-f.left,A=d.clientY-f.top;this._dragStartLngLat=this._minimapMap.unproject([m,A]),o=this._map.getCenter()},c=d=>{if(!this._isDragging||!this._minimapMap||!this._map||!this._dragStartLngLat||!o)return;if(r&&!a){const b=d.clientX-r.x,w=d.clientY-r.y;(Math.abs(b)>3||Math.abs(w)>3)&&(a=!0)}if(!a)return;const f=s.getBoundingClientRect(),m=d.clientX-f.left,A=d.clientY-f.top,y=this._minimapMap.unproject([m,A]),x=y.lng-this._dragStartLngLat.lng,v=y.lat-this._dragStartLngLat.lat;this._map.setCenter([o.lng+x,o.lat+v]),this._updateViewportRect()},h=d=>{if(this._isDragging&&!a&&this._minimapMap&&this._map){const f=s.getBoundingClientRect(),m=d.clientX-f.left,A=d.clientY-f.top,y=this._minimapMap.unproject([m,A]);this._map.flyTo({center:y})}this._isDragging=!1,a=!1,r=null,o=null,this._dragStartLngLat=void 0,s.style.cursor="pointer",this._syncMinimap(),this._updateViewportRect()};s.addEventListener("mousedown",l),document.addEventListener("mousemove",c),document.addEventListener("mouseup",h),this._dragCleanup=()=>{s.removeEventListener("mousedown",l),document.removeEventListener("mousemove",c),document.removeEventListener("mouseup",h)}}}_hidePanel(){this._dragCleanup&&(this._dragCleanup(),this._dragCleanup=void 0),this._isDragging=!1,this._dragStartLngLat=void 0,this._minimapMap&&(this._minimapMap.remove(),this._minimapMap=void 0),this._map&&this._handleMove&&(this._map.off("move",this._handleMove),this._handleMove=void 0),this._panel&&(this._panel.remove(),this._panel=void 0)}_syncMinimap(){if(!this._minimapMap||!this._map)return;const e=this._map.getCenter(),t=Math.max(0,this._map.getZoom()+this._options.zoomOffset);this._minimapMap.jumpTo({center:e,zoom:t})}_addViewportRect(){this._minimapMap&&(this._minimapMap.addSource(jf,{type:"geojson",data:{type:"Feature",geometry:{type:"Polygon",coordinates:[[]]},properties:{}}}),this._minimapMap.addLayer({id:JO,type:"fill",source:jf,paint:{"fill-color":this._options.viewportRectColor,"fill-opacity":this._options.viewportRectOpacity}}),this._minimapMap.addLayer({id:KO,type:"line",source:jf,paint:{"line-color":this._options.viewportRectColor,"line-width":2}}))}_updateViewportRect(){if(!this._minimapMap||!this._map)return;const e=this._minimapMap.getSource(jf);if(!e||!("setData"in e))return;const t=this._map.getBounds(),n=t.getSouthWest(),i=t.getNorthEast(),s=t.getNorthWest(),r=t.getSouthEast(),a=[[n.lng,n.lat],[r.lng,r.lat],[i.lng,i.lat],[s.lng,s.lat],[n.lng,n.lat]];e.setData({type:"Feature",geometry:{type:"Polygon",coordinates:[a]},properties:{}})}_checkZoomVisibility(){if(!this._map||!this._container)return;const e=this._map.getZoom(),t=this._zoomVisible;this._zoomVisible=e>=this._options.minzoom&&e<=this._options.maxzoom,t!==this._zoomVisible&&(this._container.style.display=this._zoomVisible&&this._state.visible?"":"none")}show(){return this._state.visible=!0,this._container&&(this._container.style.display=this._zoomVisible?"":"none"),this._emit("show"),this}hide(){return this._state.visible=!1,this._container&&(this._container.style.display="none"),this._emit("hide"),this}expand(){return this._state.collapsed?(this._state.collapsed=!1,this._showPanel(),this._emit("expand"),this):this}collapse(){return this._state.collapsed?this:(this._state.collapsed=!0,this._hidePanel(),this._emit("collapse"),this)}toggle(){return this._state.collapsed?this.expand():this.collapse()}getState(){return{...this._state}}},eU={position:"top-right",className:"",visible:!0,collapsed:!0,defaultMode:"distance",distanceUnit:"kilometers",areaUnit:"square-kilometers",lineColor:"#3b82f6",lineWidth:3,fillColor:"rgba(59, 130, 246, 0.2)",pointColor:"#ef4444",pointRadius:6,showSegments:!0,showTotal:!0,precision:2,panelWidth:240,maxHeight:500,backgroundColor:"",borderRadius:4,opacity:1,fontSize:12,fontColor:"",minzoom:0,maxzoom:24},Xw='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21.3 15.3a2.4 2.4 0 0 1 0 3.4l-2.6 2.6a2.4 2.4 0 0 1-3.4 0L2.7 8.7a2.41 2.41 0 0 1 0-3.4l2.6-2.6a2.41 2.41 0 0 1 3.4 0Z"/><path d="m14.5 12.5 2-2"/><path d="m11.5 9.5 2-2"/><path d="m8.5 6.5 2-2"/><path d="m17.5 15.5 2-2"/></svg>',Zw='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 3v4l-4 0"/><path d="M4 7l16 14"/><path d="M16 21v-4l4 0"/></svg>',Jw='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/></svg>',Kw='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',tU='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>',Xl={meters:{label:"Meters",factor:1},kilometers:{label:"Kilometers",factor:.001},miles:{label:"Miles",factor:621371e-9},feet:{label:"Feet",factor:3.28084},yards:{label:"Yards",factor:1.09361},"nautical-miles":{label:"Nautical Miles",factor:539957e-9}},th={"square-meters":{label:"Square Meters",factor:1},"square-kilometers":{label:"Square Kilometers",factor:1e-6},"square-miles":{label:"Square Miles",factor:3861e-10},hectares:{label:"Hectares",factor:1e-4},acres:{label:"Acres",factor:247105e-9},"square-feet":{label:"Square Feet",factor:10.7639}};function nU(e,t){const i=e.lat*Math.PI/180,s=t.lat*Math.PI/180,r=(t.lat-e.lat)*Math.PI/180,a=(t.lng-e.lng)*Math.PI/180,o=Math.sin(r/2)*Math.sin(r/2)+Math.cos(i)*Math.cos(s)*Math.sin(a/2)*Math.sin(a/2);return 6371e3*(2*Math.atan2(Math.sqrt(o),Math.sqrt(1-o)))}function iU(e){if(e.length<3)return 0;const t=6371e3;let n=0;for(let i=0;i<e.length;i++){const s=(i+1)%e.length,r=e[i].lat*Math.PI/180,a=e[s].lat*Math.PI/180,o=e[i].lng*Math.PI/180,l=e[s].lng*Math.PI/180;n+=(l-o)*(2+Math.sin(r)+Math.sin(a))}return n=Math.abs(n*t*t/2),n}var a2=class{_container;_button;_panel;_options;_state;_eventHandlers=new Map;_map;_handleZoom;_zoomVisible=!0;_sourceId;_lineLayerId;_fillLayerId;_resultValueEl;_resultUnitEl;_segmentListEl;_instructionsEl;_measurementsListEl;_boundClickHandler;_boundMoveHandler;_boundDblClickHandler;_boundKeyHandler;_markers=[];constructor(e){this._options={...eU,...e},this._state={visible:this._options.visible,collapsed:this._options.collapsed,mode:this._options.defaultMode,distanceUnit:this._options.distanceUnit,areaUnit:this._options.areaUnit,isDrawing:!1,currentPoints:[],currentValue:0,currentSegments:[],measurements:[]};const t=Qa("measure");this._sourceId=`${t}-source`,this._lineLayerId=`${t}-line`,this._fillLayerId=`${t}-fill`}onAdd(e){return this._map=e,this._container=this._createContainer(),e.isStyleLoaded()?this._setupMapSources():e.once("styledata",()=>this._setupMapSources()),this._setupZoomHandler(),this._state.collapsed||this._showPanel(),this._container}onRemove(){this._stopDrawing(),this._cleanupMapSources(),this._clearMarkers(),this._handleZoom&&this._map&&this._map.off("zoom",this._handleZoom),this._container?.remove(),this._container=void 0,this._map=void 0}getDefaultPosition(){return this._options.position}on(e,t){return this._eventHandlers.has(e)||this._eventHandlers.set(e,new Set),this._eventHandlers.get(e).add(t),this}off(e,t){return this._eventHandlers.get(e)?.delete(t),this}_emit(e,t){const n=this._eventHandlers.get(e);if(n){const i={type:e,state:{...this._state},...t};n.forEach(s=>s(i))}}_createContainer(){const e=document.createElement("div");return e.className=`maplibregl-ctrl maplibre-gl-measure-control ${this._options.className}`,e.style.opacity=String(this._options.opacity),this._state.visible||(e.style.display="none"),this._button=document.createElement("button"),this._button.type="button",this._button.className="measure-button",this._button.title="Measure distances and areas",this._button.innerHTML=Xw,this._button.addEventListener("click",()=>this._togglePanel()),e.appendChild(this._button),e}_createPanel(){const e=document.createElement("div");e.className=`measure-panel ${this._options.position.includes("left")?"right":"left"}`,e.style.width=`${this._options.panelWidth}px`,this._options.maxHeight&&this._options.maxHeight>0&&(e.style.maxHeight=`${this._options.maxHeight}px`,e.style.overflowY="auto"),this._options.backgroundColor&&(e.style.background=this._options.backgroundColor),e.style.borderRadius=`${this._options.borderRadius}px`,e.style.fontSize=`${this._options.fontSize}px`,this._options.fontColor&&(e.style.color=this._options.fontColor);const t=document.createElement("div");t.className="measure-header",t.innerHTML=`
107
107
  <span>Measure</span>
108
108
  <button type="button" class="measure-close" title="Close">${Kw}</button>
109
109
  `,t.querySelector(".measure-close")?.addEventListener("click",()=>this._togglePanel()),e.appendChild(t);const n=document.createElement("div");n.className="measure-content";const i=document.createElement("div");i.className="measure-mode-toggle",i.innerHTML=`
@@ -197,7 +197,7 @@ var iO=Object.create;var Gw=Object.defineProperty;var sO=Object.getOwnPropertyDe
197
197
  <option value="pdf" ${this._state.format==="pdf"?"selected":""}>PDF</option>
198
198
  <option value="svg" ${this._state.format==="svg"?"selected":""}>SVG</option>
199
199
  `,this._formatSelect.addEventListener("change",()=>{this._state.format=this._formatSelect.value,this._updateQualityVisibility(),this._updateCopyBtnVisibility()}),R.appendChild(this._formatSelect),S.appendChild(R),this._qualityField=document.createElement("div"),this._qualityField.className="print-field",this._qualityField.innerHTML="<label>Quality</label>";const k=document.createElement("div");if(k.className="print-quality-wrapper",this._qualityInput=document.createElement("input"),this._qualityInput.type="range",this._qualityInput.className="print-quality-range",this._qualityInput.style.color="var(--print-input-text)",this._qualityInput.min="0.1",this._qualityInput.max="1",this._qualityInput.step="0.01",this._qualityInput.value=String(this._state.quality),this._qualityValue=document.createElement("span"),this._qualityValue.className="print-quality-value",this._qualityValue.textContent=this._state.quality.toFixed(2),this._qualityInput.addEventListener("input",()=>{this._state.quality=parseFloat(this._qualityInput.value),this._qualityValue.textContent=this._state.quality.toFixed(2)}),k.appendChild(this._qualityInput),k.appendChild(this._qualityValue),this._qualityField.appendChild(k),S.appendChild(this._qualityField),n.appendChild(S),this._updateQualityVisibility(),this._options.showSizeOptions){const L=document.createElement("div");L.className="print-field",L.innerHTML="<label>Size</label>";const T=document.createElement("div");T.className="print-size-options";const C=document.createElement("label");C.className="print-radio-label",this._sizeRadioCurrent=document.createElement("input"),this._sizeRadioCurrent.type="radio",this._sizeRadioCurrent.name="print-size",this._sizeRadioCurrent.value="current",this._sizeRadioCurrent.checked=!this._state.width,this._sizeRadioCurrent.addEventListener("change",()=>{this._state.width=null,this._state.height=null,this._updateCustomSizeVisibility()}),C.appendChild(this._sizeRadioCurrent),C.appendChild(document.createTextNode(" Current")),T.appendChild(C);const I=document.createElement("label");I.className="print-radio-label",this._sizeRadioCustom=document.createElement("input"),this._sizeRadioCustom.type="radio",this._sizeRadioCustom.name="print-size",this._sizeRadioCustom.value="custom",this._sizeRadioCustom.checked=!!this._state.width,this._sizeRadioCustom.addEventListener("change",()=>{const P=this._map?.getCanvas();this._state.width=P?P.width:1920,this._state.height=P?P.height:1080,this._widthInput&&(this._widthInput.value=String(this._state.width)),this._heightInput&&(this._heightInput.value=String(this._state.height)),this._updateCustomSizeVisibility()}),I.appendChild(this._sizeRadioCustom),I.appendChild(document.createTextNode(" Custom")),T.appendChild(I),L.appendChild(T),this._customSizeInputs=document.createElement("div"),this._customSizeInputs.className="print-custom-size";const M=document.createElement("label");M.className="print-size-label",M.textContent="Width",this._widthInput=document.createElement("input"),this._widthInput.type="number",this._widthInput.className="print-size-input",this._widthInput.style.color="var(--print-input-text)",this._widthInput.min="1",this._widthInput.max="8192",this._widthInput.value=String(this._state.width||1920),this._widthInput.addEventListener("input",()=>{this._state.width=parseInt(this._widthInput.value)||null});const O=document.createElement("div");O.className="print-size-group",O.appendChild(M),O.appendChild(this._widthInput);const N=document.createElement("label");N.className="print-size-label",N.textContent="Height",this._heightInput=document.createElement("input"),this._heightInput.type="number",this._heightInput.className="print-size-input",this._heightInput.style.color="var(--print-input-text)",this._heightInput.min="1",this._heightInput.max="8192",this._heightInput.value=String(this._state.height||1080),this._heightInput.addEventListener("input",()=>{this._state.height=parseInt(this._heightInput.value)||null});const D=document.createElement("div");D.className="print-size-group",D.appendChild(N),D.appendChild(this._heightInput),this._customSizeInputs.appendChild(O),this._customSizeInputs.appendChild(D),L.appendChild(this._customSizeInputs),n.appendChild(L),this._updateCustomSizeVisibility()}if(this._options.showPageOptions){const L=document.createElement("div");L.className="print-field",L.innerHTML="<label>Page</label>",L.appendChild(this._createPageOptions()),n.appendChild(L)}return this._exportBtn=document.createElement("button"),this._exportBtn.type="button",this._exportBtn.className="print-export-btn",this._exportBtn.innerHTML=`${_U}<span>Export Map</span>`,this._exportBtn.addEventListener("click",()=>this._exportMap()),n.appendChild(this._exportBtn),this._copyBtn=document.createElement("button"),this._copyBtn.type="button",this._copyBtn.className="print-copy-btn",this._copyBtn.innerHTML=`${AU}<span>Copy to Clipboard</span>`,this._copyBtn.addEventListener("click",()=>this._copyToClipboard()),n.appendChild(this._copyBtn),this._updateCopyBtnVisibility(),this._feedbackEl=document.createElement("div"),this._feedbackEl.className="print-feedback",n.appendChild(this._feedbackEl),e.appendChild(n),e}_makeField(e,t){const n=document.createElement("div");n.className="print-field";const i=document.createElement("label");return i.textContent=e,n.appendChild(i),n.appendChild(t),n}_makeSelect(e,t){const n=document.createElement("select");return n.className="print-select",n.style.color="var(--print-input-text)",e.forEach(([i,s])=>{const r=document.createElement("option");r.value=i,r.textContent=s,r.selected=i===t,n.appendChild(r)}),n}_toHexColor(e){return/^#[0-9a-fA-F]{6}$/.test(e)?e:"#ffffff"}_createPageOptions(){const e=document.createElement("div"),t=document.createElement("div");t.className="print-row",this._pageSizeSelect=this._makeSelect([["fit","Fit to map"],["a3","A3"],["a4","A4"],["a5","A5"],["letter","Letter"],["legal","Legal"],["tabloid","Tabloid"]],this._state.pageSize),this._pageSizeSelect.addEventListener("change",()=>{this._state.pageSize=this._pageSizeSelect.value,this._updatePageOptionsDisabled()}),t.appendChild(this._makeField("Page size",this._pageSizeSelect)),this._orientationSelect=this._makeSelect([["auto","Auto"],["portrait","Portrait"],["landscape","Landscape"]],this._state.orientation),this._orientationSelect.addEventListener("change",()=>{this._state.orientation=this._orientationSelect.value}),t.appendChild(this._makeField("Orientation",this._orientationSelect)),e.appendChild(t);const n=document.createElement("div");n.className="print-row",this._dpiSelect=this._makeSelect([["72","72"],["96","96"],["150","150"],["300","300"],["600","600"]],String(this._state.dpi)),this._dpiSelect.addEventListener("change",()=>{this._state.dpi=parseInt(this._dpiSelect.value,10)||96}),n.appendChild(this._makeField("DPI",this._dpiSelect)),this._marginInput=document.createElement("input"),this._marginInput.type="number",this._marginInput.className="print-input",this._marginInput.style.color="var(--print-input-text)",this._marginInput.min="0",this._marginInput.value=String(this._state.margin),this._marginInput.addEventListener("input",()=>{this._state.margin=Math.max(0,parseFloat(this._marginInput.value)||0)}),n.appendChild(this._makeField("Margin (pt)",this._marginInput)),e.appendChild(n);const i=document.createElement("div");return i.className="print-row",this._fitModeSelect=this._makeSelect([["contain","Contain"],["cover","Cover"]],this._state.fitMode),this._fitModeSelect.addEventListener("change",()=>{this._state.fitMode=this._fitModeSelect.value}),i.appendChild(this._makeField("Fit",this._fitModeSelect)),this._pageBackgroundInput=document.createElement("input"),this._pageBackgroundInput.type="color",this._pageBackgroundInput.className="print-input",this._pageBackgroundInput.value=this._toHexColor(this._state.pageBackground),this._pageBackgroundInput.addEventListener("input",()=>{this._state.pageBackground=this._pageBackgroundInput.value}),i.appendChild(this._makeField("Background",this._pageBackgroundInput)),e.appendChild(i),this._updatePageOptionsDisabled(),e}_updatePageOptionsDisabled(){const e=this._state.pageSize==="fit";this._orientationSelect&&(this._orientationSelect.disabled=e),this._fitModeSelect&&(this._fitModeSelect.disabled=e),this._marginInput&&(this._marginInput.disabled=e),this._pageBackgroundInput&&(this._pageBackgroundInput.disabled=e)}_updateQualityVisibility(){this._qualityField&&(this._qualityField.style.display=this._state.format==="jpeg"?"":"none")}_updateCopyBtnVisibility(){if(this._copyBtn){const e=this._state.format;this._copyBtn.style.display=e==="pdf"||e==="svg"?"none":""}}_effectiveDpi(){return this._state.dpi>0?this._state.dpi:96}async _exportPdf(e){const{jsPDF:t}=await import("jspdf"),n=this._effectiveDpi(),i=e.width/n*72,s=e.height/n*72,r=new t({orientation:i>=s?"landscape":"portrait",unit:"pt",format:[Math.min(i,s),Math.max(i,s)]}),a=r.internal.pageSize.getWidth(),o=r.internal.pageSize.getHeight(),l=e.toDataURL("image/png");r.addImage(l,"PNG",0,0,a,o),r.save(`${this._state.filename}.pdf`)}_exportSvg(e){const t=e.toDataURL("image/png"),n=e.width,i=e.height,s=this._effectiveDpi(),r=`<?xml version="1.0" encoding="UTF-8"?>
200
- <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${+(n/s).toFixed(4)}in" height="${+(i/s).toFixed(4)}in" viewBox="0 0 ${n} ${i}"><image width="${n}" height="${i}" xlink:href="${t}"/></svg>`,a=new Blob([r],{type:"image/svg+xml"}),o=URL.createObjectURL(a),l=document.createElement("a");l.href=o,l.download=`${this._state.filename}.svg`,document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(o)}_crc32(e){let t=-1;for(let n=0;n<e.length;n++){t^=e[n];for(let i=0;i<8;i++)t=t>>>1^3988292384&-(t&1)}return~t>>>0}_pngWithDpi(e,t){if(e.length<33)return e;const i=Math.max(1,Math.round(t/.0254)),s=new Uint8Array(21),r=new DataView(s.buffer);r.setUint32(0,9),s[4]=112,s[5]=72,s[6]=89,s[7]=115,r.setUint32(8,i),r.setUint32(12,i),s[16]=1,r.setUint32(17,this._crc32(s.subarray(4,17)));const a=new Uint8Array(e.length+s.length);return a.set(e.subarray(0,33),0),a.set(s,33),a.set(e.subarray(33),33+s.length),a}_jpegWithDpi(e,t){if(!(e.length>18&&e[2]===255&&e[3]===224&&e[6]===74&&e[7]===70&&e[8]===73&&e[9]===70))return e;const n=Math.max(1,Math.min(65535,Math.round(t)));return e[13]=1,e[14]=n>>8&255,e[15]=n&255,e[16]=n>>8&255,e[17]=n&255,e}async _embedDpi(e,t){try{const n=new Uint8Array(await e.arrayBuffer()),i=this._effectiveDpi();if(t==="png"){const r=this._pngWithDpi(n,i);return new Blob([r],{type:"image/png"})}const s=this._jpegWithDpi(n,i);return new Blob([s],{type:"image/jpeg"})}catch{return e}}_blobToDataUrl(e){return new Promise((t,n)=>{const i=new FileReader;i.onload=()=>t(String(i.result)),i.onerror=()=>n(new Error("Failed to read image blob")),i.readAsDataURL(e)})}_updateCustomSizeVisibility(){this._customSizeInputs&&(this._customSizeInputs.style.display=this._sizeRadioCustom?.checked?"":"none")}_updateColorbarSettingsVisibility(){this._colorbarSettingsDiv&&(this._colorbarSettingsDiv.style.display=this._state.colorbar.enabled?"":"none")}_getColorStops(e){return Array.isArray(e)?e.map((t,n)=>({position:n/(e.length-1),color:t})):typeof e=="string"&&uA(e)?nr(e):nr("viridis")}_drawColorbar(e,t,n){const i=this._state.colorbar,s=i.colormap??"viridis",r=i.vmin??0,a=i.vmax??1,o=i.label??"",l=i.units??"",c=i.orientation??"vertical",h=i.position??"bottom-right",d=i.barThickness??20,f=i.barLength??150,m=i.tickCount??5,A=c==="vertical",y=16,x=11,v=12,b=4,w=A?0:24,S=A?d+b+50+(o?18:0):f+w*2,R=A?f+(o?18:0):d+b+x+6+(o?18:0);let k,L;h.includes("left")?k=t.x+y:k=t.x+t.w-S-y,h.includes("top")?L=Math.max(t.y+y,t.y+n+y):L=t.y+t.h-R-y,e.save();const T=8;e.fillStyle="rgba(255,255,255,0.9)",e.strokeStyle="rgba(0,0,0,0.2)",e.lineWidth=1,e.beginPath(),e.roundRect(k-T,L-T,S+T*2,R+T*2,4),e.fill(),e.stroke();let C=0;o&&(e.fillStyle="#333",e.font=`600 ${v}px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`,e.textAlign=A?"left":"center",e.textBaseline="top",A?e.fillText(o,k,L):e.fillText(o,k+w+f/2,L),C=18);const I=A?k:k+w,M=this._getColorStops(s);let O;A?O=e.createLinearGradient(I,L+C+f,I,L+C):O=e.createLinearGradient(I,L+C,I+f,L+C),M.forEach(N=>{O.addColorStop(N.position,N.color)}),e.fillStyle=O,A?(e.fillRect(I,L+C,d,f),e.strokeStyle="rgba(0,0,0,0.3)",e.strokeRect(I,L+C,d,f)):(e.fillRect(I,L+C,f,d),e.strokeStyle="rgba(0,0,0,0.3)",e.strokeRect(I,L+C,f,d)),e.fillStyle="#333",e.font=`${x}px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`,e.strokeStyle="#333",e.lineWidth=1;for(let N=0;N<m;N++){const D=N/(m-1),P=r+D*(a-r),U=this._formatTickValue(P,a-r),Q=l?`${U}${l}`:U;if(A){const z=L+C+f-D*f;e.beginPath(),e.moveTo(I+d,z),e.lineTo(I+d+b,z),e.stroke(),e.textAlign="left",e.textBaseline="middle",e.fillText(Q,I+d+b+4,z)}else{const z=I+D*f;e.beginPath(),e.moveTo(z,L+C+d),e.lineTo(z,L+C+d+b),e.stroke(),e.textAlign="center",e.textBaseline="top",e.fillText(Q,z,L+C+d+b+2)}}e.restore()}_formatTickValue(e,t){if(t===0)return"0";const n=Math.abs(e),i=Math.abs(t);let s;return i>=100?s=0:i>=10?s=1:i>=1?s=2:i>=.1?s=3:s=4,n>=1e6||n>0&&n<1e-4?e.toExponential(2):e.toFixed(s)}expand(){this._state.collapsed&&(this._state.collapsed=!1,this._showPanel(),this._emit("expand"))}collapse(){this._state.collapsed||(this._state.collapsed=!0,this._hidePanel(),this._emit("collapse"))}_togglePanel(){this._state.collapsed?this.expand():this.collapse()}_showPanel(){!this._panel&&this._container&&(this._panel=this._createPanel(),this._container.appendChild(this._panel)),this._button?.classList.add("active")}_hidePanel(){this._panel?.remove(),this._panel=void 0,this._button?.classList.remove("active")}_showFeedback(e){this._feedbackEl&&(this._feedbackEl.textContent=e,this._feedbackEl.classList.add("visible"),setTimeout(()=>{this._feedbackEl?.classList.remove("visible")},2e3))}_setExporting(e){this._state.exporting=e,this._exportBtn&&(this._exportBtn.disabled=e),this._copyBtn&&(this._copyBtn.disabled=e)}_captureMapCanvas(){return new Promise(e=>{this._map.once("render",()=>{e(this._map.getCanvas())}),this._map.triggerRepaint()})}_drawNorthArrow(e,t,n,i,s){const r=i/2,a=i*.18;e.save(),e.translate(t+r,n+r),e.rotate(-s*Math.PI/180),e.fillStyle="#111",e.beginPath(),e.moveTo(0,-r+a),e.lineTo(i*.16,i*.12),e.lineTo(0,i*.02),e.lineTo(-i*.16,i*.12),e.closePath(),e.fill(),e.fillStyle="#111",e.font=`bold ${Math.round(i*.22)}px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`,e.textAlign="center",e.textBaseline="middle",e.fillText("N",0,i*.3),e.restore()}_niceDistance(e){if(e<=0)return 0;if(e<1){const s=e*100,r=Math.floor(Math.log10(Math.max(s,1))),a=s/10**r;let o=1;return a>=5?o=5:a>=2&&(o=2),o*10**r/100}const t=Math.floor(Math.log10(e)),n=e/10**t;let i=1;return n>=5?i=5:n>=2&&(i=2),i*10**t}_drawScaleBar(e,t,n){if(!this._map)return;const i=this._map.getCenter(),s=this._map.getZoom(),r=156543.03392804097*Math.cos(i.lat*Math.PI/180)/2**s;if(!Number.isFinite(r)||r<=0)return;const a=n,o=Math.max(80,Math.min(160,t.w*.16))/a*r,l=this._niceDistance(o),c=Math.max(40,l/r*a),h=18,d=10;if(t.h<56)return;const f=t.x+h,m=t.y+t.h-h-24;e.save();const A=c+16,y=38;e.fillStyle="rgba(255,255,255,0.9)",e.strokeStyle="rgba(0,0,0,0.35)",e.lineWidth=1,e.beginPath(),e.rect(f-8,m-8,A,y),e.fill(),e.stroke(),e.fillStyle="#111",e.fillRect(f,m,c/2,d),e.fillStyle="#fff",e.fillRect(f+c/2,m,c/2,d),e.strokeStyle="#111",e.lineWidth=1,e.strokeRect(f,m,c,d);const x=l>=1e3?`${(l/1e3).toFixed(l%1e3===0?0:1)} km`:l>=1?`${Math.round(l)} m`:`${Math.round(l*100)} cm`;e.fillStyle="#111",e.font='600 12px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',e.textAlign="center",e.textBaseline="top",e.fillText(x,f+c/2,m+d+4),e.restore()}_getPageLayout(e){const t=e.width,n=e.height;if(this._state.pageSize==="fit"){const R=this._state.width||t,k=this._state.height||n,L=(this._state.dpi>0?this._state.dpi:96)/96,T=Math.max(1,Math.round(R*L)),C=Math.max(1,Math.round(k*L));return{pageW:T,pageH:C,content:{x:0,y:0,w:T,h:C},mapDest:{x:0,y:0,w:T,h:C},scaleX:t>0?T/t:1,clip:!1,pageWidthIn:R/96,pageHeightIn:k/96}}const[i,s]=mU[this._state.pageSize];let r=this._state.orientation;r==="auto"&&(r=t>=n?"landscape":"portrait");const a=r==="landscape"?s:i,o=r==="landscape"?i:s,l=this._state.dpi>0?this._state.dpi:96,c=Math.max(1,Math.round(a*l)),h=Math.max(1,Math.round(o*l)),d=Math.max(0,Math.round(this._state.margin/72*l)),f=d,m=d,A=Math.max(1,c-d*2),y=Math.max(1,h-d*2),x=Math.min(A/t,y/n),v=Math.max(A/t,y/n),b=this._state.fitMode==="cover"?v:x,w=t*b,S=n*b;return{pageW:c,pageH:h,content:{x:f,y:m,w:A,h:y},mapDest:{x:f+(A-w)/2,y:m+(y-S)/2,w,h:S},scaleX:b,clip:this._state.fitMode==="cover",pageWidthIn:a,pageHeightIn:o}}async _createExportCanvas(){if(!this._map)return null;try{const e=await this._captureMapCanvas(),t=this._getPageLayout(e),{pageW:n,pageH:i,content:s,mapDest:r}=t,a=document.createElement("canvas");a.width=n,a.height=i;const o=a.getContext("2d");if(!o)return null;this._state.pageSize!=="fit"&&(o.fillStyle=this._state.pageBackground,o.fillRect(0,0,n,i)),o.save(),t.clip&&(o.beginPath(),o.rect(s.x,s.y,s.w,s.h),o.clip()),o.drawImage(e,r.x,r.y,r.w,r.h),o.restore();const l=this._state.title.trim();let c=0;if(l){const h=this._options.titleFontSize;o.font=`bold ${h}px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`;const d=o.measureText(l);c=h+h*.6*2,o.fillStyle=this._options.titleBackground,o.fillRect(s.x,s.y,s.w,c),o.fillStyle=this._options.titleFontColor,o.textBaseline="middle";const f=s.x+(s.w-d.width)/2;o.fillText(l,f,s.y+c/2)}if(this._state.includeNorthArrow){const h=Math.max(44,Math.min(72,s.w*.07)),d=h+18;if(s.w>=d){const f=s.x+s.w-h-18,m=Math.max(s.y+18,s.y+c+8),A=this._map.getBearing();this._drawNorthArrow(o,f,m,h,A)}}return this._state.includeScaleBar&&this._drawScaleBar(o,s,t.scaleX),this._state.colorbar.enabled&&this._drawColorbar(o,s,c),a}catch(e){const t=e instanceof Error?e.message:"Failed to capture map canvas";return this._emit("error",{error:t}),null}}async _exportMap(){if(!this._state.exporting){this._setExporting(!0);try{const e=await this._createExportCanvas();if(!e){this._showFeedback("Export failed"),this._setExporting(!1);return}if(this._state.format==="pdf")await this._exportPdf(e),this._showFeedback("Exported!"),this._emit("export");else if(this._state.format==="svg")this._exportSvg(e),this._showFeedback("Exported!"),this._emit("export");else{const t=this._state.format==="jpeg"?"image/jpeg":"image/png",n=this._state.format==="jpeg"?this._state.quality:void 0,i=this._state.format==="jpeg"?"jpg":"png",s=await new Promise(c=>{e.toBlob(h=>c(h),t,n)});if(!s){this._showFeedback("Export failed"),this._emit("error",{error:"Failed to create image blob"}),this._setExporting(!1);return}const r=await this._embedDpi(s,this._state.format==="jpeg"?"jpeg":"png"),a=URL.createObjectURL(r),o=document.createElement("a");o.href=a,o.download=`${this._state.filename}.${i}`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(a);const l=await this._blobToDataUrl(r);this._showFeedback("Exported!"),this._emit("export",{dataUrl:l})}}catch(e){const t=e instanceof Error?e.message:"Export failed";this._showFeedback("Export failed"),this._emit("error",{error:t})}finally{this._setExporting(!1)}}}async _copyToClipboard(){if(!this._state.exporting){this._setExporting(!0);try{const e=await this._createExportCanvas();if(!e){this._showFeedback("Copy failed"),this._setExporting(!1);return}const t=await new Promise(i=>{e.toBlob(s=>i(s),"image/png")});if(!t){this._showFeedback("Copy failed"),this._emit("error",{error:"Failed to create image blob"}),this._setExporting(!1);return}await navigator.clipboard.write([new ClipboardItem({"image/png":t})]);const n=e.toDataURL("image/png");this._showFeedback("Copied!"),this._emit("copy",{dataUrl:n})}catch(e){const t=e instanceof Error?e.message:"Copy to clipboard failed";this._showFeedback("Copy failed"),this._emit("error",{error:t})}finally{this._setExporting(!1)}}}_setupZoomHandler(){this._map&&(this._handleZoom=()=>{const e=this._map.getZoom(),t=e>=this._options.minzoom&&e<=this._options.maxzoom;t!==this._zoomVisible&&(this._zoomVisible=t,this._container&&(this._container.style.display=t&&this._state.visible?"":"none"))},this._map.on("zoom",this._handleZoom),this._handleZoom())}show(){return this._state.visible=!0,this._container&&this._zoomVisible&&(this._container.style.display=""),this._emit("show"),this}hide(){return this._state.visible=!1,this._container&&(this._container.style.display="none"),this._emit("hide"),this}getState(){return{...this._state}}setTheme(e){return this._options.theme=e,this._container&&this._applyThemeClass(this._container),this}_applyThemeClass(e){e.classList.remove("maplibre-gl-print-control--light","maplibre-gl-print-control--dark"),this._options.theme==="light"?e.classList.add("maplibre-gl-print-control--light"):this._options.theme==="dark"&&e.classList.add("maplibre-gl-print-control--dark")}setFormat(e){return this._state.format=e,this._formatSelect&&(this._formatSelect.value=e),this._updateQualityVisibility(),this._updateCopyBtnVisibility(),this._emit("update"),this}setQuality(e){return this._state.quality=Math.max(.1,Math.min(1,e)),this._qualityInput&&(this._qualityInput.value=String(this._state.quality)),this._qualityValue&&(this._qualityValue.textContent=this._state.quality.toFixed(2)),this._emit("update"),this}setTitle(e){return this._state.title=e,this._titleInput&&(this._titleInput.value=e),this._emit("update"),this}async exportMap(e){const t={...this._state,colorbar:{...this._state.colorbar}};e?.format&&(this._state.format=e.format),e?.quality&&(this._state.quality=e.quality),e?.filename&&(this._state.filename=e.filename),e?.title!==void 0&&(this._state.title=e.title),e?.includeNorthArrow!==void 0&&(this._state.includeNorthArrow=e.includeNorthArrow),e?.includeScaleBar!==void 0&&(this._state.includeScaleBar=e.includeScaleBar),e?.colorbar!==void 0&&(this._state.colorbar={...this._state.colorbar,...e.colorbar}),e?.width&&(this._state.width=e.width),e?.height&&(this._state.height=e.height),e?.pageSize&&(this._state.pageSize=e.pageSize),e?.orientation&&(this._state.orientation=e.orientation),e?.dpi&&(this._state.dpi=e.dpi),e?.margin!==void 0&&(this._state.margin=e.margin),e?.pageBackground!==void 0&&(this._state.pageBackground=e.pageBackground),e?.fitMode&&(this._state.fitMode=e.fitMode);try{const n=await this._createExportCanvas();if(!n)throw new Error("Failed to capture map canvas");if(this._state.format==="pdf")return await this._exportPdf(n),this._emit("export"),"";if(this._state.format==="svg")return this._exportSvg(n),this._emit("export"),"";const i=this._state.format==="jpeg"?"image/jpeg":"image/png",s=this._state.format==="jpeg"?this._state.quality:void 0,r=await new Promise(l=>{n.toBlob(c=>l(c),i,s)});if(!r)throw new Error("Failed to create image blob");const a=await this._embedDpi(r,this._state.format==="jpeg"?"jpeg":"png"),o=await this._blobToDataUrl(a);return this._emit("export",{dataUrl:o}),o}finally{this._state.format=t.format,this._state.quality=t.quality,this._state.filename=t.filename,this._state.title=t.title,this._state.includeNorthArrow=t.includeNorthArrow,this._state.includeScaleBar=t.includeScaleBar,this._state.colorbar=t.colorbar,this._state.width=t.width,this._state.height=t.height,this._state.pageSize=t.pageSize,this._state.orientation=t.orientation,this._state.dpi=t.dpi,this._state.margin=t.margin,this._state.pageBackground=t.pageBackground,this._state.fitMode=t.fitMode}}setColorbar(e){return this._state.colorbar={...this._state.colorbar,...e},this._colorbarInput&&(this._colorbarInput.checked=this._state.colorbar.enabled??!1),this._colorbarColormapSelect&&typeof this._state.colorbar.colormap=="string"&&(this._colorbarColormapSelect.value=this._state.colorbar.colormap),this._colorbarOrientationSelect&&(this._colorbarOrientationSelect.value=this._state.colorbar.orientation??"vertical"),this._colorbarVminInput&&(this._colorbarVminInput.value=String(this._state.colorbar.vmin??0)),this._colorbarVmaxInput&&(this._colorbarVmaxInput.value=String(this._state.colorbar.vmax??1)),this._colorbarLabelInput&&(this._colorbarLabelInput.value=this._state.colorbar.label??""),this._colorbarUnitsInput&&(this._colorbarUnitsInput.value=this._state.colorbar.units??""),this._updateColorbarSettingsVisibility(),this._emit("update"),this}};function bE(e,t,n){if(e.length===0)return null;const i=document.createElement("span");i.className="maplibre-gl-sample-trigger-label",i.textContent=t;const s=document.createElement("span");s.className="maplibre-gl-sample-caret",s.textContent="▾";const r=document.createElement("button");r.type="button",r.className="maplibre-gl-sample-trigger",r.setAttribute("aria-haspopup","listbox"),r.setAttribute("aria-expanded","false"),r.setAttribute("aria-label",t),r.appendChild(i),r.appendChild(s);const a=document.createElement("div");a.className="maplibre-gl-sample-menu",a.setAttribute("role","listbox"),a.hidden=!0;let o=!1;const l=h=>{o=h,a.hidden=!h,r.setAttribute("aria-expanded",String(h)),r.classList.toggle("open",h),h&&a.firstElementChild?.focus()};for(const h of e){const d=document.createElement("button");d.type="button",d.className="maplibre-gl-sample-option",d.setAttribute("role","option"),d.textContent=h.label,d.title=h.url,d.addEventListener("click",f=>{f.stopPropagation(),l(!1),r.focus(),n(h.url)}),a.appendChild(d)}r.addEventListener("click",h=>{h.stopPropagation(),l(!o)});const c=document.createElement("div");return c.className="maplibre-gl-sample-dropdown",c.appendChild(r),c.appendChild(a),c.addEventListener("keydown",h=>{h.key==="Escape"&&o&&(l(!1),r.focus())}),c.addEventListener("focusout",h=>{const d=h.relatedTarget;(!d||!c.contains(d))&&l(!1)}),c}var vU="maplibre-gl-panel-resize-handle",yU="maplibre-gl-panel-resize-left",bU="maplibre-gl-panel-resize-right";function xE(e){if(e&&typeof e.getContainer=="function")return e.getContainer()}function h2(e){const t=e?.parentElement;return t?t.classList.contains("maplibregl-ctrl-top-left")?"top-left":t.classList.contains("maplibregl-ctrl-top-right")?"top-right":t.classList.contains("maplibregl-ctrl-bottom-left")?"bottom-left":t.classList.contains("maplibregl-ctrl-bottom-right")?"bottom-right":"top-right":"top-right"}function xU(e,t,n){const i=xE(t),s=e.getBoundingClientRect(),r=h2(n).startsWith("bottom");if(i){const o=i.getBoundingClientRect(),l=r?s.bottom-o.top-12:o.bottom-s.top-12;return Math.max(160,l)}const a=typeof window<"u"?window.innerHeight:720;return Math.max(160,a-12)}function EE(e,t,n){const i=xU(e,t,n);e.style.maxHeight=`min(80vh, 720px, ${i}px)`,e.style.overflowY="auto"}function fA(e){const{panel:t,map:n,container:i}=e,s=e.getUserSize();if(!s)return;const r=e.minWidth??260,a=e.minHeight??180,o=xE(n),l=h2(i),c=l.endsWith("right"),h=l.startsWith("bottom"),d=t.getBoundingClientRect();let f=1/0,m=1/0;if(o){const x=o.getBoundingClientRect();f=(c?d.right-x.left:x.right-d.left)-12,m=(h?d.bottom-x.top:x.bottom-d.top)-12}const A=Math.min(Math.max(r,s.width),Math.max(0,f)),y=Math.min(Math.max(a,s.height),Math.max(0,m));t.style.boxSizing="border-box",t.style.maxWidth="none",t.style.maxHeight="none",t.style.width=`${A}px`,t.style.height=`${y}px`,t.style.overflowY="auto"}function CE(e){const{panel:t,map:n,container:i}=e,s=e.minWidth??260,r=e.minHeight??180;(!t.style.position||t.style.position==="static")&&(t.style.position="relative");const a=[];for(const o of["left","right"]){const l=document.createElement("div");l.className=`${vU} ${o==="left"?yU:bU}`,l.setAttribute("aria-hidden","true"),l.addEventListener("pointerdown",c=>EU(c,o,l,e,s,r)),t.appendChild(l),a.push(l)}return a}function EU(e,t,n,i,s,r){const{panel:a,map:o}=i;e.preventDefault(),e.stopPropagation();const l=a.getBoundingClientRect(),c=e.clientX,h=e.clientY,d=l.width,f=l.height,m=l.left,A=l.top,y=l.right,x=xE(o)?.getBoundingClientRect(),v={position:a.style.position,left:a.style.left,top:a.style.top,right:a.style.right,bottom:a.style.bottom,width:a.style.width,height:a.style.height,maxWidth:a.style.maxWidth,maxHeight:a.style.maxHeight};a.style.boxSizing="border-box",a.style.position="fixed",a.style.left=`${m}px`,a.style.top=`${A}px`,a.style.right="auto",a.style.bottom="auto",a.style.width=`${d}px`,a.style.height=`${f}px`,a.style.maxWidth="none",a.style.maxHeight="none";let b=d,w=f;const S=k=>{const L=k.clientX-c,T=k.clientY-h;let C=1/0;x&&(C=Math.max(r,x.bottom-A-12));const I=Math.max(r,Math.min(f+T,C));let M,O=m;if(t==="right"){let N=1/0;x&&(N=Math.max(s,x.right-m-12)),M=Math.max(s,Math.min(d+L,N))}else{let N=1/0;x&&(N=Math.max(s,y-x.left-12)),M=Math.max(s,Math.min(d-L,N)),O=m+(d-M)}a.style.width=`${M}px`,a.style.height=`${I}px`,a.style.left=`${O}px`,b=M,w=I},R=k=>{n.releasePointerCapture?.(k.pointerId),n.removeEventListener("pointermove",S),n.removeEventListener("pointerup",R),n.removeEventListener("pointercancel",R),a.style.position=v.position,a.style.left=v.left,a.style.top=v.top,a.style.right=v.right,a.style.bottom=v.bottom,i.setUserSize({width:b,height:w}),a.style.width=v.width,a.style.height=v.height,a.style.maxWidth=v.maxWidth,a.style.maxHeight=v.maxHeight,fA(i)};n.setPointerCapture?.(e.pointerId),n.addEventListener("pointermove",S),n.addEventListener("pointerup",R),n.addEventListener("pointercancel",R)}var u2=["bone","bwr","cividis","cool","coolwarm","gray","hot","inferno","jet","magma","ocean","plasma","rainbow","RdBu","RdYlBu","RdYlGn","seismic","spectral","terrain","turbo","viridis"];function CU(e){for(const t of u2){const n=wE(t);if(JSON.stringify(n)===JSON.stringify(e))return t}return"custom"}function wE(e){return nr(e).map(t=>t.color)}var wU='<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg>',SU={position:"top-right",className:"",visible:!0,collapsed:!0,beforeId:"",defaultUrl:"",sampleData:[],sampleDataLabel:"Load sample data...",loadDefaultUrl:!1,defaultVariable:"",defaultColormap:wE("viridis"),defaultClim:[0,1],defaultSelector:{},defaultLayerName:"",defaultOpacity:1,defaultPickable:!0,panelWidth:300,maxHeight:500,backgroundColor:"rgba(255, 255, 255, 0.95)",borderRadius:4,opacity:1,fontSize:13,fontColor:"#333",minzoom:0,maxzoom:24},X0=class{_container;_button;_panel;_options;_state;_eventHandlers=new Map;_map;_handleZoom;_zoomVisible=!0;_userPanelSize=null;_mapResizeHandler;_zarrLayers=new Map;_zarrLayerPropsMap=new Map;_layerCounter=0;_activePopup;_colormapName="viridis";_customColormap;_availableVariables=[];_variablesLoading=!1;constructor(e){this._options={...SU,...e},e?.defaultColormap&&(this._colormapName=CU(e.defaultColormap),this._colormapName==="custom"&&(this._customColormap=e.defaultColormap)),this._state={visible:this._options.visible,collapsed:this._options.collapsed,url:this._options.defaultUrl,variable:this._options.defaultVariable,colormap:this._options.defaultColormap,clim:this._options.defaultClim,selector:this._options.defaultSelector,layerName:this._options.defaultLayerName,layerOpacity:this._options.defaultOpacity,pickable:this._options.defaultPickable,hasLayer:!1,layerCount:0,layers:[],loading:!1,error:null,status:null}}onAdd(e){if(this._map=e,this._container=this._createContainer(),this._render(),this._handleZoom=()=>this._checkZoomVisibility(),this._map.on("zoom",this._handleZoom),this._checkZoomVisibility(),this._mapResizeHandler=()=>this._reflowPanel(),this._map.on("resize",this._mapResizeHandler),this._options.loadDefaultUrl&&this._options.defaultUrl&&this._options.defaultVariable){const t=()=>{this._addLayer()};this._map.isStyleLoaded()?setTimeout(t,100):this._map.once("idle",t)}return this._container}onRemove(){this._removeLayer(),this._map&&this._handleZoom&&(this._map.off("zoom",this._handleZoom),this._handleZoom=void 0),this._map&&this._mapResizeHandler&&(this._map.off("resize",this._mapResizeHandler),this._mapResizeHandler=void 0),this._map=void 0,this._container?.parentNode?.removeChild(this._container),this._container=void 0,this._button=void 0,this._panel=void 0,this._eventHandlers.clear()}show(){this._state.visible||(this._state.visible=!0,this._updateDisplayState(),this._emit("show"))}hide(){this._state.visible&&(this._state.visible=!1,this._updateDisplayState(),this._emit("hide"))}expand(){this._state.collapsed&&(this._state.collapsed=!1,this._render(),this._emit("expand"))}collapse(){this._state.collapsed||(this._state.collapsed=!0,this._render(),this._emit("collapse"))}toggle(){this._state.collapsed?this.expand():this.collapse()}_reflowPanel(){this._panel&&(EE(this._panel,this._map,this._container),fA({panel:this._panel,map:this._map,container:this._container,getUserSize:()=>this._userPanelSize,setUserSize:e=>{this._userPanelSize=e}}))}getState(){return{...this._state}}update(e){this._options={...this._options,...e},e.visible!==void 0&&(this._state.visible=e.visible),e.collapsed!==void 0&&(this._state.collapsed=e.collapsed),this._render(),this._emit("update")}on(e,t){this._eventHandlers.has(e)||this._eventHandlers.set(e,new Set),this._eventHandlers.get(e).add(t)}off(e,t){this._eventHandlers.get(e)?.delete(t)}async addLayer(e,t,n){e&&(this._state.url=e),t&&(this._state.variable=t),await this._addLayer(n)}removeLayer(e){this._removeLayer(e),this._render()}getLayerIds(){return Array.from(this._zarrLayers.keys())}getLayerOpacity(e){const t=this._zarrLayers.get(e);return t?t.opacity??1:null}setLayerOpacity(e,t){const n=this._zarrLayers.get(e);if(!n||typeof n.setOpacity!="function")return;const i=Math.max(0,Math.min(1,t));n.setOpacity(i),this._map&&this._map.triggerRepaint()}getLayerVisibility(e){const t=this.getLayerOpacity(e);return t!==null&&t>0}setLayerVisibility(e,t,n=1){t?this.setLayerOpacity(e,n):this.setLayerOpacity(e,0)}getLayerUrl(e){return this._zarrLayerPropsMap.get(e)?.source??null}getLayersMap(){return this._zarrLayers}async fetchVariables(){if(!this._state.url)return[];this._variablesLoading=!0,this._render();try{const e=this._state.url.replace(/\/$/,"");try{const t=await fetch(`${e}/.zmetadata`);if(t.ok){const n=await t.json(),i=Object.keys(n.metadata||{}).filter(o=>o.endsWith("/.zarray")).map(o=>o.replace("/.zarray","")).filter(o=>o&&!o.startsWith(".")),s=new Set(["x","y","lat","lon","latitude","longitude","time","band","month","spatial_ref"]),r=new Set;for(const o of i){const l=o.split("/"),c=l[l.length-1];s.has(c)||r.add(c)}let a=Array.from(r);if(a.length===0){const o=new Set;for(const l of i){const c=l.split("/");o.add(c[c.length-1])}a=Array.from(o)}if(a.sort(),a.length>0)return this._availableVariables=a,this._variablesLoading=!1,this._render(),a}}catch{}try{const t=await fetch(`${e}/zarr.json`);t.ok&&(await t.json()).node_type}catch{}try{(await fetch(`${e}/.zgroup`)).ok}catch{}return this._variablesLoading=!1,this._render(),this._availableVariables}catch(e){return console.warn("[ZarrLayerControl] Failed to fetch variables:",e),this._variablesLoading=!1,this._render(),[]}}_emit(e,t){const n=this._eventHandlers.get(e);if(n){const i={type:e,state:this.getState(),...t};n.forEach(s=>s(i))}}_checkZoomVisibility(){if(!this._map)return;const e=this._map.getZoom(),{minzoom:t,maxzoom:n}=this._options,i=e>=t&&e<=n;i!==this._zoomVisible&&(this._zoomVisible=i,this._updateDisplayState())}_updateDisplayState(){if(!this._container)return;const e=this._state.visible&&this._zoomVisible;this._container.style.display=e?"block":"none"}_createContainer(){const e=document.createElement("div");return e.className=`maplibregl-ctrl maplibre-gl-zarr-layer${this._options.className?` ${this._options.className}`:""}`,this._state.visible&&this._zoomVisible||(e.style.display="none"),Object.assign(e.style,{backgroundColor:this._options.backgroundColor,borderRadius:`${this._options.borderRadius}px`,boxShadow:"0 0 0 2px rgba(0, 0, 0, 0.1)"}),this._options.opacity!==1&&(e.style.opacity=String(this._options.opacity)),e}_render(){if(!this._container)return;const e=this._container.querySelector(".maplibre-gl-zarr-layer-panel"),t=e?e.scrollTop:0;if(this._container.innerHTML="",this._state.collapsed?this._renderCollapsed():this._renderExpanded(),this._updateDisplayState(),t>0){const n=this._container.querySelector(".maplibre-gl-zarr-layer-panel");n&&(n.scrollTop=t)}}_renderCollapsed(){this._container&&(this._button=document.createElement("button"),this._button.type="button",this._button.className=`maplibre-gl-zarr-layer-button${this._state.hasLayer?" maplibre-gl-zarr-layer-button--active":""}`,this._button.title="Zarr Layer",this._button.setAttribute("aria-label","Zarr Layer"),this._button.innerHTML=wU,this._button.addEventListener("click",()=>this.expand()),this._container.appendChild(this._button),this._panel=void 0)}_renderExpanded(){if(!this._container)return;const e=document.createElement("div");e.className="maplibre-gl-zarr-layer-panel",e.style.width=`${this._options.panelWidth}px`,this._panel=e;const t=document.createElement("div");t.className="maplibre-gl-zarr-layer-header";const n=document.createElement("span");n.className="maplibre-gl-zarr-layer-title",n.textContent="Zarr Layer",t.appendChild(n);const i=document.createElement("button");i.className="maplibre-gl-zarr-layer-close",i.innerHTML="&times;",i.title="Close",i.addEventListener("click",()=>this.collapse()),t.appendChild(i),e.appendChild(t);const s=this._createFormGroup("Zarr URL","url"),r=document.createElement("input");r.type="text",r.className="maplibre-gl-zarr-layer-input",r.style.color="#000",r.placeholder="https://example.com/data.zarr",r.value=this._state.url,r.addEventListener("input",()=>{this._state.url=r.value}),s.appendChild(r);const a=bE(this._options.sampleData,this._options.sampleDataLabel,z=>{r.value=z,this._state.url=z});a&&e.appendChild(a),e.appendChild(s);const o=this._createFormGroup("Variable","variable"),l=document.createElement("div");if(l.className="maplibre-gl-zarr-layer-var-row",l.style.display="flex",l.style.gap="6px",this._availableVariables.length>0){const z=document.createElement("select");z.className="maplibre-gl-zarr-layer-select",z.style.color="#000",z.style.flex="1";for(const H of this._availableVariables){const W=document.createElement("option");W.value=H,W.textContent=H,H===this._state.variable&&(W.selected=!0),z.appendChild(W)}z.addEventListener("change",()=>{this._state.variable=z.value}),l.appendChild(z)}else{const z=document.createElement("input");z.type="text",z.className="maplibre-gl-zarr-layer-input",z.style.color="#000",z.style.flex="1",z.placeholder="e.g., temperature",z.value=this._state.variable,z.addEventListener("input",()=>{this._state.variable=z.value}),l.appendChild(z)}const c=document.createElement("button");c.className="maplibre-gl-zarr-layer-btn",c.textContent=this._variablesLoading?"...":"Fetch",c.disabled=this._variablesLoading||!this._state.url,c.style.padding="5px 10px",c.style.flexShrink="0",c.addEventListener("click",()=>this.fetchVariables()),l.appendChild(c),o.appendChild(l),e.appendChild(o);const h=this._createFormGroup("Colormap","colormap"),d=document.createElement("select");if(d.className="maplibre-gl-zarr-layer-select",d.style.color="#000",this._customColormap){const z=document.createElement("option");z.value="custom",z.textContent="custom",this._colormapName==="custom"&&(z.selected=!0),d.appendChild(z)}for(const z of u2){const H=document.createElement("option");H.value=z,H.textContent=z,z===this._colormapName&&(H.selected=!0),d.appendChild(H)}d.addEventListener("change",()=>{const z=d.value;z==="custom"&&this._customColormap?(this._colormapName="custom",this._state.colormap=this._customColormap):(this._colormapName=z,this._state.colormap=wE(this._colormapName)),this._updateColormapPreview()}),h.appendChild(d);const f=document.createElement("div");f.className="maplibre-gl-zarr-layer-colormap-preview",f.id="zarr-colormap-preview",f.style.background=`linear-gradient(to right, ${this._state.colormap.join(", ")})`,h.appendChild(f),e.appendChild(h);const m=document.createElement("div");m.className="maplibre-gl-zarr-layer-row";const A=this._createFormGroup("Clim Min","clim-min"),y=document.createElement("input");y.type="number",y.className="maplibre-gl-zarr-layer-input",y.style.color="#000",y.value=String(this._state.clim[0]),y.addEventListener("input",()=>{this._state.clim=[Number(y.value)||0,this._state.clim[1]]}),A.appendChild(y),m.appendChild(A);const x=this._createFormGroup("Clim Max","clim-max"),v=document.createElement("input");v.type="number",v.className="maplibre-gl-zarr-layer-input",v.style.color="#000",v.value=String(this._state.clim[1]),v.addEventListener("input",()=>{this._state.clim=[this._state.clim[0],Number(v.value)||1]}),x.appendChild(v),m.appendChild(x),e.appendChild(m);const b=this._createFormGroup("Selector (JSON)","selector"),w=document.createElement("input");w.type="text",w.className="maplibre-gl-zarr-layer-input",w.style.color="#000",w.placeholder='{"time": 0, "band": "prec"}',w.value=this._state.selector?JSON.stringify(this._state.selector):"",w.addEventListener("input",()=>{try{const z=w.value?JSON.parse(w.value):{};this._state.selector=z}catch{}}),b.appendChild(w),e.appendChild(b);const S=this._createFormGroup("Opacity","opacity"),R=document.createElement("div");R.className="maplibre-gl-zarr-layer-slider-row";const k=document.createElement("input");k.type="range",k.className="maplibre-gl-zarr-layer-slider",k.min="0",k.max="100",k.value=String(Math.round(this._state.layerOpacity*100));const L=document.createElement("span");L.className="maplibre-gl-zarr-layer-slider-value",L.textContent=`${Math.round(this._state.layerOpacity*100)}%`,k.addEventListener("input",()=>{const z=Number(k.value);this._state.layerOpacity=z/100,L.textContent=`${z}%`,this._updateOpacity()}),R.appendChild(k),R.appendChild(L),S.appendChild(R),e.appendChild(S);const T=document.createElement("div");T.className="maplibre-gl-zarr-layer-form-group maplibre-gl-zarr-layer-checkbox-group";const C=document.createElement("label");C.className="maplibre-gl-zarr-layer-checkbox-label";const I=document.createElement("input");I.type="checkbox",I.className="maplibre-gl-zarr-layer-checkbox",I.checked=this._state.pickable,I.addEventListener("change",()=>{this._state.pickable=I.checked,this._updatePickable()}),C.appendChild(I);const M=document.createElement("span");M.textContent="Pickable (click to show pixel value)",C.appendChild(M),T.appendChild(C),e.appendChild(T);const O=this._createFormGroup("Layer Name","layer-name"),N=document.createElement("input");N.type="text",N.className="maplibre-gl-zarr-layer-input",N.style.color="#000",N.placeholder="Optional custom layer name",N.value=this._state.layerName,N.addEventListener("input",()=>{this._state.layerName=N.value}),O.appendChild(N),e.appendChild(O);const D=this._createFormGroup("Before Layer ID (optional)","before-id"),P=document.createElement("input");P.type="text",P.className="maplibre-gl-zarr-layer-input",P.style.color="#000",P.placeholder="e.g. labels or water",P.value=this._options.beforeId||"",P.addEventListener("input",()=>{this._options.beforeId=P.value||""}),D.appendChild(P),e.appendChild(D);const U=document.createElement("div");U.className="maplibre-gl-zarr-layer-buttons";const Q=document.createElement("button");if(Q.className="maplibre-gl-zarr-layer-btn maplibre-gl-zarr-layer-btn--primary",Q.textContent="Add Layer",Q.disabled=this._state.loading,Q.addEventListener("click",()=>this._addLayer()),U.appendChild(Q),e.appendChild(U),this._state.loading?this._appendStatus("Loading Zarr...","info"):this._state.error?this._appendStatus(this._state.error,"error"):this._state.status&&this._appendStatus(this._state.status,"success"),this._zarrLayers.size>0){const z=document.createElement("div");z.className="maplibre-gl-zarr-layer-list";const H=document.createElement("div");H.className="maplibre-gl-zarr-layer-list-header",H.textContent=`Layers (${this._zarrLayers.size})`,z.appendChild(H);for(const[W]of this._zarrLayers){const te=this._zarrLayerPropsMap.get(W);if(!te)continue;const J=document.createElement("div");J.className="maplibre-gl-zarr-layer-list-item";const K=document.createElement("span");K.className="maplibre-gl-zarr-layer-list-label";const re=te.source,ce=te.variable,oe=te._layerName;let ge;if(oe)ge=oe;else{ge=ce||W;try{ge=`${new URL(re).pathname.split("/").pop()} / ${ce}`}catch{ge=`${re} / ${ce}`}}K.textContent=ge,K.title=`${re} (${ce})`,J.appendChild(K);const ie=document.createElement("button");ie.className="maplibre-gl-zarr-layer-list-remove",ie.innerHTML="&times;",ie.title="Remove layer",ie.addEventListener("click",()=>{this._removeLayer(W),this._render()}),J.appendChild(ie),z.appendChild(J)}e.appendChild(z)}CE({panel:e,map:this._map,container:this._container,getUserSize:()=>this._userPanelSize,setUserSize:z=>{this._userPanelSize=z}}),this._reflowPanel(),this._container.appendChild(e),this._button=void 0,requestAnimationFrame(()=>this._reflowPanel())}_createFormGroup(e,t){const n=document.createElement("div");n.className="maplibre-gl-zarr-layer-form-group";const i=document.createElement("label");return i.textContent=e,i.htmlFor=`zarr-layer-${t}`,n.appendChild(i),n}_appendStatus(e,t){if(!this._panel)return;const n=document.createElement("div");n.className=`maplibre-gl-zarr-layer-status maplibre-gl-zarr-layer-status--${t}`,n.textContent=e,this._panel.appendChild(n)}_updateColormapPreview(){const e=document.getElementById("zarr-colormap-preview");e&&(e.style.background=`linear-gradient(to right, ${this._state.colormap.join(", ")})`)}async _addLayer(e){const t=!!e?.store;if(!this._map||!t&&!this._state.url||!this._state.variable){this._state.error=t?"Please enter a variable name.":"Please enter a Zarr URL and variable name.",this._render();return}this._state.loading=!0,this._state.error=null,this._state.status=null,this._render();try{const{ZarrLayer:n}=await import("@carbonplan/zarr-layer"),i=`zarr-layer-${this._layerCounter++}`,s=e?.selector??(this._state.selector&&Object.keys(this._state.selector).length>0?this._state.selector:void 0),r={id:i,variable:this._state.variable,colormap:e?.colormap??this._state.colormap,clim:e?.clim??this._state.clim,opacity:e?.opacity??this._state.layerOpacity,selector:s};this._state.url&&(r.source=this._state.url),e?.store&&(r.store=e.store),e?.zarrVersion&&(r.zarrVersion=e.zarrVersion),e?.transformRequest&&(r.transformRequest=e.transformRequest),e?.crs&&(r.crs=e.crs),e?.proj4&&(r.proj4=e.proj4),e?.bounds&&(r.bounds=e.bounds),e?.spatialDimensions&&(r.spatialDimensions=e.spatialDimensions);const a={...r};delete a.store,delete a.transformRequest;const o=this._state.layerName?.trim();o&&(a._layerName=o),this._zarrLayerPropsMap.set(i,a);const l=new n(r);this._zarrLayers.set(i,l);let c;this._options.beforeId&&(this._map.getLayer(this._options.beforeId)?c=this._options.beforeId:console.warn(`[ZarrLayerControl] beforeId "${this._options.beforeId}" not found in map layers, adding layer on top`)),c?this._map.addLayer(l,c):this._map.addLayer(l),this._state.pickable&&this._setupLayerClickHandler(i),this._state.hasLayer=this._zarrLayers.size>0,this._state.layerCount=this._zarrLayers.size,this._state.layers=this._buildLayerInfoList(),this._state.loading=!1,this._state.status="Zarr layer added successfully.",this._state.layerName="",this._render(),this._emit("layeradd",{url:this._state.url,layerId:i})}catch(n){this._state.loading=!1,this._state.error=`Failed to load Zarr: ${n instanceof Error?n.message:String(n)}`,this._render(),this._emit("error",{error:this._state.error})}}_setupLayerClickHandler(e){if(!this._map)return;const t=this._map,n=this._zarrLayerPropsMap.get(e),i=s=>{if(!this._state.pickable)return;this._activePopup&&this._activePopup.remove();const{lngLat:r}=s;let a='<div class="maplibre-gl-zarr-layer-popup">';a+='<table class="maplibre-gl-zarr-layer-popup-table">',a+=`<tr><td><strong>Layer</strong></td><td>${e}</td></tr>`,a+=`<tr><td><strong>Variable</strong></td><td>${n?.variable||"N/A"}</td></tr>`,a+=`<tr><td><strong>Lng</strong></td><td>${r.lng.toFixed(6)}</td></tr>`,a+=`<tr><td><strong>Lat</strong></td><td>${r.lat.toFixed(6)}</td></tr>`,n?.clim&&(a+=`<tr><td><strong>Color Range</strong></td><td>${n.clim[0]} - ${n.clim[1]}</td></tr>`),n?.source&&(a+=`<tr><td><strong>Source</strong></td><td style="word-break:break-all;max-width:150px;">${n.source.split("/").pop()}</td></tr>`),a+="</table>",a+="</div>",this._activePopup=new fi.default.Popup({closeButton:!0,maxWidth:"250px"}).setLngLat(r).setHTML(a).addTo(t);const o=this._activePopup.getElement();o&&(o.style.zIndex="1000")};this._zarrLayers.get(e)._clickHandler=i,t.on("click",i)}_updatePickable(){}_removeLayer(e){if(this._map)if(e){if(this._zarrLayers.get(e))try{this._map.removeLayer(e)}catch{}this._zarrLayers.delete(e),this._zarrLayerPropsMap.delete(e),this._state.hasLayer=this._zarrLayers.size>0,this._state.layerCount=this._zarrLayers.size,this._state.layers=this._buildLayerInfoList(),this._state.status=null,this._state.error=null,this._emit("layerremove",{layerId:e})}else{for(const[t]of this._zarrLayers)try{this._map.removeLayer(t)}catch{}this._zarrLayers.clear(),this._zarrLayerPropsMap.clear(),this._state.hasLayer=!1,this._state.layerCount=0,this._state.layers=[],this._state.status=null,this._state.error=null,this._emit("layerremove")}}_updateOpacity(){if(this._zarrLayers.size===0)return;const e=this._state.layerOpacity;for(const[,t]of this._zarrLayers)typeof t.setOpacity=="function"&&t.setOpacity(e);this._map&&this._map.triggerRepaint()}_buildLayerInfoList(){const e=[];for(const[t,n]of this._zarrLayerPropsMap)e.push({id:t,name:n._layerName||void 0,url:n.source,variable:n.variable,colormap:n.colormap,clim:n.clim,selector:n.selector,opacity:n.opacity??1});return e}},IU='<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18"/><path d="M3 15h18"/><path d="M9 3v18"/><path d="M15 3v18"/></svg>',MU={position:"top-right",className:"",visible:!0,collapsed:!0,beforeId:"",defaultUrl:"",sampleData:[],sampleDataLabel:"Load sample data...",loadDefaultUrl:!1,defaultOpacity:1,defaultFillColor:"steelblue",defaultLineColor:"#333333",defaultCircleColor:"steelblue",defaultLayerName:"",defaultPickable:!0,panelWidth:300,maxHeight:500,backgroundColor:"rgba(255, 255, 255, 0.95)",borderRadius:4,opacity:1,fontSize:13,fontColor:"#333",minzoom:0,maxzoom:24};function TU(e){const{minLon:t,minLat:n,maxLon:i,maxLat:s}=e;return Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(i)&&Number.isFinite(s)&&i>t&&s>n?{type:"bounds",bounds:[[t,n],[i,s]]}:e.centerLon!==void 0&&e.centerLat!==void 0?{type:"center",center:[e.centerLon,e.centerLat],zoom:Math.max(0,Math.min(e.maxZoom-2,14))}:null}var Z0=class{_container;_button;_panel;_options;_state;_eventHandlers=new Map;_map;_handleZoom;_zoomVisible=!0;_userPanelSize=null;_mapResizeHandler;_pmtilesLayers=new Map;_layerCounter=0;_protocolRegistered=!1;_protocol;_popup;_clickHandler;constructor(e){this._options={...MU,...e},this._state={visible:this._options.visible,collapsed:this._options.collapsed,url:this._options.defaultUrl,layerName:this._options.defaultLayerName,layerOpacity:this._options.defaultOpacity,availableSourceLayers:[],selectedSourceLayers:[],pickable:this._options.defaultPickable,hasLayer:!1,layerCount:0,layers:[],loading:!1,error:null,status:null}}onAdd(e){if(this._map=e,this._container=this._createContainer(),this._render(),this._handleZoom=()=>this._checkZoomVisibility(),this._map.on("zoom",this._handleZoom),this._checkZoomVisibility(),this._mapResizeHandler=()=>this._reflowPanel(),this._map.on("resize",this._mapResizeHandler),this._setupClickHandler(),this._options.loadDefaultUrl&&this._options.defaultUrl){const t=()=>{this._addLayer()};this._map.isStyleLoaded()?setTimeout(t,100):this._map.once("idle",t)}return this._container}onRemove(){this._removeLayer(),this._map&&this._handleZoom&&(this._map.off("zoom",this._handleZoom),this._handleZoom=void 0),this._map&&this._mapResizeHandler&&(this._map.off("resize",this._mapResizeHandler),this._mapResizeHandler=void 0),this._map&&this._clickHandler&&(this._map.off("click",this._clickHandler),this._clickHandler=void 0),this._popup&&(this._popup.remove(),this._popup=void 0),this._map=void 0,this._container?.parentNode?.removeChild(this._container),this._container=void 0,this._button=void 0,this._panel=void 0,this._eventHandlers.clear()}show(){this._state.visible||(this._state.visible=!0,this._updateDisplayState(),this._emit("show"))}hide(){this._state.visible&&(this._state.visible=!1,this._updateDisplayState(),this._emit("hide"))}expand(){this._state.collapsed&&(this._state.collapsed=!1,this._render(),this._emit("expand"))}collapse(){this._state.collapsed||(this._state.collapsed=!0,this._render(),this._emit("collapse"))}toggle(){this._state.collapsed?this.expand():this.collapse()}getState(){return{...this._state}}update(e){this._options={...this._options,...e},e.visible!==void 0&&(this._state.visible=e.visible),e.collapsed!==void 0&&(this._state.collapsed=e.collapsed),this._render(),this._emit("update")}on(e,t){this._eventHandlers.has(e)||this._eventHandlers.set(e,new Set),this._eventHandlers.get(e).add(t)}off(e,t){this._eventHandlers.get(e)?.delete(t)}async addLayer(e){e&&(this._state.url=e),await this._addLayer()}removeLayer(e){this._removeLayer(e),this._render()}getLayerIds(){const e=[];for(const t of this._pmtilesLayers.values())e.push(...t.layerIds);return e}_findSourceByLayerId(e){for(const t of this._pmtilesLayers.values())if(t.layerIds.includes(e))return t}getLayerOpacity(e){let t=this._pmtilesLayers.get(e);return t||(t=this._findSourceByLayerId(e)),t?.opacity??null}setLayerOpacity(e,t){if(!this._map)return;const n=Math.max(0,Math.min(1,t)),i=this._pmtilesLayers.get(e);if(i){i.opacity=n;for(const s of i.layerIds)this._setLayerOpacityDirect(s,n);return}this._findSourceByLayerId(e)&&this._setLayerOpacityDirect(e,n)}_setLayerOpacityDirect(e,t){if(!this._map)return;const n=this._map.getLayer(e);if(!n)return;const i=n.type;i==="fill"?this._map.setPaintProperty(e,"fill-opacity",t*.6):i==="line"?this._map.setPaintProperty(e,"line-opacity",t):i==="circle"?this._map.setPaintProperty(e,"circle-opacity",t):i==="raster"&&this._map.setPaintProperty(e,"raster-opacity",t)}getLayerVisibility(e){if(!this._map)return!1;const t=this._pmtilesLayers.get(e);return t&&t.layerIds.length>0?this._map.getLayoutProperty(t.layerIds[0],"visibility")!=="none":this._findSourceByLayerId(e)?this._map.getLayoutProperty(e,"visibility")!=="none":!1}setLayerVisibility(e,t){if(!this._map)return;const n=this._pmtilesLayers.get(e);if(n){for(const i of n.layerIds)this._map.setLayoutProperty(i,"visibility",t?"visible":"none");return}this._findSourceByLayerId(e)&&this._map.setLayoutProperty(e,"visibility",t?"visible":"none")}getLayerUrl(e){return this._pmtilesLayers.get(e)?.url??null}getPickable(e){return e?this._pmtilesLayers.get(e)?.pickable??this._state.pickable:this._state.pickable}setPickable(e,t){if(t){const n=this._pmtilesLayers.get(t);n&&(n.pickable=e)}else{this._state.pickable=e;for(const n of this._pmtilesLayers.values())n.pickable=e}this._render()}_emit(e,t){const n=this._eventHandlers.get(e);if(n){const i={type:e,state:this.getState(),...t};n.forEach(s=>s(i))}}_setupClickHandler(){this._map&&(this._clickHandler=e=>{if(!this._map||!this._state.pickable)return;const t=[];for(const r of this._pmtilesLayers.values())r.pickable&&r.tileType==="vector"&&t.push(...r.layerIds);if(t.length===0)return;const n=new Set,i=[];for(const r of t){if(!this._map.getLayer(r))continue;const a=this._map.queryRenderedFeatures(e.point,{layers:[r]});if(a.length>0){const o=a[0].sourceLayer||r;n.has(o)||(n.add(o),i.push({sourceLayer:o,properties:a[0].properties||{}}))}}if(i.length===0){this._popup&&this._popup.remove();return}let s='<div class="maplibre-gl-pmtiles-popup">';s+='<div class="maplibre-gl-pmtiles-popup-content">';for(const{sourceLayer:r,properties:a}of i){const o=r.replace(/[-_]/g," ");s+=`<div class="maplibre-gl-pmtiles-popup-header">${o}</div>`;const l=Object.entries(a);if(l.length===0)s+='<div class="maplibre-gl-pmtiles-popup-empty">No properties</div>';else{s+='<table class="maplibre-gl-pmtiles-popup-table">';for(const[c,h]of l){const d=typeof h=="object"?JSON.stringify(h):String(h);s+=`<tr><td class="maplibre-gl-pmtiles-popup-key">${c}</td><td class="maplibre-gl-pmtiles-popup-value">${d}</td></tr>`}s+="</table>"}}s+="</div></div>",this._popup||(this._popup=new fi.Popup({closeButton:!0,closeOnClick:!1,maxWidth:"320px"})),this._popup.setLngLat(e.lngLat).setHTML(s).addTo(this._map)},this._map.on("click",this._clickHandler))}_checkZoomVisibility(){if(!this._map)return;const e=this._map.getZoom(),{minzoom:t,maxzoom:n}=this._options,i=e>=t&&e<=n;i!==this._zoomVisible&&(this._zoomVisible=i,this._updateDisplayState())}_updateDisplayState(){if(!this._container)return;const e=this._state.visible&&this._zoomVisible;this._container.style.display=e?"block":"none"}_createContainer(){const e=document.createElement("div");return e.className=`maplibregl-ctrl maplibre-gl-pmtiles-layer${this._options.className?` ${this._options.className}`:""}`,this._state.visible&&this._zoomVisible||(e.style.display="none"),Object.assign(e.style,{backgroundColor:this._options.backgroundColor,borderRadius:`${this._options.borderRadius}px`,boxShadow:"0 0 0 2px rgba(0, 0, 0, 0.1)"}),this._options.opacity!==1&&(e.style.opacity=String(this._options.opacity)),e}_render(){if(!this._container)return;const e=this._container.querySelector(".maplibre-gl-pmtiles-layer-panel"),t=e?e.scrollTop:0;if(this._container.innerHTML="",this._state.collapsed?this._renderCollapsed():this._renderExpanded(),this._updateDisplayState(),t>0){const n=this._container.querySelector(".maplibre-gl-pmtiles-layer-panel");n&&(n.scrollTop=t)}}_renderCollapsed(){this._container&&(this._button=document.createElement("button"),this._button.type="button",this._button.className=`maplibre-gl-pmtiles-layer-button${this._state.hasLayer?" maplibre-gl-pmtiles-layer-button--active":""}`,this._button.title="PMTiles Layer",this._button.setAttribute("aria-label","PMTiles Layer"),this._button.innerHTML=IU,this._button.addEventListener("click",()=>this.expand()),this._container.appendChild(this._button),this._panel=void 0)}_renderExpanded(){if(!this._container)return;const e=document.createElement("div");e.className="maplibre-gl-pmtiles-layer-panel",e.style.width=`${this._options.panelWidth}px`,this._panel=e;const t=document.createElement("div");t.className="maplibre-gl-pmtiles-layer-header";const n=document.createElement("span");n.className="maplibre-gl-pmtiles-layer-title",n.textContent="PMTiles Layer",t.appendChild(n);const i=document.createElement("button");i.className="maplibre-gl-pmtiles-layer-close",i.innerHTML="&times;",i.title="Close",i.addEventListener("click",()=>this.collapse()),t.appendChild(i),e.appendChild(t);const s=this._createFormGroup("PMTiles URL","url"),r=document.createElement("input");r.type="text",r.className="maplibre-gl-pmtiles-layer-input",r.style.color="#000",r.placeholder="https://example.com/tiles.pmtiles",r.value=this._state.url,r.addEventListener("input",()=>{this._state.url=r.value}),s.appendChild(r);const a=bE(this._options.sampleData,this._options.sampleDataLabel,T=>{r.value=T,this._state.url=T});a&&e.appendChild(a),e.appendChild(s);const o=this._createFormGroup("Opacity","opacity"),l=document.createElement("div");l.className="maplibre-gl-pmtiles-layer-slider-row";const c=document.createElement("input");c.type="range",c.className="maplibre-gl-pmtiles-layer-slider",c.min="0",c.max="100",c.value=String(Math.round(this._state.layerOpacity*100));const h=document.createElement("span");h.className="maplibre-gl-pmtiles-layer-slider-value",h.textContent=`${Math.round(this._state.layerOpacity*100)}%`,c.addEventListener("input",()=>{const T=Number(c.value);this._state.layerOpacity=T/100,h.textContent=`${T}%`,this._updateOpacity()}),l.appendChild(c),l.appendChild(h),o.appendChild(l),e.appendChild(o);const d=this._createFormGroup("Interactivity","pickable"),f=document.createElement("div");f.style.display="flex",f.style.alignItems="center",f.style.gap="6px";const m=document.createElement("input");m.type="checkbox",m.id="pmtiles-layer-pickable",m.checked=this._state.pickable,m.addEventListener("change",()=>{this.setPickable(m.checked)});const A=document.createElement("label");A.htmlFor="pmtiles-layer-pickable",A.textContent="Enable feature picking (click to inspect)",A.style.fontSize="12px",A.style.cursor="pointer",f.appendChild(m),f.appendChild(A),d.appendChild(f),e.appendChild(d);const y=this._createFormGroup("Source Layers","source-layers"),x=document.createElement("div");x.style.display="flex",x.style.gap="6px",x.style.alignItems="center",x.style.marginBottom="6px";const v=document.createElement("button");if(v.className="maplibre-gl-pmtiles-layer-btn",v.textContent="Fetch",v.style.padding="4px 10px",v.style.fontSize="11px",v.style.whiteSpace="nowrap",v.disabled=!this._state.url,v.addEventListener("click",()=>this._fetchSourceLayers()),x.appendChild(v),this._state.availableSourceLayers.length>0){const T=document.createElement("button");T.className="maplibre-gl-pmtiles-layer-btn",T.textContent="All",T.style.padding="4px 8px",T.style.fontSize="11px",T.addEventListener("click",()=>{this._state.selectedSourceLayers=[...this._state.availableSourceLayers],this._render()}),x.appendChild(T);const C=document.createElement("button");C.className="maplibre-gl-pmtiles-layer-btn",C.textContent="None",C.style.padding="4px 8px",C.style.fontSize="11px",C.addEventListener("click",()=>{this._state.selectedSourceLayers=[],this._render()}),x.appendChild(C);const I=document.createElement("span");I.style.fontSize="11px",I.style.color="#666",I.textContent=`(${this._state.selectedSourceLayers.length}/${this._state.availableSourceLayers.length})`,x.appendChild(I)}if(y.appendChild(x),this._state.availableSourceLayers.length>0){const T=document.createElement("div");T.style.maxHeight="120px",T.style.overflowY="auto",T.style.border="1px solid #ddd",T.style.borderRadius="3px",T.style.padding="6px",T.style.background="#fafafa";for(const C of this._state.availableSourceLayers){const I=document.createElement("label");I.style.display="flex",I.style.alignItems="center",I.style.gap="4px",I.style.fontSize="11px",I.style.cursor="pointer",I.style.padding="2px 0";const M=document.createElement("input");M.type="checkbox",M.checked=this._state.selectedSourceLayers.includes(C),M.addEventListener("change",()=>{M.checked?this._state.selectedSourceLayers.includes(C)||this._state.selectedSourceLayers.push(C):this._state.selectedSourceLayers=this._state.selectedSourceLayers.filter(O=>O!==C),this._render()}),I.appendChild(M),I.appendChild(document.createTextNode(C)),T.appendChild(I)}y.appendChild(T)}else if(!this._state.loading){const T=document.createElement("span");T.style.fontSize="11px",T.style.color="#888",T.textContent="Click Fetch to discover available layers",y.appendChild(T)}e.appendChild(y);const b=this._createFormGroup("Layer Name","layer-name"),w=document.createElement("input");w.type="text",w.className="maplibre-gl-pmtiles-layer-input",w.style.color="#000",w.placeholder="Optional custom layer name",w.value=this._state.layerName,w.addEventListener("input",()=>{this._state.layerName=w.value}),b.appendChild(w),e.appendChild(b);const S=this._createFormGroup("Before Layer ID (optional)","before-id"),R=document.createElement("input");R.type="text",R.className="maplibre-gl-pmtiles-layer-input",R.style.color="#000",R.placeholder="e.g. labels or water",R.value=this._options.beforeId||"",R.addEventListener("input",()=>{this._options.beforeId=R.value||""}),S.appendChild(R),e.appendChild(S);const k=document.createElement("div");k.className="maplibre-gl-pmtiles-layer-buttons";const L=document.createElement("button");if(L.className="maplibre-gl-pmtiles-layer-btn maplibre-gl-pmtiles-layer-btn--primary",L.textContent="Add Layer",L.disabled=this._state.loading,L.addEventListener("click",()=>this._addLayer()),k.appendChild(L),e.appendChild(k),this._state.loading?this._appendStatus("Loading PMTiles...","info"):this._state.error?this._appendStatus(this._state.error,"error"):this._state.status&&this._appendStatus(this._state.status,"success"),this._pmtilesLayers.size>0){const T=document.createElement("div");T.className="maplibre-gl-pmtiles-layer-list";const C=document.createElement("div");C.className="maplibre-gl-pmtiles-layer-list-header",C.textContent=`Layers (${this._pmtilesLayers.size})`,T.appendChild(C);for(const[I,M]of this._pmtilesLayers){const O=document.createElement("div");O.className="maplibre-gl-pmtiles-layer-list-item";const N=document.createElement("span");N.className="maplibre-gl-pmtiles-layer-list-label";let D;if(M.name)D=M.name;else try{D=new URL(M.url).pathname.split("/").pop()||M.url}catch{D=M.url}N.textContent=D,N.title=M.url;const P=document.createElement("span");P.className=`maplibre-gl-pmtiles-layer-badge${M.tileType==="raster"?" maplibre-gl-pmtiles-layer-badge--raster":""}`,P.textContent=M.tileType,N.appendChild(P),O.appendChild(N);const U=document.createElement("button");U.className="maplibre-gl-pmtiles-layer-list-remove",U.innerHTML="&times;",U.title="Remove layer",U.addEventListener("click",()=>{this._removeLayer(I),this._render()}),O.appendChild(U),T.appendChild(O)}e.appendChild(T)}CE({panel:e,map:this._map,container:this._container,getUserSize:()=>this._userPanelSize,setUserSize:T=>{this._userPanelSize=T}}),this._reflowPanel(),this._container.appendChild(e),this._button=void 0,requestAnimationFrame(()=>this._reflowPanel())}_reflowPanel(){this._panel&&(EE(this._panel,this._map,this._container),fA({panel:this._panel,map:this._map,container:this._container,getUserSize:()=>this._userPanelSize,setUserSize:e=>{this._userPanelSize=e}}))}_createFormGroup(e,t){const n=document.createElement("div");n.className="maplibre-gl-pmtiles-layer-form-group";const i=document.createElement("label");return i.textContent=e,i.htmlFor=`pmtiles-layer-${t}`,n.appendChild(i),n}_appendStatus(e,t){if(!this._panel)return;const n=document.createElement("div");n.className=`maplibre-gl-pmtiles-layer-status maplibre-gl-pmtiles-layer-status--${t}`,n.textContent=e,this._panel.appendChild(n)}async _ensureProtocol(){if(this._protocolRegistered)return;const e=await Promise.resolve().then(()=>require("./esm-oEp_aN1n.cjs"));this._protocol=new e.Protocol;const t=window.maplibregl||await import("maplibre-gl");t.config?.REGISTERED_PROTOCOLS?.pmtiles||t.addProtocol("pmtiles",this._protocol.tile),this._protocolRegistered=!0}async _fetchSourceLayers(){if(!this._state.url){this._state.error="Please enter a PMTiles URL.",this._render();return}this._state.loading=!0,this._state.error=null,this._state.status=null,this._render();try{await this._ensureProtocol();const e=new(await Promise.resolve().then(()=>require("./esm-oEp_aN1n.cjs"))).PMTiles(this._state.url);this._protocol.add(e);const t=await e.getHeader(),n=await e.getMetadata();if(t.tileType===1){const i=(n?.vector_layers||[]).map(s=>s.id);this._state.availableSourceLayers=i,this._state.selectedSourceLayers=[...i],this._state.status=`Found ${i.length} source layer(s)`}else this._state.availableSourceLayers=[],this._state.selectedSourceLayers=[],this._state.status="Raster tiles (no source layers)";this._state.loading=!1,this._render()}catch(e){this._state.loading=!1,this._state.error=`Failed to fetch: ${e instanceof Error?e.message:String(e)}`,this._render()}}async _addLayer(){if(!this._map||!this._state.url){this._state.error="Please enter a PMTiles URL.",this._render();return}this._state.loading=!0,this._state.error=null,this._state.status=null,this._render();try{await this._ensureProtocol();const e=new(await Promise.resolve().then(()=>require("./esm-oEp_aN1n.cjs"))).PMTiles(this._state.url);this._protocol.add(e);const t=await e.getHeader(),n=await e.getMetadata();let i="unknown";t.tileType===1?i="vector":(t.tileType===2||t.tileType===3||t.tileType===4)&&(i="raster");const s=`pmtiles-source-${this._layerCounter++}`,r=`pmtiles://${this._state.url}`;i==="vector"?this._map.addSource(s,{type:"vector",url:r}):this._map.addSource(s,{type:"raster",url:r,tileSize:256});const a=(n?.vector_layers||[]).map(f=>f.id),o=[],l=this._options.beforeId&&this._map.getLayer(this._options.beforeId)?this._options.beforeId:void 0,c={};if(i==="vector"){const f=this._state.selectedSourceLayers.length>0?this._state.selectedSourceLayers:a,m=bO(f.length);for(let A=0;A<f.length;A++){const y=f[A],x=m[A];c[y]=x;const v=`${s}-${y}-fill`,b=`${s}-${y}-line`,w=`${s}-${y}-circle`;this._map.addLayer({id:v,type:"fill",source:s,"source-layer":y,paint:{"fill-color":x,"fill-opacity":this._state.layerOpacity*.6},filter:["==",["geometry-type"],"Polygon"]},l),o.push(v),this._map.addLayer({id:b,type:"line",source:s,"source-layer":y,paint:{"line-color":x,"line-opacity":this._state.layerOpacity,"line-width":1},filter:["any",["==",["geometry-type"],"LineString"],["==",["geometry-type"],"Polygon"]]},l),o.push(b),this._map.addLayer({id:w,type:"circle",source:s,"source-layer":y,paint:{"circle-color":x,"circle-opacity":this._state.layerOpacity,"circle-radius":2,"circle-stroke-color":x,"circle-stroke-width":.5},filter:["==",["geometry-type"],"Point"]},l),o.push(w)}if(f.length===0){const A=`${s}-generic`;this._map.addLayer({id:A,type:"fill",source:s,paint:{"fill-color":this._options.defaultFillColor,"fill-opacity":this._state.layerOpacity*.6}},l),o.push(A)}}else{const f=`${s}-raster`;this._map.addLayer({id:f,type:"raster",source:s,paint:{"raster-opacity":this._state.layerOpacity}},l),o.push(f)}const h=TU(t);h?.type==="bounds"?this._map.fitBounds(h.bounds,{padding:40,duration:1e3}):h?.type==="center"&&this._map.flyTo({center:h.center,zoom:h.zoom,duration:1e3});const d={id:s,name:this._state.layerName?.trim()||void 0,url:this._state.url,tileType:i,sourceLayers:a,layerIds:o,opacity:this._state.layerOpacity,pickable:this._state.pickable,sourceLayerColors:c};this._pmtilesLayers.set(s,d),this._state.hasLayer=this._pmtilesLayers.size>0,this._state.layerCount=this._pmtilesLayers.size,this._state.layers=Array.from(this._pmtilesLayers.values()),this._state.loading=!1,this._state.status=`PMTiles layer added (${i}).`,this._state.layerName="",this._render(),this._emit("layeradd",{url:this._state.url,layerId:s})}catch(e){this._state.loading=!1,this._state.error=`Failed to load PMTiles: ${e instanceof Error?e.message:String(e)}`,this._render(),this._emit("error",{error:this._state.error})}}_removeLayer(e){if(this._map)if(e){const t=this._pmtilesLayers.get(e);if(t){for(const n of t.layerIds)try{this._map.getLayer(n)&&this._map.removeLayer(n)}catch{}try{this._map.getSource(e)&&this._map.removeSource(e)}catch{}}this._pmtilesLayers.delete(e),this._state.hasLayer=this._pmtilesLayers.size>0,this._state.layerCount=this._pmtilesLayers.size,this._state.layers=Array.from(this._pmtilesLayers.values()),this._state.status=null,this._state.error=null,this._emit("layerremove",{layerId:e})}else{for(const[t,n]of this._pmtilesLayers){for(const i of n.layerIds)try{this._map.getLayer(i)&&this._map.removeLayer(i)}catch{}try{this._map.getSource(t)&&this._map.removeSource(t)}catch{}}this._pmtilesLayers.clear(),this._state.hasLayer=!1,this._state.layerCount=0,this._state.layers=[],this._state.status=null,this._state.error=null,this._emit("layerremove")}}_updateOpacity(){for(const[e]of this._pmtilesLayers)this.setLayerOpacity(e,this._state.layerOpacity)}},LU={name:"rescaleFloat",fs:`uniform rescaleFloatUniforms {
200
+ <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${+(n/s).toFixed(4)}in" height="${+(i/s).toFixed(4)}in" viewBox="0 0 ${n} ${i}"><image width="${n}" height="${i}" xlink:href="${t}"/></svg>`,a=new Blob([r],{type:"image/svg+xml"}),o=URL.createObjectURL(a),l=document.createElement("a");l.href=o,l.download=`${this._state.filename}.svg`,document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(o)}_crc32(e){let t=-1;for(let n=0;n<e.length;n++){t^=e[n];for(let i=0;i<8;i++)t=t>>>1^3988292384&-(t&1)}return~t>>>0}_pngWithDpi(e,t){if(e.length<33)return e;const i=Math.max(1,Math.round(t/.0254)),s=new Uint8Array(21),r=new DataView(s.buffer);r.setUint32(0,9),s[4]=112,s[5]=72,s[6]=89,s[7]=115,r.setUint32(8,i),r.setUint32(12,i),s[16]=1,r.setUint32(17,this._crc32(s.subarray(4,17)));const a=new Uint8Array(e.length+s.length);return a.set(e.subarray(0,33),0),a.set(s,33),a.set(e.subarray(33),33+s.length),a}_jpegWithDpi(e,t){if(!(e.length>18&&e[2]===255&&e[3]===224&&e[6]===74&&e[7]===70&&e[8]===73&&e[9]===70))return e;const n=Math.max(1,Math.min(65535,Math.round(t)));return e[13]=1,e[14]=n>>8&255,e[15]=n&255,e[16]=n>>8&255,e[17]=n&255,e}async _embedDpi(e,t){try{const n=new Uint8Array(await e.arrayBuffer()),i=this._effectiveDpi();if(t==="png"){const r=this._pngWithDpi(n,i);return new Blob([r],{type:"image/png"})}const s=this._jpegWithDpi(n,i);return new Blob([s],{type:"image/jpeg"})}catch{return e}}_blobToDataUrl(e){return new Promise((t,n)=>{const i=new FileReader;i.onload=()=>t(String(i.result)),i.onerror=()=>n(new Error("Failed to read image blob")),i.readAsDataURL(e)})}_updateCustomSizeVisibility(){this._customSizeInputs&&(this._customSizeInputs.style.display=this._sizeRadioCustom?.checked?"":"none")}_updateColorbarSettingsVisibility(){this._colorbarSettingsDiv&&(this._colorbarSettingsDiv.style.display=this._state.colorbar.enabled?"":"none")}_getColorStops(e){return Array.isArray(e)?e.map((t,n)=>({position:n/(e.length-1),color:t})):typeof e=="string"&&uA(e)?nr(e):nr("viridis")}_drawColorbar(e,t,n){const i=this._state.colorbar,s=i.colormap??"viridis",r=i.vmin??0,a=i.vmax??1,o=i.label??"",l=i.units??"",c=i.orientation??"vertical",h=i.position??"bottom-right",d=i.barThickness??20,f=i.barLength??150,m=i.tickCount??5,A=c==="vertical",y=16,x=11,v=12,b=4,w=A?0:24,S=A?d+b+50+(o?18:0):f+w*2,R=A?f+(o?18:0):d+b+x+6+(o?18:0);let k,L;h.includes("left")?k=t.x+y:k=t.x+t.w-S-y,h.includes("top")?L=Math.max(t.y+y,t.y+n+y):L=t.y+t.h-R-y,e.save();const T=8;e.fillStyle="rgba(255,255,255,0.9)",e.strokeStyle="rgba(0,0,0,0.2)",e.lineWidth=1,e.beginPath(),e.roundRect(k-T,L-T,S+T*2,R+T*2,4),e.fill(),e.stroke();let C=0;o&&(e.fillStyle="#333",e.font=`600 ${v}px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`,e.textAlign=A?"left":"center",e.textBaseline="top",A?e.fillText(o,k,L):e.fillText(o,k+w+f/2,L),C=18);const I=A?k:k+w,M=this._getColorStops(s);let O;A?O=e.createLinearGradient(I,L+C+f,I,L+C):O=e.createLinearGradient(I,L+C,I+f,L+C),M.forEach(N=>{O.addColorStop(N.position,N.color)}),e.fillStyle=O,A?(e.fillRect(I,L+C,d,f),e.strokeStyle="rgba(0,0,0,0.3)",e.strokeRect(I,L+C,d,f)):(e.fillRect(I,L+C,f,d),e.strokeStyle="rgba(0,0,0,0.3)",e.strokeRect(I,L+C,f,d)),e.fillStyle="#333",e.font=`${x}px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`,e.strokeStyle="#333",e.lineWidth=1;for(let N=0;N<m;N++){const D=N/(m-1),P=r+D*(a-r),U=this._formatTickValue(P,a-r),Q=l?`${U}${l}`:U;if(A){const z=L+C+f-D*f;e.beginPath(),e.moveTo(I+d,z),e.lineTo(I+d+b,z),e.stroke(),e.textAlign="left",e.textBaseline="middle",e.fillText(Q,I+d+b+4,z)}else{const z=I+D*f;e.beginPath(),e.moveTo(z,L+C+d),e.lineTo(z,L+C+d+b),e.stroke(),e.textAlign="center",e.textBaseline="top",e.fillText(Q,z,L+C+d+b+2)}}e.restore()}_formatTickValue(e,t){if(t===0)return"0";const n=Math.abs(e),i=Math.abs(t);let s;return i>=100?s=0:i>=10?s=1:i>=1?s=2:i>=.1?s=3:s=4,n>=1e6||n>0&&n<1e-4?e.toExponential(2):e.toFixed(s)}expand(){this._state.collapsed&&(this._state.collapsed=!1,this._showPanel(),this._emit("expand"))}collapse(){this._state.collapsed||(this._state.collapsed=!0,this._hidePanel(),this._emit("collapse"))}_togglePanel(){this._state.collapsed?this.expand():this.collapse()}_showPanel(){!this._panel&&this._container&&(this._panel=this._createPanel(),this._container.appendChild(this._panel)),this._button?.classList.add("active")}_hidePanel(){this._panel?.remove(),this._panel=void 0,this._button?.classList.remove("active")}_showFeedback(e){this._feedbackEl&&(this._feedbackEl.textContent=e,this._feedbackEl.classList.add("visible"),setTimeout(()=>{this._feedbackEl?.classList.remove("visible")},2e3))}_setExporting(e){this._state.exporting=e,this._exportBtn&&(this._exportBtn.disabled=e),this._copyBtn&&(this._copyBtn.disabled=e)}_captureMapCanvas(){return new Promise(e=>{this._map.once("render",()=>{e(this._map.getCanvas())}),this._map.triggerRepaint()})}_drawNorthArrow(e,t,n,i,s){const r=i/2,a=i*.18;e.save(),e.translate(t+r,n+r),e.rotate(-s*Math.PI/180),e.fillStyle="#111",e.beginPath(),e.moveTo(0,-r+a),e.lineTo(i*.16,i*.12),e.lineTo(0,i*.02),e.lineTo(-i*.16,i*.12),e.closePath(),e.fill(),e.fillStyle="#111",e.font=`bold ${Math.round(i*.22)}px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`,e.textAlign="center",e.textBaseline="middle",e.fillText("N",0,i*.3),e.restore()}_niceDistance(e){if(e<=0)return 0;if(e<1){const s=e*100,r=Math.floor(Math.log10(Math.max(s,1))),a=s/10**r;let o=1;return a>=5?o=5:a>=2&&(o=2),o*10**r/100}const t=Math.floor(Math.log10(e)),n=e/10**t;let i=1;return n>=5?i=5:n>=2&&(i=2),i*10**t}_drawScaleBar(e,t,n){if(!this._map)return;const i=this._map.getCenter(),s=this._map.getZoom(),r=156543.03392804097*Math.cos(i.lat*Math.PI/180)/2**s;if(!Number.isFinite(r)||r<=0)return;const a=n,o=Math.max(80,Math.min(160,t.w*.16))/a*r,l=this._niceDistance(o),c=Math.max(40,l/r*a),h=18,d=10;if(t.h<56)return;const f=t.x+h,m=t.y+t.h-h-24;e.save();const A=c+16,y=38;e.fillStyle="rgba(255,255,255,0.9)",e.strokeStyle="rgba(0,0,0,0.35)",e.lineWidth=1,e.beginPath(),e.rect(f-8,m-8,A,y),e.fill(),e.stroke(),e.fillStyle="#111",e.fillRect(f,m,c/2,d),e.fillStyle="#fff",e.fillRect(f+c/2,m,c/2,d),e.strokeStyle="#111",e.lineWidth=1,e.strokeRect(f,m,c,d);const x=l>=1e3?`${(l/1e3).toFixed(l%1e3===0?0:1)} km`:l>=1?`${Math.round(l)} m`:`${Math.round(l*100)} cm`;e.fillStyle="#111",e.font='600 12px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',e.textAlign="center",e.textBaseline="top",e.fillText(x,f+c/2,m+d+4),e.restore()}_getPageLayout(e){const t=e.width,n=e.height;if(this._state.pageSize==="fit"){const R=this._state.width||t,k=this._state.height||n,L=(this._state.dpi>0?this._state.dpi:96)/96,T=Math.max(1,Math.round(R*L)),C=Math.max(1,Math.round(k*L));return{pageW:T,pageH:C,content:{x:0,y:0,w:T,h:C},mapDest:{x:0,y:0,w:T,h:C},scaleX:t>0?T/t:1,clip:!1,pageWidthIn:R/96,pageHeightIn:k/96}}const[i,s]=mU[this._state.pageSize];let r=this._state.orientation;r==="auto"&&(r=t>=n?"landscape":"portrait");const a=r==="landscape"?s:i,o=r==="landscape"?i:s,l=this._state.dpi>0?this._state.dpi:96,c=Math.max(1,Math.round(a*l)),h=Math.max(1,Math.round(o*l)),d=Math.max(0,Math.round(this._state.margin/72*l)),f=d,m=d,A=Math.max(1,c-d*2),y=Math.max(1,h-d*2),x=Math.min(A/t,y/n),v=Math.max(A/t,y/n),b=this._state.fitMode==="cover"?v:x,w=t*b,S=n*b;return{pageW:c,pageH:h,content:{x:f,y:m,w:A,h:y},mapDest:{x:f+(A-w)/2,y:m+(y-S)/2,w,h:S},scaleX:b,clip:this._state.fitMode==="cover",pageWidthIn:a,pageHeightIn:o}}async _createExportCanvas(){if(!this._map)return null;try{const e=await this._captureMapCanvas(),t=this._getPageLayout(e),{pageW:n,pageH:i,content:s,mapDest:r}=t,a=document.createElement("canvas");a.width=n,a.height=i;const o=a.getContext("2d");if(!o)return null;this._state.pageSize!=="fit"&&(o.fillStyle=this._state.pageBackground,o.fillRect(0,0,n,i)),o.save(),t.clip&&(o.beginPath(),o.rect(s.x,s.y,s.w,s.h),o.clip()),o.drawImage(e,r.x,r.y,r.w,r.h),o.restore();const l=this._state.title.trim();let c=0;if(l){const h=this._options.titleFontSize;o.font=`bold ${h}px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`;const d=o.measureText(l);c=h+h*.6*2,o.fillStyle=this._options.titleBackground,o.fillRect(s.x,s.y,s.w,c),o.fillStyle=this._options.titleFontColor,o.textBaseline="middle";const f=s.x+(s.w-d.width)/2;o.fillText(l,f,s.y+c/2)}if(this._state.includeNorthArrow){const h=Math.max(44,Math.min(72,s.w*.07)),d=h+18;if(s.w>=d){const f=s.x+s.w-h-18,m=Math.max(s.y+18,s.y+c+8),A=this._map.getBearing();this._drawNorthArrow(o,f,m,h,A)}}return this._state.includeScaleBar&&this._drawScaleBar(o,s,t.scaleX),this._state.colorbar.enabled&&this._drawColorbar(o,s,c),a}catch(e){const t=e instanceof Error?e.message:"Failed to capture map canvas";return this._emit("error",{error:t}),null}}async _exportMap(){if(!this._state.exporting){this._setExporting(!0);try{const e=await this._createExportCanvas();if(!e){this._showFeedback("Export failed"),this._setExporting(!1);return}if(this._state.format==="pdf")await this._exportPdf(e),this._showFeedback("Exported!"),this._emit("export");else if(this._state.format==="svg")this._exportSvg(e),this._showFeedback("Exported!"),this._emit("export");else{const t=this._state.format==="jpeg"?"image/jpeg":"image/png",n=this._state.format==="jpeg"?this._state.quality:void 0,i=this._state.format==="jpeg"?"jpg":"png",s=await new Promise(c=>{e.toBlob(h=>c(h),t,n)});if(!s){this._showFeedback("Export failed"),this._emit("error",{error:"Failed to create image blob"}),this._setExporting(!1);return}const r=await this._embedDpi(s,this._state.format==="jpeg"?"jpeg":"png"),a=URL.createObjectURL(r),o=document.createElement("a");o.href=a,o.download=`${this._state.filename}.${i}`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(a);const l=await this._blobToDataUrl(r);this._showFeedback("Exported!"),this._emit("export",{dataUrl:l})}}catch(e){const t=e instanceof Error?e.message:"Export failed";this._showFeedback("Export failed"),this._emit("error",{error:t})}finally{this._setExporting(!1)}}}async _copyToClipboard(){if(!this._state.exporting){this._setExporting(!0);try{const e=await this._createExportCanvas();if(!e){this._showFeedback("Copy failed"),this._setExporting(!1);return}const t=await new Promise(i=>{e.toBlob(s=>i(s),"image/png")});if(!t){this._showFeedback("Copy failed"),this._emit("error",{error:"Failed to create image blob"}),this._setExporting(!1);return}await navigator.clipboard.write([new ClipboardItem({"image/png":t})]);const n=e.toDataURL("image/png");this._showFeedback("Copied!"),this._emit("copy",{dataUrl:n})}catch(e){const t=e instanceof Error?e.message:"Copy to clipboard failed";this._showFeedback("Copy failed"),this._emit("error",{error:t})}finally{this._setExporting(!1)}}}_setupZoomHandler(){this._map&&(this._handleZoom=()=>{const e=this._map.getZoom(),t=e>=this._options.minzoom&&e<=this._options.maxzoom;t!==this._zoomVisible&&(this._zoomVisible=t,this._container&&(this._container.style.display=t&&this._state.visible?"":"none"))},this._map.on("zoom",this._handleZoom),this._handleZoom())}show(){return this._state.visible=!0,this._container&&this._zoomVisible&&(this._container.style.display=""),this._emit("show"),this}hide(){return this._state.visible=!1,this._container&&(this._container.style.display="none"),this._emit("hide"),this}getState(){return{...this._state}}setTheme(e){return this._options.theme=e,this._container&&this._applyThemeClass(this._container),this}_applyThemeClass(e){e.classList.remove("maplibre-gl-print-control--light","maplibre-gl-print-control--dark"),this._options.theme==="light"?e.classList.add("maplibre-gl-print-control--light"):this._options.theme==="dark"&&e.classList.add("maplibre-gl-print-control--dark")}setFormat(e){return this._state.format=e,this._formatSelect&&(this._formatSelect.value=e),this._updateQualityVisibility(),this._updateCopyBtnVisibility(),this._emit("update"),this}setQuality(e){return this._state.quality=Math.max(.1,Math.min(1,e)),this._qualityInput&&(this._qualityInput.value=String(this._state.quality)),this._qualityValue&&(this._qualityValue.textContent=this._state.quality.toFixed(2)),this._emit("update"),this}setTitle(e){return this._state.title=e,this._titleInput&&(this._titleInput.value=e),this._emit("update"),this}async exportMap(e){const t={...this._state,colorbar:{...this._state.colorbar}};e?.format&&(this._state.format=e.format),e?.quality&&(this._state.quality=e.quality),e?.filename&&(this._state.filename=e.filename),e?.title!==void 0&&(this._state.title=e.title),e?.includeNorthArrow!==void 0&&(this._state.includeNorthArrow=e.includeNorthArrow),e?.includeScaleBar!==void 0&&(this._state.includeScaleBar=e.includeScaleBar),e?.colorbar!==void 0&&(this._state.colorbar={...this._state.colorbar,...e.colorbar}),e?.width&&(this._state.width=e.width),e?.height&&(this._state.height=e.height),e?.pageSize&&(this._state.pageSize=e.pageSize),e?.orientation&&(this._state.orientation=e.orientation),e?.dpi&&(this._state.dpi=e.dpi),e?.margin!==void 0&&(this._state.margin=e.margin),e?.pageBackground!==void 0&&(this._state.pageBackground=e.pageBackground),e?.fitMode&&(this._state.fitMode=e.fitMode);try{const n=await this._createExportCanvas();if(!n)throw new Error("Failed to capture map canvas");if(this._state.format==="pdf")return await this._exportPdf(n),this._emit("export"),"";if(this._state.format==="svg")return this._exportSvg(n),this._emit("export"),"";const i=this._state.format==="jpeg"?"image/jpeg":"image/png",s=this._state.format==="jpeg"?this._state.quality:void 0,r=await new Promise(l=>{n.toBlob(c=>l(c),i,s)});if(!r)throw new Error("Failed to create image blob");const a=await this._embedDpi(r,this._state.format==="jpeg"?"jpeg":"png"),o=await this._blobToDataUrl(a);return this._emit("export",{dataUrl:o}),o}finally{this._state.format=t.format,this._state.quality=t.quality,this._state.filename=t.filename,this._state.title=t.title,this._state.includeNorthArrow=t.includeNorthArrow,this._state.includeScaleBar=t.includeScaleBar,this._state.colorbar=t.colorbar,this._state.width=t.width,this._state.height=t.height,this._state.pageSize=t.pageSize,this._state.orientation=t.orientation,this._state.dpi=t.dpi,this._state.margin=t.margin,this._state.pageBackground=t.pageBackground,this._state.fitMode=t.fitMode}}setColorbar(e){return this._state.colorbar={...this._state.colorbar,...e},this._colorbarInput&&(this._colorbarInput.checked=this._state.colorbar.enabled??!1),this._colorbarColormapSelect&&typeof this._state.colorbar.colormap=="string"&&(this._colorbarColormapSelect.value=this._state.colorbar.colormap),this._colorbarOrientationSelect&&(this._colorbarOrientationSelect.value=this._state.colorbar.orientation??"vertical"),this._colorbarVminInput&&(this._colorbarVminInput.value=String(this._state.colorbar.vmin??0)),this._colorbarVmaxInput&&(this._colorbarVmaxInput.value=String(this._state.colorbar.vmax??1)),this._colorbarLabelInput&&(this._colorbarLabelInput.value=this._state.colorbar.label??""),this._colorbarUnitsInput&&(this._colorbarUnitsInput.value=this._state.colorbar.units??""),this._updateColorbarSettingsVisibility(),this._emit("update"),this}};function bE(e,t,n){if(e.length===0)return null;const i=document.createElement("span");i.className="maplibre-gl-sample-trigger-label",i.textContent=t;const s=document.createElement("span");s.className="maplibre-gl-sample-caret",s.textContent="▾";const r=document.createElement("button");r.type="button",r.className="maplibre-gl-sample-trigger",r.setAttribute("aria-haspopup","listbox"),r.setAttribute("aria-expanded","false"),r.setAttribute("aria-label",t),r.appendChild(i),r.appendChild(s);const a=document.createElement("div");a.className="maplibre-gl-sample-menu",a.setAttribute("role","listbox"),a.hidden=!0;let o=!1;const l=h=>{o=h,a.hidden=!h,r.setAttribute("aria-expanded",String(h)),r.classList.toggle("open",h),h&&a.firstElementChild?.focus()};for(const h of e){const d=document.createElement("button");d.type="button",d.className="maplibre-gl-sample-option",d.setAttribute("role","option"),d.textContent=h.label,d.title=h.url,d.addEventListener("click",f=>{f.stopPropagation(),l(!1),r.focus(),n(h.url)}),a.appendChild(d)}r.addEventListener("click",h=>{h.stopPropagation(),l(!o)});const c=document.createElement("div");return c.className="maplibre-gl-sample-dropdown",c.appendChild(r),c.appendChild(a),c.addEventListener("keydown",h=>{h.key==="Escape"&&o&&(l(!1),r.focus())}),c.addEventListener("focusout",h=>{const d=h.relatedTarget;(!d||!c.contains(d))&&l(!1)}),c}var vU="maplibre-gl-panel-resize-handle",yU="maplibre-gl-panel-resize-left",bU="maplibre-gl-panel-resize-right";function xE(e){if(e&&typeof e.getContainer=="function")return e.getContainer()}function h2(e){const t=e?.parentElement;return t?t.classList.contains("maplibregl-ctrl-top-left")?"top-left":t.classList.contains("maplibregl-ctrl-top-right")?"top-right":t.classList.contains("maplibregl-ctrl-bottom-left")?"bottom-left":t.classList.contains("maplibregl-ctrl-bottom-right")?"bottom-right":"top-right":"top-right"}function xU(e,t,n){const i=xE(t),s=e.getBoundingClientRect(),r=h2(n).startsWith("bottom");if(i){const o=i.getBoundingClientRect(),l=r?s.bottom-o.top-12:o.bottom-s.top-12;return Math.max(160,l)}const a=typeof window<"u"?window.innerHeight:720;return Math.max(160,a-12)}function EE(e,t,n){const i=xU(e,t,n);e.style.maxHeight=`min(720px, ${i}px)`,e.style.overflowY="auto",e.style.scrollbarGutter="stable"}function fA(e){const{panel:t,map:n,container:i}=e,s=e.getUserSize();if(!s)return;const r=e.minWidth??260,a=e.minHeight??180,o=xE(n),l=h2(i),c=l.endsWith("right"),h=l.startsWith("bottom"),d=t.getBoundingClientRect();let f=1/0,m=1/0;if(o){const x=o.getBoundingClientRect();f=(c?d.right-x.left:x.right-d.left)-12,m=(h?d.bottom-x.top:x.bottom-d.top)-12}const A=Math.min(Math.max(r,s.width),Math.max(0,f)),y=Math.min(Math.max(a,s.height),Math.max(0,m));t.style.boxSizing="border-box",t.style.maxWidth="none",t.style.maxHeight="none",t.style.width=`${A}px`,t.style.height=`${y}px`,t.style.overflowY="auto"}function CE(e){const{panel:t,map:n,container:i}=e,s=e.minWidth??260,r=e.minHeight??180;(!t.style.position||t.style.position==="static")&&(t.style.position="relative");const a=[];for(const o of["left","right"]){const l=document.createElement("div");l.className=`${vU} ${o==="left"?yU:bU}`,l.setAttribute("aria-hidden","true"),l.addEventListener("pointerdown",c=>EU(c,o,l,e,s,r)),t.appendChild(l),a.push(l)}return a}function EU(e,t,n,i,s,r){const{panel:a,map:o}=i;e.preventDefault(),e.stopPropagation();const l=a.getBoundingClientRect(),c=e.clientX,h=e.clientY,d=l.width,f=l.height,m=l.left,A=l.top,y=l.right,x=xE(o)?.getBoundingClientRect(),v={position:a.style.position,left:a.style.left,top:a.style.top,right:a.style.right,bottom:a.style.bottom,width:a.style.width,height:a.style.height,maxWidth:a.style.maxWidth,maxHeight:a.style.maxHeight};a.style.boxSizing="border-box",a.style.position="fixed",a.style.left=`${m}px`,a.style.top=`${A}px`,a.style.right="auto",a.style.bottom="auto",a.style.width=`${d}px`,a.style.height=`${f}px`,a.style.maxWidth="none",a.style.maxHeight="none";let b=d,w=f;const S=k=>{const L=k.clientX-c,T=k.clientY-h;let C=1/0;x&&(C=Math.max(r,x.bottom-A-12));const I=Math.max(r,Math.min(f+T,C));let M,O=m;if(t==="right"){let N=1/0;x&&(N=Math.max(s,x.right-m-12)),M=Math.max(s,Math.min(d+L,N))}else{let N=1/0;x&&(N=Math.max(s,y-x.left-12)),M=Math.max(s,Math.min(d-L,N)),O=m+(d-M)}a.style.width=`${M}px`,a.style.height=`${I}px`,a.style.left=`${O}px`,b=M,w=I},R=k=>{n.releasePointerCapture?.(k.pointerId),n.removeEventListener("pointermove",S),n.removeEventListener("pointerup",R),n.removeEventListener("pointercancel",R),a.style.position=v.position,a.style.left=v.left,a.style.top=v.top,a.style.right=v.right,a.style.bottom=v.bottom,i.setUserSize({width:b,height:w}),a.style.width=v.width,a.style.height=v.height,a.style.maxWidth=v.maxWidth,a.style.maxHeight=v.maxHeight,fA(i)};n.setPointerCapture?.(e.pointerId),n.addEventListener("pointermove",S),n.addEventListener("pointerup",R),n.addEventListener("pointercancel",R)}var u2=["bone","bwr","cividis","cool","coolwarm","gray","hot","inferno","jet","magma","ocean","plasma","rainbow","RdBu","RdYlBu","RdYlGn","seismic","spectral","terrain","turbo","viridis"];function CU(e){for(const t of u2){const n=wE(t);if(JSON.stringify(n)===JSON.stringify(e))return t}return"custom"}function wE(e){return nr(e).map(t=>t.color)}var wU='<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg>',SU={position:"top-right",className:"",visible:!0,collapsed:!0,beforeId:"",defaultUrl:"",sampleData:[],sampleDataLabel:"Load sample data...",loadDefaultUrl:!1,defaultVariable:"",defaultColormap:wE("viridis"),defaultClim:[0,1],defaultSelector:{},defaultLayerName:"",defaultOpacity:1,defaultPickable:!0,panelWidth:300,maxHeight:500,backgroundColor:"rgba(255, 255, 255, 0.95)",borderRadius:4,opacity:1,fontSize:13,fontColor:"#333",minzoom:0,maxzoom:24},X0=class{_container;_button;_panel;_options;_state;_eventHandlers=new Map;_map;_handleZoom;_zoomVisible=!0;_userPanelSize=null;_mapResizeHandler;_zarrLayers=new Map;_zarrLayerPropsMap=new Map;_layerCounter=0;_activePopup;_colormapName="viridis";_customColormap;_availableVariables=[];_variablesLoading=!1;constructor(e){this._options={...SU,...e},e?.defaultColormap&&(this._colormapName=CU(e.defaultColormap),this._colormapName==="custom"&&(this._customColormap=e.defaultColormap)),this._state={visible:this._options.visible,collapsed:this._options.collapsed,url:this._options.defaultUrl,variable:this._options.defaultVariable,colormap:this._options.defaultColormap,clim:this._options.defaultClim,selector:this._options.defaultSelector,layerName:this._options.defaultLayerName,layerOpacity:this._options.defaultOpacity,pickable:this._options.defaultPickable,hasLayer:!1,layerCount:0,layers:[],loading:!1,error:null,status:null}}onAdd(e){if(this._map=e,this._container=this._createContainer(),this._render(),this._handleZoom=()=>this._checkZoomVisibility(),this._map.on("zoom",this._handleZoom),this._checkZoomVisibility(),this._mapResizeHandler=()=>this._reflowPanel(),this._map.on("resize",this._mapResizeHandler),this._options.loadDefaultUrl&&this._options.defaultUrl&&this._options.defaultVariable){const t=()=>{this._addLayer()};this._map.isStyleLoaded()?setTimeout(t,100):this._map.once("idle",t)}return this._container}onRemove(){this._removeLayer(),this._map&&this._handleZoom&&(this._map.off("zoom",this._handleZoom),this._handleZoom=void 0),this._map&&this._mapResizeHandler&&(this._map.off("resize",this._mapResizeHandler),this._mapResizeHandler=void 0),this._map=void 0,this._container?.parentNode?.removeChild(this._container),this._container=void 0,this._button=void 0,this._panel=void 0,this._eventHandlers.clear()}show(){this._state.visible||(this._state.visible=!0,this._updateDisplayState(),this._emit("show"))}hide(){this._state.visible&&(this._state.visible=!1,this._updateDisplayState(),this._emit("hide"))}expand(){this._state.collapsed&&(this._state.collapsed=!1,this._render(),this._emit("expand"))}collapse(){this._state.collapsed||(this._state.collapsed=!0,this._render(),this._emit("collapse"))}toggle(){this._state.collapsed?this.expand():this.collapse()}_reflowPanel(){this._panel&&(EE(this._panel,this._map,this._container),fA({panel:this._panel,map:this._map,container:this._container,getUserSize:()=>this._userPanelSize,setUserSize:e=>{this._userPanelSize=e}}))}getState(){return{...this._state}}update(e){this._options={...this._options,...e},e.visible!==void 0&&(this._state.visible=e.visible),e.collapsed!==void 0&&(this._state.collapsed=e.collapsed),this._render(),this._emit("update")}on(e,t){this._eventHandlers.has(e)||this._eventHandlers.set(e,new Set),this._eventHandlers.get(e).add(t)}off(e,t){this._eventHandlers.get(e)?.delete(t)}async addLayer(e,t,n){e&&(this._state.url=e),t&&(this._state.variable=t),await this._addLayer(n)}removeLayer(e){this._removeLayer(e),this._render()}getLayerIds(){return Array.from(this._zarrLayers.keys())}getLayerOpacity(e){const t=this._zarrLayers.get(e);return t?t.opacity??1:null}setLayerOpacity(e,t){const n=this._zarrLayers.get(e);if(!n||typeof n.setOpacity!="function")return;const i=Math.max(0,Math.min(1,t));n.setOpacity(i),this._map&&this._map.triggerRepaint()}getLayerVisibility(e){const t=this.getLayerOpacity(e);return t!==null&&t>0}setLayerVisibility(e,t,n=1){t?this.setLayerOpacity(e,n):this.setLayerOpacity(e,0)}getLayerUrl(e){return this._zarrLayerPropsMap.get(e)?.source??null}getLayersMap(){return this._zarrLayers}async fetchVariables(){if(!this._state.url)return[];this._variablesLoading=!0,this._render();try{const e=this._state.url.replace(/\/$/,"");try{const t=await fetch(`${e}/.zmetadata`);if(t.ok){const n=await t.json(),i=Object.keys(n.metadata||{}).filter(o=>o.endsWith("/.zarray")).map(o=>o.replace("/.zarray","")).filter(o=>o&&!o.startsWith(".")),s=new Set(["x","y","lat","lon","latitude","longitude","time","band","month","spatial_ref"]),r=new Set;for(const o of i){const l=o.split("/"),c=l[l.length-1];s.has(c)||r.add(c)}let a=Array.from(r);if(a.length===0){const o=new Set;for(const l of i){const c=l.split("/");o.add(c[c.length-1])}a=Array.from(o)}if(a.sort(),a.length>0)return this._availableVariables=a,this._variablesLoading=!1,this._render(),a}}catch{}try{const t=await fetch(`${e}/zarr.json`);t.ok&&(await t.json()).node_type}catch{}try{(await fetch(`${e}/.zgroup`)).ok}catch{}return this._variablesLoading=!1,this._render(),this._availableVariables}catch(e){return console.warn("[ZarrLayerControl] Failed to fetch variables:",e),this._variablesLoading=!1,this._render(),[]}}_emit(e,t){const n=this._eventHandlers.get(e);if(n){const i={type:e,state:this.getState(),...t};n.forEach(s=>s(i))}}_checkZoomVisibility(){if(!this._map)return;const e=this._map.getZoom(),{minzoom:t,maxzoom:n}=this._options,i=e>=t&&e<=n;i!==this._zoomVisible&&(this._zoomVisible=i,this._updateDisplayState())}_updateDisplayState(){if(!this._container)return;const e=this._state.visible&&this._zoomVisible;this._container.style.display=e?"block":"none"}_createContainer(){const e=document.createElement("div");return e.className=`maplibregl-ctrl maplibre-gl-zarr-layer${this._options.className?` ${this._options.className}`:""}`,this._state.visible&&this._zoomVisible||(e.style.display="none"),Object.assign(e.style,{backgroundColor:this._options.backgroundColor,borderRadius:`${this._options.borderRadius}px`,boxShadow:"0 0 0 2px rgba(0, 0, 0, 0.1)"}),this._options.opacity!==1&&(e.style.opacity=String(this._options.opacity)),e}_render(){if(!this._container)return;const e=this._container.querySelector(".maplibre-gl-zarr-layer-panel"),t=e?e.scrollTop:0;if(this._container.innerHTML="",this._state.collapsed?this._renderCollapsed():this._renderExpanded(),this._updateDisplayState(),t>0){const n=this._container.querySelector(".maplibre-gl-zarr-layer-panel");n&&(n.scrollTop=t)}}_renderCollapsed(){this._container&&(this._button=document.createElement("button"),this._button.type="button",this._button.className=`maplibre-gl-zarr-layer-button${this._state.hasLayer?" maplibre-gl-zarr-layer-button--active":""}`,this._button.title="Zarr Layer",this._button.setAttribute("aria-label","Zarr Layer"),this._button.innerHTML=wU,this._button.addEventListener("click",()=>this.expand()),this._container.appendChild(this._button),this._panel=void 0)}_renderExpanded(){if(!this._container)return;const e=document.createElement("div");e.className="maplibre-gl-zarr-layer-panel",e.style.width=`${this._options.panelWidth}px`,this._panel=e;const t=document.createElement("div");t.className="maplibre-gl-zarr-layer-header";const n=document.createElement("span");n.className="maplibre-gl-zarr-layer-title",n.textContent="Zarr Layer",t.appendChild(n);const i=document.createElement("button");i.className="maplibre-gl-zarr-layer-close",i.innerHTML="&times;",i.title="Close",i.addEventListener("click",()=>this.collapse()),t.appendChild(i),e.appendChild(t);const s=this._createFormGroup("Zarr URL","url"),r=document.createElement("input");r.type="text",r.className="maplibre-gl-zarr-layer-input",r.style.color="#000",r.placeholder="https://example.com/data.zarr",r.value=this._state.url,r.addEventListener("input",()=>{this._state.url=r.value}),s.appendChild(r);const a=bE(this._options.sampleData,this._options.sampleDataLabel,z=>{r.value=z,this._state.url=z});a&&e.appendChild(a),e.appendChild(s);const o=this._createFormGroup("Variable","variable"),l=document.createElement("div");if(l.className="maplibre-gl-zarr-layer-var-row",l.style.display="flex",l.style.gap="6px",this._availableVariables.length>0){const z=document.createElement("select");z.className="maplibre-gl-zarr-layer-select",z.style.color="#000",z.style.flex="1";for(const H of this._availableVariables){const W=document.createElement("option");W.value=H,W.textContent=H,H===this._state.variable&&(W.selected=!0),z.appendChild(W)}z.addEventListener("change",()=>{this._state.variable=z.value}),l.appendChild(z)}else{const z=document.createElement("input");z.type="text",z.className="maplibre-gl-zarr-layer-input",z.style.color="#000",z.style.flex="1",z.placeholder="e.g., temperature",z.value=this._state.variable,z.addEventListener("input",()=>{this._state.variable=z.value}),l.appendChild(z)}const c=document.createElement("button");c.className="maplibre-gl-zarr-layer-btn",c.textContent=this._variablesLoading?"...":"Fetch",c.disabled=this._variablesLoading||!this._state.url,c.style.padding="5px 10px",c.style.flexShrink="0",c.addEventListener("click",()=>this.fetchVariables()),l.appendChild(c),o.appendChild(l),e.appendChild(o);const h=this._createFormGroup("Colormap","colormap"),d=document.createElement("select");if(d.className="maplibre-gl-zarr-layer-select",d.style.color="#000",this._customColormap){const z=document.createElement("option");z.value="custom",z.textContent="custom",this._colormapName==="custom"&&(z.selected=!0),d.appendChild(z)}for(const z of u2){const H=document.createElement("option");H.value=z,H.textContent=z,z===this._colormapName&&(H.selected=!0),d.appendChild(H)}d.addEventListener("change",()=>{const z=d.value;z==="custom"&&this._customColormap?(this._colormapName="custom",this._state.colormap=this._customColormap):(this._colormapName=z,this._state.colormap=wE(this._colormapName)),this._updateColormapPreview()}),h.appendChild(d);const f=document.createElement("div");f.className="maplibre-gl-zarr-layer-colormap-preview",f.id="zarr-colormap-preview",f.style.background=`linear-gradient(to right, ${this._state.colormap.join(", ")})`,h.appendChild(f),e.appendChild(h);const m=document.createElement("div");m.className="maplibre-gl-zarr-layer-row";const A=this._createFormGroup("Clim Min","clim-min"),y=document.createElement("input");y.type="number",y.className="maplibre-gl-zarr-layer-input",y.style.color="#000",y.value=String(this._state.clim[0]),y.addEventListener("input",()=>{this._state.clim=[Number(y.value)||0,this._state.clim[1]]}),A.appendChild(y),m.appendChild(A);const x=this._createFormGroup("Clim Max","clim-max"),v=document.createElement("input");v.type="number",v.className="maplibre-gl-zarr-layer-input",v.style.color="#000",v.value=String(this._state.clim[1]),v.addEventListener("input",()=>{this._state.clim=[this._state.clim[0],Number(v.value)||1]}),x.appendChild(v),m.appendChild(x),e.appendChild(m);const b=this._createFormGroup("Selector (JSON)","selector"),w=document.createElement("input");w.type="text",w.className="maplibre-gl-zarr-layer-input",w.style.color="#000",w.placeholder='{"time": 0, "band": "prec"}',w.value=this._state.selector?JSON.stringify(this._state.selector):"",w.addEventListener("input",()=>{try{const z=w.value?JSON.parse(w.value):{};this._state.selector=z}catch{}}),b.appendChild(w),e.appendChild(b);const S=this._createFormGroup("Opacity","opacity"),R=document.createElement("div");R.className="maplibre-gl-zarr-layer-slider-row";const k=document.createElement("input");k.type="range",k.className="maplibre-gl-zarr-layer-slider",k.min="0",k.max="100",k.value=String(Math.round(this._state.layerOpacity*100));const L=document.createElement("span");L.className="maplibre-gl-zarr-layer-slider-value",L.textContent=`${Math.round(this._state.layerOpacity*100)}%`,k.addEventListener("input",()=>{const z=Number(k.value);this._state.layerOpacity=z/100,L.textContent=`${z}%`,this._updateOpacity()}),R.appendChild(k),R.appendChild(L),S.appendChild(R),e.appendChild(S);const T=document.createElement("div");T.className="maplibre-gl-zarr-layer-form-group maplibre-gl-zarr-layer-checkbox-group";const C=document.createElement("label");C.className="maplibre-gl-zarr-layer-checkbox-label";const I=document.createElement("input");I.type="checkbox",I.className="maplibre-gl-zarr-layer-checkbox",I.checked=this._state.pickable,I.addEventListener("change",()=>{this._state.pickable=I.checked,this._updatePickable()}),C.appendChild(I);const M=document.createElement("span");M.textContent="Pickable (click to show pixel value)",C.appendChild(M),T.appendChild(C),e.appendChild(T);const O=this._createFormGroup("Layer Name","layer-name"),N=document.createElement("input");N.type="text",N.className="maplibre-gl-zarr-layer-input",N.style.color="#000",N.placeholder="Optional custom layer name",N.value=this._state.layerName,N.addEventListener("input",()=>{this._state.layerName=N.value}),O.appendChild(N),e.appendChild(O);const D=this._createFormGroup("Before Layer ID (optional)","before-id"),P=document.createElement("input");P.type="text",P.className="maplibre-gl-zarr-layer-input",P.style.color="#000",P.placeholder="e.g. labels or water",P.value=this._options.beforeId||"",P.addEventListener("input",()=>{this._options.beforeId=P.value||""}),D.appendChild(P),e.appendChild(D);const U=document.createElement("div");U.className="maplibre-gl-zarr-layer-buttons";const Q=document.createElement("button");if(Q.className="maplibre-gl-zarr-layer-btn maplibre-gl-zarr-layer-btn--primary",Q.textContent="Add Layer",Q.disabled=this._state.loading,Q.addEventListener("click",()=>this._addLayer()),U.appendChild(Q),e.appendChild(U),this._state.loading?this._appendStatus("Loading Zarr...","info"):this._state.error?this._appendStatus(this._state.error,"error"):this._state.status&&this._appendStatus(this._state.status,"success"),this._zarrLayers.size>0){const z=document.createElement("div");z.className="maplibre-gl-zarr-layer-list";const H=document.createElement("div");H.className="maplibre-gl-zarr-layer-list-header",H.textContent=`Layers (${this._zarrLayers.size})`,z.appendChild(H);for(const[W]of this._zarrLayers){const te=this._zarrLayerPropsMap.get(W);if(!te)continue;const J=document.createElement("div");J.className="maplibre-gl-zarr-layer-list-item";const K=document.createElement("span");K.className="maplibre-gl-zarr-layer-list-label";const re=te.source,ce=te.variable,oe=te._layerName;let ge;if(oe)ge=oe;else{ge=ce||W;try{ge=`${new URL(re).pathname.split("/").pop()} / ${ce}`}catch{ge=`${re} / ${ce}`}}K.textContent=ge,K.title=`${re} (${ce})`,J.appendChild(K);const ie=document.createElement("button");ie.className="maplibre-gl-zarr-layer-list-remove",ie.innerHTML="&times;",ie.title="Remove layer",ie.addEventListener("click",()=>{this._removeLayer(W),this._render()}),J.appendChild(ie),z.appendChild(J)}e.appendChild(z)}CE({panel:e,map:this._map,container:this._container,getUserSize:()=>this._userPanelSize,setUserSize:z=>{this._userPanelSize=z}}),this._reflowPanel(),this._container.appendChild(e),this._button=void 0,requestAnimationFrame(()=>this._reflowPanel())}_createFormGroup(e,t){const n=document.createElement("div");n.className="maplibre-gl-zarr-layer-form-group";const i=document.createElement("label");return i.textContent=e,i.htmlFor=`zarr-layer-${t}`,n.appendChild(i),n}_appendStatus(e,t){if(!this._panel)return;const n=document.createElement("div");n.className=`maplibre-gl-zarr-layer-status maplibre-gl-zarr-layer-status--${t}`,n.textContent=e,this._panel.appendChild(n)}_updateColormapPreview(){const e=document.getElementById("zarr-colormap-preview");e&&(e.style.background=`linear-gradient(to right, ${this._state.colormap.join(", ")})`)}async _addLayer(e){const t=!!e?.store;if(!this._map||!t&&!this._state.url||!this._state.variable){this._state.error=t?"Please enter a variable name.":"Please enter a Zarr URL and variable name.",this._render();return}this._state.loading=!0,this._state.error=null,this._state.status=null,this._render();try{const{ZarrLayer:n}=await import("@carbonplan/zarr-layer"),i=`zarr-layer-${this._layerCounter++}`,s=e?.selector??(this._state.selector&&Object.keys(this._state.selector).length>0?this._state.selector:void 0),r={id:i,variable:this._state.variable,colormap:e?.colormap??this._state.colormap,clim:e?.clim??this._state.clim,opacity:e?.opacity??this._state.layerOpacity,selector:s};this._state.url&&(r.source=this._state.url),e?.store&&(r.store=e.store),e?.zarrVersion&&(r.zarrVersion=e.zarrVersion),e?.transformRequest&&(r.transformRequest=e.transformRequest),e?.crs&&(r.crs=e.crs),e?.proj4&&(r.proj4=e.proj4),e?.bounds&&(r.bounds=e.bounds),e?.spatialDimensions&&(r.spatialDimensions=e.spatialDimensions);const a={...r};delete a.store,delete a.transformRequest;const o=this._state.layerName?.trim();o&&(a._layerName=o),this._zarrLayerPropsMap.set(i,a);const l=new n(r);this._zarrLayers.set(i,l);let c;this._options.beforeId&&(this._map.getLayer(this._options.beforeId)?c=this._options.beforeId:console.warn(`[ZarrLayerControl] beforeId "${this._options.beforeId}" not found in map layers, adding layer on top`)),c?this._map.addLayer(l,c):this._map.addLayer(l),this._state.pickable&&this._setupLayerClickHandler(i),this._state.hasLayer=this._zarrLayers.size>0,this._state.layerCount=this._zarrLayers.size,this._state.layers=this._buildLayerInfoList(),this._state.loading=!1,this._state.status="Zarr layer added successfully.",this._state.layerName="",this._render(),this._emit("layeradd",{url:this._state.url,layerId:i})}catch(n){this._state.loading=!1,this._state.error=`Failed to load Zarr: ${n instanceof Error?n.message:String(n)}`,this._render(),this._emit("error",{error:this._state.error})}}_setupLayerClickHandler(e){if(!this._map)return;const t=this._map,n=this._zarrLayerPropsMap.get(e),i=s=>{if(!this._state.pickable)return;this._activePopup&&this._activePopup.remove();const{lngLat:r}=s;let a='<div class="maplibre-gl-zarr-layer-popup">';a+='<table class="maplibre-gl-zarr-layer-popup-table">',a+=`<tr><td><strong>Layer</strong></td><td>${e}</td></tr>`,a+=`<tr><td><strong>Variable</strong></td><td>${n?.variable||"N/A"}</td></tr>`,a+=`<tr><td><strong>Lng</strong></td><td>${r.lng.toFixed(6)}</td></tr>`,a+=`<tr><td><strong>Lat</strong></td><td>${r.lat.toFixed(6)}</td></tr>`,n?.clim&&(a+=`<tr><td><strong>Color Range</strong></td><td>${n.clim[0]} - ${n.clim[1]}</td></tr>`),n?.source&&(a+=`<tr><td><strong>Source</strong></td><td style="word-break:break-all;max-width:150px;">${n.source.split("/").pop()}</td></tr>`),a+="</table>",a+="</div>",this._activePopup=new fi.default.Popup({closeButton:!0,maxWidth:"250px"}).setLngLat(r).setHTML(a).addTo(t);const o=this._activePopup.getElement();o&&(o.style.zIndex="1000")};this._zarrLayers.get(e)._clickHandler=i,t.on("click",i)}_updatePickable(){}_removeLayer(e){if(this._map)if(e){if(this._zarrLayers.get(e))try{this._map.removeLayer(e)}catch{}this._zarrLayers.delete(e),this._zarrLayerPropsMap.delete(e),this._state.hasLayer=this._zarrLayers.size>0,this._state.layerCount=this._zarrLayers.size,this._state.layers=this._buildLayerInfoList(),this._state.status=null,this._state.error=null,this._emit("layerremove",{layerId:e})}else{for(const[t]of this._zarrLayers)try{this._map.removeLayer(t)}catch{}this._zarrLayers.clear(),this._zarrLayerPropsMap.clear(),this._state.hasLayer=!1,this._state.layerCount=0,this._state.layers=[],this._state.status=null,this._state.error=null,this._emit("layerremove")}}_updateOpacity(){if(this._zarrLayers.size===0)return;const e=this._state.layerOpacity;for(const[,t]of this._zarrLayers)typeof t.setOpacity=="function"&&t.setOpacity(e);this._map&&this._map.triggerRepaint()}_buildLayerInfoList(){const e=[];for(const[t,n]of this._zarrLayerPropsMap)e.push({id:t,name:n._layerName||void 0,url:n.source,variable:n.variable,colormap:n.colormap,clim:n.clim,selector:n.selector,opacity:n.opacity??1});return e}},IU='<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18"/><path d="M3 15h18"/><path d="M9 3v18"/><path d="M15 3v18"/></svg>',MU={position:"top-right",className:"",visible:!0,collapsed:!0,beforeId:"",defaultUrl:"",sampleData:[],sampleDataLabel:"Load sample data...",loadDefaultUrl:!1,defaultOpacity:1,defaultFillColor:"steelblue",defaultLineColor:"#333333",defaultCircleColor:"steelblue",defaultLayerName:"",defaultPickable:!0,panelWidth:300,maxHeight:500,backgroundColor:"rgba(255, 255, 255, 0.95)",borderRadius:4,opacity:1,fontSize:13,fontColor:"#333",minzoom:0,maxzoom:24};function TU(e){const{minLon:t,minLat:n,maxLon:i,maxLat:s}=e;return Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(i)&&Number.isFinite(s)&&i>t&&s>n?{type:"bounds",bounds:[[t,n],[i,s]]}:e.centerLon!==void 0&&e.centerLat!==void 0?{type:"center",center:[e.centerLon,e.centerLat],zoom:Math.max(0,Math.min(e.maxZoom-2,14))}:null}var Z0=class{_container;_button;_panel;_options;_state;_eventHandlers=new Map;_map;_handleZoom;_zoomVisible=!0;_userPanelSize=null;_mapResizeHandler;_pmtilesLayers=new Map;_layerCounter=0;_protocolRegistered=!1;_protocol;_popup;_clickHandler;constructor(e){this._options={...MU,...e},this._state={visible:this._options.visible,collapsed:this._options.collapsed,url:this._options.defaultUrl,layerName:this._options.defaultLayerName,layerOpacity:this._options.defaultOpacity,availableSourceLayers:[],selectedSourceLayers:[],pickable:this._options.defaultPickable,hasLayer:!1,layerCount:0,layers:[],loading:!1,error:null,status:null}}onAdd(e){if(this._map=e,this._container=this._createContainer(),this._render(),this._handleZoom=()=>this._checkZoomVisibility(),this._map.on("zoom",this._handleZoom),this._checkZoomVisibility(),this._mapResizeHandler=()=>this._reflowPanel(),this._map.on("resize",this._mapResizeHandler),this._setupClickHandler(),this._options.loadDefaultUrl&&this._options.defaultUrl){const t=()=>{this._addLayer()};this._map.isStyleLoaded()?setTimeout(t,100):this._map.once("idle",t)}return this._container}onRemove(){this._removeLayer(),this._map&&this._handleZoom&&(this._map.off("zoom",this._handleZoom),this._handleZoom=void 0),this._map&&this._mapResizeHandler&&(this._map.off("resize",this._mapResizeHandler),this._mapResizeHandler=void 0),this._map&&this._clickHandler&&(this._map.off("click",this._clickHandler),this._clickHandler=void 0),this._popup&&(this._popup.remove(),this._popup=void 0),this._map=void 0,this._container?.parentNode?.removeChild(this._container),this._container=void 0,this._button=void 0,this._panel=void 0,this._eventHandlers.clear()}show(){this._state.visible||(this._state.visible=!0,this._updateDisplayState(),this._emit("show"))}hide(){this._state.visible&&(this._state.visible=!1,this._updateDisplayState(),this._emit("hide"))}expand(){this._state.collapsed&&(this._state.collapsed=!1,this._render(),this._emit("expand"))}collapse(){this._state.collapsed||(this._state.collapsed=!0,this._render(),this._emit("collapse"))}toggle(){this._state.collapsed?this.expand():this.collapse()}getState(){return{...this._state}}update(e){this._options={...this._options,...e},e.visible!==void 0&&(this._state.visible=e.visible),e.collapsed!==void 0&&(this._state.collapsed=e.collapsed),this._render(),this._emit("update")}on(e,t){this._eventHandlers.has(e)||this._eventHandlers.set(e,new Set),this._eventHandlers.get(e).add(t)}off(e,t){this._eventHandlers.get(e)?.delete(t)}async addLayer(e){e&&(this._state.url=e),await this._addLayer()}removeLayer(e){this._removeLayer(e),this._render()}getLayerIds(){const e=[];for(const t of this._pmtilesLayers.values())e.push(...t.layerIds);return e}_findSourceByLayerId(e){for(const t of this._pmtilesLayers.values())if(t.layerIds.includes(e))return t}getLayerOpacity(e){let t=this._pmtilesLayers.get(e);return t||(t=this._findSourceByLayerId(e)),t?.opacity??null}setLayerOpacity(e,t){if(!this._map)return;const n=Math.max(0,Math.min(1,t)),i=this._pmtilesLayers.get(e);if(i){i.opacity=n;for(const s of i.layerIds)this._setLayerOpacityDirect(s,n);return}this._findSourceByLayerId(e)&&this._setLayerOpacityDirect(e,n)}_setLayerOpacityDirect(e,t){if(!this._map)return;const n=this._map.getLayer(e);if(!n)return;const i=n.type;i==="fill"?this._map.setPaintProperty(e,"fill-opacity",t*.6):i==="line"?this._map.setPaintProperty(e,"line-opacity",t):i==="circle"?this._map.setPaintProperty(e,"circle-opacity",t):i==="raster"&&this._map.setPaintProperty(e,"raster-opacity",t)}getLayerVisibility(e){if(!this._map)return!1;const t=this._pmtilesLayers.get(e);return t&&t.layerIds.length>0?this._map.getLayoutProperty(t.layerIds[0],"visibility")!=="none":this._findSourceByLayerId(e)?this._map.getLayoutProperty(e,"visibility")!=="none":!1}setLayerVisibility(e,t){if(!this._map)return;const n=this._pmtilesLayers.get(e);if(n){for(const i of n.layerIds)this._map.setLayoutProperty(i,"visibility",t?"visible":"none");return}this._findSourceByLayerId(e)&&this._map.setLayoutProperty(e,"visibility",t?"visible":"none")}getLayerUrl(e){return this._pmtilesLayers.get(e)?.url??null}getPickable(e){return e?this._pmtilesLayers.get(e)?.pickable??this._state.pickable:this._state.pickable}setPickable(e,t){if(t){const n=this._pmtilesLayers.get(t);n&&(n.pickable=e)}else{this._state.pickable=e;for(const n of this._pmtilesLayers.values())n.pickable=e}this._render()}_emit(e,t){const n=this._eventHandlers.get(e);if(n){const i={type:e,state:this.getState(),...t};n.forEach(s=>s(i))}}_setupClickHandler(){this._map&&(this._clickHandler=e=>{if(!this._map||!this._state.pickable)return;const t=[];for(const r of this._pmtilesLayers.values())r.pickable&&r.tileType==="vector"&&t.push(...r.layerIds);if(t.length===0)return;const n=new Set,i=[];for(const r of t){if(!this._map.getLayer(r))continue;const a=this._map.queryRenderedFeatures(e.point,{layers:[r]});if(a.length>0){const o=a[0].sourceLayer||r;n.has(o)||(n.add(o),i.push({sourceLayer:o,properties:a[0].properties||{}}))}}if(i.length===0){this._popup&&this._popup.remove();return}let s='<div class="maplibre-gl-pmtiles-popup">';s+='<div class="maplibre-gl-pmtiles-popup-content">';for(const{sourceLayer:r,properties:a}of i){const o=r.replace(/[-_]/g," ");s+=`<div class="maplibre-gl-pmtiles-popup-header">${o}</div>`;const l=Object.entries(a);if(l.length===0)s+='<div class="maplibre-gl-pmtiles-popup-empty">No properties</div>';else{s+='<table class="maplibre-gl-pmtiles-popup-table">';for(const[c,h]of l){const d=typeof h=="object"?JSON.stringify(h):String(h);s+=`<tr><td class="maplibre-gl-pmtiles-popup-key">${c}</td><td class="maplibre-gl-pmtiles-popup-value">${d}</td></tr>`}s+="</table>"}}s+="</div></div>",this._popup||(this._popup=new fi.Popup({closeButton:!0,closeOnClick:!1,maxWidth:"320px"})),this._popup.setLngLat(e.lngLat).setHTML(s).addTo(this._map)},this._map.on("click",this._clickHandler))}_checkZoomVisibility(){if(!this._map)return;const e=this._map.getZoom(),{minzoom:t,maxzoom:n}=this._options,i=e>=t&&e<=n;i!==this._zoomVisible&&(this._zoomVisible=i,this._updateDisplayState())}_updateDisplayState(){if(!this._container)return;const e=this._state.visible&&this._zoomVisible;this._container.style.display=e?"block":"none"}_createContainer(){const e=document.createElement("div");return e.className=`maplibregl-ctrl maplibre-gl-pmtiles-layer${this._options.className?` ${this._options.className}`:""}`,this._state.visible&&this._zoomVisible||(e.style.display="none"),Object.assign(e.style,{backgroundColor:this._options.backgroundColor,borderRadius:`${this._options.borderRadius}px`,boxShadow:"0 0 0 2px rgba(0, 0, 0, 0.1)"}),this._options.opacity!==1&&(e.style.opacity=String(this._options.opacity)),e}_render(){if(!this._container)return;const e=this._container.querySelector(".maplibre-gl-pmtiles-layer-panel"),t=e?e.scrollTop:0;if(this._container.innerHTML="",this._state.collapsed?this._renderCollapsed():this._renderExpanded(),this._updateDisplayState(),t>0){const n=this._container.querySelector(".maplibre-gl-pmtiles-layer-panel");n&&(n.scrollTop=t)}}_renderCollapsed(){this._container&&(this._button=document.createElement("button"),this._button.type="button",this._button.className=`maplibre-gl-pmtiles-layer-button${this._state.hasLayer?" maplibre-gl-pmtiles-layer-button--active":""}`,this._button.title="PMTiles Layer",this._button.setAttribute("aria-label","PMTiles Layer"),this._button.innerHTML=IU,this._button.addEventListener("click",()=>this.expand()),this._container.appendChild(this._button),this._panel=void 0)}_renderExpanded(){if(!this._container)return;const e=document.createElement("div");e.className="maplibre-gl-pmtiles-layer-panel",e.style.width=`${this._options.panelWidth}px`,this._panel=e;const t=document.createElement("div");t.className="maplibre-gl-pmtiles-layer-header";const n=document.createElement("span");n.className="maplibre-gl-pmtiles-layer-title",n.textContent="PMTiles Layer",t.appendChild(n);const i=document.createElement("button");i.className="maplibre-gl-pmtiles-layer-close",i.innerHTML="&times;",i.title="Close",i.addEventListener("click",()=>this.collapse()),t.appendChild(i),e.appendChild(t);const s=this._createFormGroup("PMTiles URL","url"),r=document.createElement("input");r.type="text",r.className="maplibre-gl-pmtiles-layer-input",r.style.color="#000",r.placeholder="https://example.com/tiles.pmtiles",r.value=this._state.url,r.addEventListener("input",()=>{this._state.url=r.value}),s.appendChild(r);const a=bE(this._options.sampleData,this._options.sampleDataLabel,T=>{r.value=T,this._state.url=T});a&&e.appendChild(a),e.appendChild(s);const o=this._createFormGroup("Opacity","opacity"),l=document.createElement("div");l.className="maplibre-gl-pmtiles-layer-slider-row";const c=document.createElement("input");c.type="range",c.className="maplibre-gl-pmtiles-layer-slider",c.min="0",c.max="100",c.value=String(Math.round(this._state.layerOpacity*100));const h=document.createElement("span");h.className="maplibre-gl-pmtiles-layer-slider-value",h.textContent=`${Math.round(this._state.layerOpacity*100)}%`,c.addEventListener("input",()=>{const T=Number(c.value);this._state.layerOpacity=T/100,h.textContent=`${T}%`,this._updateOpacity()}),l.appendChild(c),l.appendChild(h),o.appendChild(l),e.appendChild(o);const d=this._createFormGroup("Interactivity","pickable"),f=document.createElement("div");f.style.display="flex",f.style.alignItems="center",f.style.gap="6px";const m=document.createElement("input");m.type="checkbox",m.id="pmtiles-layer-pickable",m.checked=this._state.pickable,m.addEventListener("change",()=>{this.setPickable(m.checked)});const A=document.createElement("label");A.htmlFor="pmtiles-layer-pickable",A.textContent="Enable feature picking (click to inspect)",A.style.fontSize="12px",A.style.cursor="pointer",f.appendChild(m),f.appendChild(A),d.appendChild(f),e.appendChild(d);const y=this._createFormGroup("Source Layers","source-layers"),x=document.createElement("div");x.style.display="flex",x.style.gap="6px",x.style.alignItems="center",x.style.marginBottom="6px";const v=document.createElement("button");if(v.className="maplibre-gl-pmtiles-layer-btn",v.textContent="Fetch",v.style.padding="4px 10px",v.style.fontSize="11px",v.style.whiteSpace="nowrap",v.disabled=!this._state.url,v.addEventListener("click",()=>this._fetchSourceLayers()),x.appendChild(v),this._state.availableSourceLayers.length>0){const T=document.createElement("button");T.className="maplibre-gl-pmtiles-layer-btn",T.textContent="All",T.style.padding="4px 8px",T.style.fontSize="11px",T.addEventListener("click",()=>{this._state.selectedSourceLayers=[...this._state.availableSourceLayers],this._render()}),x.appendChild(T);const C=document.createElement("button");C.className="maplibre-gl-pmtiles-layer-btn",C.textContent="None",C.style.padding="4px 8px",C.style.fontSize="11px",C.addEventListener("click",()=>{this._state.selectedSourceLayers=[],this._render()}),x.appendChild(C);const I=document.createElement("span");I.style.fontSize="11px",I.style.color="#666",I.textContent=`(${this._state.selectedSourceLayers.length}/${this._state.availableSourceLayers.length})`,x.appendChild(I)}if(y.appendChild(x),this._state.availableSourceLayers.length>0){const T=document.createElement("div");T.style.maxHeight="120px",T.style.overflowY="auto",T.style.border="1px solid #ddd",T.style.borderRadius="3px",T.style.padding="6px",T.style.background="#fafafa";for(const C of this._state.availableSourceLayers){const I=document.createElement("label");I.style.display="flex",I.style.alignItems="center",I.style.gap="4px",I.style.fontSize="11px",I.style.cursor="pointer",I.style.padding="2px 0";const M=document.createElement("input");M.type="checkbox",M.checked=this._state.selectedSourceLayers.includes(C),M.addEventListener("change",()=>{M.checked?this._state.selectedSourceLayers.includes(C)||this._state.selectedSourceLayers.push(C):this._state.selectedSourceLayers=this._state.selectedSourceLayers.filter(O=>O!==C),this._render()}),I.appendChild(M),I.appendChild(document.createTextNode(C)),T.appendChild(I)}y.appendChild(T)}else if(!this._state.loading){const T=document.createElement("span");T.style.fontSize="11px",T.style.color="#888",T.textContent="Click Fetch to discover available layers",y.appendChild(T)}e.appendChild(y);const b=this._createFormGroup("Layer Name","layer-name"),w=document.createElement("input");w.type="text",w.className="maplibre-gl-pmtiles-layer-input",w.style.color="#000",w.placeholder="Optional custom layer name",w.value=this._state.layerName,w.addEventListener("input",()=>{this._state.layerName=w.value}),b.appendChild(w),e.appendChild(b);const S=this._createFormGroup("Before Layer ID (optional)","before-id"),R=document.createElement("input");R.type="text",R.className="maplibre-gl-pmtiles-layer-input",R.style.color="#000",R.placeholder="e.g. labels or water",R.value=this._options.beforeId||"",R.addEventListener("input",()=>{this._options.beforeId=R.value||""}),S.appendChild(R),e.appendChild(S);const k=document.createElement("div");k.className="maplibre-gl-pmtiles-layer-buttons";const L=document.createElement("button");if(L.className="maplibre-gl-pmtiles-layer-btn maplibre-gl-pmtiles-layer-btn--primary",L.textContent="Add Layer",L.disabled=this._state.loading,L.addEventListener("click",()=>this._addLayer()),k.appendChild(L),e.appendChild(k),this._state.loading?this._appendStatus("Loading PMTiles...","info"):this._state.error?this._appendStatus(this._state.error,"error"):this._state.status&&this._appendStatus(this._state.status,"success"),this._pmtilesLayers.size>0){const T=document.createElement("div");T.className="maplibre-gl-pmtiles-layer-list";const C=document.createElement("div");C.className="maplibre-gl-pmtiles-layer-list-header",C.textContent=`Layers (${this._pmtilesLayers.size})`,T.appendChild(C);for(const[I,M]of this._pmtilesLayers){const O=document.createElement("div");O.className="maplibre-gl-pmtiles-layer-list-item";const N=document.createElement("span");N.className="maplibre-gl-pmtiles-layer-list-label";let D;if(M.name)D=M.name;else try{D=new URL(M.url).pathname.split("/").pop()||M.url}catch{D=M.url}N.textContent=D,N.title=M.url;const P=document.createElement("span");P.className=`maplibre-gl-pmtiles-layer-badge${M.tileType==="raster"?" maplibre-gl-pmtiles-layer-badge--raster":""}`,P.textContent=M.tileType,N.appendChild(P),O.appendChild(N);const U=document.createElement("button");U.className="maplibre-gl-pmtiles-layer-list-remove",U.innerHTML="&times;",U.title="Remove layer",U.addEventListener("click",()=>{this._removeLayer(I),this._render()}),O.appendChild(U),T.appendChild(O)}e.appendChild(T)}CE({panel:e,map:this._map,container:this._container,getUserSize:()=>this._userPanelSize,setUserSize:T=>{this._userPanelSize=T}}),this._reflowPanel(),this._container.appendChild(e),this._button=void 0,requestAnimationFrame(()=>this._reflowPanel())}_reflowPanel(){this._panel&&(EE(this._panel,this._map,this._container),fA({panel:this._panel,map:this._map,container:this._container,getUserSize:()=>this._userPanelSize,setUserSize:e=>{this._userPanelSize=e}}))}_createFormGroup(e,t){const n=document.createElement("div");n.className="maplibre-gl-pmtiles-layer-form-group";const i=document.createElement("label");return i.textContent=e,i.htmlFor=`pmtiles-layer-${t}`,n.appendChild(i),n}_appendStatus(e,t){if(!this._panel)return;const n=document.createElement("div");n.className=`maplibre-gl-pmtiles-layer-status maplibre-gl-pmtiles-layer-status--${t}`,n.textContent=e,this._panel.appendChild(n)}async _ensureProtocol(){if(this._protocolRegistered)return;const e=await Promise.resolve().then(()=>require("./esm-oEp_aN1n.cjs"));this._protocol=new e.Protocol;const t=window.maplibregl||await import("maplibre-gl");t.config?.REGISTERED_PROTOCOLS?.pmtiles||t.addProtocol("pmtiles",this._protocol.tile),this._protocolRegistered=!0}async _fetchSourceLayers(){if(!this._state.url){this._state.error="Please enter a PMTiles URL.",this._render();return}this._state.loading=!0,this._state.error=null,this._state.status=null,this._render();try{await this._ensureProtocol();const e=new(await Promise.resolve().then(()=>require("./esm-oEp_aN1n.cjs"))).PMTiles(this._state.url);this._protocol.add(e);const t=await e.getHeader(),n=await e.getMetadata();if(t.tileType===1){const i=(n?.vector_layers||[]).map(s=>s.id);this._state.availableSourceLayers=i,this._state.selectedSourceLayers=[...i],this._state.status=`Found ${i.length} source layer(s)`}else this._state.availableSourceLayers=[],this._state.selectedSourceLayers=[],this._state.status="Raster tiles (no source layers)";this._state.loading=!1,this._render()}catch(e){this._state.loading=!1,this._state.error=`Failed to fetch: ${e instanceof Error?e.message:String(e)}`,this._render()}}async _addLayer(){if(!this._map||!this._state.url){this._state.error="Please enter a PMTiles URL.",this._render();return}this._state.loading=!0,this._state.error=null,this._state.status=null,this._render();try{await this._ensureProtocol();const e=new(await Promise.resolve().then(()=>require("./esm-oEp_aN1n.cjs"))).PMTiles(this._state.url);this._protocol.add(e);const t=await e.getHeader(),n=await e.getMetadata();let i="unknown";t.tileType===1?i="vector":(t.tileType===2||t.tileType===3||t.tileType===4)&&(i="raster");const s=`pmtiles-source-${this._layerCounter++}`,r=`pmtiles://${this._state.url}`;i==="vector"?this._map.addSource(s,{type:"vector",url:r}):this._map.addSource(s,{type:"raster",url:r,tileSize:256});const a=(n?.vector_layers||[]).map(f=>f.id),o=[],l=this._options.beforeId&&this._map.getLayer(this._options.beforeId)?this._options.beforeId:void 0,c={};if(i==="vector"){const f=this._state.selectedSourceLayers.length>0?this._state.selectedSourceLayers:a,m=bO(f.length);for(let A=0;A<f.length;A++){const y=f[A],x=m[A];c[y]=x;const v=`${s}-${y}-fill`,b=`${s}-${y}-line`,w=`${s}-${y}-circle`;this._map.addLayer({id:v,type:"fill",source:s,"source-layer":y,paint:{"fill-color":x,"fill-opacity":this._state.layerOpacity*.6},filter:["==",["geometry-type"],"Polygon"]},l),o.push(v),this._map.addLayer({id:b,type:"line",source:s,"source-layer":y,paint:{"line-color":x,"line-opacity":this._state.layerOpacity,"line-width":1},filter:["any",["==",["geometry-type"],"LineString"],["==",["geometry-type"],"Polygon"]]},l),o.push(b),this._map.addLayer({id:w,type:"circle",source:s,"source-layer":y,paint:{"circle-color":x,"circle-opacity":this._state.layerOpacity,"circle-radius":2,"circle-stroke-color":x,"circle-stroke-width":.5},filter:["==",["geometry-type"],"Point"]},l),o.push(w)}if(f.length===0){const A=`${s}-generic`;this._map.addLayer({id:A,type:"fill",source:s,paint:{"fill-color":this._options.defaultFillColor,"fill-opacity":this._state.layerOpacity*.6}},l),o.push(A)}}else{const f=`${s}-raster`;this._map.addLayer({id:f,type:"raster",source:s,paint:{"raster-opacity":this._state.layerOpacity}},l),o.push(f)}const h=TU(t);h?.type==="bounds"?this._map.fitBounds(h.bounds,{padding:40,duration:1e3}):h?.type==="center"&&this._map.flyTo({center:h.center,zoom:h.zoom,duration:1e3});const d={id:s,name:this._state.layerName?.trim()||void 0,url:this._state.url,tileType:i,sourceLayers:a,layerIds:o,opacity:this._state.layerOpacity,pickable:this._state.pickable,sourceLayerColors:c};this._pmtilesLayers.set(s,d),this._state.hasLayer=this._pmtilesLayers.size>0,this._state.layerCount=this._pmtilesLayers.size,this._state.layers=Array.from(this._pmtilesLayers.values()),this._state.loading=!1,this._state.status=`PMTiles layer added (${i}).`,this._state.layerName="",this._render(),this._emit("layeradd",{url:this._state.url,layerId:s})}catch(e){this._state.loading=!1,this._state.error=`Failed to load PMTiles: ${e instanceof Error?e.message:String(e)}`,this._render(),this._emit("error",{error:this._state.error})}}_removeLayer(e){if(this._map)if(e){const t=this._pmtilesLayers.get(e);if(t){for(const n of t.layerIds)try{this._map.getLayer(n)&&this._map.removeLayer(n)}catch{}try{this._map.getSource(e)&&this._map.removeSource(e)}catch{}}this._pmtilesLayers.delete(e),this._state.hasLayer=this._pmtilesLayers.size>0,this._state.layerCount=this._pmtilesLayers.size,this._state.layers=Array.from(this._pmtilesLayers.values()),this._state.status=null,this._state.error=null,this._emit("layerremove",{layerId:e})}else{for(const[t,n]of this._pmtilesLayers){for(const i of n.layerIds)try{this._map.getLayer(i)&&this._map.removeLayer(i)}catch{}try{this._map.getSource(t)&&this._map.removeSource(t)}catch{}}this._pmtilesLayers.clear(),this._state.hasLayer=!1,this._state.layerCount=0,this._state.layers=[],this._state.status=null,this._state.error=null,this._emit("layerremove")}}_updateOpacity(){for(const[e]of this._pmtilesLayers)this.setLayerOpacity(e,this._state.layerOpacity)}},LU={name:"rescaleFloat",fs:`uniform rescaleFloatUniforms {
201
201
  float minVal;
202
202
  float maxVal;
203
203
  float isSingleBand;
@@ -227,7 +227,7 @@ var iO=Object.create;var Gw=Object.defineProperty;var sO=Object.getOwnPropertyDe
227
227
  </div>
228
228
  <div><strong>Date:</strong> ${this._state.stacItem.properties?.datetime||"N/A"}</div>
229
229
  <div><strong>Assets:</strong> ${this._state.assets.length} available</div>
230
- `,e.appendChild(o)}if(this._cogLayers.size>0){const o=document.createElement("div");o.className="maplibre-gl-stac-layer-list";const l=document.createElement("div");l.className="maplibre-gl-stac-layer-list-header",l.textContent=`Layers (${this._cogLayers.size})`,o.appendChild(l);for(const[c]of this._cogLayers){const h=document.createElement("div");h.className="maplibre-gl-stac-layer-list-item";const d=document.createElement("span");d.className="maplibre-gl-stac-layer-list-label",d.textContent=this._cogLayerPropsMap.get(c)?._layerName||c,d.title=c,h.appendChild(d);const f=document.createElement("button");f.className="maplibre-gl-stac-layer-list-remove",f.innerHTML="×",f.title="Remove layer",f.addEventListener("click",()=>{this._removeLayer(c),this._render()}),h.appendChild(f),o.appendChild(h)}e.appendChild(o)}this._container.appendChild(e),this._panel=e,this._button=void 0}_createFormGroup(e,t){const n=document.createElement("div");n.className="maplibre-gl-stac-layer-form-group";const i=document.createElement("label");return i.textContent=e,i.htmlFor=`stac-layer-${t}`,n.appendChild(i),n}_appendStatus(e,t,n){const i=document.createElement("div");i.className=`maplibre-gl-stac-layer-status maplibre-gl-stac-layer-status--${n}`,i.textContent=t,e.appendChild(i)}_autoSetRescale(){if(!this._state.selectedAsset)return;const e=this._state.assets.find(n=>n.key===this._state.selectedAsset);if(!e)return;const t=e.dataType?.toLowerCase();t==="uint16"?(this._state.rescaleMin=0,this._state.rescaleMax=1e4):t==="int16"?(this._state.rescaleMin=-32768,this._state.rescaleMax=32767):t==="float32"||t==="float64"?(this._state.rescaleMin=0,this._state.rescaleMax=1):t==="uint8"&&(this._state.rescaleMin=0,this._state.rescaleMax=255)}_updateColormapPreview(){const e=this._colormapPreview;if(!e)return;if(this._state.colormap==="none"){e.style.display="none";return}const t=nr(this._state.colormap);if(t&&t.length>0){const n=t.map(i=>i.color).join(", ");e.style.background=`linear-gradient(to right, ${n})`,e.style.display="block"}else e.style.display="none"}async _fetchStacItem(){if(!this._state.stacUrl){this._state.error="Please enter a STAC item URL.",this._render();return}this._state.loading=!0,this._state.error=null,this._state.status=null,this._state.stacItem=null,this._state.assets=[],this._state.selectedAsset=null,this._render();try{const e=await fetch(this._state.stacUrl);if(!e.ok)throw new Error(`Failed to fetch: ${e.status} ${e.statusText}`);const t=await e.text(),n=JSON.parse(t);if(n.type!=="Feature"||!n.assets)throw new Error("Invalid STAC item: missing 'type: Feature' or 'assets'");this._state.stacItem=n;const i=[],s=t.match(/"assets"\s*:\s*\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}/);if(s){const o=s[1].matchAll(/"([^"]+)"\s*:\s*\{/g);for(const l of o)i.push(l[1])}const r=i.length>0?i:Object.keys(n.assets),a=[];for(const o of r){const l=n.assets[o];if(!l)continue;const c=l;if(c.type?.includes("geotiff")||c.type?.includes("image/tiff")||c.href?.endsWith(".tif")||c.href?.endsWith(".tiff")){const h=c["raster:bands"]?.[0],d=c["eo:bands"]?.[0];a.push({key:o,href:c.href,type:c.type||"image/tiff",title:c.title||o,dataType:h?.data_type||c.data_type,nodata:h?.nodata??c.nodata,scale:h?.scale,offset:h?.offset,centerWavelength:d?.center_wavelength,commonName:d?.common_name})}}a.sort((o,l)=>o.centerWavelength!==void 0&&l.centerWavelength!==void 0?o.centerWavelength-l.centerWavelength:o.centerWavelength!==void 0?-1:l.centerWavelength!==void 0?1:0),this._state.assets=a,this._state.loading=!1,this._state.status=`Found ${a.length} COG asset(s)`,this._emit("stacload",{url:this._state.stacUrl})}catch(e){this._state.loading=!1,this._state.error=`Failed to load STAC: ${e instanceof Error?e.message:String(e)}`,this._emit("error",{error:this._state.error})}this._render()}async _ensureOverlay(){if(this._deckOverlay||!this._map)return;const{MapboxOverlay:e}=await import("@deck.gl/mapbox");this._deckOverlay=new e({interleaved:!!this._options.beforeId,layers:[]}),this._map.addControl(this._deckOverlay)}_setupClickHandler(){if(!this._map||this._mapClickHandler)return;const e=this._map;this._mapClickHandler=t=>{if(!this._state.pickable||this._cogLayers.size===0)return;this._activePopup&&this._activePopup.remove();const{lngLat:n}=t,i=Array.from(this._cogLayers.keys()),s=this._cogLayerPropsMap.get(i[0]);let r='<div class="maplibre-gl-stac-layer-popup">';r+='<table class="maplibre-gl-stac-layer-popup-table">',r+=`<tr><td><strong>Layers</strong></td><td>${i.length} STAC layer(s)</td></tr>`,r+=`<tr><td><strong>Lng</strong></td><td>${n.lng.toFixed(6)}</td></tr>`,r+=`<tr><td><strong>Lat</strong></td><td>${n.lat.toFixed(6)}</td></tr>`,s&&(r+=`<tr><td><strong>Rescale</strong></td><td>${s._rescaleMin} - ${s._rescaleMax}</td></tr>`,s._colormap&&s._colormap!=="none"&&(r+=`<tr><td><strong>Colormap</strong></td><td>${s._colormap}</td></tr>`)),r+="</table></div>",this._activePopup=new fi.default.Popup({closeButton:!0,maxWidth:"280px"}).setLngLat(n).setHTML(r).addTo(e);const a=this._activePopup.getElement();a&&(a.style.zIndex="1000")},e.on("click",this._mapClickHandler)}async _addLayer(){if(!this._map){this._state.error="Map not available.",this._render();return}if(this._state.rgbMode){const[t,n,i]=this._state.rgbAssets;if(!t||!n||!i){this._state.error="Please select assets for all RGB bands.",this._render();return}const s=this._state.assets.find(o=>o.key===t),r=this._state.assets.find(o=>o.key===n),a=this._state.assets.find(o=>o.key===i);if(!s||!r||!a){this._state.error="One or more selected assets not found.",this._render();return}this._state.loading=!0,this._state.error=null,this._state.status=null,this._render();try{await this._ensureOverlay();const{COGLayer:o}=await import("@developmentseed/deck.gl-geotiff"),{fromUrl:l}=await Promise.resolve().then(()=>require("./geotiff-B55EjXJz.cjs"));this._patchCOGLayer(o);const c=`stac-${this._state.stacItem?.id||"layer"}-rgb-${this._layerCounter++}`,[h,d,f]=await Promise.all([l(s.href),l(r.href),l(a.href)]),m=await h.getImageCount(),A=await d.getImageCount(),y=await f.getImageCount(),x=[],v=[],b=[];for(let I=0;I<m;I++)x.push(await h.getImage(I));for(let I=0;I<A;I++)v.push(await d.getImage(I));for(let I=0;I<y;I++)b.push(await f.getImage(I));const w=this._state.rescaleMin,S=this._state.rescaleMax,R=S-w,k={id:c,geotiff:h,opacity:this._state.layerOpacity,pickable:this._state.pickable,_rescaleMin:w,_rescaleMax:S,_isRgb:!0,_preRescaled:!0,getTileData:async(I,M)=>{const{window:O,pool:N,device:D}=M,P=I.getWidth(),U=I.getHeight();let Q=v[0],z=b[0];for(const fe of v)if(fe.getWidth()===P&&fe.getHeight()===U){Q=fe;break}for(const fe of b)if(fe.getWidth()===P&&fe.getHeight()===U){z=fe;break}const H={window:O,pool:N,interleave:!1},[W,te,J]=await Promise.all([I.readRasters(H),Q.readRasters(H),z.readRasters(H)]),K=W.width,re=W.height,ce=W[0],oe=te[0],ge=J[0],ie=new Uint8ClampedArray(K*re*4);for(let fe=0;fe<K*re;fe++){const ye=ce[fe],$=oe[fe],Se=ge[fe];if(ye===0&&$===0&&Se===0)ie[fe*4]=0,ie[fe*4+1]=0,ie[fe*4+2]=0,ie[fe*4+3]=0;else{const Z=Math.max(0,Math.min(255,(ye-w)/R*255)),Qe=Math.max(0,Math.min(255,($-w)/R*255)),Le=Math.max(0,Math.min(255,(Se-w)/R*255));ie[fe*4]=Z,ie[fe*4+1]=Qe,ie[fe*4+2]=Le,ie[fe*4+3]=255}}return{texture:D.createTexture({data:ie,format:"rgba8unorm",width:K,height:re,sampler:{magFilter:"nearest",minFilter:"nearest"}}),width:K,height:re,_preRescaled:!0}}},L=await this._buildGeoKeysParser();L&&(k.geoKeysParser=L);const T=this._state.layerName?.trim();T&&(k._layerName=T),this._cogLayerPropsMap.set(c,k);const C=new o(k);if(this._cogLayers.set(c,C),this._deckOverlay.setProps({layers:Array.from(this._cogLayers.values())}),this._state.stacItem?.bbox){const[I,M,O,N]=this._state.stacItem.bbox;this._map.fitBounds([[I,M],[O,N]],{padding:50,duration:1e3})}this._state.hasLayer=this._cogLayers.size>0,this._state.layerCount=this._cogLayers.size,this._state.loading=!1,this._state.status=`Added RGB layer: ${t}, ${n}, ${i}`,this._state.layerName="",this._render(),this._emit("layeradd",{layerId:c,assetKey:`${t},${n},${i}`,url:s.href,layerName:T||void 0})}catch(o){this._state.loading=!1,this._state.error=`Failed to add RGB layer: ${o instanceof Error?o.message:String(o)}`,this._render(),this._emit("error",{error:this._state.error})}return}if(!this._state.selectedAsset){this._state.error="Please select an asset.",this._render();return}const e=this._state.assets.find(t=>t.key===this._state.selectedAsset);if(!e){this._state.error="Selected asset not found.",this._render();return}this._state.loading=!0,this._state.error=null,this._state.status=null,this._render();try{await this._ensureOverlay();const{COGLayer:t}=await import("@developmentseed/deck.gl-geotiff");this._patchCOGLayer(t);const n=`stac-${this._state.stacItem?.id||"layer"}-${e.key}-${this._layerCounter++}`,i={id:n,geotiff:e.href,opacity:this._state.layerOpacity,pickable:this._state.pickable,_rescaleMin:this._state.rescaleMin,_rescaleMax:this._state.rescaleMax,_colormap:this._state.colormap},s=this._state.layerName?.trim();s&&(i._layerName=s);const r=await this._buildGeoKeysParser();r&&(i.geoKeysParser=r),this._cogLayerPropsMap.set(n,i);const a=new t(i);if(this._cogLayers.set(n,a),this._deckOverlay.setProps({layers:Array.from(this._cogLayers.values())}),this._state.stacItem?.bbox){const[o,l,c,h]=this._state.stacItem.bbox;this._map.fitBounds([[o,l],[c,h]],{padding:50,duration:1e3})}this._state.hasLayer=this._cogLayers.size>0,this._state.layerCount=this._cogLayers.size,this._state.loading=!1,this._state.status=`Added layer: ${e.title||e.key}`,this._state.layerName="",this._render(),this._emit("layeradd",{layerId:n,assetKey:e.key,url:e.href,layerName:s||void 0})}catch(t){this._state.loading=!1,this._state.error=`Failed to add layer: ${t instanceof Error?t.message:String(t)}`,this._render(),this._emit("error",{error:this._state.error})}}_updateOpacity(){if(!this._deckOverlay)return;for(const[,t]of this._cogLayerPropsMap)t.opacity=this._state.layerOpacity;const e=Array.from(this._cogLayers.entries()).map(([t])=>{const n=this._cogLayerPropsMap.get(t);return this._cogLayers.get(t).clone(n)});this._deckOverlay.setProps({layers:e})}_updateRescaleAndColormap(){if(!this._deckOverlay||this._cogLayers.size===0)return;for(const[,t]of this._cogLayerPropsMap)t._isRgb||(t._rescaleMin=this._state.rescaleMin,t._rescaleMax=this._state.rescaleMax,t._colormap=this._state.colormap);const e=Array.from(this._cogLayers.entries()).map(([t])=>{const n=this._cogLayerPropsMap.get(t);return this._cogLayers.get(t).clone(n)});this._deckOverlay.setProps({layers:e})}_removeLayer(e){this._map&&(this._cogLayers.delete(e),this._cogLayerPropsMap.delete(e),this._deckOverlay&&this._deckOverlay.setProps({layers:Array.from(this._cogLayers.values())}),this._state.hasLayer=this._cogLayers.size>0,this._state.layerCount=this._cogLayers.size,this._state.status=null,this._state.error=null,this._emit("layerremove",{layerId:e}))}_removeAllLayers(){for(const[e]of this._cogLayers)this._removeLayer(e)}_patchCOGLayer(e){if(e.__stacPatched)return;e.__stacPatched=!0;const t=e.prototype._renderSubLayers;e.prototype._renderSubLayers=function(...i){const s=t.apply(this,i),r=this.props.opacity;return r==null?s:d2(s,Math.max(0,Math.min(1,r)))};const n=e.prototype._parseGeoTIFF;e.prototype._parseGeoTIFF=async function(){const{parseCOGTileMatrixSet:i,texture:s}=await import("@developmentseed/deck.gl-geotiff");if(typeof i!="function"||typeof s?.inferTextureFormat!="function")return n.call(this);const{fromUrl:r}=await Promise.resolve().then(()=>require("./geotiff-B55EjXJz.cjs")),{CreateTexture:a,FilterNoDataVal:o,Colormap:l}=await import("@developmentseed/deck.gl-raster/gpu-modules"),c=await Promise.resolve().then(()=>require("./lib-B4jvG7hB.cjs")),h=c.default||c,d=this.props.geotiff,f=typeof d=="string"?await r(d):d,m=this.props.geoKeysParser;let A;try{A=await i(f,m)}catch{A=await i(f,void 0)}const y=await f.getImage(),x=await f.getImageCount(),v=[];for(let z=0;z<x;z++)v.push(await f.getImage(z));const b=m?await m(y.getGeoKeys()):null;let w=null,S=null;if(b&&typeof h=="function"){const z=h(b.def,"EPSG:4326");if(w=(H,W)=>z.forward([H,W],!1),S=(H,W)=>z.inverse([H,W],!1),this.props.onGeoTIFFLoad){const H=y.getBoundingBox(),W=[z.forward([H[0],H[1]]),z.forward([H[2],H[1]]),z.forward([H[2],H[3]]),z.forward([H[0],H[3]])],te=W.map(re=>re[0]),J=W.map(re=>re[1]),K={west:Math.min(...te),south:Math.min(...J),east:Math.max(...te),north:Math.max(...J)};this.props.onGeoTIFFLoad(f,{projection:b,geographicBounds:K})}}const{BitsPerSample:R,SampleFormat:k,SamplesPerPixel:L,GDAL_NODATA:T}=y.getFileDirectory();let C=null;if(T){const z=T[T.length-1]==="\0"?T.slice(0,-1):T;z.length>0&&(C=parseFloat(z))}const I=this,M=I.props._rescaleMin??0,O=I.props._rescaleMax??1e4,N=async(z,H)=>{const{device:W}=H,te=await z.readRasters({...H,interleave:!0}),J=typeof R=="object"&&R?.[0]!==void 0?R[0]:R,K=te.width*te.height;if(L===1&&J===16){const ce=new Uint8ClampedArray(K*4),oe=O-M,ge=I.props._colormap;let ie=null;ge&&ge!=="none"&&(ie=nr(ge));for(let fe=0;fe<K;fe++){const ye=te[fe];if(ye===0||ye===C)ce[fe*4]=0,ce[fe*4+1]=0,ce[fe*4+2]=0,ce[fe*4+3]=0;else{const $=Math.max(0,Math.min(1,(ye-M)/oe));if(ie){const Se=RU(ie,$);ce[fe*4]=Se[0],ce[fe*4+1]=Se[1],ce[fe*4+2]=Se[2],ce[fe*4+3]=255}else{const Se=Math.round($*255);ce[fe*4]=Se,ce[fe*4+1]=Se,ce[fe*4+2]=Se,ce[fe*4+3]=255}}}return{texture:W.createTexture({data:ce,format:"rgba8unorm",width:te.width,height:te.height,sampler:{magFilter:"nearest",minFilter:"nearest"}}),height:te.height,width:te.width,_preRescaled:!0,_colormapApplied:!!ie}}if(L===3){const ce=new Uint8ClampedArray(K*4);for(let oe=0;oe<K;oe++){const ge=te[oe*3],ie=te[oe*3+1],fe=te[oe*3+2];ge===0&&ie===0&&fe===0?(ce[oe*4]=0,ce[oe*4+1]=0,ce[oe*4+2]=0,ce[oe*4+3]=0):(ce[oe*4]=ge,ce[oe*4+1]=ie,ce[oe*4+2]=fe,ce[oe*4+3]=255)}return{texture:W.createTexture({data:ce,format:"rgba8unorm",width:te.width,height:te.height,sampler:{magFilter:"nearest",minFilter:"nearest"}}),height:te.height,width:te.width,_preRescaled:!0}}const re=s.inferTextureFormat(L,R,k);return{texture:W.createTexture({data:te,format:re,width:te.width,height:te.height,sampler:{magFilter:"nearest",minFilter:"nearest"}}),height:te.height,width:te.width}},D=this;let P=null,U=null;const Q=z=>{const H=[{module:a,props:{textureName:z.texture}}];if(!z._preRescaled){C!==null&&H.push({module:o,props:{value:C}});const te=D.props._rescaleMin??0,J=D.props._rescaleMax??255;H.push({module:LU,props:{minVal:te,maxVal:J,isSingleBand:L===1?1:0}})}const W=D.props._colormap;if(W&&W!=="none"&&!z._colormapApplied){if(W!==P){const te=BU(nr(W));U=D.context.device.createTexture({data:te.data,format:"rgba8unorm",width:te.width,height:te.height,sampler:{minFilter:"linear",magFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}}),P=W}H.push({module:l,props:{colormapTexture:U}})}return{renderPipeline:H}};D.setState({metadata:A,forwardReproject:w,inverseReproject:S,images:v,defaultGetTileData:N,defaultRenderTile:Q})}}async _registerCommonProjections(e){e.defs("EPSG:3978","+proj=lcc +lat_0=49 +lon_0=-95 +lat_1=49 +lat_2=77 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs +type=crs"),e.defs("EPSG:3979","+proj=lcc +lat_0=49 +lon_0=-95 +lat_1=49 +lat_2=77 +x_0=0 +y_0=0 +ellps=GRS80 +towgs84=-0.991,1.9072,0.5129,-1.25033e-07,-4.6785e-08,-5.6529e-08,0 +units=m +no_defs +type=crs")}async _buildGeoKeysParser(){try{const e=await Promise.resolve().then(()=>require("./main-dist-DOx_Axbx.cjs")),t=e.default||e;if(!t||typeof t.toProj4!="function")return console.warn("geotiff-geokeys-to-proj4 not available or invalid"),null;const n=await Promise.resolve().then(()=>require("./lib-B4jvG7hB.cjs")),i=n.default||n;return typeof i=="function"&&await this._registerCommonProjections(i),async s=>{try{const r=t.toProj4(s);if(r&&r.proj4){let a=r.proj4;a=a.replace(/\+axis=\w+\s*/g,"");let o={};if(typeof i=="function")try{i.defs("custom",a),o=i.defs("custom")||{}}catch(l){console.error("STAC proj4 parsing error:",l)}return{def:a,parsed:o,coordinatesUnits:r.coordinatesUnits||"metre"}}}catch(r){console.error("STAC geoKeysParser error:",r)}return null}}catch(e){return console.error("STAC _buildGeoKeysParser error:",e),null}}},DU=[{name:"Element84 Earth Search",url:"https://earth-search.aws.element84.com/v1"},{name:"Microsoft Planetary Computer",url:"https://planetarycomputer.microsoft.com/api/stac/v1"}],FU=["viridis","plasma","inferno","magma","cividis","coolwarm","bwr","seismic","RdBu","RdYlBu","RdYlGn","spectral","jet","rainbow","turbo","terrain","ocean","hot","cool","gray","bone"],OU={position:"top-right",className:"",visible:!0,collapsed:!0,panelWidth:360,maxHeight:500,backgroundColor:"rgba(255, 255, 255, 0.95)",borderRadius:4,opacity:1,fontSize:13,fontColor:"#1a1a1a",catalogs:DU,maxItems:20,defaultRescaleMin:0,defaultRescaleMax:1e4,defaultColormap:"viridis",defaultRgbMode:!0,showFootprints:!0,minzoom:0,maxzoom:24},UU=`<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
230
+ `,e.appendChild(o)}if(this._cogLayers.size>0){const o=document.createElement("div");o.className="maplibre-gl-stac-layer-list";const l=document.createElement("div");l.className="maplibre-gl-stac-layer-list-header",l.textContent=`Layers (${this._cogLayers.size})`,o.appendChild(l);for(const[c]of this._cogLayers){const h=document.createElement("div");h.className="maplibre-gl-stac-layer-list-item";const d=document.createElement("span");d.className="maplibre-gl-stac-layer-list-label",d.textContent=this._cogLayerPropsMap.get(c)?._layerName||c,d.title=c,h.appendChild(d);const f=document.createElement("button");f.className="maplibre-gl-stac-layer-list-remove",f.innerHTML="×",f.title="Remove layer",f.addEventListener("click",()=>{this._removeLayer(c),this._render()}),h.appendChild(f),o.appendChild(h)}e.appendChild(o)}this._container.appendChild(e),this._panel=e,this._button=void 0}_createFormGroup(e,t){const n=document.createElement("div");n.className="maplibre-gl-stac-layer-form-group";const i=document.createElement("label");return i.textContent=e,i.htmlFor=`stac-layer-${t}`,n.appendChild(i),n}_appendStatus(e,t,n){const i=document.createElement("div");i.className=`maplibre-gl-stac-layer-status maplibre-gl-stac-layer-status--${n}`,i.textContent=t,e.appendChild(i)}_autoSetRescale(){if(!this._state.selectedAsset)return;const e=this._state.assets.find(n=>n.key===this._state.selectedAsset);if(!e)return;const t=e.dataType?.toLowerCase();t==="uint16"?(this._state.rescaleMin=0,this._state.rescaleMax=1e4):t==="int16"?(this._state.rescaleMin=-32768,this._state.rescaleMax=32767):t==="float32"||t==="float64"?(this._state.rescaleMin=0,this._state.rescaleMax=1):t==="uint8"&&(this._state.rescaleMin=0,this._state.rescaleMax=255)}_updateColormapPreview(){const e=this._colormapPreview;if(!e)return;if(this._state.colormap==="none"){e.style.display="none";return}const t=nr(this._state.colormap);if(t&&t.length>0){const n=t.map(i=>i.color).join(", ");e.style.background=`linear-gradient(to right, ${n})`,e.style.display="block"}else e.style.display="none"}async _fetchStacItem(){if(!this._state.stacUrl){this._state.error="Please enter a STAC item URL.",this._render();return}this._state.loading=!0,this._state.error=null,this._state.status=null,this._state.stacItem=null,this._state.assets=[],this._state.selectedAsset=null,this._render();try{const e=await fetch(this._state.stacUrl);if(!e.ok)throw new Error(`Failed to fetch: ${e.status} ${e.statusText}`);const t=await e.text(),n=JSON.parse(t);if(n.type!=="Feature"||!n.assets)throw new Error("Invalid STAC item: missing 'type: Feature' or 'assets'");this._state.stacItem=n;const i=[],s=t.match(/"assets"\s*:\s*\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}/);if(s){const o=s[1].matchAll(/"([^"]+)"\s*:\s*\{/g);for(const l of o)i.push(l[1])}const r=i.length>0?i:Object.keys(n.assets),a=[];for(const o of r){const l=n.assets[o];if(!l)continue;const c=l;if(c.type?.includes("geotiff")||c.type?.includes("image/tiff")||c.href?.endsWith(".tif")||c.href?.endsWith(".tiff")){const h=c["raster:bands"]?.[0],d=c["eo:bands"]?.[0];a.push({key:o,href:c.href,type:c.type||"image/tiff",title:c.title||o,dataType:h?.data_type||c.data_type,nodata:h?.nodata??c.nodata,scale:h?.scale,offset:h?.offset,centerWavelength:d?.center_wavelength,commonName:d?.common_name})}}a.sort((o,l)=>o.centerWavelength!==void 0&&l.centerWavelength!==void 0?o.centerWavelength-l.centerWavelength:o.centerWavelength!==void 0?-1:l.centerWavelength!==void 0?1:0),this._state.assets=a,this._state.loading=!1,this._state.status=`Found ${a.length} COG asset(s)`,this._emit("stacload",{url:this._state.stacUrl})}catch(e){this._state.loading=!1,this._state.error=`Failed to load STAC: ${e instanceof Error?e.message:String(e)}`,this._emit("error",{error:this._state.error})}this._render()}async _ensureOverlay(){if(this._deckOverlay||!this._map)return;const{MapboxOverlay:e}=await import("@deck.gl/mapbox");this._deckOverlay=new e({interleaved:!!this._options.beforeId,layers:[]}),this._map.addControl(this._deckOverlay)}_setupClickHandler(){if(!this._map||this._mapClickHandler)return;const e=this._map;this._mapClickHandler=t=>{if(!this._state.pickable||this._cogLayers.size===0)return;this._activePopup&&this._activePopup.remove();const{lngLat:n}=t,i=Array.from(this._cogLayers.keys()),s=this._cogLayerPropsMap.get(i[0]);let r='<div class="maplibre-gl-stac-layer-popup">';r+='<table class="maplibre-gl-stac-layer-popup-table">',r+=`<tr><td><strong>Layers</strong></td><td>${i.length} STAC layer(s)</td></tr>`,r+=`<tr><td><strong>Lng</strong></td><td>${n.lng.toFixed(6)}</td></tr>`,r+=`<tr><td><strong>Lat</strong></td><td>${n.lat.toFixed(6)}</td></tr>`,s&&(r+=`<tr><td><strong>Rescale</strong></td><td>${s._rescaleMin} - ${s._rescaleMax}</td></tr>`,s._colormap&&s._colormap!=="none"&&(r+=`<tr><td><strong>Colormap</strong></td><td>${s._colormap}</td></tr>`)),r+="</table></div>",this._activePopup=new fi.default.Popup({closeButton:!0,maxWidth:"280px"}).setLngLat(n).setHTML(r).addTo(e);const a=this._activePopup.getElement();a&&(a.style.zIndex="1000")},e.on("click",this._mapClickHandler)}async _addLayer(){if(!this._map){this._state.error="Map not available.",this._render();return}if(this._state.rgbMode){const[t,n,i]=this._state.rgbAssets;if(!t||!n||!i){this._state.error="Please select assets for all RGB bands.",this._render();return}const s=this._state.assets.find(o=>o.key===t),r=this._state.assets.find(o=>o.key===n),a=this._state.assets.find(o=>o.key===i);if(!s||!r||!a){this._state.error="One or more selected assets not found.",this._render();return}this._state.loading=!0,this._state.error=null,this._state.status=null,this._render();try{await this._ensureOverlay();const{COGLayer:o}=await import("@developmentseed/deck.gl-geotiff"),{fromUrl:l}=await Promise.resolve().then(()=>require("./geotiff-DnbYMY3e.cjs"));this._patchCOGLayer(o);const c=`stac-${this._state.stacItem?.id||"layer"}-rgb-${this._layerCounter++}`,[h,d,f]=await Promise.all([l(s.href),l(r.href),l(a.href)]),m=await h.getImageCount(),A=await d.getImageCount(),y=await f.getImageCount(),x=[],v=[],b=[];for(let I=0;I<m;I++)x.push(await h.getImage(I));for(let I=0;I<A;I++)v.push(await d.getImage(I));for(let I=0;I<y;I++)b.push(await f.getImage(I));const w=this._state.rescaleMin,S=this._state.rescaleMax,R=S-w,k={id:c,geotiff:h,opacity:this._state.layerOpacity,pickable:this._state.pickable,_rescaleMin:w,_rescaleMax:S,_isRgb:!0,_preRescaled:!0,getTileData:async(I,M)=>{const{window:O,pool:N,device:D}=M,P=I.getWidth(),U=I.getHeight();let Q=v[0],z=b[0];for(const fe of v)if(fe.getWidth()===P&&fe.getHeight()===U){Q=fe;break}for(const fe of b)if(fe.getWidth()===P&&fe.getHeight()===U){z=fe;break}const H={window:O,pool:N,interleave:!1},[W,te,J]=await Promise.all([I.readRasters(H),Q.readRasters(H),z.readRasters(H)]),K=W.width,re=W.height,ce=W[0],oe=te[0],ge=J[0],ie=new Uint8ClampedArray(K*re*4);for(let fe=0;fe<K*re;fe++){const ye=ce[fe],$=oe[fe],Se=ge[fe];if(ye===0&&$===0&&Se===0)ie[fe*4]=0,ie[fe*4+1]=0,ie[fe*4+2]=0,ie[fe*4+3]=0;else{const Z=Math.max(0,Math.min(255,(ye-w)/R*255)),Qe=Math.max(0,Math.min(255,($-w)/R*255)),Le=Math.max(0,Math.min(255,(Se-w)/R*255));ie[fe*4]=Z,ie[fe*4+1]=Qe,ie[fe*4+2]=Le,ie[fe*4+3]=255}}return{texture:D.createTexture({data:ie,format:"rgba8unorm",width:K,height:re,sampler:{magFilter:"nearest",minFilter:"nearest"}}),width:K,height:re,_preRescaled:!0}}},L=await this._buildGeoKeysParser();L&&(k.geoKeysParser=L);const T=this._state.layerName?.trim();T&&(k._layerName=T),this._cogLayerPropsMap.set(c,k);const C=new o(k);if(this._cogLayers.set(c,C),this._deckOverlay.setProps({layers:Array.from(this._cogLayers.values())}),this._state.stacItem?.bbox){const[I,M,O,N]=this._state.stacItem.bbox;this._map.fitBounds([[I,M],[O,N]],{padding:50,duration:1e3})}this._state.hasLayer=this._cogLayers.size>0,this._state.layerCount=this._cogLayers.size,this._state.loading=!1,this._state.status=`Added RGB layer: ${t}, ${n}, ${i}`,this._state.layerName="",this._render(),this._emit("layeradd",{layerId:c,assetKey:`${t},${n},${i}`,url:s.href,layerName:T||void 0})}catch(o){this._state.loading=!1,this._state.error=`Failed to add RGB layer: ${o instanceof Error?o.message:String(o)}`,this._render(),this._emit("error",{error:this._state.error})}return}if(!this._state.selectedAsset){this._state.error="Please select an asset.",this._render();return}const e=this._state.assets.find(t=>t.key===this._state.selectedAsset);if(!e){this._state.error="Selected asset not found.",this._render();return}this._state.loading=!0,this._state.error=null,this._state.status=null,this._render();try{await this._ensureOverlay();const{COGLayer:t}=await import("@developmentseed/deck.gl-geotiff");this._patchCOGLayer(t);const n=`stac-${this._state.stacItem?.id||"layer"}-${e.key}-${this._layerCounter++}`,i={id:n,geotiff:e.href,opacity:this._state.layerOpacity,pickable:this._state.pickable,_rescaleMin:this._state.rescaleMin,_rescaleMax:this._state.rescaleMax,_colormap:this._state.colormap},s=this._state.layerName?.trim();s&&(i._layerName=s);const r=await this._buildGeoKeysParser();r&&(i.geoKeysParser=r),this._cogLayerPropsMap.set(n,i);const a=new t(i);if(this._cogLayers.set(n,a),this._deckOverlay.setProps({layers:Array.from(this._cogLayers.values())}),this._state.stacItem?.bbox){const[o,l,c,h]=this._state.stacItem.bbox;this._map.fitBounds([[o,l],[c,h]],{padding:50,duration:1e3})}this._state.hasLayer=this._cogLayers.size>0,this._state.layerCount=this._cogLayers.size,this._state.loading=!1,this._state.status=`Added layer: ${e.title||e.key}`,this._state.layerName="",this._render(),this._emit("layeradd",{layerId:n,assetKey:e.key,url:e.href,layerName:s||void 0})}catch(t){this._state.loading=!1,this._state.error=`Failed to add layer: ${t instanceof Error?t.message:String(t)}`,this._render(),this._emit("error",{error:this._state.error})}}_updateOpacity(){if(!this._deckOverlay)return;for(const[,t]of this._cogLayerPropsMap)t.opacity=this._state.layerOpacity;const e=Array.from(this._cogLayers.entries()).map(([t])=>{const n=this._cogLayerPropsMap.get(t);return this._cogLayers.get(t).clone(n)});this._deckOverlay.setProps({layers:e})}_updateRescaleAndColormap(){if(!this._deckOverlay||this._cogLayers.size===0)return;for(const[,t]of this._cogLayerPropsMap)t._isRgb||(t._rescaleMin=this._state.rescaleMin,t._rescaleMax=this._state.rescaleMax,t._colormap=this._state.colormap);const e=Array.from(this._cogLayers.entries()).map(([t])=>{const n=this._cogLayerPropsMap.get(t);return this._cogLayers.get(t).clone(n)});this._deckOverlay.setProps({layers:e})}_removeLayer(e){this._map&&(this._cogLayers.delete(e),this._cogLayerPropsMap.delete(e),this._deckOverlay&&this._deckOverlay.setProps({layers:Array.from(this._cogLayers.values())}),this._state.hasLayer=this._cogLayers.size>0,this._state.layerCount=this._cogLayers.size,this._state.status=null,this._state.error=null,this._emit("layerremove",{layerId:e}))}_removeAllLayers(){for(const[e]of this._cogLayers)this._removeLayer(e)}_patchCOGLayer(e){if(e.__stacPatched)return;e.__stacPatched=!0;const t=e.prototype._renderSubLayers;e.prototype._renderSubLayers=function(...i){const s=t.apply(this,i),r=this.props.opacity;return r==null?s:d2(s,Math.max(0,Math.min(1,r)))};const n=e.prototype._parseGeoTIFF;e.prototype._parseGeoTIFF=async function(){const{parseCOGTileMatrixSet:i,texture:s}=await import("@developmentseed/deck.gl-geotiff");if(typeof i!="function"||typeof s?.inferTextureFormat!="function")return n.call(this);const{fromUrl:r}=await Promise.resolve().then(()=>require("./geotiff-DnbYMY3e.cjs")),{CreateTexture:a,FilterNoDataVal:o,Colormap:l}=await import("@developmentseed/deck.gl-raster/gpu-modules"),c=await Promise.resolve().then(()=>require("./lib-B4jvG7hB.cjs")),h=c.default||c,d=this.props.geotiff,f=typeof d=="string"?await r(d):d,m=this.props.geoKeysParser;let A;try{A=await i(f,m)}catch{A=await i(f,void 0)}const y=await f.getImage(),x=await f.getImageCount(),v=[];for(let z=0;z<x;z++)v.push(await f.getImage(z));const b=m?await m(y.getGeoKeys()):null;let w=null,S=null;if(b&&typeof h=="function"){const z=h(b.def,"EPSG:4326");if(w=(H,W)=>z.forward([H,W],!1),S=(H,W)=>z.inverse([H,W],!1),this.props.onGeoTIFFLoad){const H=y.getBoundingBox(),W=[z.forward([H[0],H[1]]),z.forward([H[2],H[1]]),z.forward([H[2],H[3]]),z.forward([H[0],H[3]])],te=W.map(re=>re[0]),J=W.map(re=>re[1]),K={west:Math.min(...te),south:Math.min(...J),east:Math.max(...te),north:Math.max(...J)};this.props.onGeoTIFFLoad(f,{projection:b,geographicBounds:K})}}const{BitsPerSample:R,SampleFormat:k,SamplesPerPixel:L,GDAL_NODATA:T}=y.getFileDirectory();let C=null;if(T){const z=T[T.length-1]==="\0"?T.slice(0,-1):T;z.length>0&&(C=parseFloat(z))}const I=this,M=I.props._rescaleMin??0,O=I.props._rescaleMax??1e4,N=async(z,H)=>{const{device:W}=H,te=await z.readRasters({...H,interleave:!0}),J=typeof R=="object"&&R?.[0]!==void 0?R[0]:R,K=te.width*te.height;if(L===1&&J===16){const ce=new Uint8ClampedArray(K*4),oe=O-M,ge=I.props._colormap;let ie=null;ge&&ge!=="none"&&(ie=nr(ge));for(let fe=0;fe<K;fe++){const ye=te[fe];if(ye===0||ye===C)ce[fe*4]=0,ce[fe*4+1]=0,ce[fe*4+2]=0,ce[fe*4+3]=0;else{const $=Math.max(0,Math.min(1,(ye-M)/oe));if(ie){const Se=RU(ie,$);ce[fe*4]=Se[0],ce[fe*4+1]=Se[1],ce[fe*4+2]=Se[2],ce[fe*4+3]=255}else{const Se=Math.round($*255);ce[fe*4]=Se,ce[fe*4+1]=Se,ce[fe*4+2]=Se,ce[fe*4+3]=255}}}return{texture:W.createTexture({data:ce,format:"rgba8unorm",width:te.width,height:te.height,sampler:{magFilter:"nearest",minFilter:"nearest"}}),height:te.height,width:te.width,_preRescaled:!0,_colormapApplied:!!ie}}if(L===3){const ce=new Uint8ClampedArray(K*4);for(let oe=0;oe<K;oe++){const ge=te[oe*3],ie=te[oe*3+1],fe=te[oe*3+2];ge===0&&ie===0&&fe===0?(ce[oe*4]=0,ce[oe*4+1]=0,ce[oe*4+2]=0,ce[oe*4+3]=0):(ce[oe*4]=ge,ce[oe*4+1]=ie,ce[oe*4+2]=fe,ce[oe*4+3]=255)}return{texture:W.createTexture({data:ce,format:"rgba8unorm",width:te.width,height:te.height,sampler:{magFilter:"nearest",minFilter:"nearest"}}),height:te.height,width:te.width,_preRescaled:!0}}const re=s.inferTextureFormat(L,R,k);return{texture:W.createTexture({data:te,format:re,width:te.width,height:te.height,sampler:{magFilter:"nearest",minFilter:"nearest"}}),height:te.height,width:te.width}},D=this;let P=null,U=null;const Q=z=>{const H=[{module:a,props:{textureName:z.texture}}];if(!z._preRescaled){C!==null&&H.push({module:o,props:{value:C}});const te=D.props._rescaleMin??0,J=D.props._rescaleMax??255;H.push({module:LU,props:{minVal:te,maxVal:J,isSingleBand:L===1?1:0}})}const W=D.props._colormap;if(W&&W!=="none"&&!z._colormapApplied){if(W!==P){const te=BU(nr(W));U=D.context.device.createTexture({data:te.data,format:"rgba8unorm",width:te.width,height:te.height,sampler:{minFilter:"linear",magFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}}),P=W}H.push({module:l,props:{colormapTexture:U}})}return{renderPipeline:H}};D.setState({metadata:A,forwardReproject:w,inverseReproject:S,images:v,defaultGetTileData:N,defaultRenderTile:Q})}}async _registerCommonProjections(e){e.defs("EPSG:3978","+proj=lcc +lat_0=49 +lon_0=-95 +lat_1=49 +lat_2=77 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs +type=crs"),e.defs("EPSG:3979","+proj=lcc +lat_0=49 +lon_0=-95 +lat_1=49 +lat_2=77 +x_0=0 +y_0=0 +ellps=GRS80 +towgs84=-0.991,1.9072,0.5129,-1.25033e-07,-4.6785e-08,-5.6529e-08,0 +units=m +no_defs +type=crs")}async _buildGeoKeysParser(){try{const e=await Promise.resolve().then(()=>require("./main-dist-DOx_Axbx.cjs")),t=e.default||e;if(!t||typeof t.toProj4!="function")return console.warn("geotiff-geokeys-to-proj4 not available or invalid"),null;const n=await Promise.resolve().then(()=>require("./lib-B4jvG7hB.cjs")),i=n.default||n;return typeof i=="function"&&await this._registerCommonProjections(i),async s=>{try{const r=t.toProj4(s);if(r&&r.proj4){let a=r.proj4;a=a.replace(/\+axis=\w+\s*/g,"");let o={};if(typeof i=="function")try{i.defs("custom",a),o=i.defs("custom")||{}}catch(l){console.error("STAC proj4 parsing error:",l)}return{def:a,parsed:o,coordinatesUnits:r.coordinatesUnits||"metre"}}}catch(r){console.error("STAC geoKeysParser error:",r)}return null}}catch(e){return console.error("STAC _buildGeoKeysParser error:",e),null}}},DU=[{name:"Element84 Earth Search",url:"https://earth-search.aws.element84.com/v1"},{name:"Microsoft Planetary Computer",url:"https://planetarycomputer.microsoft.com/api/stac/v1"}],FU=["viridis","plasma","inferno","magma","cividis","coolwarm","bwr","seismic","RdBu","RdYlBu","RdYlGn","spectral","jet","rainbow","turbo","terrain","ocean","hot","cool","gray","bone"],OU={position:"top-right",className:"",visible:!0,collapsed:!0,panelWidth:360,maxHeight:500,backgroundColor:"rgba(255, 255, 255, 0.95)",borderRadius:4,opacity:1,fontSize:13,fontColor:"#1a1a1a",catalogs:DU,maxItems:20,defaultRescaleMin:0,defaultRescaleMax:1e4,defaultColormap:"viridis",defaultRgbMode:!0,showFootprints:!0,minzoom:0,maxzoom:24},UU=`<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
231
231
  <circle cx="11" cy="11" r="8"/>
232
232
  <path d="m21 21-4.3-4.3"/>
233
233
  <path d="M11 8v6"/>
@@ -240,7 +240,7 @@ var iO=Object.create;var Gw=Object.defineProperty;var sO=Object.getOwnPropertyDe
240
240
  {
241
241
  "type": "FeatureCollection",
242
242
  "features": [...]
243
- }`,P.value=this._state.geojsonText,P.rows=6,P.addEventListener("input",()=>{this._state.geojsonText=P.value}),D.appendChild(P);const U=document.createElement("div");U.className="maplibre-gl-add-vector-format-hint",U.textContent="Paste a valid GeoJSON FeatureCollection, Feature, or Geometry",D.appendChild(U),e.appendChild(D)}const l=this._createFormGroup("Fill Color","fill-color"),c=document.createElement("div");c.className="maplibre-gl-add-vector-color-row";const h=document.createElement("input");h.type="color",h.id="add-vector-fill-color",h.className="maplibre-gl-add-vector-color-input",h.value=this._state.fillColor,h.addEventListener("input",()=>{this._state.fillColor=h.value}),c.appendChild(h);const d=document.createElement("input");d.type="text",d.className="maplibre-gl-add-vector-input",d.style.color="#000",d.style.flex="1",d.value=this._state.fillColor,d.addEventListener("input",()=>{this._state.fillColor=d.value,h.value=d.value}),c.appendChild(d),l.appendChild(c),e.appendChild(l);const f=this._createFormGroup("Stroke Color","stroke-color"),m=document.createElement("div");m.className="maplibre-gl-add-vector-color-row";const A=document.createElement("input");A.type="color",A.id="add-vector-stroke-color",A.className="maplibre-gl-add-vector-color-input",A.value=this._state.strokeColor,A.addEventListener("input",()=>{this._state.strokeColor=A.value}),m.appendChild(A);const y=document.createElement("input");y.type="text",y.className="maplibre-gl-add-vector-input",y.style.color="#000",y.style.flex="1",y.value=this._state.strokeColor,y.addEventListener("input",()=>{this._state.strokeColor=y.value,A.value=y.value}),m.appendChild(y),f.appendChild(m),e.appendChild(f);const x=this._createFormGroup("Opacity","opacity"),v=document.createElement("div");v.className="maplibre-gl-add-vector-slider-row";const b=document.createElement("input");b.type="range",b.id="add-vector-opacity",b.className="maplibre-gl-add-vector-slider",b.min="0",b.max="100",b.value=String(Math.round(this._state.layerOpacity*100));const w=document.createElement("span");w.className="maplibre-gl-add-vector-slider-value",w.textContent=`${Math.round(this._state.layerOpacity*100)}%`,b.addEventListener("input",()=>{const D=Number(b.value);this._state.layerOpacity=D/100,w.textContent=`${D}%`;for(const[,P]of this._vectorLayers){for(const U of P.layerIds)this._setLayerOpacityDirect(U,this._state.layerOpacity);P.opacity=this._state.layerOpacity}}),v.appendChild(b),v.appendChild(w),x.appendChild(v),e.appendChild(x);const S=document.createElement("div");S.className="maplibre-gl-add-vector-form-group maplibre-gl-add-vector-checkbox-group";const R=document.createElement("label");R.className="maplibre-gl-add-vector-checkbox-label";const k=document.createElement("input");k.type="checkbox",k.id="add-vector-pickable",k.className="maplibre-gl-add-vector-checkbox",k.checked=this._state.pickable,k.style.marginRight="6px",k.addEventListener("change",()=>{this._state.pickable=k.checked}),R.appendChild(k);const L=document.createElement("span");L.textContent="Pickable (click to show feature info)",R.appendChild(L),S.appendChild(R),e.appendChild(S);const T=this._createFormGroup("Layer Name","layer-name"),C=document.createElement("input");C.type="text",C.id="add-vector-layer-name",C.className="maplibre-gl-add-vector-input",C.style.color="#000",C.placeholder="Optional custom layer name",C.value=this._state.layerName,C.addEventListener("input",()=>{this._state.layerName=C.value}),T.appendChild(C),e.appendChild(T);const I=this._createFormGroup("Before Layer ID","before-id"),M=document.createElement("input");M.type="text",M.id="add-vector-before-id",M.className="maplibre-gl-add-vector-input",M.style.color="#000",M.placeholder="Optional layer ID to insert before",M.value=this._state.beforeId,M.addEventListener("input",()=>{this._state.beforeId=M.value}),I.appendChild(M),e.appendChild(I);const O=document.createElement("div");O.className="maplibre-gl-add-vector-buttons";const N=document.createElement("button");if(N.className="maplibre-gl-add-vector-btn maplibre-gl-add-vector-btn--primary",N.textContent="Add Layer",N.disabled=this._state.loading,N.addEventListener("click",()=>this._addLayer()),O.appendChild(N),e.appendChild(O),this._state.loading?this._appendStatus("Loading vector data...","info"):this._state.error?this._appendStatus(this._state.error,"error"):this._state.status&&this._appendStatus(this._state.status,"success"),this._vectorLayers.size>0){const D=document.createElement("div");D.className="maplibre-gl-add-vector-list";const P=document.createElement("div");P.className="maplibre-gl-add-vector-list-header",P.textContent=`Layers (${this._vectorLayers.size})`,D.appendChild(P);for(const[U,Q]of this._vectorLayers){const z=document.createElement("div");z.className="maplibre-gl-add-vector-list-item";const H=document.createElement("span");H.className="maplibre-gl-add-vector-list-label";let W;try{W=new URL(Q.url).pathname.split("/").pop()||Q.url}catch{W=Q.url}H.textContent=W,H.title=Q.url;const te=document.createElement("span");if(te.className=`maplibre-gl-add-vector-badge ${GU(Q.format)}`,te.textContent=Q.format==="auto"?"geojson":Q.format,H.appendChild(te),Q.viewportLoading){const K=document.createElement("span");K.className="maplibre-gl-add-vector-badge maplibre-gl-add-vector-badge--viewport",K.textContent="viewport",K.title=`Min zoom: ${Q.viewportMinZoom??this._state.viewportMinZoom}`,H.appendChild(K)}z.appendChild(H);const J=document.createElement("button");J.className="maplibre-gl-add-vector-list-remove",J.innerHTML="&times;",J.title="Remove layer",J.addEventListener("click",()=>{this._removeLayer(U),this._render()}),z.appendChild(J),D.appendChild(z)}e.appendChild(D)}CE({panel:e,map:this._map,container:this._container,getUserSize:()=>this._userPanelSize,setUserSize:D=>{this._userPanelSize=D}}),this._reflowPanel(),this._container.appendChild(e),this._button=void 0,requestAnimationFrame(()=>this._reflowPanel())}_createFormGroup(e,t){const n=document.createElement("div");n.className="maplibre-gl-add-vector-form-group";const i=document.createElement("label");return i.textContent=e,i.htmlFor=`add-vector-${t}`,n.appendChild(i),n}_appendStatus(e,t){if(!this._panel)return;const n=document.createElement("div");n.className=`maplibre-gl-add-vector-status maplibre-gl-add-vector-status--${t}`,n.textContent=e,this._panel.appendChild(n)}async _addLayer(){if(!this._map){this._state.error="Map not initialized.",this._render();return}if(this._state.inputMode==="url"&&!this._state.url){this._state.error="Please enter a vector URL.",this._render();return}if(this._state.inputMode==="text"&&!this._state.geojsonText.trim()){this._state.error="Please paste GeoJSON content.",this._render();return}const e=this._map;this._state.loading=!0,this._state.error=null,this._state.status=null,this._render();try{let t,n="geojson",i="";if(this._state.inputMode==="text")try{const A=JSON.parse(this._state.geojsonText);t=this._normalizeGeoJSON(A),i="inline-geojson"}catch(A){throw new Error(`Invalid GeoJSON: ${A instanceof Error?A.message:"Failed to parse JSON"}`)}else if(i=this._state.url,n=this._state.format,n==="auto"&&(n=vv(this._state.url)),n==="geojson"){let A;try{A=await fetch(this._state.url)}catch{throw new Error("CORS error: The server doesn't allow cross-origin requests. Try using a CORS-enabled URL.")}if(!A.ok)throw new Error(`Failed to fetch: ${A.status} ${A.statusText}`);const y=await A.json();t=this._normalizeGeoJSON(y)}else if(n==="geoparquet")this._state.viewportLoading?t={type:"FeatureCollection",features:[]}:t=await this._loadGeoParquet(this._state.url);else if(n==="flatgeobuf")t=await this._loadFlatGeobuf(this._state.url);else throw new Error(`Unsupported format: ${n}`);let s=this._state.layerName?.trim();if(!s&&this._state.inputMode==="url")try{s=(new URL(this._state.url).pathname.split("/").pop()||"").replace(/\.[^.]+$/,"")}catch{}s||(s=Qa("addvec"));const r=`${s}-source`,a=new Set;for(const A of t.features)A.geometry&&a.add(A.geometry.type);e.addSource(r,{type:"geojson",data:t,generateId:!0});const o=[],l=this._state.beforeId?.trim(),c=this._options.beforeId,h=l||c,d=h&&e.getLayer(h)?h:void 0,f=n==="geoparquet"&&this._state.viewportLoading;if(f||a.has("Polygon")||a.has("MultiPolygon")){const A=`${s}-fill`;e.addLayer({id:A,type:"fill",source:r,filter:["any",["==",["geometry-type"],"Polygon"],["==",["geometry-type"],"MultiPolygon"]],paint:{"fill-color":this._state.fillColor,"fill-opacity":this._state.layerOpacity}},d),o.push(A);const y=`${s}-outline`;e.addLayer({id:y,type:"line",source:r,filter:["any",["==",["geometry-type"],"Polygon"],["==",["geometry-type"],"MultiPolygon"]],paint:{"line-color":this._state.strokeColor,"line-width":2,"line-opacity":this._state.layerOpacity}},d),o.push(y)}if(f||a.has("LineString")||a.has("MultiLineString")){const A=`${s}-line`;e.addLayer({id:A,type:"line",source:r,filter:["any",["==",["geometry-type"],"LineString"],["==",["geometry-type"],"MultiLineString"]],paint:{"line-color":this._state.strokeColor,"line-width":2,"line-opacity":this._state.layerOpacity}},d),o.push(A)}if(f||a.has("Point")||a.has("MultiPoint")){const A=`${s}-point`;e.addLayer({id:A,type:"circle",source:r,filter:["any",["==",["geometry-type"],"Point"],["==",["geometry-type"],"MultiPoint"]],paint:{"circle-radius":6,"circle-color":this._state.circleColor,"circle-stroke-color":this._state.strokeColor,"circle-stroke-width":2,"circle-opacity":this._state.layerOpacity}},d),o.push(A)}if(this._state.pickable)for(const A of o)e.on("mouseenter",A,()=>{e.getCanvas().style.cursor="pointer"}),e.on("mouseleave",A,()=>{e.getCanvas().style.cursor=""}),e.on("click",A,y=>{if(!y.features||y.features.length===0)return;const x=y.features[0].properties||{},v=Object.entries(x);if(v.length===0)return;let b='<div class="maplibre-gl-add-vector-popup">';b+='<table class="maplibre-gl-add-vector-popup-table">';for(const[w,S]of v)b+=`<tr><td><strong>${w}</strong></td><td>${S}</td></tr>`;b+="</table></div>",this._activePopup&&this._activePopup.remove(),this._activePopup=new fi.default.Popup({closeButton:!0,maxWidth:"300px"}).setLngLat(y.lngLat).setHTML(b).addTo(e)});const m={id:s,url:i,format:n,sourceId:r,layerIds:o,featureCount:t.features.length,geometryTypes:Array.from(a),opacity:this._state.layerOpacity,fillColor:this._state.fillColor,strokeColor:this._state.strokeColor,pickable:this._state.pickable,viewportLoading:n==="geoparquet"&&this._state.viewportLoading,viewportMinZoom:n==="geoparquet"&&this._state.viewportLoading?this._state.viewportMinZoom:void 0};if(this._vectorLayers.set(s,m),this._state.hasLayer=this._vectorLayers.size>0,this._state.layerCount=this._vectorLayers.size,this._state.layers=Array.from(this._vectorLayers.values()),this._state.loading=!1,n==="geoparquet"&&this._state.viewportLoading)try{await this._setupViewportLoading(s,i,r);const A=this._vectorLayers.get(s)?.featureCount??0;this._state.status=`Viewport loading enabled (${A} features in view, minzoom: ${this._state.viewportMinZoom}).`,this._state.layers=Array.from(this._vectorLayers.values())}catch(A){console.warn("Viewport loading setup failed, falling back to full download:",A),m.viewportLoading=!1,m.viewportMinZoom=void 0;const y=await this._loadGeoParquet(i),x=this._map.getSource(r);x&&x.type==="geojson"&&x.setData(y),m.featureCount=y.features.length,this._state.layers=Array.from(this._vectorLayers.values()),this._state.status=`Added ${y.features.length} features (${n}, viewport loading failed).`}else{const A=this._state.inputMode==="text"?"inline GeoJSON":n;this._state.status=`Added ${t.features.length} features (${A}).`}this._options.fitBounds&&t.features.length>0&&!m.viewportLoading&&this._fitToData(t),this._render(),this._emit("layeradd",{url:i,layerId:s})}catch(t){this._state.loading=!1,this._state.error=`Failed to load: ${t instanceof Error?t.message:String(t)}`,this._render(),this._emit("error",{error:this._state.error})}}_normalizeGeoJSON(e){return e.type==="FeatureCollection"?e:e.type==="Feature"?{type:"FeatureCollection",features:[e]}:{type:"FeatureCollection",features:[{type:"Feature",properties:{},geometry:e}]}}async _fetchWithCorsProxy(e){try{const n=await fetch(e,{mode:"cors"});if(n.ok)return n}catch{}if(this._options.corsProxy){const n=this._options.corsProxy+encodeURIComponent(e);try{const i=await fetch(n,{mode:"cors"});if(i.ok)return i}catch{}}const t="https://corsproxy.io/?";try{const n=await fetch(t+encodeURIComponent(e),{mode:"cors"});if(n.ok)return n}catch{}throw new Error("CORS error: Unable to fetch the file. The server doesn't allow cross-origin requests.")}async _loadGeoParquet(e){const{getDuckDBConverter:t}=await Promise.resolve().then(()=>require("./DuckDBConverter-D4z5GfYH.cjs")).then(a=>a.DuckDBConverter_exports),n=t(),i=await this._fetchWithCorsProxy(e);let s;try{s=await i.arrayBuffer()}catch(a){throw new Error(`Failed to read GeoParquet response: ${a instanceof Error?a.message:String(a)}`)}let r;try{r=await n.convert(s,"data.parquet")}catch(a){throw new Error(`Failed to convert GeoParquet: ${a instanceof Error?a.message:String(a)}`)}if(r.geojson)return r.geojson;throw new Error("Failed to convert GeoParquet: No GeoJSON output")}async _loadFlatGeobuf(e){const t=await Promise.resolve().then(()=>require("./geojson-CxMdRvJX.cjs")),n=await fetch(e);if(!n.ok)throw new Error(`Failed to fetch: ${n.status} ${n.statusText}`);if(!n.body)throw new Error("Response body is null - streaming not supported");const i=[];for await(const s of t.deserialize(n.body))i.push(s);return{type:"FeatureCollection",features:i}}_fitToData(e){if(!this._map)return;let t=1/0,n=1/0,i=-1/0,s=-1/0;const r=o=>{t=Math.min(t,o[0]),i=Math.max(i,o[0]),n=Math.min(n,o[1]),s=Math.max(s,o[1])},a=o=>{for(const l of o)typeof l[0]=="number"?r(l):a(l)};for(const o of e.features){if(!o.geometry)continue;const l=o.geometry;l.type==="Point"?r(l.coordinates):(l.type==="MultiPoint"||l.type==="LineString"||l.type==="MultiLineString"||l.type==="Polygon"||l.type==="MultiPolygon")&&a(l.coordinates)}t!==1/0&&this._map.fitBounds([[t,n],[i,s]],{padding:this._options.fitBoundsPadding})}async _setupViewportLoading(e,t,n){if(!this._map)return;const{getDuckDBConverter:i}=await Promise.resolve().then(()=>require("./DuckDBConverter-D4z5GfYH.cjs")).then(a=>a.DuckDBConverter_exports),s=i(),r=`${e}.parquet`;try{await s.registerRemoteParquet(t,r);const a=await s.getParquetSchema(r);if(!a.geometryColumn)throw new Error("No geometry column found in parquet file");const o=this._vectorLayers.get(e);o&&(o.viewportLoading=!0,o.duckdbFileName=r,o.geometryColumn=a.geometryColumn??void 0,o.geometryColumnType=a.geometryColumnType??void 0,o.propertyColumns=a.propertyColumns),this._viewportLoadingLayers.add(e);const l=NB(()=>{this._updateViewportData(e)},this._options.geoparquetDebounceMs),c=this._viewportHandler;this._viewportHandler=()=>{c&&c(),l()},c&&this._map.off("moveend",c),this._map.on("moveend",this._viewportHandler),await this._updateViewportData(e)}catch(a){throw console.error("Failed to setup viewport loading:",a),await s.unregisterFile(r),a}}async _updateViewportData(e){if(!this._map)return;const t=this._vectorLayers.get(e);if(!t||!t.viewportLoading||!t.duckdbFileName||!t.geometryColumn)return;const n=t.viewportMinZoom??this._state.viewportMinZoom??8;if(this._map.getZoom()<n){for(const i of t.layerIds)this._map.getLayer(i)&&this._map.setLayoutProperty(i,"visibility","none");return}for(const i of t.layerIds)this._map.getLayer(i)&&this._map.setLayoutProperty(i,"visibility","visible");this._viewportLoadingState.set(e,!0);try{const{getDuckDBConverter:i}=await Promise.resolve().then(()=>require("./DuckDBConverter-D4z5GfYH.cjs")).then(c=>c.DuckDBConverter_exports),s=i(),r=this._map.getBounds(),a=[r.getWest(),r.getSouth(),r.getEast(),r.getNorth()],o=await s.queryByBounds(t.duckdbFileName,a,t.geometryColumn,t.propertyColumns||[],t.geometryColumnType),l=this._map.getSource(t.sourceId);l&&l.type==="geojson"&&l.setData(o),t.featureCount=o.features.length,this._state.layers=Array.from(this._vectorLayers.values())}catch(i){console.error("Failed to update viewport data:",i)}finally{this._viewportLoadingState.set(e,!1)}}async _cleanupViewportLoading(){if(this._map&&this._viewportHandler&&(this._map.off("moveend",this._viewportHandler),this._viewportHandler=void 0),this._viewportLoadingLayers.size>0)try{const{getDuckDBConverter:e}=await Promise.resolve().then(()=>require("./DuckDBConverter-D4z5GfYH.cjs")).then(n=>n.DuckDBConverter_exports),t=e();for(const n of this._viewportLoadingLayers){const i=this._vectorLayers.get(n);i?.duckdbFileName&&await t.unregisterFile(i.duckdbFileName)}}catch{}this._viewportLoadingLayers.clear(),this._viewportLoadingState.clear()}async _cleanupLayerViewportLoading(e){const t=this._vectorLayers.get(e);if(!(!t?.viewportLoading||!t.duckdbFileName)){try{const{getDuckDBConverter:n}=await Promise.resolve().then(()=>require("./DuckDBConverter-D4z5GfYH.cjs")).then(i=>i.DuckDBConverter_exports);await n().unregisterFile(t.duckdbFileName)}catch{}this._viewportLoadingLayers.delete(e),this._viewportLoadingState.delete(e),this._viewportLoadingLayers.size===0&&this._viewportHandler&&(this._map&&this._map.off("moveend",this._viewportHandler),this._viewportHandler=void 0)}}_removeLayer(e){if(this._map)if(e){const t=this._vectorLayers.get(e);if(t){t.viewportLoading&&this._cleanupLayerViewportLoading(e);for(const n of t.layerIds)try{this._map.getLayer(n)&&this._map.removeLayer(n)}catch{}try{this._map.getSource(t.sourceId)&&this._map.removeSource(t.sourceId)}catch{}}this._vectorLayers.delete(e),this._state.hasLayer=this._vectorLayers.size>0,this._state.layerCount=this._vectorLayers.size,this._state.layers=Array.from(this._vectorLayers.values()),this._state.status=null,this._state.error=null,this._emit("layerremove",{layerId:e})}else this._removeAllLayers()}_removeAllLayers(){if(this._map){for(const[,e]of this._vectorLayers){for(const t of e.layerIds)try{this._map.getLayer(t)&&this._map.removeLayer(t)}catch{}try{this._map.getSource(e.sourceId)&&this._map.removeSource(e.sourceId)}catch{}}this._vectorLayers.clear(),this._state.hasLayer=!1,this._state.layerCount=0,this._state.layers=[],this._state.status=null,this._state.error=null,this._emit("layerremove")}}},HU=`<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
243
+ }`,P.value=this._state.geojsonText,P.rows=6,P.addEventListener("input",()=>{this._state.geojsonText=P.value}),D.appendChild(P);const U=document.createElement("div");U.className="maplibre-gl-add-vector-format-hint",U.textContent="Paste a valid GeoJSON FeatureCollection, Feature, or Geometry",D.appendChild(U),e.appendChild(D)}const l=this._createFormGroup("Fill Color","fill-color"),c=document.createElement("div");c.className="maplibre-gl-add-vector-color-row";const h=document.createElement("input");h.type="color",h.id="add-vector-fill-color",h.className="maplibre-gl-add-vector-color-input",h.value=this._state.fillColor,h.addEventListener("input",()=>{this._state.fillColor=h.value}),c.appendChild(h);const d=document.createElement("input");d.type="text",d.className="maplibre-gl-add-vector-input",d.style.color="#000",d.style.flex="1",d.value=this._state.fillColor,d.addEventListener("input",()=>{this._state.fillColor=d.value,h.value=d.value}),c.appendChild(d),l.appendChild(c),e.appendChild(l);const f=this._createFormGroup("Stroke Color","stroke-color"),m=document.createElement("div");m.className="maplibre-gl-add-vector-color-row";const A=document.createElement("input");A.type="color",A.id="add-vector-stroke-color",A.className="maplibre-gl-add-vector-color-input",A.value=this._state.strokeColor,A.addEventListener("input",()=>{this._state.strokeColor=A.value}),m.appendChild(A);const y=document.createElement("input");y.type="text",y.className="maplibre-gl-add-vector-input",y.style.color="#000",y.style.flex="1",y.value=this._state.strokeColor,y.addEventListener("input",()=>{this._state.strokeColor=y.value,A.value=y.value}),m.appendChild(y),f.appendChild(m),e.appendChild(f);const x=this._createFormGroup("Opacity","opacity"),v=document.createElement("div");v.className="maplibre-gl-add-vector-slider-row";const b=document.createElement("input");b.type="range",b.id="add-vector-opacity",b.className="maplibre-gl-add-vector-slider",b.min="0",b.max="100",b.value=String(Math.round(this._state.layerOpacity*100));const w=document.createElement("span");w.className="maplibre-gl-add-vector-slider-value",w.textContent=`${Math.round(this._state.layerOpacity*100)}%`,b.addEventListener("input",()=>{const D=Number(b.value);this._state.layerOpacity=D/100,w.textContent=`${D}%`;for(const[,P]of this._vectorLayers){for(const U of P.layerIds)this._setLayerOpacityDirect(U,this._state.layerOpacity);P.opacity=this._state.layerOpacity}}),v.appendChild(b),v.appendChild(w),x.appendChild(v),e.appendChild(x);const S=document.createElement("div");S.className="maplibre-gl-add-vector-form-group maplibre-gl-add-vector-checkbox-group";const R=document.createElement("label");R.className="maplibre-gl-add-vector-checkbox-label";const k=document.createElement("input");k.type="checkbox",k.id="add-vector-pickable",k.className="maplibre-gl-add-vector-checkbox",k.checked=this._state.pickable,k.style.marginRight="6px",k.addEventListener("change",()=>{this._state.pickable=k.checked}),R.appendChild(k);const L=document.createElement("span");L.textContent="Pickable (click to show feature info)",R.appendChild(L),S.appendChild(R),e.appendChild(S);const T=this._createFormGroup("Layer Name","layer-name"),C=document.createElement("input");C.type="text",C.id="add-vector-layer-name",C.className="maplibre-gl-add-vector-input",C.style.color="#000",C.placeholder="Optional custom layer name",C.value=this._state.layerName,C.addEventListener("input",()=>{this._state.layerName=C.value}),T.appendChild(C),e.appendChild(T);const I=this._createFormGroup("Before Layer ID","before-id"),M=document.createElement("input");M.type="text",M.id="add-vector-before-id",M.className="maplibre-gl-add-vector-input",M.style.color="#000",M.placeholder="Optional layer ID to insert before",M.value=this._state.beforeId,M.addEventListener("input",()=>{this._state.beforeId=M.value}),I.appendChild(M),e.appendChild(I);const O=document.createElement("div");O.className="maplibre-gl-add-vector-buttons";const N=document.createElement("button");if(N.className="maplibre-gl-add-vector-btn maplibre-gl-add-vector-btn--primary",N.textContent="Add Layer",N.disabled=this._state.loading,N.addEventListener("click",()=>this._addLayer()),O.appendChild(N),e.appendChild(O),this._state.loading?this._appendStatus("Loading vector data...","info"):this._state.error?this._appendStatus(this._state.error,"error"):this._state.status&&this._appendStatus(this._state.status,"success"),this._vectorLayers.size>0){const D=document.createElement("div");D.className="maplibre-gl-add-vector-list";const P=document.createElement("div");P.className="maplibre-gl-add-vector-list-header",P.textContent=`Layers (${this._vectorLayers.size})`,D.appendChild(P);for(const[U,Q]of this._vectorLayers){const z=document.createElement("div");z.className="maplibre-gl-add-vector-list-item";const H=document.createElement("span");H.className="maplibre-gl-add-vector-list-label";let W;try{W=new URL(Q.url).pathname.split("/").pop()||Q.url}catch{W=Q.url}H.textContent=W,H.title=Q.url;const te=document.createElement("span");if(te.className=`maplibre-gl-add-vector-badge ${GU(Q.format)}`,te.textContent=Q.format==="auto"?"geojson":Q.format,H.appendChild(te),Q.viewportLoading){const K=document.createElement("span");K.className="maplibre-gl-add-vector-badge maplibre-gl-add-vector-badge--viewport",K.textContent="viewport",K.title=`Min zoom: ${Q.viewportMinZoom??this._state.viewportMinZoom}`,H.appendChild(K)}z.appendChild(H);const J=document.createElement("button");J.className="maplibre-gl-add-vector-list-remove",J.innerHTML="&times;",J.title="Remove layer",J.addEventListener("click",()=>{this._removeLayer(U),this._render()}),z.appendChild(J),D.appendChild(z)}e.appendChild(D)}CE({panel:e,map:this._map,container:this._container,getUserSize:()=>this._userPanelSize,setUserSize:D=>{this._userPanelSize=D}}),this._reflowPanel(),this._container.appendChild(e),this._button=void 0,requestAnimationFrame(()=>this._reflowPanel())}_createFormGroup(e,t){const n=document.createElement("div");n.className="maplibre-gl-add-vector-form-group";const i=document.createElement("label");return i.textContent=e,i.htmlFor=`add-vector-${t}`,n.appendChild(i),n}_appendStatus(e,t){if(!this._panel)return;const n=document.createElement("div");n.className=`maplibre-gl-add-vector-status maplibre-gl-add-vector-status--${t}`,n.textContent=e,this._panel.appendChild(n)}async _addLayer(){if(!this._map){this._state.error="Map not initialized.",this._render();return}if(this._state.inputMode==="url"&&!this._state.url){this._state.error="Please enter a vector URL.",this._render();return}if(this._state.inputMode==="text"&&!this._state.geojsonText.trim()){this._state.error="Please paste GeoJSON content.",this._render();return}const e=this._map;this._state.loading=!0,this._state.error=null,this._state.status=null,this._render();try{let t,n="geojson",i="";if(this._state.inputMode==="text")try{const A=JSON.parse(this._state.geojsonText);t=this._normalizeGeoJSON(A),i="inline-geojson"}catch(A){throw new Error(`Invalid GeoJSON: ${A instanceof Error?A.message:"Failed to parse JSON"}`)}else if(i=this._state.url,n=this._state.format,n==="auto"&&(n=vv(this._state.url)),n==="geojson"){let A;try{A=await fetch(this._state.url)}catch{throw new Error("CORS error: The server doesn't allow cross-origin requests. Try using a CORS-enabled URL.")}if(!A.ok)throw new Error(`Failed to fetch: ${A.status} ${A.statusText}`);const y=await A.json();t=this._normalizeGeoJSON(y)}else if(n==="geoparquet")this._state.viewportLoading?t={type:"FeatureCollection",features:[]}:t=await this._loadGeoParquet(this._state.url);else if(n==="flatgeobuf")t=await this._loadFlatGeobuf(this._state.url);else throw new Error(`Unsupported format: ${n}`);let s=this._state.layerName?.trim();if(!s&&this._state.inputMode==="url")try{s=(new URL(this._state.url).pathname.split("/").pop()||"").replace(/\.[^.]+$/,"")}catch{}s||(s=Qa("addvec"));const r=`${s}-source`,a=new Set;for(const A of t.features)A.geometry&&a.add(A.geometry.type);e.addSource(r,{type:"geojson",data:t,generateId:!0});const o=[],l=this._state.beforeId?.trim(),c=this._options.beforeId,h=l||c,d=h&&e.getLayer(h)?h:void 0,f=n==="geoparquet"&&this._state.viewportLoading;if(f||a.has("Polygon")||a.has("MultiPolygon")){const A=`${s}-fill`;e.addLayer({id:A,type:"fill",source:r,filter:["any",["==",["geometry-type"],"Polygon"],["==",["geometry-type"],"MultiPolygon"]],paint:{"fill-color":this._state.fillColor,"fill-opacity":this._state.layerOpacity}},d),o.push(A);const y=`${s}-outline`;e.addLayer({id:y,type:"line",source:r,filter:["any",["==",["geometry-type"],"Polygon"],["==",["geometry-type"],"MultiPolygon"]],paint:{"line-color":this._state.strokeColor,"line-width":2,"line-opacity":this._state.layerOpacity}},d),o.push(y)}if(f||a.has("LineString")||a.has("MultiLineString")){const A=`${s}-line`;e.addLayer({id:A,type:"line",source:r,filter:["any",["==",["geometry-type"],"LineString"],["==",["geometry-type"],"MultiLineString"]],paint:{"line-color":this._state.strokeColor,"line-width":2,"line-opacity":this._state.layerOpacity}},d),o.push(A)}if(f||a.has("Point")||a.has("MultiPoint")){const A=`${s}-point`;e.addLayer({id:A,type:"circle",source:r,filter:["any",["==",["geometry-type"],"Point"],["==",["geometry-type"],"MultiPoint"]],paint:{"circle-radius":6,"circle-color":this._state.circleColor,"circle-stroke-color":this._state.strokeColor,"circle-stroke-width":2,"circle-opacity":this._state.layerOpacity}},d),o.push(A)}if(this._state.pickable)for(const A of o)e.on("mouseenter",A,()=>{e.getCanvas().style.cursor="pointer"}),e.on("mouseleave",A,()=>{e.getCanvas().style.cursor=""}),e.on("click",A,y=>{if(!y.features||y.features.length===0)return;const x=y.features[0].properties||{},v=Object.entries(x);if(v.length===0)return;let b='<div class="maplibre-gl-add-vector-popup">';b+='<table class="maplibre-gl-add-vector-popup-table">';for(const[w,S]of v)b+=`<tr><td><strong>${w}</strong></td><td>${S}</td></tr>`;b+="</table></div>",this._activePopup&&this._activePopup.remove(),this._activePopup=new fi.default.Popup({closeButton:!0,maxWidth:"300px"}).setLngLat(y.lngLat).setHTML(b).addTo(e)});const m={id:s,url:i,format:n,sourceId:r,layerIds:o,featureCount:t.features.length,geometryTypes:Array.from(a),opacity:this._state.layerOpacity,fillColor:this._state.fillColor,strokeColor:this._state.strokeColor,pickable:this._state.pickable,viewportLoading:n==="geoparquet"&&this._state.viewportLoading,viewportMinZoom:n==="geoparquet"&&this._state.viewportLoading?this._state.viewportMinZoom:void 0};if(this._vectorLayers.set(s,m),this._state.hasLayer=this._vectorLayers.size>0,this._state.layerCount=this._vectorLayers.size,this._state.layers=Array.from(this._vectorLayers.values()),this._state.loading=!1,n==="geoparquet"&&this._state.viewportLoading)try{await this._setupViewportLoading(s,i,r);const A=this._vectorLayers.get(s)?.featureCount??0;this._state.status=`Viewport loading enabled (${A} features in view, minzoom: ${this._state.viewportMinZoom}).`,this._state.layers=Array.from(this._vectorLayers.values())}catch(A){console.warn("Viewport loading setup failed, falling back to full download:",A),m.viewportLoading=!1,m.viewportMinZoom=void 0;const y=await this._loadGeoParquet(i),x=this._map.getSource(r);x&&x.type==="geojson"&&x.setData(y),m.featureCount=y.features.length,this._state.layers=Array.from(this._vectorLayers.values()),this._state.status=`Added ${y.features.length} features (${n}, viewport loading failed).`}else{const A=this._state.inputMode==="text"?"inline GeoJSON":n;this._state.status=`Added ${t.features.length} features (${A}).`}this._options.fitBounds&&t.features.length>0&&!m.viewportLoading&&this._fitToData(t),this._render(),this._emit("layeradd",{url:i,layerId:s})}catch(t){this._state.loading=!1,this._state.error=`Failed to load: ${t instanceof Error?t.message:String(t)}`,this._render(),this._emit("error",{error:this._state.error})}}_normalizeGeoJSON(e){return e.type==="FeatureCollection"?e:e.type==="Feature"?{type:"FeatureCollection",features:[e]}:{type:"FeatureCollection",features:[{type:"Feature",properties:{},geometry:e}]}}async _fetchWithCorsProxy(e){try{const n=await fetch(e,{mode:"cors"});if(n.ok)return n}catch{}if(this._options.corsProxy){const n=this._options.corsProxy+encodeURIComponent(e);try{const i=await fetch(n,{mode:"cors"});if(i.ok)return i}catch{}}const t="https://corsproxy.io/?";try{const n=await fetch(t+encodeURIComponent(e),{mode:"cors"});if(n.ok)return n}catch{}throw new Error("CORS error: Unable to fetch the file. The server doesn't allow cross-origin requests.")}async _loadGeoParquet(e){const{getDuckDBConverter:t}=await Promise.resolve().then(()=>require("./DuckDBConverter-BtujCPmE.cjs")).then(a=>a.DuckDBConverter_exports),n=t(),i=await this._fetchWithCorsProxy(e);let s;try{s=await i.arrayBuffer()}catch(a){throw new Error(`Failed to read GeoParquet response: ${a instanceof Error?a.message:String(a)}`)}let r;try{r=await n.convert(s,"data.parquet")}catch(a){throw new Error(`Failed to convert GeoParquet: ${a instanceof Error?a.message:String(a)}`)}if(r.geojson)return r.geojson;throw new Error("Failed to convert GeoParquet: No GeoJSON output")}async _loadFlatGeobuf(e){const t=await Promise.resolve().then(()=>require("./geojson-CxMdRvJX.cjs")),n=await fetch(e);if(!n.ok)throw new Error(`Failed to fetch: ${n.status} ${n.statusText}`);if(!n.body)throw new Error("Response body is null - streaming not supported");const i=[];for await(const s of t.deserialize(n.body))i.push(s);return{type:"FeatureCollection",features:i}}_fitToData(e){if(!this._map)return;let t=1/0,n=1/0,i=-1/0,s=-1/0;const r=o=>{t=Math.min(t,o[0]),i=Math.max(i,o[0]),n=Math.min(n,o[1]),s=Math.max(s,o[1])},a=o=>{for(const l of o)typeof l[0]=="number"?r(l):a(l)};for(const o of e.features){if(!o.geometry)continue;const l=o.geometry;l.type==="Point"?r(l.coordinates):(l.type==="MultiPoint"||l.type==="LineString"||l.type==="MultiLineString"||l.type==="Polygon"||l.type==="MultiPolygon")&&a(l.coordinates)}t!==1/0&&this._map.fitBounds([[t,n],[i,s]],{padding:this._options.fitBoundsPadding})}async _setupViewportLoading(e,t,n){if(!this._map)return;const{getDuckDBConverter:i}=await Promise.resolve().then(()=>require("./DuckDBConverter-BtujCPmE.cjs")).then(a=>a.DuckDBConverter_exports),s=i(),r=`${e}.parquet`;try{await s.registerRemoteParquet(t,r);const a=await s.getParquetSchema(r);if(!a.geometryColumn)throw new Error("No geometry column found in parquet file");const o=this._vectorLayers.get(e);o&&(o.viewportLoading=!0,o.duckdbFileName=r,o.geometryColumn=a.geometryColumn??void 0,o.geometryColumnType=a.geometryColumnType??void 0,o.propertyColumns=a.propertyColumns),this._viewportLoadingLayers.add(e);const l=NB(()=>{this._updateViewportData(e)},this._options.geoparquetDebounceMs),c=this._viewportHandler;this._viewportHandler=()=>{c&&c(),l()},c&&this._map.off("moveend",c),this._map.on("moveend",this._viewportHandler),await this._updateViewportData(e)}catch(a){throw console.error("Failed to setup viewport loading:",a),await s.unregisterFile(r),a}}async _updateViewportData(e){if(!this._map)return;const t=this._vectorLayers.get(e);if(!t||!t.viewportLoading||!t.duckdbFileName||!t.geometryColumn)return;const n=t.viewportMinZoom??this._state.viewportMinZoom??8;if(this._map.getZoom()<n){for(const i of t.layerIds)this._map.getLayer(i)&&this._map.setLayoutProperty(i,"visibility","none");return}for(const i of t.layerIds)this._map.getLayer(i)&&this._map.setLayoutProperty(i,"visibility","visible");this._viewportLoadingState.set(e,!0);try{const{getDuckDBConverter:i}=await Promise.resolve().then(()=>require("./DuckDBConverter-BtujCPmE.cjs")).then(c=>c.DuckDBConverter_exports),s=i(),r=this._map.getBounds(),a=[r.getWest(),r.getSouth(),r.getEast(),r.getNorth()],o=await s.queryByBounds(t.duckdbFileName,a,t.geometryColumn,t.propertyColumns||[],t.geometryColumnType),l=this._map.getSource(t.sourceId);l&&l.type==="geojson"&&l.setData(o),t.featureCount=o.features.length,this._state.layers=Array.from(this._vectorLayers.values())}catch(i){console.error("Failed to update viewport data:",i)}finally{this._viewportLoadingState.set(e,!1)}}async _cleanupViewportLoading(){if(this._map&&this._viewportHandler&&(this._map.off("moveend",this._viewportHandler),this._viewportHandler=void 0),this._viewportLoadingLayers.size>0)try{const{getDuckDBConverter:e}=await Promise.resolve().then(()=>require("./DuckDBConverter-BtujCPmE.cjs")).then(n=>n.DuckDBConverter_exports),t=e();for(const n of this._viewportLoadingLayers){const i=this._vectorLayers.get(n);i?.duckdbFileName&&await t.unregisterFile(i.duckdbFileName)}}catch{}this._viewportLoadingLayers.clear(),this._viewportLoadingState.clear()}async _cleanupLayerViewportLoading(e){const t=this._vectorLayers.get(e);if(!(!t?.viewportLoading||!t.duckdbFileName)){try{const{getDuckDBConverter:n}=await Promise.resolve().then(()=>require("./DuckDBConverter-BtujCPmE.cjs")).then(i=>i.DuckDBConverter_exports);await n().unregisterFile(t.duckdbFileName)}catch{}this._viewportLoadingLayers.delete(e),this._viewportLoadingState.delete(e),this._viewportLoadingLayers.size===0&&this._viewportHandler&&(this._map&&this._map.off("moveend",this._viewportHandler),this._viewportHandler=void 0)}}_removeLayer(e){if(this._map)if(e){const t=this._vectorLayers.get(e);if(t){t.viewportLoading&&this._cleanupLayerViewportLoading(e);for(const n of t.layerIds)try{this._map.getLayer(n)&&this._map.removeLayer(n)}catch{}try{this._map.getSource(t.sourceId)&&this._map.removeSource(t.sourceId)}catch{}}this._vectorLayers.delete(e),this._state.hasLayer=this._vectorLayers.size>0,this._state.layerCount=this._vectorLayers.size,this._state.layers=Array.from(this._vectorLayers.values()),this._state.status=null,this._state.error=null,this._emit("layerremove",{layerId:e})}else this._removeAllLayers()}_removeAllLayers(){if(this._map){for(const[,e]of this._vectorLayers){for(const t of e.layerIds)try{this._map.getLayer(t)&&this._map.removeLayer(t)}catch{}try{this._map.getSource(e.sourceId)&&this._map.removeSource(e.sourceId)}catch{}}this._vectorLayers.clear(),this._state.hasLayer=!1,this._state.layerCount=0,this._state.layers=[],this._state.status=null,this._state.error=null,this._emit("layerremove")}}},HU=`<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
244
244
  <path d="M3 3h7v7H3z" fill="#4292c6" fill-opacity="0.7" stroke="#2171b5"/>
245
245
  <path d="M10 3h7v7h-7z" fill="#9ecae1" fill-opacity="0.7" stroke="#6baed6"/>
246
246
  <path d="M17 3h4v7h-4z" fill="#08519c" fill-opacity="0.7" stroke="#08306b"/>
@@ -250,7 +250,7 @@ var iO=Object.create;var Gw=Object.defineProperty;var sO=Object.getOwnPropertyDe
250
250
  <path d="M3 17h7v4H3z" fill="#2171b5" fill-opacity="0.7" stroke="#08519c"/>
251
251
  <path d="M10 17h7v4h-7z" fill="#08306b" fill-opacity="0.7" stroke="#08306b"/>
252
252
  <path d="M17 17h4v4h-4z" fill="#4292c6" fill-opacity="0.7" stroke="#2171b5"/>
253
- </svg>`,$U=[{value:"quantile",label:"Quantile"},{value:"equal_interval",label:"Equal Interval"},{value:"natural_breaks",label:"Natural Breaks (Jenks)"},{value:"std_mean",label:"Standard Deviation"},{value:"head_tail",label:"Head/Tail Breaks"}],VU={position:"top-right",className:"",visible:!0,collapsed:!0,beforeId:"",defaultUrl:"",defaultLayerName:"",loadDefaultUrl:!1,defaultFormat:"auto",defaultColumn:"",defaultColormap:"viridis",defaultScheme:"quantile",defaultK:5,defaultOpacity:.8,defaultOutlineColor:"#ffffff",defaultExtrude:!1,defaultScaleFactor:1,defaultPickable:!0,fitBounds:!0,fitBoundsPadding:50,panelWidth:320,maxHeight:500,backgroundColor:"rgba(255, 255, 255, 0.95)",borderRadius:4,opacity:1,fontSize:13,fontColor:"#333",minzoom:0,maxzoom:24};function qU(e){const t=e.toLowerCase();return t.endsWith(".geojson")||t.endsWith(".json")?"geojson":t.endsWith(".parquet")||t.endsWith(".geoparquet")?"geoparquet":t.endsWith(".fgb")?"flatgeobuf":"geojson"}function WU(e,t,n){const i=[...e].filter(c=>!isNaN(c)).sort((c,h)=>c-h),s=i.length;if(s===0)return{breaks:[0,1],bins:e.map(()=>0)};const r=i[0],a=i[s-1];let o;switch(t){case"equal_interval":{o=[r];const c=(a-r)/n;for(let h=1;h<n;h++)o.push(r+c*h);o.push(a);break}case"quantile":o=[r];for(let c=1;c<n;c++){const h=Math.floor(c*s/n);o.push(i[Math.min(h,s-1)])}o.push(a),o=[...new Set(o)].sort((c,h)=>c-h);break;case"natural_breaks":o=YU(i,n);break;case"std_mean":{const c=i.reduce((m,A)=>m+A,0)/s,h=i.reduce((m,A)=>m+(A-c)**2,0)/s,d=Math.sqrt(h);o=[r];const f=[-2,-1,0,1,2].map(m=>c+m*d);for(const m of f)m>r&&m<a&&o.push(m);o.push(a),o=[...new Set(o)].sort((m,A)=>m-A);break}case"head_tail":{o=[r];let c=i;for(;o.length<n&&c.length>1;){const h=c.reduce((d,f)=>d+f,0)/c.length;if(h<=o[o.length-1])break;o.push(h),c=c.filter(d=>d>h)}o.push(a),o=[...new Set(o)].sort((h,d)=>h-d);break}default:{o=[r];const c=(a-r)/n;for(let h=1;h<n;h++)o.push(r+c*h);o.push(a)}}const l=e.map(c=>{if(isNaN(c))return 0;for(let h=0;h<o.length-1;h++)if(c<=o[h+1])return Math.min(h,o.length-2);return o.length-2});return{breaks:o,bins:l}}function YU(e,t){const n=e.length;if(n<=t)return[...new Set(e)].sort((l,c)=>l-c);const i=Array.from({length:n+1},()=>new Array(t+1).fill(1/0)),s=Array.from({length:n+1},()=>new Array(t+1).fill(0));for(let l=1;l<=t;l++)i[1][l]=0,s[1][l]=1;for(let l=2;l<=n;l++){let c=0,h=0;for(let d=1;d<=l;d++){const f=e[l-1];h+=f,c+=f*f;const m=c-h*h/d,A=l-d+1;if(A!==1)for(let y=2;y<=t;y++)i[l][y]>=m+i[A-1][y-1]&&(s[l][y]=A,i[l][y]=m+i[A-1][y-1])}i[l][1]=c-h*h/l,s[l][1]=1}const r=new Array(t+1);r[t]=n;let a=t;for(;a>=2;)r[a-1]=s[r[a]][a]-1,a--;r[0]=0;const o=[e[0]];for(let l=1;l<t;l++)r[l]<n&&o.push(e[r[l]]);return o.push(e[n-1]),[...new Set(o)].sort((l,c)=>l-c)}function jU(e,t){const n=nr(e),i=[];for(let s=0;s<t;s++){const r=t===1?.5:s/(t-1);i.push(DB(n,r))}return i}var m2=class{_container;_button;_panel;_options;_state;_eventHandlers=new Map;_map;_handleZoom;_zoomVisible=!0;_choroplethLayers=new Map;_legendControls=new Map;_activePopup;_cachedGeojson;_cachedColumns=[];constructor(e){this._options={...VU,...e},this._state={visible:this._options.visible,collapsed:this._options.collapsed,url:this._options.defaultUrl,layerName:this._options.defaultLayerName,beforeId:this._options.beforeId,format:this._options.defaultFormat,column:this._options.defaultColumn,colormap:this._options.defaultColormap,scheme:this._options.defaultScheme,k:this._options.defaultK,opacity:this._options.defaultOpacity,showOutline:!0,outlineColor:this._options.defaultOutlineColor,extrude:this._options.defaultExtrude,scaleFactor:this._options.defaultScaleFactor,pickable:this._options.defaultPickable,hasLayer:!1,layerCount:0,layers:[],loading:!1,error:null,status:null,availableColumns:[]}}onAdd(e){if(this._map=e,this._container=this._createContainer(),this._render(),this._handleZoom=()=>this._checkZoomVisibility(),this._map.on("zoom",this._handleZoom),this._checkZoomVisibility(),this._options.loadDefaultUrl&&this._options.defaultUrl){const t=()=>this._loadData();this._map.isStyleLoaded()?setTimeout(t,100):this._map.once("idle",t)}return this._container}onRemove(){this._removeAllLayers(),this._removeAllLegendControls(),this._map&&this._handleZoom&&(this._map.off("zoom",this._handleZoom),this._handleZoom=void 0),this._map=void 0,this._container?.parentNode?.removeChild(this._container),this._container=void 0,this._button=void 0,this._panel=void 0,this._eventHandlers.clear()}show(){this._state.visible||(this._state.visible=!0,this._updateDisplayState(),this._emit("show"))}hide(){this._state.visible&&(this._state.visible=!1,this._updateDisplayState(),this._emit("hide"))}expand(){this._state.collapsed&&(this._state.collapsed=!1,this._render(),this._emit("expand"))}collapse(){this._state.collapsed||(this._state.collapsed=!0,this._render(),this._emit("collapse"))}toggle(){this._state.collapsed?this.expand():this.collapse()}getState(){return{...this._state}}update(e){this._options={...this._options,...e},e.visible!==void 0&&(this._state.visible=e.visible),e.collapsed!==void 0&&(this._state.collapsed=e.collapsed),this._render(),this._emit("update")}on(e,t){this._eventHandlers.has(e)||this._eventHandlers.set(e,new Set),this._eventHandlers.get(e).add(t)}off(e,t){this._eventHandlers.get(e)?.delete(t)}async addLayer(e,t,n){e&&(this._state.url=e),t&&(this._state.column=t),n?.colormap&&(this._state.colormap=n.colormap),n?.scheme&&(this._state.scheme=n.scheme),n?.k&&(this._state.k=n.k),await this._loadData(),this._cachedGeojson&&this._state.column&&await this._addChoroplethLayer()}removeLayer(e){this._removeLayer(e),this._render()}getLayerIds(){const e=[];for(const t of this._choroplethLayers.values())e.push(...t.layerIds);return e}_emit(e,t){const n=this._eventHandlers.get(e);if(n){const i={type:e,state:this.getState(),...t};n.forEach(s=>s(i))}}_checkZoomVisibility(){if(!this._map)return;const e=this._map.getZoom(),{minzoom:t,maxzoom:n}=this._options,i=e>=t&&e<=n;i!==this._zoomVisible&&(this._zoomVisible=i,this._updateDisplayState())}_updateDisplayState(){if(!this._container)return;const e=this._state.visible&&this._zoomVisible;this._container.style.display=e?"block":"none"}_createContainer(){const e=document.createElement("div");return e.className=`maplibregl-ctrl maplibre-gl-choropleth${this._options.className?` ${this._options.className}`:""}`,this._state.visible&&this._zoomVisible||(e.style.display="none"),Object.assign(e.style,{backgroundColor:this._options.backgroundColor,borderRadius:`${this._options.borderRadius}px`,boxShadow:"0 0 0 2px rgba(0, 0, 0, 0.1)"}),this._options.opacity!==1&&(e.style.opacity=String(this._options.opacity)),e}_render(){if(!this._container)return;const e=this._container.querySelector(".maplibre-gl-choropleth-panel"),t=e?e.scrollTop:0;if(this._container.innerHTML="",this._state.collapsed?this._renderCollapsed():this._renderExpanded(),this._updateDisplayState(),t>0){const n=this._container.querySelector(".maplibre-gl-choropleth-panel");n&&(n.scrollTop=t)}}_renderCollapsed(){this._container&&(this._button=document.createElement("button"),this._button.type="button",this._button.className=`maplibre-gl-choropleth-button${this._state.hasLayer?" maplibre-gl-choropleth-button--active":""}`,this._button.title="Choropleth Map",this._button.setAttribute("aria-label","Choropleth Map"),this._button.innerHTML=HU,this._button.addEventListener("click",()=>this.expand()),this._container.appendChild(this._button),this._panel=void 0)}_renderExpanded(){if(!this._container)return;const e=document.createElement("div");e.className="maplibre-gl-choropleth-panel",e.style.width=`${this._options.panelWidth}px`,this._options.maxHeight&&this._options.maxHeight>0&&(e.style.maxHeight=`${this._options.maxHeight}px`,e.style.overflowY="auto"),this._panel=e;const t=document.createElement("div");t.className="maplibre-gl-choropleth-header";const n=document.createElement("span");n.className="maplibre-gl-choropleth-title",n.textContent="Choropleth Map",t.appendChild(n);const i=document.createElement("button");i.className="maplibre-gl-choropleth-close",i.innerHTML="&times;",i.title="Close",i.addEventListener("click",()=>this.collapse()),t.appendChild(i),e.appendChild(t);const s=document.createElement("div");s.className="maplibre-gl-choropleth-section-title",s.textContent="Data Source",s.style.marginTop="0",s.style.borderTop="none",s.style.paddingTop="0",e.appendChild(s);const r=this._createFormGroup("Vector URL","url"),a=document.createElement("input");a.type="text",a.id="choropleth-url",a.className="maplibre-gl-choropleth-input",a.style.color="#000",a.placeholder="https://data.source.coop/giswqs/opengeos/h3_res4_geo.parquet",a.value=this._state.url,a.addEventListener("input",()=>{this._state.url=a.value}),r.appendChild(a);const o=document.createElement("div");o.className="maplibre-gl-choropleth-format-hint",o.textContent="Supports GeoJSON, GeoParquet, and FlatGeobuf",r.appendChild(o),e.appendChild(r);const l=this._createFormGroup("Format","format"),c=document.createElement("select");c.id="choropleth-format",c.className="maplibre-gl-choropleth-select",c.style.color="#000";for(const f of[{value:"auto",label:"Auto-detect"},{value:"geojson",label:"GeoJSON"},{value:"geoparquet",label:"GeoParquet"},{value:"flatgeobuf",label:"FlatGeobuf"}]){const m=document.createElement("option");m.value=f.value,m.textContent=f.label,m.selected=f.value===this._state.format,c.appendChild(m)}c.addEventListener("change",()=>{this._state.format=c.value}),l.appendChild(c),e.appendChild(l);const h=document.createElement("div");h.className="maplibre-gl-choropleth-buttons";const d=document.createElement("button");if(d.className="maplibre-gl-choropleth-btn maplibre-gl-choropleth-btn--primary",d.textContent=this._cachedGeojson?"Reload Data":"Load Data",d.disabled=this._state.loading,d.addEventListener("click",()=>this._loadData()),h.appendChild(d),e.appendChild(h),this._cachedColumns.length>0){const f=document.createElement("div");f.className="maplibre-gl-choropleth-section-title",f.textContent="Classification",e.appendChild(f);const m=this._createFormGroup("Column","column"),A=document.createElement("select");A.id="choropleth-column",A.className="maplibre-gl-choropleth-select",A.style.color="#000";const y=document.createElement("option");y.value="",y.textContent="-- Select column --",y.disabled=!0,y.selected=!this._state.column,A.appendChild(y);for(const q of this._cachedColumns){const pe=document.createElement("option");pe.value=q,pe.textContent=q,pe.selected=q===this._state.column,A.appendChild(pe)}A.addEventListener("change",()=>{this._state.column=A.value}),m.appendChild(A),e.appendChild(m);const x=document.createElement("div");x.className="maplibre-gl-choropleth-row";const v=this._createFormGroup("Scheme","scheme"),b=document.createElement("select");b.id="choropleth-scheme",b.className="maplibre-gl-choropleth-select",b.style.color="#000";for(const q of $U){const pe=document.createElement("option");pe.value=q.value,pe.textContent=q.label,pe.selected=q.value===this._state.scheme,b.appendChild(pe)}b.addEventListener("change",()=>{this._state.scheme=b.value}),v.appendChild(b),x.appendChild(v);const w=this._createFormGroup("Classes","k"),S=document.createElement("input");S.type="number",S.id="choropleth-k",S.className="maplibre-gl-choropleth-input",S.style.color="#000",S.min="2",S.max="20",S.value=String(this._state.k),S.addEventListener("change",()=>{this._state.k=Math.max(2,Math.min(20,Number(S.value)||5)),S.value=String(this._state.k)}),w.appendChild(S),x.appendChild(w),e.appendChild(x);const R=document.createElement("div");R.className="maplibre-gl-choropleth-section-title",R.textContent="Styling",e.appendChild(R);const k=this._createFormGroup("Colormap","colormap"),L=document.createElement("select");L.id="choropleth-colormap",L.className="maplibre-gl-choropleth-select",L.style.color="#000";for(const q of dA()){const pe=document.createElement("option");pe.value=q,pe.textContent=q,pe.selected=q===this._state.colormap,L.appendChild(pe)}L.addEventListener("change",()=>{this._state.colormap=L.value,this._updateColormapPreview(T,this._state.colormap)}),k.appendChild(L);const T=document.createElement("div");T.className="maplibre-gl-choropleth-colormap-preview",this._updateColormapPreview(T,this._state.colormap),k.appendChild(T),e.appendChild(k);const C=this._createFormGroup("Opacity","opacity"),I=document.createElement("div");I.className="maplibre-gl-choropleth-slider-row";const M=document.createElement("input");M.type="range",M.id="choropleth-opacity",M.className="maplibre-gl-choropleth-slider",M.min="0",M.max="100",M.value=String(Math.round(this._state.opacity*100));const O=document.createElement("span");O.className="maplibre-gl-choropleth-slider-value",O.textContent=`${Math.round(this._state.opacity*100)}%`,M.addEventListener("input",()=>{const q=Number(M.value);this._state.opacity=q/100,O.textContent=`${q}%`}),I.appendChild(M),I.appendChild(O),C.appendChild(I),e.appendChild(C);const N=document.createElement("div");N.className="maplibre-gl-choropleth-form-group maplibre-gl-choropleth-checkbox-group";const D=document.createElement("label");D.className="maplibre-gl-choropleth-checkbox-label";const P=document.createElement("input");P.type="checkbox",P.id="choropleth-show-outline",P.className="maplibre-gl-choropleth-checkbox",P.checked=this._state.showOutline,P.addEventListener("change",()=>{this._state.showOutline=P.checked,Q.style.display=P.checked?"block":"none"}),D.appendChild(P);const U=document.createElement("span");U.textContent="Show Outline",D.appendChild(U),N.appendChild(D),e.appendChild(N);const Q=this._createFormGroup("Outline Color","outline-color");Q.style.display=this._state.showOutline?"block":"none";const z=document.createElement("div");z.className="maplibre-gl-choropleth-color-row";const H=document.createElement("input");H.type="color",H.id="choropleth-outline-color",H.className="maplibre-gl-choropleth-color-input",H.value=this._state.outlineColor,H.addEventListener("input",()=>{this._state.outlineColor=H.value,W.value=H.value}),z.appendChild(H);const W=document.createElement("input");W.type="text",W.className="maplibre-gl-choropleth-input",W.style.color="#000",W.style.flex="1",W.value=this._state.outlineColor,W.addEventListener("input",()=>{this._state.outlineColor=W.value,H.value=W.value}),z.appendChild(W),Q.appendChild(z),e.appendChild(Q);const te=document.createElement("div");te.className="maplibre-gl-choropleth-form-group maplibre-gl-choropleth-checkbox-group";const J=document.createElement("label");J.className="maplibre-gl-choropleth-checkbox-label";const K=document.createElement("input");K.type="checkbox",K.id="choropleth-extrude",K.className="maplibre-gl-choropleth-checkbox",K.checked=this._state.extrude,K.addEventListener("change",()=>{this._state.extrude=K.checked,ce.style.display=K.checked?"block":"none"}),J.appendChild(K);const re=document.createElement("span");re.textContent="3D Extrusion (fill-extrusion)",J.appendChild(re),te.appendChild(J),e.appendChild(te);const ce=this._createFormGroup("Scale Factor","scale-factor");ce.style.display=this._state.extrude?"block":"none";const oe=document.createElement("input");oe.type="number",oe.id="choropleth-scale-factor",oe.className="maplibre-gl-choropleth-input",oe.style.color="#000",oe.step="0.1",oe.min="0.001",oe.value=String(this._state.scaleFactor),oe.addEventListener("change",()=>{this._state.scaleFactor=Math.max(.001,Number(oe.value)||1)});const ge=document.createElement("div");ge.className="maplibre-gl-choropleth-format-hint",ge.textContent="Divide column values by this factor for extrusion height",ce.appendChild(oe),ce.appendChild(ge),e.appendChild(ce);const ie=document.createElement("div");ie.className="maplibre-gl-choropleth-form-group maplibre-gl-choropleth-checkbox-group";const fe=document.createElement("label");fe.className="maplibre-gl-choropleth-checkbox-label";const ye=document.createElement("input");ye.type="checkbox",ye.id="choropleth-pickable",ye.className="maplibre-gl-choropleth-checkbox",ye.checked=this._state.pickable,ye.addEventListener("change",()=>{this._state.pickable=ye.checked}),fe.appendChild(ye);const $=document.createElement("span");$.textContent="Pickable (click to show feature info)",fe.appendChild($),ie.appendChild(fe),e.appendChild(ie);const Se=this._createFormGroup("Layer Name","layer-name"),Z=document.createElement("input");Z.type="text",Z.id="choropleth-layer-name",Z.className="maplibre-gl-choropleth-input",Z.style.color="#000",Z.placeholder="Optional custom layer name",Z.value=this._state.layerName,Z.addEventListener("input",()=>{this._state.layerName=Z.value}),Se.appendChild(Z),e.appendChild(Se);const Qe=this._createFormGroup("Before Layer ID","before-id"),Le=document.createElement("input");Le.type="text",Le.id="choropleth-before-id",Le.className="maplibre-gl-choropleth-input",Le.style.color="#000",Le.placeholder="Optional layer ID to insert before",Le.value=this._state.beforeId,Le.addEventListener("input",()=>{this._state.beforeId=Le.value}),Qe.appendChild(Le),e.appendChild(Qe);const et=document.createElement("div");et.className="maplibre-gl-choropleth-buttons";const ne=document.createElement("button");ne.className="maplibre-gl-choropleth-btn maplibre-gl-choropleth-btn--primary",ne.textContent="Add Choropleth",ne.disabled=this._state.loading||!this._state.column,ne.addEventListener("click",()=>this._addChoroplethLayer()),et.appendChild(ne),e.appendChild(et)}if(this._state.loading?this._appendStatus("Loading data...","info"):this._state.error?this._appendStatus(this._state.error,"error"):this._state.status&&this._appendStatus(this._state.status,"success"),this._choroplethLayers.size>0){const f=document.createElement("div");f.className="maplibre-gl-choropleth-layer-list";const m=document.createElement("div");m.className="maplibre-gl-choropleth-layer-header",m.textContent=`Choropleth Layers (${this._choroplethLayers.size})`,f.appendChild(m);for(const[A,y]of this._choroplethLayers){const x=document.createElement("div");x.className="maplibre-gl-choropleth-layer-item";const v=document.createElement("span");v.className="maplibre-gl-choropleth-layer-label",v.textContent=`${y.id} (${y.column}, ${y.scheme})`,v.title=`${y.url} - ${y.column}`,x.appendChild(v);const b=document.createElement("button");if(b.className="maplibre-gl-choropleth-layer-remove",b.innerHTML="&times;",b.title="Remove layer",b.addEventListener("click",()=>{this._removeLayer(A),this._render()}),x.appendChild(b),f.appendChild(x),y.legendColors&&y.legendLabels){const w=document.createElement("div");w.className="maplibre-gl-choropleth-legend";const S=document.createElement("div");S.style.display="flex",S.style.justifyContent="space-between",S.style.alignItems="center",S.style.marginBottom="4px";const R=document.createElement("div");R.className="maplibre-gl-choropleth-legend-title",R.style.marginBottom="0",R.textContent=y.column,S.appendChild(R);const k=this._legendControls.has(A),L=document.createElement("button");L.className=`maplibre-gl-choropleth-btn${k?" maplibre-gl-choropleth-btn--danger":" maplibre-gl-choropleth-btn--primary"}`,L.style.flex="0 0 auto",L.style.padding="3px 8px",L.style.fontSize="10px",L.textContent=k?"Remove Legend":"Add to Map",L.addEventListener("click",()=>{this._legendControls.has(A)?this._removeLegendControl(A):this._addLegendControl(A,y),this._render()}),S.appendChild(L),w.appendChild(S);for(let T=0;T<y.legendColors.length;T++){const C=document.createElement("div");C.className="maplibre-gl-choropleth-legend-item";const I=document.createElement("div");I.className="maplibre-gl-choropleth-legend-swatch",I.style.backgroundColor=y.legendColors[T],C.appendChild(I);const M=document.createElement("span");M.textContent=y.legendLabels[T]||"",C.appendChild(M),w.appendChild(C)}f.appendChild(w)}}e.appendChild(f)}this._container.appendChild(e),this._button=void 0}_createFormGroup(e,t){const n=document.createElement("div");n.className="maplibre-gl-choropleth-form-group";const i=document.createElement("label");return i.textContent=e,i.htmlFor=`choropleth-${t}`,n.appendChild(i),n}_appendStatus(e,t){if(!this._panel)return;const n=document.createElement("div");n.className=`maplibre-gl-choropleth-status maplibre-gl-choropleth-status--${t}`,n.textContent=e,this._panel.appendChild(n)}_updateColormapPreview(e,t){if(!uA(t))return;const n=nr(t).map(i=>`${i.color} ${i.position*100}%`).join(", ");e.style.background=`linear-gradient(to right, ${n})`}async _loadData(){if(!this._map||!this._state.url){this._state.error="Please enter a vector URL.",this._render();return}this._state.loading=!0,this._state.error=null,this._state.status=null,this._render();try{let e=this._state.format;e==="auto"&&(e=qU(this._state.url));let t;if(e==="geojson"){let i;try{i=await fetch(this._state.url)}catch{throw new Error("CORS error: The server doesn't allow cross-origin requests.")}if(!i.ok)throw new Error(`Failed to fetch: ${i.status} ${i.statusText}`);const s=await i.json();t=this._normalizeGeoJSON(s)}else if(e==="geoparquet")t=await this._loadGeoParquet(this._state.url);else if(e==="flatgeobuf")t=await this._loadFlatGeobuf(this._state.url);else throw new Error(`Unsupported format: ${e}`);this._cachedGeojson=t;const n=this._detectNumericColumns(t);this._cachedColumns=n,this._state.availableColumns=n,!this._state.column&&n.length>0&&(this._state.column=n[0]),this._state.loading=!1,this._state.status=`Loaded ${t.features.length} features, ${n.length} numeric columns.`,this._render()}catch(e){this._state.loading=!1,this._state.error=`Failed to load: ${e instanceof Error?e.message:String(e)}`,this._render(),this._emit("error",{error:this._state.error})}}_detectNumericColumns(e){const t=new Map,n=Math.min(e.features.length,100);for(let s=0;s<n;s++){const r=e.features[s]?.properties;if(r)for(const[a,o]of Object.entries(r)){t.has(a)||t.set(a,{numericCount:0,totalCount:0});const l=t.get(a);l.totalCount++,typeof o=="number"&&!isNaN(o)&&l.numericCount++}}const i=[];for(const[s,r]of t)r.totalCount>0&&r.numericCount/r.totalCount>.8&&i.push(s);return i.sort()}async _addChoroplethLayer(){if(!this._map||!this._cachedGeojson||!this._state.column){this._state.error="Load data and select a column first.",this._render();return}this._state.loading=!0,this._state.error=null,this._state.status=null,this._render();try{const e=this._cachedGeojson,t=this._state.column,n=this._state.k,i=this._state.scheme,s=this._state.colormap,r=this._state.opacity,a=this._state.showOutline,o=a?this._state.outlineColor:"transparent",l=this._state.extrude,c=this._state.scaleFactor,{breaks:h,bins:d}=WU(e.features.map(N=>{const D=N.properties?.[t];return typeof D=="number"?D:NaN}),i,n),f=h.length-1,m=jU(s,f),A={type:"FeatureCollection",features:e.features.map((N,D)=>({...N,properties:{...N.properties,_choropleth_color:m[d[D]]||m[0],_choropleth_bin:d[D]}}))};let y=this._state.layerName?.trim();if(!y)try{y=(new URL(this._state.url).pathname.split("/").pop()||"").replace(/\.[^.]+$/,"")}catch{}y||(y=Qa("choropleth")),y=`${y}-${t}`;const x=`${y}-source`,v=new Set;for(const N of A.features)N.geometry&&v.add(N.geometry.type);this._map.addSource(x,{type:"geojson",data:A,generateId:!0});const b=[],w=this._state.beforeId?.trim(),S=this._options.beforeId,R=w||S,k=R&&this._map.getLayer(R)?R:void 0,L=v.has("Polygon")||v.has("MultiPolygon"),T=v.has("LineString")||v.has("MultiLineString"),C=v.has("Point")||v.has("MultiPoint");if(L)if(l){const N=["interpolate",["linear"],["get",t]],D=["interpolate",["linear"],["get",t]];for(let U=0;U<h.length;U++){const Q=Math.min(U,m.length-1);N.push(h[U],m[Q]),D.push(h[U],h[U]/c)}const P=`${y}-extrusion`;this._map.addLayer({id:P,type:"fill-extrusion",source:x,filter:["any",["==",["geometry-type"],"Polygon"],["==",["geometry-type"],"MultiPolygon"]],paint:{"fill-extrusion-color":N,"fill-extrusion-height":D,"fill-extrusion-base":10,"fill-extrusion-opacity":r}},k),b.push(P)}else{const N=`${y}-fill`;if(this._map.addLayer({id:N,type:"fill",source:x,filter:["any",["==",["geometry-type"],"Polygon"],["==",["geometry-type"],"MultiPolygon"]],paint:{"fill-color":["get","_choropleth_color"],"fill-opacity":r,"fill-outline-color":o}},k),b.push(N),a){const D=`${y}-outline`;this._map.addLayer({id:D,type:"line",source:x,filter:["any",["==",["geometry-type"],"Polygon"],["==",["geometry-type"],"MultiPolygon"]],paint:{"line-color":o,"line-width":.5,"line-opacity":r}},k),b.push(D)}}if(T){const N=`${y}-line`;this._map.addLayer({id:N,type:"line",source:x,filter:["any",["==",["geometry-type"],"LineString"],["==",["geometry-type"],"MultiLineString"]],paint:{"line-color":["get","_choropleth_color"],"line-width":2,"line-opacity":r}},k),b.push(N)}if(C){const N=`${y}-point`;this._map.addLayer({id:N,type:"circle",source:x,filter:["any",["==",["geometry-type"],"Point"],["==",["geometry-type"],"MultiPoint"]],paint:{"circle-color":["get","_choropleth_color"],"circle-radius":6,"circle-stroke-color":o,"circle-stroke-width":a?1:0,"circle-opacity":r}},k),b.push(N)}if(this._state.pickable&&this._map){const N=this._map;for(const D of b)N.on("mouseenter",D,()=>{N.getCanvas().style.cursor="pointer"}),N.on("mouseleave",D,()=>{N.getCanvas().style.cursor=""}),N.on("click",D,P=>{if(!P.features||P.features.length===0)return;const U=P.features[0].properties||{},Q=Object.entries(U).filter(([H])=>!H.startsWith("_choropleth_"));if(Q.length===0)return;let z='<div class="maplibre-gl-choropleth-popup">';z+='<table class="maplibre-gl-choropleth-popup-table">';for(const[H,W]of Q){const te=typeof W=="number"?Number.isInteger(W)?W.toString():W.toFixed(4):String(W);z+=`<tr><td><strong>${H}</strong></td><td>${te}</td></tr>`}z+="</table></div>",this._activePopup&&this._activePopup.remove(),this._activePopup=new fi.default.Popup({closeButton:!0,maxWidth:"300px"}).setLngLat(P.lngLat).setHTML(z).addTo(N)})}const I=m,M=[];for(let N=0;N<h.length-1;N++){const D=this._formatBreak(h[N]),P=this._formatBreak(h[N+1]);M.push(`${D} – ${P}`)}const O={id:y,url:this._state.url,sourceId:x,layerIds:b,featureCount:A.features.length,geometryTypes:Array.from(v),column:t,scheme:i,k:f,colormap:s,breaks:h,legendColors:I,legendLabels:M,opacity:r,extrude:l,scaleFactor:c};this._choroplethLayers.set(y,O),this._state.hasLayer=this._choroplethLayers.size>0,this._state.layerCount=this._choroplethLayers.size,this._state.layers=Array.from(this._choroplethLayers.values()),this._state.loading=!1,this._state.status=`Added choropleth: ${t} (${f} classes, ${i}).`,this._options.fitBounds&&A.features.length>0&&this._fitToData(A),this._render(),this._emit("layeradd",{url:this._state.url,layerId:y})}catch(e){this._state.loading=!1,this._state.error=`Failed: ${e instanceof Error?e.message:String(e)}`,this._render(),this._emit("error",{error:this._state.error})}}_formatBreak(e){return Math.abs(e)>=1e3?Math.round(e).toLocaleString():Math.abs(e)>=1?e.toFixed(2):Math.abs(e)>=.01?e.toFixed(4):e.toExponential(2)}_normalizeGeoJSON(e){return e.type==="FeatureCollection"?e:e.type==="Feature"?{type:"FeatureCollection",features:[e]}:{type:"FeatureCollection",features:[{type:"Feature",properties:{},geometry:e}]}}async _fetchWithCorsProxy(e){try{const n=await fetch(e,{mode:"cors"});if(n.ok)return n}catch{}const t="https://corsproxy.io/?";try{const n=await fetch(t+encodeURIComponent(e),{mode:"cors"});if(n.ok)return n}catch{}throw new Error("CORS error: Unable to fetch the file. The server doesn't allow cross-origin requests.")}async _loadGeoParquet(e){const{getDuckDBConverter:t}=await Promise.resolve().then(()=>require("./DuckDBConverter-D4z5GfYH.cjs")).then(a=>a.DuckDBConverter_exports),n=t(),i=await this._fetchWithCorsProxy(e);let s;try{s=await i.arrayBuffer()}catch(a){throw new Error(`Failed to read GeoParquet response: ${a instanceof Error?a.message:String(a)}`)}let r;try{r=await n.convert(s,"data.parquet")}catch(a){throw new Error(`Failed to convert GeoParquet: ${a instanceof Error?a.message:String(a)}`)}if(r.geojson)return r.geojson;throw new Error("Failed to convert GeoParquet: No GeoJSON output")}async _loadFlatGeobuf(e){const t=await Promise.resolve().then(()=>require("./geojson-CxMdRvJX.cjs")),n=await fetch(e);if(!n.ok)throw new Error(`Failed to fetch: ${n.status} ${n.statusText}`);if(!n.body)throw new Error("Response body is null - streaming not supported");const i=[];for await(const s of t.deserialize(n.body))i.push(s);return{type:"FeatureCollection",features:i}}_fitToData(e){if(!this._map)return;let t=1/0,n=1/0,i=-1/0,s=-1/0;const r=o=>{t=Math.min(t,o[0]),i=Math.max(i,o[0]),n=Math.min(n,o[1]),s=Math.max(s,o[1])},a=o=>{for(const l of o)typeof l[0]=="number"?r(l):a(l)};for(const o of e.features){if(!o.geometry)continue;const l=o.geometry;l.type==="Point"?r(l.coordinates):(l.type==="MultiPoint"||l.type==="LineString"||l.type==="MultiLineString"||l.type==="Polygon"||l.type==="MultiPolygon")&&a(l.coordinates)}t!==1/0&&this._map.fitBounds([[t,n],[i,s]],{padding:this._options.fitBoundsPadding})}_removeLayer(e){if(this._map)if(e){const t=this._choroplethLayers.get(e);if(t){for(const n of t.layerIds)try{this._map.getLayer(n)&&this._map.removeLayer(n)}catch{}try{this._map.getSource(t.sourceId)&&this._map.removeSource(t.sourceId)}catch{}}this._choroplethLayers.delete(e),this._removeLegendControl(e),this._state.hasLayer=this._choroplethLayers.size>0,this._state.layerCount=this._choroplethLayers.size,this._state.layers=Array.from(this._choroplethLayers.values()),this._state.status=null,this._state.error=null,this._emit("layerremove",{layerId:e})}else this._removeAllLayers()}_addLegendControl(e,t){if(!this._map||this._legendControls.has(e))return;const n=t.legendColors.map((s,r)=>({label:t.legendLabels[r]||"",color:s,shape:"square"})),i=new aE({title:t.column,items:n,position:"bottom-left",collapsible:!0,collapsed:!1,visible:!0});this._map.addControl(i,"bottom-left"),this._legendControls.set(e,i)}_removeLegendControl(e){if(!this._map)return;const t=this._legendControls.get(e);t&&(this._map.removeControl(t),this._legendControls.delete(e))}_removeAllLegendControls(){if(this._map){for(const[,e]of this._legendControls)try{this._map.removeControl(e)}catch{}this._legendControls.clear()}}_removeAllLayers(){if(this._map){for(const[,e]of this._choroplethLayers){for(const t of e.layerIds)try{this._map.getLayer(t)&&this._map.removeLayer(t)}catch{}try{this._map.getSource(e.sourceId)&&this._map.removeSource(e.sourceId)}catch{}}this._choroplethLayers.clear(),this._removeAllLegendControls(),this._state.hasLayer=!1,this._state.layerCount=0,this._state.layers=[],this._state.status=null,this._state.error=null,this._emit("layerremove")}}},XU={position:"top-right",className:"",visible:!0,collapsed:!0,panelWidth:280,maxHeight:0,backgroundColor:"rgba(255, 255, 255, 0.95)",borderRadius:4,opacity:1,fontSize:12,fontColor:"#333",minzoom:0,maxzoom:24},ZU='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="none"><defs><linearGradient id="cbg" x1="0" y1="1" x2="0" y2="0"><stop offset="0%" stop-color="#440154"/><stop offset="25%" stop-color="#31688e"/><stop offset="50%" stop-color="#21918c"/><stop offset="75%" stop-color="#90d743"/><stop offset="100%" stop-color="#fde725"/></linearGradient></defs><rect x="8" y="2" width="8" height="20" rx="2" fill="url(#cbg)" stroke="currentColor" stroke-width="1.5"/></svg>',JU='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',g2=class{_container;_button;_panel;_options;_state;_eventHandlers=new Map;_map;_handleZoom;_handleResize;_zoomVisible=!0;_colorbar;_colorbars=[];_colorbarEntries=[];_colorbarSelect;_colormapSelect;_vminInput;_vmaxInput;_labelInput;_unitsInput;_orientationSelect;_positionSelect;_addBtn;_updateBtn;_removeBtn;_previewEl;_customColorsTextarea;_modeNamedRadio;_modeCustomRadio;_namedSection;_customSection;constructor(e){this._options={...XU,...e},this._state={visible:this._options.visible,collapsed:this._options.collapsed,mode:"named",colormap:"viridis",customColors:"#440154, #31688e, #21918c, #90d743, #fde725",vmin:0,vmax:100,label:"",units:"",orientation:"vertical",colorbarPosition:"bottom-right",hasColorbar:!1,selectedColorbarIndex:-1,colorbars:[]}}onAdd(e){return this._map=e,this._container=this._createContainer(),this._setupZoomHandler(),this._state.collapsed||this._showPanel(),this._container}onRemove(){this._handleZoom&&this._map&&this._map.off("zoom",this._handleZoom),this._handleResize&&(window.removeEventListener("resize",this._handleResize),this._handleResize=void 0),this._removeAllColorbars(),this._container?.remove(),this._container=void 0,this._map=void 0}getDefaultPosition(){return this._options.position}on(e,t){return this._eventHandlers.has(e)||this._eventHandlers.set(e,new Set),this._eventHandlers.get(e).add(t),this}off(e,t){return this._eventHandlers.get(e)?.delete(t),this}_emit(e){const t=this._eventHandlers.get(e);if(t){const n={type:e,state:{...this._state}};t.forEach(i=>i(n))}}expand(){this._state.collapsed&&(this._state.collapsed=!1,this._showPanel(),this._emit("expand"))}collapse(){this._state.collapsed||(this._state.collapsed=!0,this._hidePanel(),this._emit("collapse"))}show(){return this._state.visible=!0,this._container&&this._zoomVisible&&(this._container.style.display=""),this._emit("show"),this}hide(){return this._state.visible=!1,this._container&&(this._container.style.display="none"),this._emit("hide"),this}getState(){return{...this._state,colorbars:this._colorbarEntries.map(e=>({...e}))}}setState(e){this._map&&this._colorbars.forEach(s=>{this._map.removeControl(s)});const t=(e.colorbars??[]).map(s=>({...s}));this._colorbars=[],this._colorbarEntries=t,this._map&&t.forEach(s=>{const r=this._createColorbar(s);this._map.addControl(r,s.colorbarPosition),this._colorbars.push(r)});const n=typeof e.selectedColorbarIndex=="number"&&e.selectedColorbarIndex>=0&&e.selectedColorbarIndex<t.length?e.selectedColorbarIndex:t.length>0?t.length-1:-1,i=n>=0?t[n]:{mode:e.mode??this._state.mode,colormap:e.colormap??this._state.colormap,customColors:e.customColors??this._state.customColors,vmin:e.vmin??this._state.vmin,vmax:e.vmax??this._state.vmax,label:e.label??this._state.label,units:e.units??this._state.units,orientation:e.orientation??this._state.orientation,colorbarPosition:e.colorbarPosition??this._state.colorbarPosition};return this._state={...this._state,...i,visible:e.visible??this._state.visible,collapsed:e.collapsed??this._state.collapsed,hasColorbar:t.length>0,selectedColorbarIndex:n,colorbars:t.map(s=>({...s}))},this._colorbar=n>=0?this._colorbars[n]:void 0,this._applyEntryToForm(i),this._state.collapsed?this._hidePanel():this._showPanel(),this._container&&(this._container.style.display=this._state.visible&&this._zoomVisible?"":"none"),this._updateButtonStates(),this._emit("colorbarupdate"),this}_createContainer(){const e=document.createElement("div");return e.className=`maplibregl-ctrl maplibre-gl-colorbar-gui-control ${this._options.className}`,this._state.visible||(e.style.display="none"),this._button=document.createElement("button"),this._button.type="button",this._button.className="colorbar-gui-button",this._button.title="Colorbar",this._button.innerHTML=ZU,this._button.addEventListener("click",()=>this._togglePanel()),e.appendChild(this._button),e}_createPanel(){const e=document.createElement("div");e.className=`colorbar-gui-panel ${this._options.position.includes("left")?"right":"left"}`,e.style.width=`${this._options.panelWidth}px`,e.style.overflowY="auto",e.style.background=this._options.backgroundColor,e.style.borderRadius=`${this._options.borderRadius}px`,e.style.fontSize=`${this._options.fontSize}px`,e.style.color=this._options.fontColor;const t=document.createElement("div");t.className="colorbar-gui-header",t.innerHTML=`
253
+ </svg>`,$U=[{value:"quantile",label:"Quantile"},{value:"equal_interval",label:"Equal Interval"},{value:"natural_breaks",label:"Natural Breaks (Jenks)"},{value:"std_mean",label:"Standard Deviation"},{value:"head_tail",label:"Head/Tail Breaks"}],VU={position:"top-right",className:"",visible:!0,collapsed:!0,beforeId:"",defaultUrl:"",defaultLayerName:"",loadDefaultUrl:!1,defaultFormat:"auto",defaultColumn:"",defaultColormap:"viridis",defaultScheme:"quantile",defaultK:5,defaultOpacity:.8,defaultOutlineColor:"#ffffff",defaultExtrude:!1,defaultScaleFactor:1,defaultPickable:!0,fitBounds:!0,fitBoundsPadding:50,panelWidth:320,maxHeight:500,backgroundColor:"rgba(255, 255, 255, 0.95)",borderRadius:4,opacity:1,fontSize:13,fontColor:"#333",minzoom:0,maxzoom:24};function qU(e){const t=e.toLowerCase();return t.endsWith(".geojson")||t.endsWith(".json")?"geojson":t.endsWith(".parquet")||t.endsWith(".geoparquet")?"geoparquet":t.endsWith(".fgb")?"flatgeobuf":"geojson"}function WU(e,t,n){const i=[...e].filter(c=>!isNaN(c)).sort((c,h)=>c-h),s=i.length;if(s===0)return{breaks:[0,1],bins:e.map(()=>0)};const r=i[0],a=i[s-1];let o;switch(t){case"equal_interval":{o=[r];const c=(a-r)/n;for(let h=1;h<n;h++)o.push(r+c*h);o.push(a);break}case"quantile":o=[r];for(let c=1;c<n;c++){const h=Math.floor(c*s/n);o.push(i[Math.min(h,s-1)])}o.push(a),o=[...new Set(o)].sort((c,h)=>c-h);break;case"natural_breaks":o=YU(i,n);break;case"std_mean":{const c=i.reduce((m,A)=>m+A,0)/s,h=i.reduce((m,A)=>m+(A-c)**2,0)/s,d=Math.sqrt(h);o=[r];const f=[-2,-1,0,1,2].map(m=>c+m*d);for(const m of f)m>r&&m<a&&o.push(m);o.push(a),o=[...new Set(o)].sort((m,A)=>m-A);break}case"head_tail":{o=[r];let c=i;for(;o.length<n&&c.length>1;){const h=c.reduce((d,f)=>d+f,0)/c.length;if(h<=o[o.length-1])break;o.push(h),c=c.filter(d=>d>h)}o.push(a),o=[...new Set(o)].sort((h,d)=>h-d);break}default:{o=[r];const c=(a-r)/n;for(let h=1;h<n;h++)o.push(r+c*h);o.push(a)}}const l=e.map(c=>{if(isNaN(c))return 0;for(let h=0;h<o.length-1;h++)if(c<=o[h+1])return Math.min(h,o.length-2);return o.length-2});return{breaks:o,bins:l}}function YU(e,t){const n=e.length;if(n<=t)return[...new Set(e)].sort((l,c)=>l-c);const i=Array.from({length:n+1},()=>new Array(t+1).fill(1/0)),s=Array.from({length:n+1},()=>new Array(t+1).fill(0));for(let l=1;l<=t;l++)i[1][l]=0,s[1][l]=1;for(let l=2;l<=n;l++){let c=0,h=0;for(let d=1;d<=l;d++){const f=e[l-1];h+=f,c+=f*f;const m=c-h*h/d,A=l-d+1;if(A!==1)for(let y=2;y<=t;y++)i[l][y]>=m+i[A-1][y-1]&&(s[l][y]=A,i[l][y]=m+i[A-1][y-1])}i[l][1]=c-h*h/l,s[l][1]=1}const r=new Array(t+1);r[t]=n;let a=t;for(;a>=2;)r[a-1]=s[r[a]][a]-1,a--;r[0]=0;const o=[e[0]];for(let l=1;l<t;l++)r[l]<n&&o.push(e[r[l]]);return o.push(e[n-1]),[...new Set(o)].sort((l,c)=>l-c)}function jU(e,t){const n=nr(e),i=[];for(let s=0;s<t;s++){const r=t===1?.5:s/(t-1);i.push(DB(n,r))}return i}var m2=class{_container;_button;_panel;_options;_state;_eventHandlers=new Map;_map;_handleZoom;_zoomVisible=!0;_choroplethLayers=new Map;_legendControls=new Map;_activePopup;_cachedGeojson;_cachedColumns=[];constructor(e){this._options={...VU,...e},this._state={visible:this._options.visible,collapsed:this._options.collapsed,url:this._options.defaultUrl,layerName:this._options.defaultLayerName,beforeId:this._options.beforeId,format:this._options.defaultFormat,column:this._options.defaultColumn,colormap:this._options.defaultColormap,scheme:this._options.defaultScheme,k:this._options.defaultK,opacity:this._options.defaultOpacity,showOutline:!0,outlineColor:this._options.defaultOutlineColor,extrude:this._options.defaultExtrude,scaleFactor:this._options.defaultScaleFactor,pickable:this._options.defaultPickable,hasLayer:!1,layerCount:0,layers:[],loading:!1,error:null,status:null,availableColumns:[]}}onAdd(e){if(this._map=e,this._container=this._createContainer(),this._render(),this._handleZoom=()=>this._checkZoomVisibility(),this._map.on("zoom",this._handleZoom),this._checkZoomVisibility(),this._options.loadDefaultUrl&&this._options.defaultUrl){const t=()=>this._loadData();this._map.isStyleLoaded()?setTimeout(t,100):this._map.once("idle",t)}return this._container}onRemove(){this._removeAllLayers(),this._removeAllLegendControls(),this._map&&this._handleZoom&&(this._map.off("zoom",this._handleZoom),this._handleZoom=void 0),this._map=void 0,this._container?.parentNode?.removeChild(this._container),this._container=void 0,this._button=void 0,this._panel=void 0,this._eventHandlers.clear()}show(){this._state.visible||(this._state.visible=!0,this._updateDisplayState(),this._emit("show"))}hide(){this._state.visible&&(this._state.visible=!1,this._updateDisplayState(),this._emit("hide"))}expand(){this._state.collapsed&&(this._state.collapsed=!1,this._render(),this._emit("expand"))}collapse(){this._state.collapsed||(this._state.collapsed=!0,this._render(),this._emit("collapse"))}toggle(){this._state.collapsed?this.expand():this.collapse()}getState(){return{...this._state}}update(e){this._options={...this._options,...e},e.visible!==void 0&&(this._state.visible=e.visible),e.collapsed!==void 0&&(this._state.collapsed=e.collapsed),this._render(),this._emit("update")}on(e,t){this._eventHandlers.has(e)||this._eventHandlers.set(e,new Set),this._eventHandlers.get(e).add(t)}off(e,t){this._eventHandlers.get(e)?.delete(t)}async addLayer(e,t,n){e&&(this._state.url=e),t&&(this._state.column=t),n?.colormap&&(this._state.colormap=n.colormap),n?.scheme&&(this._state.scheme=n.scheme),n?.k&&(this._state.k=n.k),await this._loadData(),this._cachedGeojson&&this._state.column&&await this._addChoroplethLayer()}removeLayer(e){this._removeLayer(e),this._render()}getLayerIds(){const e=[];for(const t of this._choroplethLayers.values())e.push(...t.layerIds);return e}_emit(e,t){const n=this._eventHandlers.get(e);if(n){const i={type:e,state:this.getState(),...t};n.forEach(s=>s(i))}}_checkZoomVisibility(){if(!this._map)return;const e=this._map.getZoom(),{minzoom:t,maxzoom:n}=this._options,i=e>=t&&e<=n;i!==this._zoomVisible&&(this._zoomVisible=i,this._updateDisplayState())}_updateDisplayState(){if(!this._container)return;const e=this._state.visible&&this._zoomVisible;this._container.style.display=e?"block":"none"}_createContainer(){const e=document.createElement("div");return e.className=`maplibregl-ctrl maplibre-gl-choropleth${this._options.className?` ${this._options.className}`:""}`,this._state.visible&&this._zoomVisible||(e.style.display="none"),Object.assign(e.style,{backgroundColor:this._options.backgroundColor,borderRadius:`${this._options.borderRadius}px`,boxShadow:"0 0 0 2px rgba(0, 0, 0, 0.1)"}),this._options.opacity!==1&&(e.style.opacity=String(this._options.opacity)),e}_render(){if(!this._container)return;const e=this._container.querySelector(".maplibre-gl-choropleth-panel"),t=e?e.scrollTop:0;if(this._container.innerHTML="",this._state.collapsed?this._renderCollapsed():this._renderExpanded(),this._updateDisplayState(),t>0){const n=this._container.querySelector(".maplibre-gl-choropleth-panel");n&&(n.scrollTop=t)}}_renderCollapsed(){this._container&&(this._button=document.createElement("button"),this._button.type="button",this._button.className=`maplibre-gl-choropleth-button${this._state.hasLayer?" maplibre-gl-choropleth-button--active":""}`,this._button.title="Choropleth Map",this._button.setAttribute("aria-label","Choropleth Map"),this._button.innerHTML=HU,this._button.addEventListener("click",()=>this.expand()),this._container.appendChild(this._button),this._panel=void 0)}_renderExpanded(){if(!this._container)return;const e=document.createElement("div");e.className="maplibre-gl-choropleth-panel",e.style.width=`${this._options.panelWidth}px`,this._options.maxHeight&&this._options.maxHeight>0&&(e.style.maxHeight=`${this._options.maxHeight}px`,e.style.overflowY="auto"),this._panel=e;const t=document.createElement("div");t.className="maplibre-gl-choropleth-header";const n=document.createElement("span");n.className="maplibre-gl-choropleth-title",n.textContent="Choropleth Map",t.appendChild(n);const i=document.createElement("button");i.className="maplibre-gl-choropleth-close",i.innerHTML="&times;",i.title="Close",i.addEventListener("click",()=>this.collapse()),t.appendChild(i),e.appendChild(t);const s=document.createElement("div");s.className="maplibre-gl-choropleth-section-title",s.textContent="Data Source",s.style.marginTop="0",s.style.borderTop="none",s.style.paddingTop="0",e.appendChild(s);const r=this._createFormGroup("Vector URL","url"),a=document.createElement("input");a.type="text",a.id="choropleth-url",a.className="maplibre-gl-choropleth-input",a.style.color="#000",a.placeholder="https://data.source.coop/giswqs/opengeos/h3_res4_geo.parquet",a.value=this._state.url,a.addEventListener("input",()=>{this._state.url=a.value}),r.appendChild(a);const o=document.createElement("div");o.className="maplibre-gl-choropleth-format-hint",o.textContent="Supports GeoJSON, GeoParquet, and FlatGeobuf",r.appendChild(o),e.appendChild(r);const l=this._createFormGroup("Format","format"),c=document.createElement("select");c.id="choropleth-format",c.className="maplibre-gl-choropleth-select",c.style.color="#000";for(const f of[{value:"auto",label:"Auto-detect"},{value:"geojson",label:"GeoJSON"},{value:"geoparquet",label:"GeoParquet"},{value:"flatgeobuf",label:"FlatGeobuf"}]){const m=document.createElement("option");m.value=f.value,m.textContent=f.label,m.selected=f.value===this._state.format,c.appendChild(m)}c.addEventListener("change",()=>{this._state.format=c.value}),l.appendChild(c),e.appendChild(l);const h=document.createElement("div");h.className="maplibre-gl-choropleth-buttons";const d=document.createElement("button");if(d.className="maplibre-gl-choropleth-btn maplibre-gl-choropleth-btn--primary",d.textContent=this._cachedGeojson?"Reload Data":"Load Data",d.disabled=this._state.loading,d.addEventListener("click",()=>this._loadData()),h.appendChild(d),e.appendChild(h),this._cachedColumns.length>0){const f=document.createElement("div");f.className="maplibre-gl-choropleth-section-title",f.textContent="Classification",e.appendChild(f);const m=this._createFormGroup("Column","column"),A=document.createElement("select");A.id="choropleth-column",A.className="maplibre-gl-choropleth-select",A.style.color="#000";const y=document.createElement("option");y.value="",y.textContent="-- Select column --",y.disabled=!0,y.selected=!this._state.column,A.appendChild(y);for(const q of this._cachedColumns){const pe=document.createElement("option");pe.value=q,pe.textContent=q,pe.selected=q===this._state.column,A.appendChild(pe)}A.addEventListener("change",()=>{this._state.column=A.value}),m.appendChild(A),e.appendChild(m);const x=document.createElement("div");x.className="maplibre-gl-choropleth-row";const v=this._createFormGroup("Scheme","scheme"),b=document.createElement("select");b.id="choropleth-scheme",b.className="maplibre-gl-choropleth-select",b.style.color="#000";for(const q of $U){const pe=document.createElement("option");pe.value=q.value,pe.textContent=q.label,pe.selected=q.value===this._state.scheme,b.appendChild(pe)}b.addEventListener("change",()=>{this._state.scheme=b.value}),v.appendChild(b),x.appendChild(v);const w=this._createFormGroup("Classes","k"),S=document.createElement("input");S.type="number",S.id="choropleth-k",S.className="maplibre-gl-choropleth-input",S.style.color="#000",S.min="2",S.max="20",S.value=String(this._state.k),S.addEventListener("change",()=>{this._state.k=Math.max(2,Math.min(20,Number(S.value)||5)),S.value=String(this._state.k)}),w.appendChild(S),x.appendChild(w),e.appendChild(x);const R=document.createElement("div");R.className="maplibre-gl-choropleth-section-title",R.textContent="Styling",e.appendChild(R);const k=this._createFormGroup("Colormap","colormap"),L=document.createElement("select");L.id="choropleth-colormap",L.className="maplibre-gl-choropleth-select",L.style.color="#000";for(const q of dA()){const pe=document.createElement("option");pe.value=q,pe.textContent=q,pe.selected=q===this._state.colormap,L.appendChild(pe)}L.addEventListener("change",()=>{this._state.colormap=L.value,this._updateColormapPreview(T,this._state.colormap)}),k.appendChild(L);const T=document.createElement("div");T.className="maplibre-gl-choropleth-colormap-preview",this._updateColormapPreview(T,this._state.colormap),k.appendChild(T),e.appendChild(k);const C=this._createFormGroup("Opacity","opacity"),I=document.createElement("div");I.className="maplibre-gl-choropleth-slider-row";const M=document.createElement("input");M.type="range",M.id="choropleth-opacity",M.className="maplibre-gl-choropleth-slider",M.min="0",M.max="100",M.value=String(Math.round(this._state.opacity*100));const O=document.createElement("span");O.className="maplibre-gl-choropleth-slider-value",O.textContent=`${Math.round(this._state.opacity*100)}%`,M.addEventListener("input",()=>{const q=Number(M.value);this._state.opacity=q/100,O.textContent=`${q}%`}),I.appendChild(M),I.appendChild(O),C.appendChild(I),e.appendChild(C);const N=document.createElement("div");N.className="maplibre-gl-choropleth-form-group maplibre-gl-choropleth-checkbox-group";const D=document.createElement("label");D.className="maplibre-gl-choropleth-checkbox-label";const P=document.createElement("input");P.type="checkbox",P.id="choropleth-show-outline",P.className="maplibre-gl-choropleth-checkbox",P.checked=this._state.showOutline,P.addEventListener("change",()=>{this._state.showOutline=P.checked,Q.style.display=P.checked?"block":"none"}),D.appendChild(P);const U=document.createElement("span");U.textContent="Show Outline",D.appendChild(U),N.appendChild(D),e.appendChild(N);const Q=this._createFormGroup("Outline Color","outline-color");Q.style.display=this._state.showOutline?"block":"none";const z=document.createElement("div");z.className="maplibre-gl-choropleth-color-row";const H=document.createElement("input");H.type="color",H.id="choropleth-outline-color",H.className="maplibre-gl-choropleth-color-input",H.value=this._state.outlineColor,H.addEventListener("input",()=>{this._state.outlineColor=H.value,W.value=H.value}),z.appendChild(H);const W=document.createElement("input");W.type="text",W.className="maplibre-gl-choropleth-input",W.style.color="#000",W.style.flex="1",W.value=this._state.outlineColor,W.addEventListener("input",()=>{this._state.outlineColor=W.value,H.value=W.value}),z.appendChild(W),Q.appendChild(z),e.appendChild(Q);const te=document.createElement("div");te.className="maplibre-gl-choropleth-form-group maplibre-gl-choropleth-checkbox-group";const J=document.createElement("label");J.className="maplibre-gl-choropleth-checkbox-label";const K=document.createElement("input");K.type="checkbox",K.id="choropleth-extrude",K.className="maplibre-gl-choropleth-checkbox",K.checked=this._state.extrude,K.addEventListener("change",()=>{this._state.extrude=K.checked,ce.style.display=K.checked?"block":"none"}),J.appendChild(K);const re=document.createElement("span");re.textContent="3D Extrusion (fill-extrusion)",J.appendChild(re),te.appendChild(J),e.appendChild(te);const ce=this._createFormGroup("Scale Factor","scale-factor");ce.style.display=this._state.extrude?"block":"none";const oe=document.createElement("input");oe.type="number",oe.id="choropleth-scale-factor",oe.className="maplibre-gl-choropleth-input",oe.style.color="#000",oe.step="0.1",oe.min="0.001",oe.value=String(this._state.scaleFactor),oe.addEventListener("change",()=>{this._state.scaleFactor=Math.max(.001,Number(oe.value)||1)});const ge=document.createElement("div");ge.className="maplibre-gl-choropleth-format-hint",ge.textContent="Divide column values by this factor for extrusion height",ce.appendChild(oe),ce.appendChild(ge),e.appendChild(ce);const ie=document.createElement("div");ie.className="maplibre-gl-choropleth-form-group maplibre-gl-choropleth-checkbox-group";const fe=document.createElement("label");fe.className="maplibre-gl-choropleth-checkbox-label";const ye=document.createElement("input");ye.type="checkbox",ye.id="choropleth-pickable",ye.className="maplibre-gl-choropleth-checkbox",ye.checked=this._state.pickable,ye.addEventListener("change",()=>{this._state.pickable=ye.checked}),fe.appendChild(ye);const $=document.createElement("span");$.textContent="Pickable (click to show feature info)",fe.appendChild($),ie.appendChild(fe),e.appendChild(ie);const Se=this._createFormGroup("Layer Name","layer-name"),Z=document.createElement("input");Z.type="text",Z.id="choropleth-layer-name",Z.className="maplibre-gl-choropleth-input",Z.style.color="#000",Z.placeholder="Optional custom layer name",Z.value=this._state.layerName,Z.addEventListener("input",()=>{this._state.layerName=Z.value}),Se.appendChild(Z),e.appendChild(Se);const Qe=this._createFormGroup("Before Layer ID","before-id"),Le=document.createElement("input");Le.type="text",Le.id="choropleth-before-id",Le.className="maplibre-gl-choropleth-input",Le.style.color="#000",Le.placeholder="Optional layer ID to insert before",Le.value=this._state.beforeId,Le.addEventListener("input",()=>{this._state.beforeId=Le.value}),Qe.appendChild(Le),e.appendChild(Qe);const et=document.createElement("div");et.className="maplibre-gl-choropleth-buttons";const ne=document.createElement("button");ne.className="maplibre-gl-choropleth-btn maplibre-gl-choropleth-btn--primary",ne.textContent="Add Choropleth",ne.disabled=this._state.loading||!this._state.column,ne.addEventListener("click",()=>this._addChoroplethLayer()),et.appendChild(ne),e.appendChild(et)}if(this._state.loading?this._appendStatus("Loading data...","info"):this._state.error?this._appendStatus(this._state.error,"error"):this._state.status&&this._appendStatus(this._state.status,"success"),this._choroplethLayers.size>0){const f=document.createElement("div");f.className="maplibre-gl-choropleth-layer-list";const m=document.createElement("div");m.className="maplibre-gl-choropleth-layer-header",m.textContent=`Choropleth Layers (${this._choroplethLayers.size})`,f.appendChild(m);for(const[A,y]of this._choroplethLayers){const x=document.createElement("div");x.className="maplibre-gl-choropleth-layer-item";const v=document.createElement("span");v.className="maplibre-gl-choropleth-layer-label",v.textContent=`${y.id} (${y.column}, ${y.scheme})`,v.title=`${y.url} - ${y.column}`,x.appendChild(v);const b=document.createElement("button");if(b.className="maplibre-gl-choropleth-layer-remove",b.innerHTML="&times;",b.title="Remove layer",b.addEventListener("click",()=>{this._removeLayer(A),this._render()}),x.appendChild(b),f.appendChild(x),y.legendColors&&y.legendLabels){const w=document.createElement("div");w.className="maplibre-gl-choropleth-legend";const S=document.createElement("div");S.style.display="flex",S.style.justifyContent="space-between",S.style.alignItems="center",S.style.marginBottom="4px";const R=document.createElement("div");R.className="maplibre-gl-choropleth-legend-title",R.style.marginBottom="0",R.textContent=y.column,S.appendChild(R);const k=this._legendControls.has(A),L=document.createElement("button");L.className=`maplibre-gl-choropleth-btn${k?" maplibre-gl-choropleth-btn--danger":" maplibre-gl-choropleth-btn--primary"}`,L.style.flex="0 0 auto",L.style.padding="3px 8px",L.style.fontSize="10px",L.textContent=k?"Remove Legend":"Add to Map",L.addEventListener("click",()=>{this._legendControls.has(A)?this._removeLegendControl(A):this._addLegendControl(A,y),this._render()}),S.appendChild(L),w.appendChild(S);for(let T=0;T<y.legendColors.length;T++){const C=document.createElement("div");C.className="maplibre-gl-choropleth-legend-item";const I=document.createElement("div");I.className="maplibre-gl-choropleth-legend-swatch",I.style.backgroundColor=y.legendColors[T],C.appendChild(I);const M=document.createElement("span");M.textContent=y.legendLabels[T]||"",C.appendChild(M),w.appendChild(C)}f.appendChild(w)}}e.appendChild(f)}this._container.appendChild(e),this._button=void 0}_createFormGroup(e,t){const n=document.createElement("div");n.className="maplibre-gl-choropleth-form-group";const i=document.createElement("label");return i.textContent=e,i.htmlFor=`choropleth-${t}`,n.appendChild(i),n}_appendStatus(e,t){if(!this._panel)return;const n=document.createElement("div");n.className=`maplibre-gl-choropleth-status maplibre-gl-choropleth-status--${t}`,n.textContent=e,this._panel.appendChild(n)}_updateColormapPreview(e,t){if(!uA(t))return;const n=nr(t).map(i=>`${i.color} ${i.position*100}%`).join(", ");e.style.background=`linear-gradient(to right, ${n})`}async _loadData(){if(!this._map||!this._state.url){this._state.error="Please enter a vector URL.",this._render();return}this._state.loading=!0,this._state.error=null,this._state.status=null,this._render();try{let e=this._state.format;e==="auto"&&(e=qU(this._state.url));let t;if(e==="geojson"){let i;try{i=await fetch(this._state.url)}catch{throw new Error("CORS error: The server doesn't allow cross-origin requests.")}if(!i.ok)throw new Error(`Failed to fetch: ${i.status} ${i.statusText}`);const s=await i.json();t=this._normalizeGeoJSON(s)}else if(e==="geoparquet")t=await this._loadGeoParquet(this._state.url);else if(e==="flatgeobuf")t=await this._loadFlatGeobuf(this._state.url);else throw new Error(`Unsupported format: ${e}`);this._cachedGeojson=t;const n=this._detectNumericColumns(t);this._cachedColumns=n,this._state.availableColumns=n,!this._state.column&&n.length>0&&(this._state.column=n[0]),this._state.loading=!1,this._state.status=`Loaded ${t.features.length} features, ${n.length} numeric columns.`,this._render()}catch(e){this._state.loading=!1,this._state.error=`Failed to load: ${e instanceof Error?e.message:String(e)}`,this._render(),this._emit("error",{error:this._state.error})}}_detectNumericColumns(e){const t=new Map,n=Math.min(e.features.length,100);for(let s=0;s<n;s++){const r=e.features[s]?.properties;if(r)for(const[a,o]of Object.entries(r)){t.has(a)||t.set(a,{numericCount:0,totalCount:0});const l=t.get(a);l.totalCount++,typeof o=="number"&&!isNaN(o)&&l.numericCount++}}const i=[];for(const[s,r]of t)r.totalCount>0&&r.numericCount/r.totalCount>.8&&i.push(s);return i.sort()}async _addChoroplethLayer(){if(!this._map||!this._cachedGeojson||!this._state.column){this._state.error="Load data and select a column first.",this._render();return}this._state.loading=!0,this._state.error=null,this._state.status=null,this._render();try{const e=this._cachedGeojson,t=this._state.column,n=this._state.k,i=this._state.scheme,s=this._state.colormap,r=this._state.opacity,a=this._state.showOutline,o=a?this._state.outlineColor:"transparent",l=this._state.extrude,c=this._state.scaleFactor,{breaks:h,bins:d}=WU(e.features.map(N=>{const D=N.properties?.[t];return typeof D=="number"?D:NaN}),i,n),f=h.length-1,m=jU(s,f),A={type:"FeatureCollection",features:e.features.map((N,D)=>({...N,properties:{...N.properties,_choropleth_color:m[d[D]]||m[0],_choropleth_bin:d[D]}}))};let y=this._state.layerName?.trim();if(!y)try{y=(new URL(this._state.url).pathname.split("/").pop()||"").replace(/\.[^.]+$/,"")}catch{}y||(y=Qa("choropleth")),y=`${y}-${t}`;const x=`${y}-source`,v=new Set;for(const N of A.features)N.geometry&&v.add(N.geometry.type);this._map.addSource(x,{type:"geojson",data:A,generateId:!0});const b=[],w=this._state.beforeId?.trim(),S=this._options.beforeId,R=w||S,k=R&&this._map.getLayer(R)?R:void 0,L=v.has("Polygon")||v.has("MultiPolygon"),T=v.has("LineString")||v.has("MultiLineString"),C=v.has("Point")||v.has("MultiPoint");if(L)if(l){const N=["interpolate",["linear"],["get",t]],D=["interpolate",["linear"],["get",t]];for(let U=0;U<h.length;U++){const Q=Math.min(U,m.length-1);N.push(h[U],m[Q]),D.push(h[U],h[U]/c)}const P=`${y}-extrusion`;this._map.addLayer({id:P,type:"fill-extrusion",source:x,filter:["any",["==",["geometry-type"],"Polygon"],["==",["geometry-type"],"MultiPolygon"]],paint:{"fill-extrusion-color":N,"fill-extrusion-height":D,"fill-extrusion-base":10,"fill-extrusion-opacity":r}},k),b.push(P)}else{const N=`${y}-fill`;if(this._map.addLayer({id:N,type:"fill",source:x,filter:["any",["==",["geometry-type"],"Polygon"],["==",["geometry-type"],"MultiPolygon"]],paint:{"fill-color":["get","_choropleth_color"],"fill-opacity":r,"fill-outline-color":o}},k),b.push(N),a){const D=`${y}-outline`;this._map.addLayer({id:D,type:"line",source:x,filter:["any",["==",["geometry-type"],"Polygon"],["==",["geometry-type"],"MultiPolygon"]],paint:{"line-color":o,"line-width":.5,"line-opacity":r}},k),b.push(D)}}if(T){const N=`${y}-line`;this._map.addLayer({id:N,type:"line",source:x,filter:["any",["==",["geometry-type"],"LineString"],["==",["geometry-type"],"MultiLineString"]],paint:{"line-color":["get","_choropleth_color"],"line-width":2,"line-opacity":r}},k),b.push(N)}if(C){const N=`${y}-point`;this._map.addLayer({id:N,type:"circle",source:x,filter:["any",["==",["geometry-type"],"Point"],["==",["geometry-type"],"MultiPoint"]],paint:{"circle-color":["get","_choropleth_color"],"circle-radius":6,"circle-stroke-color":o,"circle-stroke-width":a?1:0,"circle-opacity":r}},k),b.push(N)}if(this._state.pickable&&this._map){const N=this._map;for(const D of b)N.on("mouseenter",D,()=>{N.getCanvas().style.cursor="pointer"}),N.on("mouseleave",D,()=>{N.getCanvas().style.cursor=""}),N.on("click",D,P=>{if(!P.features||P.features.length===0)return;const U=P.features[0].properties||{},Q=Object.entries(U).filter(([H])=>!H.startsWith("_choropleth_"));if(Q.length===0)return;let z='<div class="maplibre-gl-choropleth-popup">';z+='<table class="maplibre-gl-choropleth-popup-table">';for(const[H,W]of Q){const te=typeof W=="number"?Number.isInteger(W)?W.toString():W.toFixed(4):String(W);z+=`<tr><td><strong>${H}</strong></td><td>${te}</td></tr>`}z+="</table></div>",this._activePopup&&this._activePopup.remove(),this._activePopup=new fi.default.Popup({closeButton:!0,maxWidth:"300px"}).setLngLat(P.lngLat).setHTML(z).addTo(N)})}const I=m,M=[];for(let N=0;N<h.length-1;N++){const D=this._formatBreak(h[N]),P=this._formatBreak(h[N+1]);M.push(`${D} – ${P}`)}const O={id:y,url:this._state.url,sourceId:x,layerIds:b,featureCount:A.features.length,geometryTypes:Array.from(v),column:t,scheme:i,k:f,colormap:s,breaks:h,legendColors:I,legendLabels:M,opacity:r,extrude:l,scaleFactor:c};this._choroplethLayers.set(y,O),this._state.hasLayer=this._choroplethLayers.size>0,this._state.layerCount=this._choroplethLayers.size,this._state.layers=Array.from(this._choroplethLayers.values()),this._state.loading=!1,this._state.status=`Added choropleth: ${t} (${f} classes, ${i}).`,this._options.fitBounds&&A.features.length>0&&this._fitToData(A),this._render(),this._emit("layeradd",{url:this._state.url,layerId:y})}catch(e){this._state.loading=!1,this._state.error=`Failed: ${e instanceof Error?e.message:String(e)}`,this._render(),this._emit("error",{error:this._state.error})}}_formatBreak(e){return Math.abs(e)>=1e3?Math.round(e).toLocaleString():Math.abs(e)>=1?e.toFixed(2):Math.abs(e)>=.01?e.toFixed(4):e.toExponential(2)}_normalizeGeoJSON(e){return e.type==="FeatureCollection"?e:e.type==="Feature"?{type:"FeatureCollection",features:[e]}:{type:"FeatureCollection",features:[{type:"Feature",properties:{},geometry:e}]}}async _fetchWithCorsProxy(e){try{const n=await fetch(e,{mode:"cors"});if(n.ok)return n}catch{}const t="https://corsproxy.io/?";try{const n=await fetch(t+encodeURIComponent(e),{mode:"cors"});if(n.ok)return n}catch{}throw new Error("CORS error: Unable to fetch the file. The server doesn't allow cross-origin requests.")}async _loadGeoParquet(e){const{getDuckDBConverter:t}=await Promise.resolve().then(()=>require("./DuckDBConverter-BtujCPmE.cjs")).then(a=>a.DuckDBConverter_exports),n=t(),i=await this._fetchWithCorsProxy(e);let s;try{s=await i.arrayBuffer()}catch(a){throw new Error(`Failed to read GeoParquet response: ${a instanceof Error?a.message:String(a)}`)}let r;try{r=await n.convert(s,"data.parquet")}catch(a){throw new Error(`Failed to convert GeoParquet: ${a instanceof Error?a.message:String(a)}`)}if(r.geojson)return r.geojson;throw new Error("Failed to convert GeoParquet: No GeoJSON output")}async _loadFlatGeobuf(e){const t=await Promise.resolve().then(()=>require("./geojson-CxMdRvJX.cjs")),n=await fetch(e);if(!n.ok)throw new Error(`Failed to fetch: ${n.status} ${n.statusText}`);if(!n.body)throw new Error("Response body is null - streaming not supported");const i=[];for await(const s of t.deserialize(n.body))i.push(s);return{type:"FeatureCollection",features:i}}_fitToData(e){if(!this._map)return;let t=1/0,n=1/0,i=-1/0,s=-1/0;const r=o=>{t=Math.min(t,o[0]),i=Math.max(i,o[0]),n=Math.min(n,o[1]),s=Math.max(s,o[1])},a=o=>{for(const l of o)typeof l[0]=="number"?r(l):a(l)};for(const o of e.features){if(!o.geometry)continue;const l=o.geometry;l.type==="Point"?r(l.coordinates):(l.type==="MultiPoint"||l.type==="LineString"||l.type==="MultiLineString"||l.type==="Polygon"||l.type==="MultiPolygon")&&a(l.coordinates)}t!==1/0&&this._map.fitBounds([[t,n],[i,s]],{padding:this._options.fitBoundsPadding})}_removeLayer(e){if(this._map)if(e){const t=this._choroplethLayers.get(e);if(t){for(const n of t.layerIds)try{this._map.getLayer(n)&&this._map.removeLayer(n)}catch{}try{this._map.getSource(t.sourceId)&&this._map.removeSource(t.sourceId)}catch{}}this._choroplethLayers.delete(e),this._removeLegendControl(e),this._state.hasLayer=this._choroplethLayers.size>0,this._state.layerCount=this._choroplethLayers.size,this._state.layers=Array.from(this._choroplethLayers.values()),this._state.status=null,this._state.error=null,this._emit("layerremove",{layerId:e})}else this._removeAllLayers()}_addLegendControl(e,t){if(!this._map||this._legendControls.has(e))return;const n=t.legendColors.map((s,r)=>({label:t.legendLabels[r]||"",color:s,shape:"square"})),i=new aE({title:t.column,items:n,position:"bottom-left",collapsible:!0,collapsed:!1,visible:!0});this._map.addControl(i,"bottom-left"),this._legendControls.set(e,i)}_removeLegendControl(e){if(!this._map)return;const t=this._legendControls.get(e);t&&(this._map.removeControl(t),this._legendControls.delete(e))}_removeAllLegendControls(){if(this._map){for(const[,e]of this._legendControls)try{this._map.removeControl(e)}catch{}this._legendControls.clear()}}_removeAllLayers(){if(this._map){for(const[,e]of this._choroplethLayers){for(const t of e.layerIds)try{this._map.getLayer(t)&&this._map.removeLayer(t)}catch{}try{this._map.getSource(e.sourceId)&&this._map.removeSource(e.sourceId)}catch{}}this._choroplethLayers.clear(),this._removeAllLegendControls(),this._state.hasLayer=!1,this._state.layerCount=0,this._state.layers=[],this._state.status=null,this._state.error=null,this._emit("layerremove")}}},XU={position:"top-right",className:"",visible:!0,collapsed:!0,panelWidth:280,maxHeight:0,backgroundColor:"rgba(255, 255, 255, 0.95)",borderRadius:4,opacity:1,fontSize:12,fontColor:"#333",minzoom:0,maxzoom:24},ZU='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="none"><defs><linearGradient id="cbg" x1="0" y1="1" x2="0" y2="0"><stop offset="0%" stop-color="#440154"/><stop offset="25%" stop-color="#31688e"/><stop offset="50%" stop-color="#21918c"/><stop offset="75%" stop-color="#90d743"/><stop offset="100%" stop-color="#fde725"/></linearGradient></defs><rect x="8" y="2" width="8" height="20" rx="2" fill="url(#cbg)" stroke="currentColor" stroke-width="1.5"/></svg>',JU='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',g2=class{_container;_button;_panel;_options;_state;_eventHandlers=new Map;_map;_handleZoom;_handleResize;_zoomVisible=!0;_colorbar;_colorbars=[];_colorbarEntries=[];_colorbarSelect;_colormapSelect;_vminInput;_vmaxInput;_labelInput;_unitsInput;_orientationSelect;_positionSelect;_addBtn;_updateBtn;_removeBtn;_previewEl;_customColorsTextarea;_modeNamedRadio;_modeCustomRadio;_namedSection;_customSection;constructor(e){this._options={...XU,...e},this._state={visible:this._options.visible,collapsed:this._options.collapsed,mode:"named",colormap:"viridis",customColors:"#440154, #31688e, #21918c, #90d743, #fde725",vmin:0,vmax:100,label:"",units:"",orientation:"vertical",colorbarPosition:"bottom-right",hasColorbar:!1,selectedColorbarIndex:-1,colorbars:[]}}onAdd(e){return this._map=e,this._container=this._createContainer(),this._setupZoomHandler(),this._state.collapsed||this._showPanel(),this._container}onRemove(){this._handleZoom&&this._map&&this._map.off("zoom",this._handleZoom),this._handleResize&&(window.removeEventListener("resize",this._handleResize),this._handleResize=void 0),this._removeAllColorbars(),this._container?.remove(),this._container=void 0,this._map=void 0}getDefaultPosition(){return this._options.position}on(e,t){return this._eventHandlers.has(e)||this._eventHandlers.set(e,new Set),this._eventHandlers.get(e).add(t),this}off(e,t){return this._eventHandlers.get(e)?.delete(t),this}_emit(e){const t=this._eventHandlers.get(e);if(t){const n={type:e,state:{...this._state}};t.forEach(i=>i(n))}}expand(){this._state.collapsed&&(this._state.collapsed=!1,this._showPanel(),this._emit("expand"))}collapse(){this._state.collapsed||(this._state.collapsed=!0,this._hidePanel(),this._emit("collapse"))}show(){return this._state.visible=!0,this._container&&this._zoomVisible&&(this._container.style.display=""),this._emit("show"),this}hide(){return this._state.visible=!1,this._container&&(this._container.style.display="none"),this._emit("hide"),this}getState(){return{...this._state,colorbars:this._colorbarEntries.map(e=>({...e}))}}setState(e){this._map&&this._colorbars.forEach(s=>{this._map.removeControl(s)});const t=(e.colorbars??[]).map(s=>({...s}));this._colorbars=[],this._colorbarEntries=t,this._map&&t.forEach(s=>{const r=this._createColorbar(s);this._map.addControl(r,s.colorbarPosition),this._colorbars.push(r)});const n=typeof e.selectedColorbarIndex=="number"&&e.selectedColorbarIndex>=0&&e.selectedColorbarIndex<t.length?e.selectedColorbarIndex:t.length>0?t.length-1:-1,i=n>=0?t[n]:{mode:e.mode??this._state.mode,colormap:e.colormap??this._state.colormap,customColors:e.customColors??this._state.customColors,vmin:e.vmin??this._state.vmin,vmax:e.vmax??this._state.vmax,label:e.label??this._state.label,units:e.units??this._state.units,orientation:e.orientation??this._state.orientation,colorbarPosition:e.colorbarPosition??this._state.colorbarPosition};return this._state={...this._state,...i,visible:e.visible??this._state.visible,collapsed:e.collapsed??this._state.collapsed,hasColorbar:t.length>0,selectedColorbarIndex:n,colorbars:t.map(s=>({...s}))},this._colorbar=n>=0?this._colorbars[n]:void 0,this._applyEntryToForm(i),this._state.collapsed?this._hidePanel():this._showPanel(),this._container&&(this._container.style.display=this._state.visible&&this._zoomVisible?"":"none"),this._updateButtonStates(),this._emit("colorbarupdate"),this}_createContainer(){const e=document.createElement("div");return e.className=`maplibregl-ctrl maplibre-gl-colorbar-gui-control ${this._options.className}`,this._state.visible||(e.style.display="none"),this._button=document.createElement("button"),this._button.type="button",this._button.className="colorbar-gui-button",this._button.title="Colorbar",this._button.innerHTML=ZU,this._button.addEventListener("click",()=>this._togglePanel()),e.appendChild(this._button),e}_createPanel(){const e=document.createElement("div");e.className=`colorbar-gui-panel ${this._options.position.includes("left")?"right":"left"}`,e.style.width=`${this._options.panelWidth}px`,e.style.overflowY="auto",e.style.background=this._options.backgroundColor,e.style.borderRadius=`${this._options.borderRadius}px`,e.style.fontSize=`${this._options.fontSize}px`,e.style.color=this._options.fontColor;const t=document.createElement("div");t.className="colorbar-gui-header",t.innerHTML=`
254
254
  <span>Colorbar</span>
255
255
  <button type="button" class="colorbar-gui-close" title="Close">${JU}</button>
256
256
  `,t.querySelector(".colorbar-gui-close")?.addEventListener("click",()=>this._togglePanel()),e.appendChild(t);const n=document.createElement("div");n.className="colorbar-gui-content";const i=this._createField("Colorbar");this._colorbarSelect=document.createElement("select"),this._colorbarSelect.className="colorbar-gui-select",this._colorbarSelect.addEventListener("change",()=>{this._selectColorbar(parseInt(this._colorbarSelect.value,10))}),i.appendChild(this._colorbarSelect),n.appendChild(i),this._renderColorbarSelect();const s=this._createField("Color Source"),r=document.createElement("div");r.className="colorbar-gui-mode-row";const a=document.createElement("label");a.className="colorbar-gui-radio-label",this._modeNamedRadio=document.createElement("input"),this._modeNamedRadio.type="radio",this._modeNamedRadio.name="colorbar-mode",this._modeNamedRadio.checked=this._state.mode==="named",this._modeNamedRadio.addEventListener("change",()=>{this._modeNamedRadio.checked&&this._setMode("named")}),a.appendChild(this._modeNamedRadio),a.appendChild(document.createTextNode(" Named Colormap")),r.appendChild(a);const o=document.createElement("label");o.className="colorbar-gui-radio-label",this._modeCustomRadio=document.createElement("input"),this._modeCustomRadio.type="radio",this._modeCustomRadio.name="colorbar-mode",this._modeCustomRadio.checked=this._state.mode==="custom",this._modeCustomRadio.addEventListener("change",()=>{this._modeCustomRadio.checked&&this._setMode("custom")}),o.appendChild(this._modeCustomRadio),o.appendChild(document.createTextNode(" Custom Colors")),r.appendChild(o),s.appendChild(r),n.appendChild(s),this._namedSection=document.createElement("div");const l=this._createField("Colormap");this._colormapSelect=document.createElement("select"),this._colormapSelect.className="colorbar-gui-select",dA().forEach(w=>{const S=document.createElement("option");S.value=w,S.textContent=w,S.selected=w===this._state.colormap,this._colormapSelect.appendChild(S)}),this._colormapSelect.addEventListener("change",()=>{this._state.colormap=this._colormapSelect.value,this._updatePreview()}),l.appendChild(this._colormapSelect),this._namedSection.appendChild(l),n.appendChild(this._namedSection),this._customSection=document.createElement("div");const c=this._createField("Colors (comma-separated)");this._customColorsTextarea=document.createElement("textarea"),this._customColorsTextarea.className="colorbar-gui-textarea",this._customColorsTextarea.rows=3,this._customColorsTextarea.value=this._state.customColors,this._customColorsTextarea.placeholder=`e.g., red, #00ff00, blue, yellow
@@ -269,7 +269,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
269
269
  `}[_]}}])})(),me=(function(){function _(){s(this,_)}return o(_,null,[{key:"log10",value:function(u){var p=Math.log(u);return W.isInfinite(p)||W.isNaN(p)?p:p/_.LOG_10}},{key:"min",value:function(u,p,g,E){var B=u;return p<B&&(B=p),g<B&&(B=g),E<B&&(B=E),B}},{key:"clamp",value:function(){if(typeof arguments[2]=="number"&&typeof arguments[0]=="number"&&typeof arguments[1]=="number"){var u=arguments[0],p=arguments[1],g=arguments[2];return u<p?p:u>g?g:u}if(Number.isInteger(arguments[2])&&Number.isInteger(arguments[0])&&Number.isInteger(arguments[1])){var E=arguments[0],B=arguments[1],F=arguments[2];return E<B?B:E>F?F:E}}},{key:"wrap",value:function(u,p){return u<0?p- -u%p:u%p}},{key:"max",value:function(){if(arguments.length===3){var u=arguments[1],p=arguments[2],g=arguments[0];return u>g&&(g=u),p>g&&(g=p),g}if(arguments.length===4){var E=arguments[1],B=arguments[2],F=arguments[3],G=arguments[0];return E>G&&(G=E),B>G&&(G=B),F>G&&(G=F),G}}},{key:"average",value:function(u,p){return(u+p)/2}}])})();me.LOG_10=Math.log(10);var qe=(function(){function _(){s(this,_)}return o(_,null,[{key:"segmentToSegment",value:function(u,p,g,E){if(u.equals(p))return _.pointToSegment(u,g,E);if(g.equals(E))return _.pointToSegment(E,u,p);var B=!1;if(fe.intersects(u,p,g,E)){var F=(p.x-u.x)*(E.y-g.y)-(p.y-u.y)*(E.x-g.x);if(F===0)B=!0;else{var G=(u.y-g.y)*(E.x-g.x)-(u.x-g.x)*(E.y-g.y),Y=((u.y-g.y)*(p.x-u.x)-(u.x-g.x)*(p.y-u.y))/F,ae=G/F;(ae<0||ae>1||Y<0||Y>1)&&(B=!0)}}else B=!0;return B?me.min(_.pointToSegment(u,g,E),_.pointToSegment(p,g,E),_.pointToSegment(g,u,p),_.pointToSegment(E,u,p)):0}},{key:"pointToSegment",value:function(u,p,g){if(p.x===g.x&&p.y===g.y)return u.distance(p);var E=(g.x-p.x)*(g.x-p.x)+(g.y-p.y)*(g.y-p.y),B=((u.x-p.x)*(g.x-p.x)+(u.y-p.y)*(g.y-p.y))/E;if(B<=0)return u.distance(p);if(B>=1)return u.distance(g);var F=((p.y-u.y)*(g.x-p.x)-(p.x-u.x)*(g.y-p.y))/E;return Math.abs(F)*Math.sqrt(E)}},{key:"pointToLinePerpendicular",value:function(u,p,g){var E=(g.x-p.x)*(g.x-p.x)+(g.y-p.y)*(g.y-p.y),B=((p.y-u.y)*(g.x-p.x)-(p.x-u.x)*(g.y-p.y))/E;return Math.abs(B)*Math.sqrt(E)}},{key:"pointToSegmentString",value:function(u,p){if(p.length===0)throw new R("Line array must contain at least one vertex");for(var g=u.distance(p[0]),E=0;E<p.length-1;E++){var B=_.pointToSegment(u,p[E],p[E+1]);B<g&&(g=B)}return g}}])})(),tt=(function(){return o((function _(){s(this,_)}),[{key:"create",value:function(){if(arguments.length===1)arguments[0]instanceof Array||X(arguments[0],_e);else if(arguments.length!==2){if(arguments.length===3){var _=arguments[0],u=arguments[1];return this.create(_,u)}}}}])})(),_t=(function(){return o((function _(){s(this,_)}),[{key:"filter",value:function(_){}}])})(),je=(function(){return o((function _(){s(this,_)}),null,[{key:"ofLine",value:function(_){var u=_.size();if(u<=1)return 0;var p=0,g=new ie;_.getCoordinate(0,g);for(var E=g.x,B=g.y,F=1;F<u;F++){_.getCoordinate(F,g);var G=g.x,Y=g.y,ae=G-E,xe=Y-B;p+=Math.sqrt(ae*ae+xe*xe),E=G,B=Y}return p}}])})(),Ue=o((function _(){s(this,_)})),At=(function(){function _(){s(this,_)}return o(_,null,[{key:"copyCoord",value:function(u,p,g,E){for(var B=Math.min(u.getDimension(),g.getDimension()),F=0;F<B;F++)g.setOrdinate(E,F,u.getOrdinate(p,F))}},{key:"isRing",value:function(u){var p=u.size();return p===0||!(p<=3)&&u.getOrdinate(0,_e.X)===u.getOrdinate(p-1,_e.X)&&u.getOrdinate(0,_e.Y)===u.getOrdinate(p-1,_e.Y)}},{key:"scroll",value:function(){if(arguments.length===2){if(X(arguments[0],_e)&&Number.isInteger(arguments[1])){var u=arguments[0],p=arguments[1];_.scroll(u,p,_.isRing(u))}else if(X(arguments[0],_e)&&arguments[1]instanceof ie){var g=arguments[0],E=arguments[1],B=_.indexOf(E,g);if(B<=0)return null;_.scroll(g,B)}}else if(arguments.length===3){var F=arguments[0],G=arguments[1],Y=arguments[2];if(G<=0)return null;for(var ae=F.copy(),xe=Y?F.size()-1:F.size(),Ie=0;Ie<xe;Ie++)for(var Ge=0;Ge<F.getDimension();Ge++)F.setOrdinate(Ie,Ge,ae.getOrdinate((G+Ie)%xe,Ge));if(Y)for(var ut=0;ut<F.getDimension();ut++)F.setOrdinate(xe,ut,F.getOrdinate(0,ut))}}},{key:"isEqual",value:function(u,p){var g=u.size();if(g!==p.size())return!1;for(var E=Math.min(u.getDimension(),p.getDimension()),B=0;B<g;B++)for(var F=0;F<E;F++){var G=u.getOrdinate(B,F),Y=p.getOrdinate(B,F);if(u.getOrdinate(B,F)!==p.getOrdinate(B,F)&&(!W.isNaN(G)||!W.isNaN(Y)))return!1}return!0}},{key:"minCoordinateIndex",value:function(){if(arguments.length===1){var u=arguments[0];return _.minCoordinateIndex(u,0,u.size()-1)}if(arguments.length===3){for(var p=arguments[0],g=arguments[2],E=-1,B=null,F=arguments[1];F<=g;F++){var G=p.getCoordinate(F);(B===null||B.compareTo(G)>0)&&(B=G,E=F)}return E}}},{key:"extend",value:function(u,p,g){var E=u.create(g,p.getDimension()),B=p.size();if(_.copy(p,0,E,0,B),B>0)for(var F=B;F<g;F++)_.copy(p,B-1,E,F,1);return E}},{key:"reverse",value:function(u){for(var p=u.size()-1,g=Math.trunc(p/2),E=0;E<=g;E++)_.swap(u,E,p-E)}},{key:"swap",value:function(u,p,g){if(p===g)return null;for(var E=0;E<u.getDimension();E++){var B=u.getOrdinate(p,E);u.setOrdinate(p,E,u.getOrdinate(g,E)),u.setOrdinate(g,E,B)}}},{key:"copy",value:function(u,p,g,E,B){for(var F=0;F<B;F++)_.copyCoord(u,p+F,g,E+F)}},{key:"ensureValidRing",value:function(u,p){var g=p.size();return g===0?p:g<=3?_.createClosedRing(u,p,4):p.getOrdinate(0,_e.X)===p.getOrdinate(g-1,_e.X)&&p.getOrdinate(0,_e.Y)===p.getOrdinate(g-1,_e.Y)?p:_.createClosedRing(u,p,g+1)}},{key:"indexOf",value:function(u,p){for(var g=0;g<p.size();g++)if(u.x===p.getOrdinate(g,_e.X)&&u.y===p.getOrdinate(g,_e.Y))return g;return-1}},{key:"createClosedRing",value:function(u,p,g){var E=u.create(g,p.getDimension()),B=p.size();_.copy(p,0,E,0,B);for(var F=B;F<g;F++)_.copy(p,0,E,F,1);return E}},{key:"minCoordinate",value:function(u){for(var p=null,g=0;g<u.size();g++){var E=u.getCoordinate(g);(p===null||p.compareTo(E)>0)&&(p=E)}return p}}])})(),Ne=(function(){function _(){s(this,_)}return o(_,null,[{key:"toDimensionSymbol",value:function(u){switch(u){case _.FALSE:return _.SYM_FALSE;case _.TRUE:return _.SYM_TRUE;case _.DONTCARE:return _.SYM_DONTCARE;case _.P:return _.SYM_P;case _.L:return _.SYM_L;case _.A:return _.SYM_A}throw new R("Unknown dimension value: "+u)}},{key:"toDimensionValue",value:function(u){switch(Ce.toUpperCase(u)){case _.SYM_FALSE:return _.FALSE;case _.SYM_TRUE:return _.TRUE;case _.SYM_DONTCARE:return _.DONTCARE;case _.SYM_P:return _.P;case _.SYM_L:return _.L;case _.SYM_A:return _.A}throw new R("Unknown dimension symbol: "+u)}}])})();Ne.P=0,Ne.L=1,Ne.A=2,Ne.FALSE=-1,Ne.TRUE=-2,Ne.DONTCARE=-3,Ne.SYM_FALSE="F",Ne.SYM_TRUE="T",Ne.SYM_DONTCARE="*",Ne.SYM_P="0",Ne.SYM_L="1",Ne.SYM_A="2";var Qn=(function(){return o((function _(){s(this,_)}),[{key:"filter",value:function(_){}}])})(),en=(function(){return o((function _(){s(this,_)}),[{key:"filter",value:function(_,u){}},{key:"isDone",value:function(){}},{key:"isGeometryChanged",value:function(){}}])})(),zi=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,[{key:"computeEnvelopeInternal",value:function(){return this.isEmpty()?new fe:this._points.expandEnvelope(new fe)}},{key:"isRing",value:function(){return this.isClosed()&&this.isSimple()}},{key:"getCoordinates",value:function(){return this._points.toCoordinateArray()}},{key:"copyInternal",value:function(){return new u(this._points.copy(),this._factory)}},{key:"equalsExact",value:function(){if(arguments.length===2&&typeof arguments[1]=="number"&&arguments[0]instanceof ye){var p=arguments[0],g=arguments[1];if(!this.isEquivalentClass(p))return!1;var E=p;if(this._points.size()!==E._points.size())return!1;for(var B=0;B<this._points.size();B++)if(!this.equal(this._points.getCoordinate(B),E._points.getCoordinate(B),g))return!1;return!0}return A(u,"equalsExact",this,1).apply(this,arguments)}},{key:"normalize",value:function(){for(var p=0;p<Math.trunc(this._points.size()/2);p++){var g=this._points.size()-1-p;if(!this._points.getCoordinate(p).equals(this._points.getCoordinate(g))){if(this._points.getCoordinate(p).compareTo(this._points.getCoordinate(g))>0){var E=this._points.copy();At.reverse(E),this._points=E}return null}}}},{key:"getCoordinate",value:function(){return this.isEmpty()?null:this._points.getCoordinate(0)}},{key:"getBoundaryDimension",value:function(){return this.isClosed()?Ne.FALSE:0}},{key:"isClosed",value:function(){return!this.isEmpty()&&this.getCoordinateN(0).equals2D(this.getCoordinateN(this.getNumPoints()-1))}},{key:"reverseInternal",value:function(){var p=this._points.copy();return At.reverse(p),this.getFactory().createLineString(p)}},{key:"getEndPoint",value:function(){return this.isEmpty()?null:this.getPointN(this.getNumPoints()-1)}},{key:"getTypeCode",value:function(){return ye.TYPECODE_LINESTRING}},{key:"getDimension",value:function(){return 1}},{key:"getLength",value:function(){return je.ofLine(this._points)}},{key:"getNumPoints",value:function(){return this._points.size()}},{key:"compareToSameClass",value:function(){if(arguments.length===1){for(var p=arguments[0],g=0,E=0;g<this._points.size()&&E<p._points.size();){var B=this._points.getCoordinate(g).compareTo(p._points.getCoordinate(E));if(B!==0)return B;g++,E++}return g<this._points.size()?1:E<p._points.size()?-1:0}if(arguments.length===2){var F=arguments[0];return arguments[1].compare(this._points,F._points)}}},{key:"apply",value:function(){if(X(arguments[0],_t))for(var p=arguments[0],g=0;g<this._points.size();g++)p.filter(this._points.getCoordinate(g));else if(X(arguments[0],en)){var E=arguments[0];if(this._points.size()===0)return null;for(var B=0;B<this._points.size()&&(E.filter(this._points,B),!E.isDone());B++);E.isGeometryChanged()&&this.geometryChanged()}else X(arguments[0],Qn)?arguments[0].filter(this):X(arguments[0],k)&&arguments[0].filter(this)}},{key:"getBoundary",value:function(){throw new Qe}},{key:"isEquivalentClass",value:function(p){return p instanceof u}},{key:"getCoordinateN",value:function(p){return this._points.getCoordinate(p)}},{key:"getGeometryType",value:function(){return ye.TYPENAME_LINESTRING}},{key:"getCoordinateSequence",value:function(){return this._points}},{key:"isEmpty",value:function(){return this._points.size()===0}},{key:"init",value:function(p){if(p===null&&(p=this.getFactory().getCoordinateSequenceFactory().create([])),p.size()===1)throw new R("Invalid number of points in LineString (found "+p.size()+" - must be 0 or >= 2)");this._points=p}},{key:"isCoordinate",value:function(p){for(var g=0;g<this._points.size();g++)if(this._points.getCoordinate(g).equals(p))return!0;return!1}},{key:"getStartPoint",value:function(){return this.isEmpty()?null:this.getPointN(0)}},{key:"getPointN",value:function(p){return this.getFactory().createPoint(this._points.getCoordinate(p))}},{key:"interfaces_",get:function(){return[Ue]}}],[{key:"constructor_",value:function(){if(this._points=null,arguments.length!==0){if(arguments.length===2){var p=arguments[0],g=arguments[1];ye.constructor_.call(this,g),this.init(p)}}}}])})(ye),Ms=o((function _(){s(this,_)})),Wo=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,[{key:"computeEnvelopeInternal",value:function(){if(this.isEmpty())return new fe;var p=new fe;return p.expandToInclude(this._coordinates.getX(0),this._coordinates.getY(0)),p}},{key:"getCoordinates",value:function(){return this.isEmpty()?[]:[this.getCoordinate()]}},{key:"copyInternal",value:function(){return new u(this._coordinates.copy(),this._factory)}},{key:"equalsExact",value:function(){if(arguments.length===2&&typeof arguments[1]=="number"&&arguments[0]instanceof ye){var p=arguments[0],g=arguments[1];return!!this.isEquivalentClass(p)&&(!(!this.isEmpty()||!p.isEmpty())||this.isEmpty()===p.isEmpty()&&this.equal(p.getCoordinate(),this.getCoordinate(),g))}return A(u,"equalsExact",this,1).apply(this,arguments)}},{key:"normalize",value:function(){}},{key:"getCoordinate",value:function(){return this._coordinates.size()!==0?this._coordinates.getCoordinate(0):null}},{key:"getBoundaryDimension",value:function(){return Ne.FALSE}},{key:"reverseInternal",value:function(){return this.getFactory().createPoint(this._coordinates.copy())}},{key:"getTypeCode",value:function(){return ye.TYPECODE_POINT}},{key:"getDimension",value:function(){return 0}},{key:"getNumPoints",value:function(){return this.isEmpty()?0:1}},{key:"getX",value:function(){if(this.getCoordinate()===null)throw new IllegalStateException("getX called on empty Point");return this.getCoordinate().x}},{key:"compareToSameClass",value:function(){if(arguments.length===1){var p=arguments[0];return this.getCoordinate().compareTo(p.getCoordinate())}if(arguments.length===2){var g=arguments[0];return arguments[1].compare(this._coordinates,g._coordinates)}}},{key:"apply",value:function(){if(X(arguments[0],_t)){var p=arguments[0];if(this.isEmpty())return null;p.filter(this.getCoordinate())}else if(X(arguments[0],en)){var g=arguments[0];if(this.isEmpty())return null;g.filter(this._coordinates,0),g.isGeometryChanged()&&this.geometryChanged()}else X(arguments[0],Qn)?arguments[0].filter(this):X(arguments[0],k)&&arguments[0].filter(this)}},{key:"getBoundary",value:function(){return this.getFactory().createGeometryCollection()}},{key:"getGeometryType",value:function(){return ye.TYPENAME_POINT}},{key:"getCoordinateSequence",value:function(){return this._coordinates}},{key:"getY",value:function(){if(this.getCoordinate()===null)throw new IllegalStateException("getY called on empty Point");return this.getCoordinate().y}},{key:"isEmpty",value:function(){return this._coordinates.size()===0}},{key:"init",value:function(p){p===null&&(p=this.getFactory().getCoordinateSequenceFactory().create([])),re.isTrue(p.size()<=1),this._coordinates=p}},{key:"isSimple",value:function(){return!0}},{key:"interfaces_",get:function(){return[Ms]}}],[{key:"constructor_",value:function(){this._coordinates=null;var p=arguments[0],g=arguments[1];ye.constructor_.call(this,g),this.init(p)}}])})(ye),Cr=(function(){function _(){s(this,_)}return o(_,null,[{key:"ofRing",value:function(){if(arguments[0]instanceof Array){var u=arguments[0];return Math.abs(_.ofRingSigned(u))}if(X(arguments[0],_e)){var p=arguments[0];return Math.abs(_.ofRingSigned(p))}}},{key:"ofRingSigned",value:function(){if(arguments[0]instanceof Array){var u=arguments[0];if(u.length<3)return 0;for(var p=0,g=u[0].x,E=1;E<u.length-1;E++){var B=u[E].x-g,F=u[E+1].y;p+=B*(u[E-1].y-F)}return p/2}if(X(arguments[0],_e)){var G=arguments[0],Y=G.size();if(Y<3)return 0;var ae=new ie,xe=new ie,Ie=new ie;G.getCoordinate(0,xe),G.getCoordinate(1,Ie);var Ge=xe.x;Ie.x-=Ge;for(var ut=0,Rt=1;Rt<Y-1;Rt++)ae.y=xe.y,xe.x=Ie.x,xe.y=Ie.y,G.getCoordinate(Rt+1,Ie),Ie.x-=Ge,ut+=xe.x*(ae.y-Ie.y);return ut/2}}}])})(),le=(function(){return o((function _(){s(this,_)}),null,[{key:"sort",value:function(){var _=arguments,u=arguments[0];if(arguments.length===1)u.sort((function(Ge,ut){return Ge.compareTo(ut)}));else if(arguments.length===2)u.sort((function(Ge,ut){return _[1].compare(Ge,ut)}));else if(arguments.length===3){var p=u.slice(arguments[1],arguments[2]);p.sort();var g=u.slice(0,arguments[1]).concat(p,u.slice(arguments[2],u.length));u.splice(0,u.length);var E,B=l(g);try{for(B.s();!(E=B.n()).done;){var F=E.value;u.push(F)}}catch(Ge){B.e(Ge)}finally{B.f()}}else if(arguments.length===4){var G=u.slice(arguments[1],arguments[2]);G.sort((function(Ge,ut){return _[3].compare(Ge,ut)}));var Y=u.slice(0,arguments[1]).concat(G,u.slice(arguments[2],u.length));u.splice(0,u.length);var ae,xe=l(Y);try{for(xe.s();!(ae=xe.n()).done;){var Ie=ae.value;u.push(Ie)}}catch(Ge){xe.e(Ge)}finally{xe.f()}}}},{key:"asList",value:function(_){var u,p=new Pe,g=l(_);try{for(g.s();!(u=g.n()).done;){var E=u.value;p.add(E)}}catch(B){g.e(B)}finally{g.f()}return p}},{key:"copyOf",value:function(_,u){return _.slice(0,u)}}])})(),Te=o((function _(){s(this,_)})),Fe=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,[{key:"computeEnvelopeInternal",value:function(){return this._shell.getEnvelopeInternal()}},{key:"getCoordinates",value:function(){if(this.isEmpty())return[];for(var p=new Array(this.getNumPoints()).fill(null),g=-1,E=this._shell.getCoordinates(),B=0;B<E.length;B++)p[++g]=E[B];for(var F=0;F<this._holes.length;F++)for(var G=this._holes[F].getCoordinates(),Y=0;Y<G.length;Y++)p[++g]=G[Y];return p}},{key:"getArea",value:function(){var p=0;p+=Cr.ofRing(this._shell.getCoordinateSequence());for(var g=0;g<this._holes.length;g++)p-=Cr.ofRing(this._holes[g].getCoordinateSequence());return p}},{key:"copyInternal",value:function(){for(var p=this._shell.copy(),g=new Array(this._holes.length).fill(null),E=0;E<this._holes.length;E++)g[E]=this._holes[E].copy();return new u(p,g,this._factory)}},{key:"isRectangle",value:function(){if(this.getNumInteriorRing()!==0||this._shell===null||this._shell.getNumPoints()!==5)return!1;for(var p=this._shell.getCoordinateSequence(),g=this.getEnvelopeInternal(),E=0;E<5;E++){var B=p.getX(E);if(B!==g.getMinX()&&B!==g.getMaxX())return!1;var F=p.getY(E);if(F!==g.getMinY()&&F!==g.getMaxY())return!1}for(var G=p.getX(0),Y=p.getY(0),ae=1;ae<=4;ae++){var xe=p.getX(ae),Ie=p.getY(ae);if(xe!==G==(Ie!==Y))return!1;G=xe,Y=Ie}return!0}},{key:"equalsExact",value:function(){if(arguments.length===2&&typeof arguments[1]=="number"&&arguments[0]instanceof ye){var p=arguments[0],g=arguments[1];if(!this.isEquivalentClass(p))return!1;var E=p,B=this._shell,F=E._shell;if(!B.equalsExact(F,g)||this._holes.length!==E._holes.length)return!1;for(var G=0;G<this._holes.length;G++)if(!this._holes[G].equalsExact(E._holes[G],g))return!1;return!0}return A(u,"equalsExact",this,1).apply(this,arguments)}},{key:"normalize",value:function(){if(arguments.length===0){this._shell=this.normalized(this._shell,!0);for(var p=0;p<this._holes.length;p++)this._holes[p]=this.normalized(this._holes[p],!1);le.sort(this._holes)}else if(arguments.length===2){var g=arguments[0],E=arguments[1];if(g.isEmpty())return null;var B=g.getCoordinateSequence(),F=At.minCoordinateIndex(B,0,B.size()-2);At.scroll(B,F,!0),be.isCCW(B)===E&&At.reverse(B)}}},{key:"getCoordinate",value:function(){return this._shell.getCoordinate()}},{key:"getNumInteriorRing",value:function(){return this._holes.length}},{key:"getBoundaryDimension",value:function(){return 1}},{key:"reverseInternal",value:function(){for(var p=this.getExteriorRing().reverse(),g=new Array(this.getNumInteriorRing()).fill(null),E=0;E<g.length;E++)g[E]=this.getInteriorRingN(E).reverse();return this.getFactory().createPolygon(p,g)}},{key:"getTypeCode",value:function(){return ye.TYPECODE_POLYGON}},{key:"getDimension",value:function(){return 2}},{key:"getLength",value:function(){var p=0;p+=this._shell.getLength();for(var g=0;g<this._holes.length;g++)p+=this._holes[g].getLength();return p}},{key:"getNumPoints",value:function(){for(var p=this._shell.getNumPoints(),g=0;g<this._holes.length;g++)p+=this._holes[g].getNumPoints();return p}},{key:"convexHull",value:function(){return this.getExteriorRing().convexHull()}},{key:"normalized",value:function(p,g){var E=p.copy();return this.normalize(E,g),E}},{key:"compareToSameClass",value:function(){if(arguments.length===1){var p=arguments[0],g=this._shell,E=p._shell;return g.compareToSameClass(E)}if(arguments.length===2){var B=arguments[1],F=arguments[0],G=this._shell,Y=F._shell,ae=G.compareToSameClass(Y,B);if(ae!==0)return ae;for(var xe=this.getNumInteriorRing(),Ie=F.getNumInteriorRing(),Ge=0;Ge<xe&&Ge<Ie;){var ut=this.getInteriorRingN(Ge),Rt=F.getInteriorRingN(Ge),Ft=ut.compareToSameClass(Rt,B);if(Ft!==0)return Ft;Ge++}return Ge<xe?1:Ge<Ie?-1:0}}},{key:"apply",value:function(){if(X(arguments[0],_t)){var p=arguments[0];this._shell.apply(p);for(var g=0;g<this._holes.length;g++)this._holes[g].apply(p)}else if(X(arguments[0],en)){var E=arguments[0];if(this._shell.apply(E),!E.isDone())for(var B=0;B<this._holes.length&&(this._holes[B].apply(E),!E.isDone());B++);E.isGeometryChanged()&&this.geometryChanged()}else if(X(arguments[0],Qn))arguments[0].filter(this);else if(X(arguments[0],k)){var F=arguments[0];F.filter(this),this._shell.apply(F);for(var G=0;G<this._holes.length;G++)this._holes[G].apply(F)}}},{key:"getBoundary",value:function(){if(this.isEmpty())return this.getFactory().createMultiLineString();var p=new Array(this._holes.length+1).fill(null);p[0]=this._shell;for(var g=0;g<this._holes.length;g++)p[g+1]=this._holes[g];return p.length<=1?this.getFactory().createLinearRing(p[0].getCoordinateSequence()):this.getFactory().createMultiLineString(p)}},{key:"getGeometryType",value:function(){return ye.TYPENAME_POLYGON}},{key:"getExteriorRing",value:function(){return this._shell}},{key:"isEmpty",value:function(){return this._shell.isEmpty()}},{key:"getInteriorRingN",value:function(p){return this._holes[p]}},{key:"interfaces_",get:function(){return[Te]}}],[{key:"constructor_",value:function(){this._shell=null,this._holes=null;var p=arguments[0],g=arguments[1],E=arguments[2];if(ye.constructor_.call(this,E),p===null&&(p=this.getFactory().createLinearRing()),g===null&&(g=[]),ye.hasNullElements(g))throw new R("holes must not contain null elements");if(p.isEmpty()&&ye.hasNonEmptyElements(g))throw new R("shell is empty but holes are not");this._shell=p,this._holes=g}}])})(ye),ke=(function(_){function u(p){var g;return s(this,u),(g=i(this,u)).array=[],p instanceof Se&&g.addAll(p),g}return d(u,_),o(u,[{key:"contains",value:function(p){var g,E=l(this.array);try{for(E.s();!(g=E.n()).done;)if(g.value.compareTo(p)===0)return!0}catch(B){E.e(B)}finally{E.f()}return!1}},{key:"add",value:function(p){if(this.contains(p))return!1;for(var g=0,E=this.array.length;g<E;g++)if(this.array[g].compareTo(p)===1)return!!this.array.splice(g,0,p);return this.array.push(p),!0}},{key:"addAll",value:function(p){var g,E=l(p);try{for(E.s();!(g=E.n()).done;){var B=g.value;this.add(B)}}catch(F){E.e(F)}finally{E.f()}return!0}},{key:"remove",value:function(){throw new Qe}},{key:"size",value:function(){return this.array.length}},{key:"isEmpty",value:function(){return this.array.length===0}},{key:"toArray",value:function(){return this.array.slice()}},{key:"iterator",value:function(){return new ze(this.array)}}])})((function(_){function u(){return s(this,u),i(this,u,arguments)}return d(u,_),o(u)})(Le)),ze=(function(){return o((function _(u){s(this,_),this.array=u,this.position=0}),[{key:"next",value:function(){if(this.position===this.array.length)throw new Z;return this.array[this.position++]}},{key:"hasNext",value:function(){return this.position<this.array.length}},{key:"remove",value:function(){throw new Qe}}])})(),vt=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,[{key:"computeEnvelopeInternal",value:function(){for(var p=new fe,g=0;g<this._geometries.length;g++)p.expandToInclude(this._geometries[g].getEnvelopeInternal());return p}},{key:"getGeometryN",value:function(p){return this._geometries[p]}},{key:"getCoordinates",value:function(){for(var p=new Array(this.getNumPoints()).fill(null),g=-1,E=0;E<this._geometries.length;E++)for(var B=this._geometries[E].getCoordinates(),F=0;F<B.length;F++)p[++g]=B[F];return p}},{key:"getArea",value:function(){for(var p=0,g=0;g<this._geometries.length;g++)p+=this._geometries[g].getArea();return p}},{key:"copyInternal",value:function(){for(var p=new Array(this._geometries.length).fill(null),g=0;g<p.length;g++)p[g]=this._geometries[g].copy();return new u(p,this._factory)}},{key:"equalsExact",value:function(){if(arguments.length===2&&typeof arguments[1]=="number"&&arguments[0]instanceof ye){var p=arguments[0],g=arguments[1];if(!this.isEquivalentClass(p))return!1;var E=p;if(this._geometries.length!==E._geometries.length)return!1;for(var B=0;B<this._geometries.length;B++)if(!this._geometries[B].equalsExact(E._geometries[B],g))return!1;return!0}return A(u,"equalsExact",this,1).apply(this,arguments)}},{key:"normalize",value:function(){for(var p=0;p<this._geometries.length;p++)this._geometries[p].normalize();le.sort(this._geometries)}},{key:"getCoordinate",value:function(){return this.isEmpty()?null:this._geometries[0].getCoordinate()}},{key:"getBoundaryDimension",value:function(){for(var p=Ne.FALSE,g=0;g<this._geometries.length;g++)p=Math.max(p,this._geometries[g].getBoundaryDimension());return p}},{key:"reverseInternal",value:function(){for(var p=this._geometries.length,g=new Pe(p),E=0;E<p;E++)g.add(this._geometries[E].reverse());return this.getFactory().buildGeometry(g)}},{key:"getTypeCode",value:function(){return ye.TYPECODE_GEOMETRYCOLLECTION}},{key:"getDimension",value:function(){for(var p=Ne.FALSE,g=0;g<this._geometries.length;g++)p=Math.max(p,this._geometries[g].getDimension());return p}},{key:"getLength",value:function(){for(var p=0,g=0;g<this._geometries.length;g++)p+=this._geometries[g].getLength();return p}},{key:"getNumPoints",value:function(){for(var p=0,g=0;g<this._geometries.length;g++)p+=this._geometries[g].getNumPoints();return p}},{key:"getNumGeometries",value:function(){return this._geometries.length}},{key:"compareToSameClass",value:function(){if(arguments.length===1){var p=arguments[0],g=new ke(le.asList(this._geometries)),E=new ke(le.asList(p._geometries));return this.compare(g,E)}if(arguments.length===2){for(var B=arguments[1],F=arguments[0],G=this.getNumGeometries(),Y=F.getNumGeometries(),ae=0;ae<G&&ae<Y;){var xe=this.getGeometryN(ae),Ie=F.getGeometryN(ae),Ge=xe.compareToSameClass(Ie,B);if(Ge!==0)return Ge;ae++}return ae<G?1:ae<Y?-1:0}}},{key:"apply",value:function(){if(X(arguments[0],_t))for(var p=arguments[0],g=0;g<this._geometries.length;g++)this._geometries[g].apply(p);else if(X(arguments[0],en)){var E=arguments[0];if(this._geometries.length===0)return null;for(var B=0;B<this._geometries.length&&(this._geometries[B].apply(E),!E.isDone());B++);E.isGeometryChanged()&&this.geometryChanged()}else if(X(arguments[0],Qn)){var F=arguments[0];F.filter(this);for(var G=0;G<this._geometries.length;G++)this._geometries[G].apply(F)}else if(X(arguments[0],k)){var Y=arguments[0];Y.filter(this);for(var ae=0;ae<this._geometries.length;ae++)this._geometries[ae].apply(Y)}}},{key:"getBoundary",value:function(){return ye.checkNotGeometryCollection(this),re.shouldNeverReachHere(),null}},{key:"getGeometryType",value:function(){return ye.TYPENAME_GEOMETRYCOLLECTION}},{key:"isEmpty",value:function(){for(var p=0;p<this._geometries.length;p++)if(!this._geometries[p].isEmpty())return!1;return!0}}],[{key:"constructor_",value:function(){if(this._geometries=null,arguments.length!==0){if(arguments.length===2){var p=arguments[0],g=arguments[1];if(ye.constructor_.call(this,g),p===null&&(p=[]),ye.hasNullElements(p))throw new R("geometries must not contain null elements");this._geometries=p}}}}])})(ye),wt=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,[{key:"copyInternal",value:function(){for(var p=new Array(this._geometries.length).fill(null),g=0;g<p.length;g++)p[g]=this._geometries[g].copy();return new u(p,this._factory)}},{key:"isValid",value:function(){return!0}},{key:"equalsExact",value:function(){if(arguments.length===2&&typeof arguments[1]=="number"&&arguments[0]instanceof ye){var p=arguments[0],g=arguments[1];return!!this.isEquivalentClass(p)&&A(u,"equalsExact",this,1).call(this,p,g)}return A(u,"equalsExact",this,1).apply(this,arguments)}},{key:"getCoordinate",value:function(){if(arguments.length===1&&Number.isInteger(arguments[0])){var p=arguments[0];return this._geometries[p].getCoordinate()}return A(u,"getCoordinate",this,1).apply(this,arguments)}},{key:"getBoundaryDimension",value:function(){return Ne.FALSE}},{key:"getTypeCode",value:function(){return ye.TYPECODE_MULTIPOINT}},{key:"getDimension",value:function(){return 0}},{key:"getBoundary",value:function(){return this.getFactory().createGeometryCollection()}},{key:"getGeometryType",value:function(){return ye.TYPENAME_MULTIPOINT}},{key:"interfaces_",get:function(){return[Ms]}}],[{key:"constructor_",value:function(){var p=arguments[0],g=arguments[1];vt.constructor_.call(this,p,g)}}])})(vt),zt=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,[{key:"copyInternal",value:function(){return new u(this._points.copy(),this._factory)}},{key:"getBoundaryDimension",value:function(){return Ne.FALSE}},{key:"isClosed",value:function(){return!!this.isEmpty()||A(u,"isClosed",this,1).call(this)}},{key:"reverseInternal",value:function(){var p=this._points.copy();return At.reverse(p),this.getFactory().createLinearRing(p)}},{key:"getTypeCode",value:function(){return ye.TYPECODE_LINEARRING}},{key:"validateConstruction",value:function(){if(!this.isEmpty()&&!A(u,"isClosed",this,1).call(this))throw new R("Points of LinearRing do not form a closed linestring");if(this.getCoordinateSequence().size()>=1&&this.getCoordinateSequence().size()<u.MINIMUM_VALID_SIZE)throw new R("Invalid number of points in LinearRing (found "+this.getCoordinateSequence().size()+" - must be 0 or >= 4)")}},{key:"getGeometryType",value:function(){return ye.TYPENAME_LINEARRING}}],[{key:"constructor_",value:function(){var p=arguments[0],g=arguments[1];zi.constructor_.call(this,p,g),this.validateConstruction()}}])})(zi);zt.MINIMUM_VALID_SIZE=4;var Qt=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,[{key:"setOrdinate",value:function(p,g){switch(p){case u.X:this.x=g;break;case u.Y:this.y=g;break;default:throw new R("Invalid ordinate index: "+p)}}},{key:"getZ",value:function(){return ie.NULL_ORDINATE}},{key:"getOrdinate",value:function(p){switch(p){case u.X:return this.x;case u.Y:return this.y}throw new R("Invalid ordinate index: "+p)}},{key:"setZ",value:function(p){throw new R("CoordinateXY dimension 2 does not support z-ordinate")}},{key:"copy",value:function(){return new u(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+")"}},{key:"setCoordinate",value:function(p){this.x=p.x,this.y=p.y,this.z=p.getZ()}}],[{key:"constructor_",value:function(){if(arguments.length===0)ie.constructor_.call(this);else if(arguments.length===1){if(arguments[0]instanceof u){var p=arguments[0];ie.constructor_.call(this,p.x,p.y)}else if(arguments[0]instanceof ie){var g=arguments[0];ie.constructor_.call(this,g.x,g.y)}}else if(arguments.length===2){var E=arguments[0],B=arguments[1];ie.constructor_.call(this,E,B,ie.NULL_ORDINATE)}}}])})(ie);Qt.X=0,Qt.Y=1,Qt.Z=-1,Qt.M=-1;var cn=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,[{key:"getM",value:function(){return this._m}},{key:"setOrdinate",value:function(p,g){switch(p){case u.X:this.x=g;break;case u.Y:this.y=g;break;case u.M:this._m=g;break;default:throw new R("Invalid ordinate index: "+p)}}},{key:"setM",value:function(p){this._m=p}},{key:"getZ",value:function(){return ie.NULL_ORDINATE}},{key:"getOrdinate",value:function(p){switch(p){case u.X:return this.x;case u.Y:return this.y;case u.M:return this._m}throw new R("Invalid ordinate index: "+p)}},{key:"setZ",value:function(p){throw new R("CoordinateXY dimension 2 does not support z-ordinate")}},{key:"copy",value:function(){return new u(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+" m="+this.getM()+")"}},{key:"setCoordinate",value:function(p){this.x=p.x,this.y=p.y,this.z=p.getZ(),this._m=p.getM()}}],[{key:"constructor_",value:function(){if(this._m=null,arguments.length===0)ie.constructor_.call(this),this._m=0;else if(arguments.length===1){if(arguments[0]instanceof u){var p=arguments[0];ie.constructor_.call(this,p.x,p.y),this._m=p._m}else if(arguments[0]instanceof ie){var g=arguments[0];ie.constructor_.call(this,g.x,g.y),this._m=this.getM()}}else if(arguments.length===3){var E=arguments[0],B=arguments[1],F=arguments[2];ie.constructor_.call(this,E,B,ie.NULL_ORDINATE),this._m=F}}}])})(ie);cn.X=0,cn.Y=1,cn.Z=-1,cn.M=2;var Xt=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,[{key:"getM",value:function(){return this._m}},{key:"setOrdinate",value:function(p,g){switch(p){case ie.X:this.x=g;break;case ie.Y:this.y=g;break;case ie.Z:this.z=g;break;case ie.M:this._m=g;break;default:throw new R("Invalid ordinate index: "+p)}}},{key:"setM",value:function(p){this._m=p}},{key:"getOrdinate",value:function(p){switch(p){case ie.X:return this.x;case ie.Y:return this.y;case ie.Z:return this.getZ();case ie.M:return this.getM()}throw new R("Invalid ordinate index: "+p)}},{key:"copy",value:function(){return new u(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+", "+this.getZ()+" m="+this.getM()+")"}},{key:"setCoordinate",value:function(p){this.x=p.x,this.y=p.y,this.z=p.getZ(),this._m=p.getM()}}],[{key:"constructor_",value:function(){if(this._m=null,arguments.length===0)ie.constructor_.call(this),this._m=0;else if(arguments.length===1){if(arguments[0]instanceof u){var p=arguments[0];ie.constructor_.call(this,p),this._m=p._m}else if(arguments[0]instanceof ie){var g=arguments[0];ie.constructor_.call(this,g),this._m=this.getM()}}else if(arguments.length===4){var E=arguments[0],B=arguments[1],F=arguments[2],G=arguments[3];ie.constructor_.call(this,E,B,F),this._m=G}}}])})(ie),Zt=(function(){function _(){s(this,_)}return o(_,null,[{key:"measures",value:function(u){return u instanceof Qt?0:u instanceof cn||u instanceof Xt?1:0}},{key:"dimension",value:function(u){return u instanceof Qt?2:u instanceof cn?3:u instanceof Xt?4:3}},{key:"create",value:function(){if(arguments.length===1){var u=arguments[0];return _.create(u,0)}if(arguments.length===2){var p=arguments[0],g=arguments[1];return p===2?new Qt:p===3&&g===0?new ie:p===3&&g===1?new cn:p===4&&g===1?new Xt:new ie}}}])})(),Gn=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,[{key:"getCoordinate",value:function(p){return this.get(p)}},{key:"addAll",value:function(){if(arguments.length===2&&typeof arguments[1]=="boolean"&&X(arguments[0],Se)){for(var p=arguments[1],g=!1,E=arguments[0].iterator();E.hasNext();)this.add(E.next(),p),g=!0;return g}return A(u,"addAll",this,1).apply(this,arguments)}},{key:"clone",value:function(){for(var p=A(u,"clone",this,1).call(this),g=0;g<this.size();g++)p.add(g,this.get(g).clone());return p}},{key:"toCoordinateArray",value:function(){if(arguments.length===0)return this.toArray(u.coordArrayType);if(arguments.length===1){if(arguments[0])return this.toArray(u.coordArrayType);for(var p=this.size(),g=new Array(p).fill(null),E=0;E<p;E++)g[E]=this.get(p-E-1);return g}}},{key:"add",value:function(){if(arguments.length===1){var p=arguments[0];return A(u,"add",this,1).call(this,p)}if(arguments.length===2){if(arguments[0]instanceof Array&&typeof arguments[1]=="boolean"){var g=arguments[0],E=arguments[1];return this.add(g,E,!0),!0}if(arguments[0]instanceof ie&&typeof arguments[1]=="boolean"){var B=arguments[0];if(!arguments[1]&&this.size()>=1&&this.get(this.size()-1).equals2D(B))return null;A(u,"add",this,1).call(this,B)}else if(arguments[0]instanceof Object&&typeof arguments[1]=="boolean"){var F=arguments[0],G=arguments[1];return this.add(F,G),!0}}else if(arguments.length===3){if(typeof arguments[2]=="boolean"&&arguments[0]instanceof Array&&typeof arguments[1]=="boolean"){var Y=arguments[0],ae=arguments[1];if(arguments[2])for(var xe=0;xe<Y.length;xe++)this.add(Y[xe],ae);else for(var Ie=Y.length-1;Ie>=0;Ie--)this.add(Y[Ie],ae);return!0}if(typeof arguments[2]=="boolean"&&Number.isInteger(arguments[0])&&arguments[1]instanceof ie){var Ge=arguments[0],ut=arguments[1];if(!arguments[2]){var Rt=this.size();if(Rt>0&&(Ge>0&&this.get(Ge-1).equals2D(ut)||Ge<Rt&&this.get(Ge).equals2D(ut)))return null}A(u,"add",this,1).call(this,Ge,ut)}}else if(arguments.length===4){var Ft=arguments[0],vn=arguments[1],pn=arguments[2],Dn=arguments[3],Ki=1;pn>Dn&&(Ki=-1);for(var ps=pn;ps!==Dn;ps+=Ki)this.add(Ft[ps],vn);return!0}}},{key:"closeRing",value:function(){if(this.size()>0){var p=this.get(0).copy();this.add(p,!1)}}}],[{key:"constructor_",value:function(){if(arguments.length!==0){if(arguments.length===1){var p=arguments[0];this.ensureCapacity(p.length),this.add(p,!0)}else if(arguments.length===2){var g=arguments[0],E=arguments[1];this.ensureCapacity(g.length),this.add(g,E)}}}}])})(Pe);Gn.coordArrayType=new Array(0).fill(null);var In=(function(){function _(){s(this,_)}return o(_,null,[{key:"isRing",value:function(u){return!(u.length<4)&&!!u[0].equals2D(u[u.length-1])}},{key:"ptNotInList",value:function(u,p){for(var g=0;g<u.length;g++){var E=u[g];if(_.indexOf(E,p)<0)return E}return null}},{key:"scroll",value:function(u,p){var g=_.indexOf(p,u);if(g<0)return null;var E=new Array(u.length).fill(null);xt.arraycopy(u,g,E,0,u.length-g),xt.arraycopy(u,0,E,u.length-g,g),xt.arraycopy(E,0,u,0,u.length)}},{key:"equals",value:function(){if(arguments.length===2){var u=arguments[0],p=arguments[1];if(u===p)return!0;if(u===null||p===null||u.length!==p.length)return!1;for(var g=0;g<u.length;g++)if(!u[g].equals(p[g]))return!1;return!0}if(arguments.length===3){var E=arguments[0],B=arguments[1],F=arguments[2];if(E===B)return!0;if(E===null||B===null||E.length!==B.length)return!1;for(var G=0;G<E.length;G++)if(F.compare(E[G],B[G])!==0)return!1;return!0}}},{key:"intersection",value:function(u,p){for(var g=new Gn,E=0;E<u.length;E++)p.intersects(u[E])&&g.add(u[E],!0);return g.toCoordinateArray()}},{key:"measures",value:function(u){if(u===null||u.length===0)return 0;var p,g=0,E=l(u);try{for(E.s();!(p=E.n()).done;){var B=p.value;g=Math.max(g,Zt.measures(B))}}catch(F){E.e(F)}finally{E.f()}return g}},{key:"hasRepeatedPoints",value:function(u){for(var p=1;p<u.length;p++)if(u[p-1].equals(u[p]))return!0;return!1}},{key:"removeRepeatedPoints",value:function(u){return _.hasRepeatedPoints(u)?new Gn(u,!1).toCoordinateArray():u}},{key:"reverse",value:function(u){for(var p=u.length-1,g=Math.trunc(p/2),E=0;E<=g;E++){var B=u[E];u[E]=u[p-E],u[p-E]=B}}},{key:"removeNull",value:function(u){for(var p=0,g=0;g<u.length;g++)u[g]!==null&&p++;var E=new Array(p).fill(null);if(p===0)return E;for(var B=0,F=0;F<u.length;F++)u[F]!==null&&(E[B++]=u[F]);return E}},{key:"copyDeep",value:function(){if(arguments.length===1){for(var u=arguments[0],p=new Array(u.length).fill(null),g=0;g<u.length;g++)p[g]=u[g].copy();return p}if(arguments.length===5)for(var E=arguments[0],B=arguments[1],F=arguments[2],G=arguments[3],Y=arguments[4],ae=0;ae<Y;ae++)F[G+ae]=E[B+ae].copy()}},{key:"isEqualReversed",value:function(u,p){for(var g=0;g<u.length;g++){var E=u[g],B=p[u.length-g-1];if(E.compareTo(B)!==0)return!1}return!0}},{key:"envelope",value:function(u){for(var p=new fe,g=0;g<u.length;g++)p.expandToInclude(u[g]);return p}},{key:"toCoordinateArray",value:function(u){return u.toArray(_.coordArrayType)}},{key:"dimension",value:function(u){if(u===null||u.length===0)return 3;var p,g=0,E=l(u);try{for(E.s();!(p=E.n()).done;){var B=p.value;g=Math.max(g,Zt.dimension(B))}}catch(F){E.e(F)}finally{E.f()}return g}},{key:"atLeastNCoordinatesOrNothing",value:function(u,p){return p.length>=u?p:[]}},{key:"indexOf",value:function(u,p){for(var g=0;g<p.length;g++)if(u.equals(p[g]))return g;return-1}},{key:"increasingDirection",value:function(u){for(var p=0;p<Math.trunc(u.length/2);p++){var g=u.length-1-p,E=u[p].compareTo(u[g]);if(E!==0)return E}return 1}},{key:"compare",value:function(u,p){for(var g=0;g<u.length&&g<p.length;){var E=u[g].compareTo(p[g]);if(E!==0)return E;g++}return g<p.length?-1:g<u.length?1:0}},{key:"minCoordinate",value:function(u){for(var p=null,g=0;g<u.length;g++)(p===null||p.compareTo(u[g])>0)&&(p=u[g]);return p}},{key:"extract",value:function(u,p,g){p=me.clamp(p,0,u.length);var E=(g=me.clamp(g,-1,u.length))-p+1;g<0&&(E=0),p>=u.length&&(E=0),g<p&&(E=0);var B=new Array(E).fill(null);if(E===0)return B;for(var F=0,G=p;G<=g;G++)B[F++]=u[G];return B}}])})(),j=(function(){return o((function _(){s(this,_)}),[{key:"compare",value:function(_,u){var p=_,g=u;return In.compare(p,g)}},{key:"interfaces_",get:function(){return[te]}}])})(),Ee=(function(){return o((function _(){s(this,_)}),[{key:"compare",value:function(_,u){var p=_,g=u;if(p.length<g.length)return-1;if(p.length>g.length)return 1;if(p.length===0)return 0;var E=In.compare(p,g);return In.isEqualReversed(p,g)?0:E}},{key:"OLDcompare",value:function(_,u){var p=_,g=u;if(p.length<g.length)return-1;if(p.length>g.length)return 1;if(p.length===0)return 0;for(var E=In.increasingDirection(p),B=In.increasingDirection(g),F=E>0?0:p.length-1,G=B>0?0:p.length-1,Y=0;Y<p.length;Y++){var ae=p[F].compareTo(g[G]);if(ae!==0)return ae;F+=E,G+=B}return 0}},{key:"interfaces_",get:function(){return[te]}}])})();In.ForwardComparator=j,In.BidirectionalComparator=Ee,In.coordArrayType=new Array(0).fill(null);var we=(function(){return o((function _(u){s(this,_),this.str=u}),[{key:"append",value:function(_){this.str+=_}},{key:"setCharAt",value:function(_,u){this.str=this.str.substr(0,_)+u+this.str.substr(_+1)}},{key:"toString",value:function(){return this.str}}])})(),Me=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"getM",value:function(u){return this.hasM()?this._coordinates[u].getM():W.NaN}},{key:"setOrdinate",value:function(u,p,g){switch(p){case _e.X:this._coordinates[u].x=g;break;case _e.Y:this._coordinates[u].y=g;break;default:this._coordinates[u].setOrdinate(p,g)}}},{key:"getZ",value:function(u){return this.hasZ()?this._coordinates[u].getZ():W.NaN}},{key:"size",value:function(){return this._coordinates.length}},{key:"getOrdinate",value:function(u,p){switch(p){case _e.X:return this._coordinates[u].x;case _e.Y:return this._coordinates[u].y;default:return this._coordinates[u].getOrdinate(p)}}},{key:"getCoordinate",value:function(){if(arguments.length===1){var u=arguments[0];return this._coordinates[u]}if(arguments.length===2){var p=arguments[0];arguments[1].setCoordinate(this._coordinates[p])}}},{key:"getCoordinateCopy",value:function(u){var p=this.createCoordinate();return p.setCoordinate(this._coordinates[u]),p}},{key:"createCoordinate",value:function(){return Zt.create(this.getDimension(),this.getMeasures())}},{key:"getDimension",value:function(){return this._dimension}},{key:"getX",value:function(u){return this._coordinates[u].x}},{key:"getMeasures",value:function(){return this._measures}},{key:"expandEnvelope",value:function(u){for(var p=0;p<this._coordinates.length;p++)u.expandToInclude(this._coordinates[p]);return u}},{key:"copy",value:function(){for(var u=new Array(this.size()).fill(null),p=0;p<this._coordinates.length;p++){var g=this.createCoordinate();g.setCoordinate(this._coordinates[p]),u[p]=g}return new _(u,this._dimension,this._measures)}},{key:"toString",value:function(){if(this._coordinates.length>0){var u=new we(17*this._coordinates.length);u.append("("),u.append(this._coordinates[0]);for(var p=1;p<this._coordinates.length;p++)u.append(", "),u.append(this._coordinates[p]);return u.append(")"),u.toString()}return"()"}},{key:"getY",value:function(u){return this._coordinates[u].y}},{key:"toCoordinateArray",value:function(){return this._coordinates}},{key:"interfaces_",get:function(){return[_e,C]}}],[{key:"constructor_",value:function(){if(this._dimension=3,this._measures=0,this._coordinates=null,arguments.length===1){if(arguments[0]instanceof Array){var u=arguments[0];_.constructor_.call(this,u,In.dimension(u),In.measures(u))}else if(Number.isInteger(arguments[0])){var p=arguments[0];this._coordinates=new Array(p).fill(null);for(var g=0;g<p;g++)this._coordinates[g]=new ie}else if(X(arguments[0],_e)){var E=arguments[0];if(E===null)return this._coordinates=new Array(0).fill(null),null;this._dimension=E.getDimension(),this._measures=E.getMeasures(),this._coordinates=new Array(E.size()).fill(null);for(var B=0;B<this._coordinates.length;B++)this._coordinates[B]=E.getCoordinateCopy(B)}}else if(arguments.length===2){if(arguments[0]instanceof Array&&Number.isInteger(arguments[1])){var F=arguments[0],G=arguments[1];_.constructor_.call(this,F,G,In.measures(F))}else if(Number.isInteger(arguments[0])&&Number.isInteger(arguments[1])){var Y=arguments[0],ae=arguments[1];this._coordinates=new Array(Y).fill(null),this._dimension=ae;for(var xe=0;xe<Y;xe++)this._coordinates[xe]=Zt.create(ae)}}else if(arguments.length===3){if(Number.isInteger(arguments[2])&&arguments[0]instanceof Array&&Number.isInteger(arguments[1])){var Ie=arguments[0],Ge=arguments[1],ut=arguments[2];this._dimension=Ge,this._measures=ut,this._coordinates=Ie===null?new Array(0).fill(null):Ie}else if(Number.isInteger(arguments[2])&&Number.isInteger(arguments[0])&&Number.isInteger(arguments[1])){var Rt=arguments[0],Ft=arguments[1],vn=arguments[2];this._coordinates=new Array(Rt).fill(null),this._dimension=Ft,this._measures=vn;for(var pn=0;pn<Rt;pn++)this._coordinates[pn]=this.createCoordinate()}}}}])})(),ve=(function(){function _(){s(this,_)}return o(_,[{key:"readResolve",value:function(){return _.instance()}},{key:"create",value:function(){if(arguments.length===1){if(arguments[0]instanceof Array)return new Me(arguments[0]);if(X(arguments[0],_e))return new Me(arguments[0])}else{if(arguments.length===2){var u=arguments[1];return u>3&&(u=3),u<2&&(u=2),new Me(arguments[0],u)}if(arguments.length===3){var p=arguments[2],g=arguments[1]-p;return p>1&&(p=1),g>3&&(g=3),g<2&&(g=2),new Me(arguments[0],g+p,p)}}}},{key:"interfaces_",get:function(){return[tt,C]}}],[{key:"instance",value:function(){return _.instanceObject}}])})();ve.instanceObject=new ve;var He=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,[{key:"copyInternal",value:function(){for(var p=new Array(this._geometries.length).fill(null),g=0;g<p.length;g++)p[g]=this._geometries[g].copy();return new u(p,this._factory)}},{key:"equalsExact",value:function(){if(arguments.length===2&&typeof arguments[1]=="number"&&arguments[0]instanceof ye){var p=arguments[0],g=arguments[1];return!!this.isEquivalentClass(p)&&A(u,"equalsExact",this,1).call(this,p,g)}return A(u,"equalsExact",this,1).apply(this,arguments)}},{key:"getBoundaryDimension",value:function(){return 1}},{key:"getTypeCode",value:function(){return ye.TYPECODE_MULTIPOLYGON}},{key:"getDimension",value:function(){return 2}},{key:"getBoundary",value:function(){if(this.isEmpty())return this.getFactory().createMultiLineString();for(var p=new Pe,g=0;g<this._geometries.length;g++)for(var E=this._geometries[g].getBoundary(),B=0;B<E.getNumGeometries();B++)p.add(E.getGeometryN(B));var F=new Array(p.size()).fill(null);return this.getFactory().createMultiLineString(p.toArray(F))}},{key:"getGeometryType",value:function(){return ye.TYPENAME_MULTIPOLYGON}},{key:"interfaces_",get:function(){return[Te]}}],[{key:"constructor_",value:function(){var p=arguments[0],g=arguments[1];vt.constructor_.call(this,p,g)}}])})(vt),lt=(function(){return o((function _(){s(this,_)}),[{key:"get",value:function(){}},{key:"put",value:function(){}},{key:"size",value:function(){}},{key:"values",value:function(){}},{key:"entrySet",value:function(){}}])})(),nt=(function(_){function u(){var p;return s(this,u),(p=i(this,u)).map=new Map,p}return d(u,_),o(u,[{key:"get",value:function(p){return this.map.get(p)||null}},{key:"put",value:function(p,g){return this.map.set(p,g),g}},{key:"values",value:function(){for(var p=new Pe,g=this.map.values(),E=g.next();!E.done;)p.add(E.value),E=g.next();return p}},{key:"entrySet",value:function(){var p=new et;return this.map.entries().forEach((function(g){return p.add(g)})),p}},{key:"size",value:function(){return this.map.size()}}])})(lt),ct=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"equals",value:function(u){if(!(u instanceof _))return!1;var p=u;return this._modelType===p._modelType&&this._scale===p._scale}},{key:"compareTo",value:function(u){var p=u,g=this.getMaximumSignificantDigits(),E=p.getMaximumSignificantDigits();return de.compare(g,E)}},{key:"getScale",value:function(){return this._scale}},{key:"isFloating",value:function(){return this._modelType===_.FLOATING||this._modelType===_.FLOATING_SINGLE}},{key:"getType",value:function(){return this._modelType}},{key:"toString",value:function(){var u="UNKNOWN";return this._modelType===_.FLOATING?u="Floating":this._modelType===_.FLOATING_SINGLE?u="Floating-Single":this._modelType===_.FIXED&&(u="Fixed (Scale="+this.getScale()+")"),u}},{key:"makePrecise",value:function(){if(typeof arguments[0]=="number"){var u=arguments[0];return W.isNaN(u)||this._modelType===_.FLOATING_SINGLE?u:this._modelType===_.FIXED?Math.round(u*this._scale)/this._scale:u}if(arguments[0]instanceof ie){var p=arguments[0];if(this._modelType===_.FLOATING)return null;p.x=this.makePrecise(p.x),p.y=this.makePrecise(p.y)}}},{key:"getMaximumSignificantDigits",value:function(){var u=16;return this._modelType===_.FLOATING?u=16:this._modelType===_.FLOATING_SINGLE?u=6:this._modelType===_.FIXED&&(u=1+Math.trunc(Math.ceil(Math.log(this.getScale())/Math.log(10)))),u}},{key:"setScale",value:function(u){this._scale=Math.abs(u)}},{key:"interfaces_",get:function(){return[C,L]}}],[{key:"constructor_",value:function(){if(this._modelType=null,this._scale=null,arguments.length===0)this._modelType=_.FLOATING;else if(arguments.length===1){if(arguments[0]instanceof Et){var u=arguments[0];this._modelType=u,u===_.FIXED&&this.setScale(1)}else if(typeof arguments[0]=="number"){var p=arguments[0];this._modelType=_.FIXED,this.setScale(p)}else if(arguments[0]instanceof _){var g=arguments[0];this._modelType=g._modelType,this._scale=g._scale}}}},{key:"mostPrecise",value:function(u,p){return u.compareTo(p)>=0?u:p}}])})(),Et=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"readResolve",value:function(){return _.nameToTypeMap.get(this._name)}},{key:"toString",value:function(){return this._name}},{key:"interfaces_",get:function(){return[C]}}],[{key:"constructor_",value:function(){this._name=null;var u=arguments[0];this._name=u,_.nameToTypeMap.put(u,this)}}])})();Et.nameToTypeMap=new nt,ct.Type=Et,ct.FIXED=new Et("FIXED"),ct.FLOATING=new Et("FLOATING"),ct.FLOATING_SINGLE=new Et("FLOATING SINGLE"),ct.maximumPreciseValue=9007199254740992;var Ut=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,[{key:"copyInternal",value:function(){for(var p=new Array(this._geometries.length).fill(null),g=0;g<p.length;g++)p[g]=this._geometries[g].copy();return new u(p,this._factory)}},{key:"equalsExact",value:function(){if(arguments.length===2&&typeof arguments[1]=="number"&&arguments[0]instanceof ye){var p=arguments[0],g=arguments[1];return!!this.isEquivalentClass(p)&&A(u,"equalsExact",this,1).call(this,p,g)}return A(u,"equalsExact",this,1).apply(this,arguments)}},{key:"getBoundaryDimension",value:function(){return this.isClosed()?Ne.FALSE:0}},{key:"isClosed",value:function(){if(this.isEmpty())return!1;for(var p=0;p<this._geometries.length;p++)if(!this._geometries[p].isClosed())return!1;return!0}},{key:"getTypeCode",value:function(){return ye.TYPECODE_MULTILINESTRING}},{key:"getDimension",value:function(){return 1}},{key:"getBoundary",value:function(){throw new Qe}},{key:"getGeometryType",value:function(){return ye.TYPENAME_MULTILINESTRING}},{key:"interfaces_",get:function(){return[Ue]}}],[{key:"constructor_",value:function(){var p=arguments[0],g=arguments[1];vt.constructor_.call(this,p,g)}}])})(vt),Pt=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"createEmpty",value:function(u){switch(u){case-1:return this.createGeometryCollection();case 0:return this.createPoint();case 1:return this.createLineString();case 2:return this.createPolygon();default:throw new R("Invalid dimension: "+u)}}},{key:"toGeometry",value:function(u){return u.isNull()?this.createPoint():u.getMinX()===u.getMaxX()&&u.getMinY()===u.getMaxY()?this.createPoint(new ie(u.getMinX(),u.getMinY())):u.getMinX()===u.getMaxX()||u.getMinY()===u.getMaxY()?this.createLineString([new ie(u.getMinX(),u.getMinY()),new ie(u.getMaxX(),u.getMaxY())]):this.createPolygon(this.createLinearRing([new ie(u.getMinX(),u.getMinY()),new ie(u.getMinX(),u.getMaxY()),new ie(u.getMaxX(),u.getMaxY()),new ie(u.getMaxX(),u.getMinY()),new ie(u.getMinX(),u.getMinY())]),null)}},{key:"createLineString",value:function(){if(arguments.length===0)return this.createLineString(this.getCoordinateSequenceFactory().create([]));if(arguments.length===1){if(arguments[0]instanceof Array){var u=arguments[0];return this.createLineString(u!==null?this.getCoordinateSequenceFactory().create(u):null)}if(X(arguments[0],_e))return new zi(arguments[0],this)}}},{key:"createMultiLineString",value:function(){return arguments.length===0?new Ut(null,this):arguments.length===1?new Ut(arguments[0],this):void 0}},{key:"buildGeometry",value:function(u){for(var p=null,g=!1,E=!1,B=u.iterator();B.hasNext();){var F=B.next(),G=F.getTypeCode();p===null&&(p=G),G!==p&&(g=!0),F instanceof vt&&(E=!0)}if(p===null)return this.createGeometryCollection();if(g||E)return this.createGeometryCollection(_.toGeometryArray(u));var Y=u.iterator().next();if(u.size()>1){if(Y instanceof Fe)return this.createMultiPolygon(_.toPolygonArray(u));if(Y instanceof zi)return this.createMultiLineString(_.toLineStringArray(u));if(Y instanceof Wo)return this.createMultiPoint(_.toPointArray(u));re.shouldNeverReachHere("Unhandled geometry type: "+Y.getGeometryType())}return Y}},{key:"createMultiPointFromCoords",value:function(u){return this.createMultiPoint(u!==null?this.getCoordinateSequenceFactory().create(u):null)}},{key:"createPoint",value:function(){if(arguments.length===0)return this.createPoint(this.getCoordinateSequenceFactory().create([]));if(arguments.length===1){if(arguments[0]instanceof ie){var u=arguments[0];return this.createPoint(u!==null?this.getCoordinateSequenceFactory().create([u]):null)}if(X(arguments[0],_e))return new Wo(arguments[0],this)}}},{key:"getCoordinateSequenceFactory",value:function(){return this._coordinateSequenceFactory}},{key:"createPolygon",value:function(){if(arguments.length===0)return this.createPolygon(null,null);if(arguments.length===1){if(X(arguments[0],_e)){var u=arguments[0];return this.createPolygon(this.createLinearRing(u))}if(arguments[0]instanceof Array){var p=arguments[0];return this.createPolygon(this.createLinearRing(p))}if(arguments[0]instanceof zt){var g=arguments[0];return this.createPolygon(g,null)}}else if(arguments.length===2)return new Fe(arguments[0],arguments[1],this)}},{key:"getSRID",value:function(){return this._SRID}},{key:"createGeometryCollection",value:function(){return arguments.length===0?new vt(null,this):arguments.length===1?new vt(arguments[0],this):void 0}},{key:"getPrecisionModel",value:function(){return this._precisionModel}},{key:"createLinearRing",value:function(){if(arguments.length===0)return this.createLinearRing(this.getCoordinateSequenceFactory().create([]));if(arguments.length===1){if(arguments[0]instanceof Array){var u=arguments[0];return this.createLinearRing(u!==null?this.getCoordinateSequenceFactory().create(u):null)}if(X(arguments[0],_e))return new zt(arguments[0],this)}}},{key:"createMultiPolygon",value:function(){return arguments.length===0?new He(null,this):arguments.length===1?new He(arguments[0],this):void 0}},{key:"createMultiPoint",value:function(){if(arguments.length===0)return new wt(null,this);if(arguments.length===1){if(arguments[0]instanceof Array)return new wt(arguments[0],this);if(X(arguments[0],_e)){var u=arguments[0];if(u===null)return this.createMultiPoint(new Array(0).fill(null));for(var p=new Array(u.size()).fill(null),g=0;g<u.size();g++){var E=this.getCoordinateSequenceFactory().create(1,u.getDimension(),u.getMeasures());At.copy(u,g,E,0,1),p[g]=this.createPoint(E)}return this.createMultiPoint(p)}}}},{key:"interfaces_",get:function(){return[C]}}],[{key:"constructor_",value:function(){if(this._precisionModel=null,this._coordinateSequenceFactory=null,this._SRID=null,arguments.length===0)_.constructor_.call(this,new ct,0);else if(arguments.length===1){if(X(arguments[0],tt)){var u=arguments[0];_.constructor_.call(this,new ct,0,u)}else if(arguments[0]instanceof ct){var p=arguments[0];_.constructor_.call(this,p,0,_.getDefaultCoordinateSequenceFactory())}}else if(arguments.length===2){var g=arguments[0],E=arguments[1];_.constructor_.call(this,g,E,_.getDefaultCoordinateSequenceFactory())}else if(arguments.length===3){var B=arguments[0],F=arguments[1],G=arguments[2];this._precisionModel=B,this._coordinateSequenceFactory=G,this._SRID=F}}},{key:"toMultiPolygonArray",value:function(u){var p=new Array(u.size()).fill(null);return u.toArray(p)}},{key:"toGeometryArray",value:function(u){if(u===null)return null;var p=new Array(u.size()).fill(null);return u.toArray(p)}},{key:"getDefaultCoordinateSequenceFactory",value:function(){return ve.instance()}},{key:"toMultiLineStringArray",value:function(u){var p=new Array(u.size()).fill(null);return u.toArray(p)}},{key:"toLineStringArray",value:function(u){var p=new Array(u.size()).fill(null);return u.toArray(p)}},{key:"toMultiPointArray",value:function(u){var p=new Array(u.size()).fill(null);return u.toArray(p)}},{key:"toLinearRingArray",value:function(u){var p=new Array(u.size()).fill(null);return u.toArray(p)}},{key:"toPointArray",value:function(u){var p=new Array(u.size()).fill(null);return u.toArray(p)}},{key:"toPolygonArray",value:function(u){var p=new Array(u.size()).fill(null);return u.toArray(p)}},{key:"createPointFromInternalCoord",value:function(u,p){return p.getPrecisionModel().makePrecise(u),p.getFactory().createPoint(u)}}])})(),tn="XY",Bn="XYZ",Pn="XYM",jn="XYZM",Mn={POINT:"Point",LINE_STRING:"LineString",LINEAR_RING:"LinearRing",POLYGON:"Polygon",MULTI_POINT:"MultiPoint",MULTI_LINE_STRING:"MultiLineString",MULTI_POLYGON:"MultiPolygon",GEOMETRY_COLLECTION:"GeometryCollection",CIRCLE:"Circle"},Lt="EMPTY",mi=1,qt=2,bi=3,eo=4,xi=5,Vl=6;for(var Hn in Mn)Mn[Hn].toUpperCase();var js=(function(){return o((function _(u){s(this,_),this.wkt=u,this.index_=-1}),[{key:"isAlpha_",value:function(_){return _>="a"&&_<="z"||_>="A"&&_<="Z"}},{key:"isNumeric_",value:function(_,u){return _>="0"&&_<="9"||_=="."&&!(u!==void 0&&u)}},{key:"isWhiteSpace_",value:function(_){return _==" "||_==" "||_=="\r"||_==`
270
270
  `}},{key:"nextChar_",value:function(){return this.wkt.charAt(++this.index_)}},{key:"nextToken",value:function(){var _,u=this.nextChar_(),p=this.index_,g=u;if(u=="(")_=qt;else if(u==",")_=xi;else if(u==")")_=bi;else if(this.isNumeric_(u)||u=="-")_=eo,g=this.readNumber_();else if(this.isAlpha_(u))_=mi,g=this.readText_();else{if(this.isWhiteSpace_(u))return this.nextToken();if(u!=="")throw new Error("Unexpected character: "+u);_=Vl}return{position:p,value:g,type:_}}},{key:"readNumber_",value:function(){var _,u=this.index_,p=!1,g=!1;do _=="."?p=!0:_!="e"&&_!="E"||(g=!0),_=this.nextChar_();while(this.isNumeric_(_,p)||!g&&(_=="e"||_=="E")||g&&(_=="-"||_=="+"));return parseFloat(this.wkt.substring(u,this.index_--))}},{key:"readText_",value:function(){var _,u=this.index_;do _=this.nextChar_();while(this.isAlpha_(_));return this.wkt.substring(u,this.index_--).toUpperCase()}}])})(),Xs=(function(){return o((function _(u,p){s(this,_),this.lexer_=u,this.token_,this.layout_=tn,this.factory=p}),[{key:"consume_",value:function(){this.token_=this.lexer_.nextToken()}},{key:"isTokenType",value:function(_){return this.token_.type==_}},{key:"match",value:function(_){var u=this.isTokenType(_);return u&&this.consume_(),u}},{key:"parse",value:function(){return this.consume_(),this.parseGeometry_()}},{key:"parseGeometryLayout_",value:function(){var _=tn,u=this.token_;if(this.isTokenType(mi)){var p=u.value;p==="Z"?_=Bn:p==="M"?_=Pn:p==="ZM"&&(_=jn),_!==tn&&this.consume_()}return _}},{key:"parseGeometryCollectionText_",value:function(){if(this.match(qt)){var _=[];do _.push(this.parseGeometry_());while(this.match(xi));if(this.match(bi))return _}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePointText_",value:function(){if(this.match(qt)){var _=this.parsePoint_();if(this.match(bi))return _}else if(this.isEmptyGeometry_())return null;throw new Error(this.formatErrorMessage_())}},{key:"parseLineStringText_",value:function(){if(this.match(qt)){var _=this.parsePointList_();if(this.match(bi))return _}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePolygonText_",value:function(){if(this.match(qt)){var _=this.parseLineStringTextList_();if(this.match(bi))return _}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiPointText_",value:function(){var _;if(this.match(qt)){if(_=this.token_.type==qt?this.parsePointTextList_():this.parsePointList_(),this.match(bi))return _}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiLineStringText_",value:function(){if(this.match(qt)){var _=this.parseLineStringTextList_();if(this.match(bi))return _}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiPolygonText_",value:function(){if(this.match(qt)){var _=this.parsePolygonTextList_();if(this.match(bi))return _}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePoint_",value:function(){for(var _=[],u=this.layout_.length,p=0;p<u;++p){var g=this.token_;if(!this.match(eo))break;_.push(g.value)}if(_.length==u)return _;throw new Error(this.formatErrorMessage_())}},{key:"parsePointList_",value:function(){for(var _=[this.parsePoint_()];this.match(xi);)_.push(this.parsePoint_());return _}},{key:"parsePointTextList_",value:function(){for(var _=[this.parsePointText_()];this.match(xi);)_.push(this.parsePointText_());return _}},{key:"parseLineStringTextList_",value:function(){for(var _=[this.parseLineStringText_()];this.match(xi);)_.push(this.parseLineStringText_());return _}},{key:"parsePolygonTextList_",value:function(){for(var _=[this.parsePolygonText_()];this.match(xi);)_.push(this.parsePolygonText_());return _}},{key:"isEmptyGeometry_",value:function(){var _=this.isTokenType(mi)&&this.token_.value==Lt;return _&&this.consume_(),_}},{key:"formatErrorMessage_",value:function(){return"Unexpected `"+this.token_.value+"` at position "+this.token_.position+" in `"+this.lexer_.wkt+"`"}},{key:"parseGeometry_",value:function(){var _=this.factory,u=function(Ft){return r(ie,y(Ft))},p=function(Ft){var vn=Ft.map((function(pn){return _.createLinearRing(pn.map(u))}));return vn.length>1?_.createPolygon(vn[0],vn.slice(1)):_.createPolygon(vn[0])},g=this.token_;if(this.match(mi)){var E=g.value;if(this.layout_=this.parseGeometryLayout_(),E=="GEOMETRYCOLLECTION"){var B=this.parseGeometryCollectionText_();return _.createGeometryCollection(B)}switch(E){case"POINT":var F=this.parsePointText_();return F?_.createPoint(r(ie,y(F))):_.createPoint();case"LINESTRING":var G=this.parseLineStringText_().map(u);return _.createLineString(G);case"LINEARRING":var Y=this.parseLineStringText_().map(u);return _.createLinearRing(Y);case"POLYGON":var ae=this.parsePolygonText_();return ae&&ae.length!==0?p(ae):_.createPolygon();case"MULTIPOINT":var xe=this.parseMultiPointText_();if(!xe||xe.length===0)return _.createMultiPoint();var Ie=xe.map(u).map((function(Ft){return _.createPoint(Ft)}));return _.createMultiPoint(Ie);case"MULTILINESTRING":var Ge=this.parseMultiLineStringText_().map((function(Ft){return _.createLineString(Ft.map(u))}));return _.createMultiLineString(Ge);case"MULTIPOLYGON":var ut=this.parseMultiPolygonText_();if(!ut||ut.length===0)return _.createMultiPolygon();var Rt=ut.map(p);return _.createMultiPolygon(Rt);default:throw new Error("Invalid geometry type: "+E)}}throw new Error(this.formatErrorMessage_())}}])})();function Ei(_){if(_.isEmpty())return"";var u=_.getCoordinate(),p=[u.x,u.y];return u.z===void 0||Number.isNaN(u.z)||p.push(u.z),u.m===void 0||Number.isNaN(u.m)||p.push(u.m),p.join(" ")}function Ji(_){for(var u=_.getCoordinates().map((function(B){var F=[B.x,B.y];return B.z===void 0||Number.isNaN(B.z)||F.push(B.z),B.m===void 0||Number.isNaN(B.m)||F.push(B.m),F})),p=[],g=0,E=u.length;g<E;++g)p.push(u[g].join(" "));return p.join(", ")}function Xc(_){var u=[];u.push("("+Ji(_.getExteriorRing())+")");for(var p=0,g=_.getNumInteriorRing();p<g;++p)u.push("("+Ji(_.getInteriorRingN(p))+")");return u.join(", ")}var to={Point:Ei,LineString:Ji,LinearRing:Ji,Polygon:Xc,MultiPoint:function(_){for(var u=[],p=0,g=_.getNumGeometries();p<g;++p)u.push("("+Ei(_.getGeometryN(p))+")");return u.join(", ")},MultiLineString:function(_){for(var u=[],p=0,g=_.getNumGeometries();p<g;++p)u.push("("+Ji(_.getGeometryN(p))+")");return u.join(", ")},MultiPolygon:function(_){for(var u=[],p=0,g=_.getNumGeometries();p<g;++p)u.push("("+Xc(_.getGeometryN(p))+")");return u.join(", ")},GeometryCollection:function(_){for(var u=[],p=0,g=_.getNumGeometries();p<g;++p)u.push(cw(_.getGeometryN(p)));return u.join(", ")}};function cw(_){var u=_.getGeometryType(),p=to[u];u=u.toUpperCase();var g=(function(E){var B="";if(E.isEmpty())return B;var F=E.getCoordinate();return F.z===void 0||Number.isNaN(F.z)||(B+="Z"),F.m===void 0||Number.isNaN(F.m)||(B+="M"),B})(_);return g.length>0&&(u+=" "+g),_.isEmpty()?u+" "+Lt:u+" ("+p(_)+")"}var AF=(function(){return o((function _(u){s(this,_),this.geometryFactory=u||new Pt,this.precisionModel=this.geometryFactory.getPrecisionModel()}),[{key:"read",value:function(_){return new Xs(new js(_),this.geometryFactory).parse()}},{key:"write",value:function(_){return cw(_)}}])})(),sv=(function(){return o((function _(u){s(this,_),this.parser=new AF(u)}),[{key:"write",value:function(_){return this.parser.write(_)}}],[{key:"toLineString",value:function(_,u){if(arguments.length!==2)throw new Error("Not implemented");return"LINESTRING ( "+_.x+" "+_.y+", "+u.x+" "+u.y+" )"}}])})(),Kn=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"getIndexAlongSegment",value:function(u,p){return this.computeIntLineIndex(),this._intLineIndex[u][p]}},{key:"getTopologySummary",value:function(){var u=new we;return this.isEndPoint()&&u.append(" endpoint"),this._isProper&&u.append(" proper"),this.isCollinear()&&u.append(" collinear"),u.toString()}},{key:"computeIntersection",value:function(u,p,g,E){this._inputLines[0][0]=u,this._inputLines[0][1]=p,this._inputLines[1][0]=g,this._inputLines[1][1]=E,this._result=this.computeIntersect(u,p,g,E)}},{key:"getIntersectionNum",value:function(){return this._result}},{key:"computeIntLineIndex",value:function(){if(arguments.length===0)this._intLineIndex===null&&(this._intLineIndex=Array(2).fill().map((function(){return Array(2)})),this.computeIntLineIndex(0),this.computeIntLineIndex(1));else if(arguments.length===1){var u=arguments[0];this.getEdgeDistance(u,0)>this.getEdgeDistance(u,1)?(this._intLineIndex[u][0]=0,this._intLineIndex[u][1]=1):(this._intLineIndex[u][0]=1,this._intLineIndex[u][1]=0)}}},{key:"isProper",value:function(){return this.hasIntersection()&&this._isProper}},{key:"setPrecisionModel",value:function(u){this._precisionModel=u}},{key:"isInteriorIntersection",value:function(){if(arguments.length===0)return!!this.isInteriorIntersection(0)||!!this.isInteriorIntersection(1);if(arguments.length===1){for(var u=arguments[0],p=0;p<this._result;p++)if(!this._intPt[p].equals2D(this._inputLines[u][0])&&!this._intPt[p].equals2D(this._inputLines[u][1]))return!0;return!1}}},{key:"getIntersection",value:function(u){return this._intPt[u]}},{key:"isEndPoint",value:function(){return this.hasIntersection()&&!this._isProper}},{key:"hasIntersection",value:function(){return this._result!==_.NO_INTERSECTION}},{key:"getEdgeDistance",value:function(u,p){return _.computeEdgeDistance(this._intPt[p],this._inputLines[u][0],this._inputLines[u][1])}},{key:"isCollinear",value:function(){return this._result===_.COLLINEAR_INTERSECTION}},{key:"toString",value:function(){return sv.toLineString(this._inputLines[0][0],this._inputLines[0][1])+" - "+sv.toLineString(this._inputLines[1][0],this._inputLines[1][1])+this.getTopologySummary()}},{key:"getEndpoint",value:function(u,p){return this._inputLines[u][p]}},{key:"isIntersection",value:function(u){for(var p=0;p<this._result;p++)if(this._intPt[p].equals2D(u))return!0;return!1}},{key:"getIntersectionAlongSegment",value:function(u,p){return this.computeIntLineIndex(),this._intPt[this._intLineIndex[u][p]]}}],[{key:"constructor_",value:function(){this._result=null,this._inputLines=Array(2).fill().map((function(){return Array(2)})),this._intPt=new Array(2).fill(null),this._intLineIndex=null,this._isProper=null,this._pa=null,this._pb=null,this._precisionModel=null,this._intPt[0]=new ie,this._intPt[1]=new ie,this._pa=this._intPt[0],this._pb=this._intPt[1],this._result=0}},{key:"computeEdgeDistance",value:function(u,p,g){var E=Math.abs(g.x-p.x),B=Math.abs(g.y-p.y),F=-1;if(u.equals(p))F=0;else if(u.equals(g))F=E>B?E:B;else{var G=Math.abs(u.x-p.x),Y=Math.abs(u.y-p.y);(F=E>B?G:Y)!==0||u.equals(p)||(F=Math.max(G,Y))}return re.isTrue(!(F===0&&!u.equals(p)),"Bad distance calculation"),F}},{key:"nonRobustComputeEdgeDistance",value:function(u,p,g){var E=u.x-p.x,B=u.y-p.y,F=Math.sqrt(E*E+B*B);return re.isTrue(!(F===0&&!u.equals(p)),"Invalid distance calculation"),F}}])})();Kn.DONT_INTERSECT=0,Kn.DO_INTERSECT=1,Kn.COLLINEAR=2,Kn.NO_INTERSECTION=0,Kn.POINT_INTERSECTION=1,Kn.COLLINEAR_INTERSECTION=2;var ql=(function(_){function u(){return s(this,u),i(this,u)}return d(u,_),o(u,[{key:"isInSegmentEnvelopes",value:function(p){var g=new fe(this._inputLines[0][0],this._inputLines[0][1]),E=new fe(this._inputLines[1][0],this._inputLines[1][1]);return g.contains(p)&&E.contains(p)}},{key:"computeIntersection",value:function(){if(arguments.length!==3)return A(u,"computeIntersection",this,1).apply(this,arguments);var p=arguments[0],g=arguments[1],E=arguments[2];if(this._isProper=!1,fe.intersects(g,E,p)&&be.index(g,E,p)===0&&be.index(E,g,p)===0)return this._isProper=!0,(p.equals(g)||p.equals(E))&&(this._isProper=!1),this._result=Kn.POINT_INTERSECTION,null;this._result=Kn.NO_INTERSECTION}},{key:"intersection",value:function(p,g,E,B){var F=this.intersectionSafe(p,g,E,B);return this.isInSegmentEnvelopes(F)||(F=new ie(u.nearestEndpoint(p,g,E,B))),this._precisionModel!==null&&this._precisionModel.makePrecise(F),F}},{key:"checkDD",value:function(p,g,E,B,F){var G=Ae.intersection(p,g,E,B),Y=this.isInSegmentEnvelopes(G);xt.out.println("DD in env = "+Y+" --------------------- "+G),F.distance(G)>1e-4&&xt.out.println("Distance = "+F.distance(G))}},{key:"intersectionSafe",value:function(p,g,E,B){var F=it.intersection(p,g,E,B);return F===null&&(F=u.nearestEndpoint(p,g,E,B)),F}},{key:"computeCollinearIntersection",value:function(p,g,E,B){var F=fe.intersects(p,g,E),G=fe.intersects(p,g,B),Y=fe.intersects(E,B,p),ae=fe.intersects(E,B,g);return F&&G?(this._intPt[0]=E,this._intPt[1]=B,Kn.COLLINEAR_INTERSECTION):Y&&ae?(this._intPt[0]=p,this._intPt[1]=g,Kn.COLLINEAR_INTERSECTION):F&&Y?(this._intPt[0]=E,this._intPt[1]=p,!E.equals(p)||G||ae?Kn.COLLINEAR_INTERSECTION:Kn.POINT_INTERSECTION):F&&ae?(this._intPt[0]=E,this._intPt[1]=g,!E.equals(g)||G||Y?Kn.COLLINEAR_INTERSECTION:Kn.POINT_INTERSECTION):G&&Y?(this._intPt[0]=B,this._intPt[1]=p,!B.equals(p)||F||ae?Kn.COLLINEAR_INTERSECTION:Kn.POINT_INTERSECTION):G&&ae?(this._intPt[0]=B,this._intPt[1]=g,!B.equals(g)||F||Y?Kn.COLLINEAR_INTERSECTION:Kn.POINT_INTERSECTION):Kn.NO_INTERSECTION}},{key:"computeIntersect",value:function(p,g,E,B){if(this._isProper=!1,!fe.intersects(p,g,E,B))return Kn.NO_INTERSECTION;var F=be.index(p,g,E),G=be.index(p,g,B);if(F>0&&G>0||F<0&&G<0)return Kn.NO_INTERSECTION;var Y=be.index(E,B,p),ae=be.index(E,B,g);return Y>0&&ae>0||Y<0&&ae<0?Kn.NO_INTERSECTION:F===0&&G===0&&Y===0&&ae===0?this.computeCollinearIntersection(p,g,E,B):(F===0||G===0||Y===0||ae===0?(this._isProper=!1,p.equals2D(E)||p.equals2D(B)?this._intPt[0]=p:g.equals2D(E)||g.equals2D(B)?this._intPt[0]=g:F===0?this._intPt[0]=new ie(E):G===0?this._intPt[0]=new ie(B):Y===0?this._intPt[0]=new ie(p):ae===0&&(this._intPt[0]=new ie(g))):(this._isProper=!0,this._intPt[0]=this.intersection(p,g,E,B)),Kn.POINT_INTERSECTION)}}],[{key:"nearestEndpoint",value:function(p,g,E,B){var F=p,G=qe.pointToSegment(p,E,B),Y=qe.pointToSegment(g,E,B);return Y<G&&(G=Y,F=g),(Y=qe.pointToSegment(E,p,g))<G&&(G=Y,F=E),(Y=qe.pointToSegment(B,p,g))<G&&(G=Y,F=B),F}}])})(Kn),vF=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"countSegment",value:function(u,p){if(u.x<this._p.x&&p.x<this._p.x)return null;if(this._p.x===p.x&&this._p.y===p.y)return this._isPointOnSegment=!0,null;if(u.y===this._p.y&&p.y===this._p.y){var g=u.x,E=p.x;return g>E&&(g=p.x,E=u.x),this._p.x>=g&&this._p.x<=E&&(this._isPointOnSegment=!0),null}if(u.y>this._p.y&&p.y<=this._p.y||p.y>this._p.y&&u.y<=this._p.y){var B=be.index(u,p,this._p);if(B===be.COLLINEAR)return this._isPointOnSegment=!0,null;p.y<u.y&&(B=-B),B===be.LEFT&&this._crossingCount++}}},{key:"isPointInPolygon",value:function(){return this.getLocation()!==$.EXTERIOR}},{key:"getLocation",value:function(){return this._isPointOnSegment?$.BOUNDARY:this._crossingCount%2==1?$.INTERIOR:$.EXTERIOR}},{key:"isOnSegment",value:function(){return this._isPointOnSegment}}],[{key:"constructor_",value:function(){this._p=null,this._crossingCount=0,this._isPointOnSegment=!1;var u=arguments[0];this._p=u}},{key:"locatePointInRing",value:function(){if(arguments[0]instanceof ie&&X(arguments[1],_e)){for(var u=arguments[1],p=new _(arguments[0]),g=new ie,E=new ie,B=1;B<u.size();B++)if(u.getCoordinate(B,g),u.getCoordinate(B-1,E),p.countSegment(g,E),p.isOnSegment())return p.getLocation();return p.getLocation()}if(arguments[0]instanceof ie&&arguments[1]instanceof Array){for(var F=arguments[1],G=new _(arguments[0]),Y=1;Y<F.length;Y++){var ae=F[Y],xe=F[Y-1];if(G.countSegment(ae,xe),G.isOnSegment())return G.getLocation()}return G.getLocation()}}}])})(),rv=(function(){function _(){s(this,_)}return o(_,null,[{key:"isOnLine",value:function(){if(arguments[0]instanceof ie&&X(arguments[1],_e)){for(var u=arguments[0],p=arguments[1],g=new ql,E=new ie,B=new ie,F=p.size(),G=1;G<F;G++)if(p.getCoordinate(G-1,E),p.getCoordinate(G,B),g.computeIntersection(u,E,B),g.hasIntersection())return!0;return!1}if(arguments[0]instanceof ie&&arguments[1]instanceof Array){for(var Y=arguments[0],ae=arguments[1],xe=new ql,Ie=1;Ie<ae.length;Ie++){var Ge=ae[Ie-1],ut=ae[Ie];if(xe.computeIntersection(Y,Ge,ut),xe.hasIntersection())return!0}return!1}}},{key:"locateInRing",value:function(u,p){return vF.locatePointInRing(u,p)}},{key:"isInRing",value:function(u,p){return _.locateInRing(u,p)!==$.EXTERIOR}}])})(),wr=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"setAllLocations",value:function(u){for(var p=0;p<this.location.length;p++)this.location[p]=u}},{key:"isNull",value:function(){for(var u=0;u<this.location.length;u++)if(this.location[u]!==$.NONE)return!1;return!0}},{key:"setAllLocationsIfNull",value:function(u){for(var p=0;p<this.location.length;p++)this.location[p]===$.NONE&&(this.location[p]=u)}},{key:"isLine",value:function(){return this.location.length===1}},{key:"merge",value:function(u){if(u.location.length>this.location.length){var p=new Array(3).fill(null);p[q.ON]=this.location[q.ON],p[q.LEFT]=$.NONE,p[q.RIGHT]=$.NONE,this.location=p}for(var g=0;g<this.location.length;g++)this.location[g]===$.NONE&&g<u.location.length&&(this.location[g]=u.location[g])}},{key:"getLocations",value:function(){return this.location}},{key:"flip",value:function(){if(this.location.length<=1)return null;var u=this.location[q.LEFT];this.location[q.LEFT]=this.location[q.RIGHT],this.location[q.RIGHT]=u}},{key:"toString",value:function(){var u=new V;return this.location.length>1&&u.append($.toLocationSymbol(this.location[q.LEFT])),u.append($.toLocationSymbol(this.location[q.ON])),this.location.length>1&&u.append($.toLocationSymbol(this.location[q.RIGHT])),u.toString()}},{key:"setLocations",value:function(u,p,g){this.location[q.ON]=u,this.location[q.LEFT]=p,this.location[q.RIGHT]=g}},{key:"get",value:function(u){return u<this.location.length?this.location[u]:$.NONE}},{key:"isArea",value:function(){return this.location.length>1}},{key:"isAnyNull",value:function(){for(var u=0;u<this.location.length;u++)if(this.location[u]===$.NONE)return!0;return!1}},{key:"setLocation",value:function(){if(arguments.length===1){var u=arguments[0];this.setLocation(q.ON,u)}else if(arguments.length===2){var p=arguments[0],g=arguments[1];this.location[p]=g}}},{key:"init",value:function(u){this.location=new Array(u).fill(null),this.setAllLocations($.NONE)}},{key:"isEqualOnSide",value:function(u,p){return this.location[p]===u.location[p]}},{key:"allPositionsEqual",value:function(u){for(var p=0;p<this.location.length;p++)if(this.location[p]!==u)return!1;return!0}}],[{key:"constructor_",value:function(){if(this.location=null,arguments.length===1){if(arguments[0]instanceof Array){var u=arguments[0];this.init(u.length)}else if(Number.isInteger(arguments[0])){var p=arguments[0];this.init(1),this.location[q.ON]=p}else if(arguments[0]instanceof _){var g=arguments[0];if(this.init(g.location.length),g!==null)for(var E=0;E<this.location.length;E++)this.location[E]=g.location[E]}}else if(arguments.length===3){var B=arguments[0],F=arguments[1],G=arguments[2];this.init(3),this.location[q.ON]=B,this.location[q.LEFT]=F,this.location[q.RIGHT]=G}}}])})(),Sr=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"getGeometryCount",value:function(){var u=0;return this.elt[0].isNull()||u++,this.elt[1].isNull()||u++,u}},{key:"setAllLocations",value:function(u,p){this.elt[u].setAllLocations(p)}},{key:"isNull",value:function(u){return this.elt[u].isNull()}},{key:"setAllLocationsIfNull",value:function(){if(arguments.length===1){var u=arguments[0];this.setAllLocationsIfNull(0,u),this.setAllLocationsIfNull(1,u)}else if(arguments.length===2){var p=arguments[0],g=arguments[1];this.elt[p].setAllLocationsIfNull(g)}}},{key:"isLine",value:function(u){return this.elt[u].isLine()}},{key:"merge",value:function(u){for(var p=0;p<2;p++)this.elt[p]===null&&u.elt[p]!==null?this.elt[p]=new wr(u.elt[p]):this.elt[p].merge(u.elt[p])}},{key:"flip",value:function(){this.elt[0].flip(),this.elt[1].flip()}},{key:"getLocation",value:function(){if(arguments.length===1){var u=arguments[0];return this.elt[u].get(q.ON)}if(arguments.length===2){var p=arguments[0],g=arguments[1];return this.elt[p].get(g)}}},{key:"toString",value:function(){var u=new V;return this.elt[0]!==null&&(u.append("A:"),u.append(this.elt[0].toString())),this.elt[1]!==null&&(u.append(" B:"),u.append(this.elt[1].toString())),u.toString()}},{key:"isArea",value:function(){if(arguments.length===0)return this.elt[0].isArea()||this.elt[1].isArea();if(arguments.length===1){var u=arguments[0];return this.elt[u].isArea()}}},{key:"isAnyNull",value:function(u){return this.elt[u].isAnyNull()}},{key:"setLocation",value:function(){if(arguments.length===2){var u=arguments[0],p=arguments[1];this.elt[u].setLocation(q.ON,p)}else if(arguments.length===3){var g=arguments[0],E=arguments[1],B=arguments[2];this.elt[g].setLocation(E,B)}}},{key:"isEqualOnSide",value:function(u,p){return this.elt[0].isEqualOnSide(u.elt[0],p)&&this.elt[1].isEqualOnSide(u.elt[1],p)}},{key:"allPositionsEqual",value:function(u,p){return this.elt[u].allPositionsEqual(p)}},{key:"toLine",value:function(u){this.elt[u].isArea()&&(this.elt[u]=new wr(this.elt[u].location[0]))}}],[{key:"constructor_",value:function(){if(this.elt=new Array(2).fill(null),arguments.length===1){if(Number.isInteger(arguments[0])){var u=arguments[0];this.elt[0]=new wr(u),this.elt[1]=new wr(u)}else if(arguments[0]instanceof _){var p=arguments[0];this.elt[0]=new wr(p.elt[0]),this.elt[1]=new wr(p.elt[1])}}else if(arguments.length===2){var g=arguments[0],E=arguments[1];this.elt[0]=new wr($.NONE),this.elt[1]=new wr($.NONE),this.elt[g].setLocation(E)}else if(arguments.length===3){var B=arguments[0],F=arguments[1],G=arguments[2];this.elt[0]=new wr(B,F,G),this.elt[1]=new wr(B,F,G)}else if(arguments.length===4){var Y=arguments[0],ae=arguments[1],xe=arguments[2],Ie=arguments[3];this.elt[0]=new wr($.NONE,$.NONE,$.NONE),this.elt[1]=new wr($.NONE,$.NONE,$.NONE),this.elt[Y].setLocations(ae,xe,Ie)}}},{key:"toLineLabel",value:function(u){for(var p=new _($.NONE),g=0;g<2;g++)p.setLocation(g,u.getLocation(g));return p}}])})(),$f=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"computeRing",value:function(){if(this._ring!==null)return null;for(var _=new Array(this._pts.size()).fill(null),u=0;u<this._pts.size();u++)_[u]=this._pts.get(u);this._ring=this._geometryFactory.createLinearRing(_),this._isHole=be.isCCW(this._ring.getCoordinates())}},{key:"isIsolated",value:function(){return this._label.getGeometryCount()===1}},{key:"computePoints",value:function(_){this._startDe=_;var u=_,p=!0;do{if(u===null)throw new Ye("Found null DirectedEdge");if(u.getEdgeRing()===this)throw new Ye("Directed Edge visited twice during ring-building at "+u.getCoordinate());this._edges.add(u);var g=u.getLabel();re.isTrue(g.isArea()),this.mergeLabel(g),this.addPoints(u.getEdge(),u.isForward(),p),p=!1,this.setEdgeRing(u,this),u=this.getNext(u)}while(u!==this._startDe)}},{key:"getLinearRing",value:function(){return this._ring}},{key:"getCoordinate",value:function(_){return this._pts.get(_)}},{key:"computeMaxNodeDegree",value:function(){this._maxNodeDegree=0;var _=this._startDe;do{var u=_.getNode().getEdges().getOutgoingDegree(this);u>this._maxNodeDegree&&(this._maxNodeDegree=u),_=this.getNext(_)}while(_!==this._startDe);this._maxNodeDegree*=2}},{key:"addPoints",value:function(_,u,p){var g=_.getCoordinates();if(u){var E=1;p&&(E=0);for(var B=E;B<g.length;B++)this._pts.add(g[B])}else{var F=g.length-2;p&&(F=g.length-1);for(var G=F;G>=0;G--)this._pts.add(g[G])}}},{key:"isHole",value:function(){return this._isHole}},{key:"setInResult",value:function(){var _=this._startDe;do _.getEdge().setInResult(!0),_=_.getNext();while(_!==this._startDe)}},{key:"containsPoint",value:function(_){var u=this.getLinearRing();if(!u.getEnvelopeInternal().contains(_)||!rv.isInRing(_,u.getCoordinates()))return!1;for(var p=this._holes.iterator();p.hasNext();)if(p.next().containsPoint(_))return!1;return!0}},{key:"addHole",value:function(_){this._holes.add(_)}},{key:"isShell",value:function(){return this._shell===null}},{key:"getLabel",value:function(){return this._label}},{key:"getEdges",value:function(){return this._edges}},{key:"getMaxNodeDegree",value:function(){return this._maxNodeDegree<0&&this.computeMaxNodeDegree(),this._maxNodeDegree}},{key:"getShell",value:function(){return this._shell}},{key:"mergeLabel",value:function(){if(arguments.length===1){var _=arguments[0];this.mergeLabel(_,0),this.mergeLabel(_,1)}else if(arguments.length===2){var u=arguments[1],p=arguments[0].getLocation(u,q.RIGHT);if(p===$.NONE)return null;if(this._label.getLocation(u)===$.NONE)return this._label.setLocation(u,p),null}}},{key:"setShell",value:function(_){this._shell=_,_!==null&&_.addHole(this)}},{key:"toPolygon",value:function(_){for(var u=new Array(this._holes.size()).fill(null),p=0;p<this._holes.size();p++)u[p]=this._holes.get(p).getLinearRing();return _.createPolygon(this.getLinearRing(),u)}}],[{key:"constructor_",value:function(){if(this._startDe=null,this._maxNodeDegree=-1,this._edges=new Pe,this._pts=new Pe,this._label=new Sr($.NONE),this._ring=null,this._isHole=null,this._shell=null,this._holes=new Pe,this._geometryFactory=null,arguments.length!==0){if(arguments.length===2){var _=arguments[0],u=arguments[1];this._geometryFactory=u,this.computePoints(_),this.computeRing()}}}}])})(),yF=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,[{key:"setEdgeRing",value:function(p,g){p.setMinEdgeRing(g)}},{key:"getNext",value:function(p){return p.getNextMin()}}],[{key:"constructor_",value:function(){var p=arguments[0],g=arguments[1];$f.constructor_.call(this,p,g)}}])})($f),bF=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,[{key:"buildMinimalRings",value:function(){var p=new Pe,g=this._startDe;do{if(g.getMinEdgeRing()===null){var E=new yF(g,this._geometryFactory);p.add(E)}g=g.getNext()}while(g!==this._startDe);return p}},{key:"setEdgeRing",value:function(p,g){p.setEdgeRing(g)}},{key:"linkDirectedEdgesForMinimalEdgeRings",value:function(){var p=this._startDe;do p.getNode().getEdges().linkMinimalDirectedEdges(this),p=p.getNext();while(p!==this._startDe)}},{key:"getNext",value:function(p){return p.getNext()}}],[{key:"constructor_",value:function(){var p=arguments[0],g=arguments[1];$f.constructor_.call(this,p,g)}}])})($f),hw=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"setVisited",value:function(_){this._isVisited=_}},{key:"setInResult",value:function(_){this._isInResult=_}},{key:"isCovered",value:function(){return this._isCovered}},{key:"isCoveredSet",value:function(){return this._isCoveredSet}},{key:"setLabel",value:function(_){this._label=_}},{key:"getLabel",value:function(){return this._label}},{key:"setCovered",value:function(_){this._isCovered=_,this._isCoveredSet=!0}},{key:"updateIM",value:function(_){re.isTrue(this._label.getGeometryCount()>=2,"found partial label"),this.computeIM(_)}},{key:"isInResult",value:function(){return this._isInResult}},{key:"isVisited",value:function(){return this._isVisited}}],[{key:"constructor_",value:function(){if(this._label=null,this._isInResult=!1,this._isCovered=!1,this._isCoveredSet=!1,this._isVisited=!1,arguments.length!==0){if(arguments.length===1){var _=arguments[0];this._label=_}}}}])})(),Vf=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,[{key:"isIncidentEdgeInResult",value:function(){for(var p=this.getEdges().getEdges().iterator();p.hasNext();)if(p.next().getEdge().isInResult())return!0;return!1}},{key:"isIsolated",value:function(){return this._label.getGeometryCount()===1}},{key:"getCoordinate",value:function(){return this._coord}},{key:"print",value:function(p){p.println("node "+this._coord+" lbl: "+this._label)}},{key:"computeIM",value:function(p){}},{key:"computeMergedLocation",value:function(p,g){var E=$.NONE;if(E=this._label.getLocation(g),!p.isNull(g)){var B=p.getLocation(g);E!==$.BOUNDARY&&(E=B)}return E}},{key:"setLabel",value:function(){if(arguments.length!==2||!Number.isInteger(arguments[1])||!Number.isInteger(arguments[0]))return A(u,"setLabel",this,1).apply(this,arguments);var p=arguments[0],g=arguments[1];this._label===null?this._label=new Sr(p,g):this._label.setLocation(p,g)}},{key:"getEdges",value:function(){return this._edges}},{key:"mergeLabel",value:function(){if(arguments[0]instanceof u){var p=arguments[0];this.mergeLabel(p._label)}else if(arguments[0]instanceof Sr)for(var g=arguments[0],E=0;E<2;E++){var B=this.computeMergedLocation(g,E);this._label.getLocation(E)===$.NONE&&this._label.setLocation(E,B)}}},{key:"add",value:function(p){this._edges.insert(p),p.setNode(this)}},{key:"setLabelBoundary",value:function(p){if(this._label===null)return null;var g=$.NONE;this._label!==null&&(g=this._label.getLocation(p));var E=null;switch(g){case $.BOUNDARY:E=$.INTERIOR;break;case $.INTERIOR:default:E=$.BOUNDARY}this._label.setLocation(p,E)}}],[{key:"constructor_",value:function(){this._coord=null,this._edges=null;var p=arguments[0],g=arguments[1];this._coord=p,this._edges=g,this._label=new Sr(0,$.NONE)}}])})(hw),xF=(function(_){function u(){return s(this,u),i(this,u,arguments)}return d(u,_),o(u)})(lt);function uw(_){return _==null?0:_.color}function An(_){return _==null?null:_.parent}function xa(_,u){_!==null&&(_.color=u)}function av(_){return _==null?null:_.left}function dw(_){return _==null?null:_.right}var cd=(function(_){function u(){var p;return s(this,u),(p=i(this,u)).root_=null,p.size_=0,p}return d(u,_),o(u,[{key:"get",value:function(p){for(var g=this.root_;g!==null;){var E=p.compareTo(g.key);if(E<0)g=g.left;else{if(!(E>0))return g.value;g=g.right}}return null}},{key:"put",value:function(p,g){if(this.root_===null)return this.root_={key:p,value:g,left:null,right:null,parent:null,color:0,getValue:function(){return this.value},getKey:function(){return this.key}},this.size_=1,null;var E,B,F=this.root_;do if(E=F,(B=p.compareTo(F.key))<0)F=F.left;else{if(!(B>0)){var G=F.value;return F.value=g,G}F=F.right}while(F!==null);var Y={key:p,left:null,right:null,value:g,parent:E,color:0,getValue:function(){return this.value},getKey:function(){return this.key}};return B<0?E.left=Y:E.right=Y,this.fixAfterInsertion(Y),this.size_++,null}},{key:"fixAfterInsertion",value:function(p){var g;for(p.color=1;p!=null&&p!==this.root_&&p.parent.color===1;)An(p)===av(An(An(p)))?uw(g=dw(An(An(p))))===1?(xa(An(p),0),xa(g,0),xa(An(An(p)),1),p=An(An(p))):(p===dw(An(p))&&(p=An(p),this.rotateLeft(p)),xa(An(p),0),xa(An(An(p)),1),this.rotateRight(An(An(p)))):uw(g=av(An(An(p))))===1?(xa(An(p),0),xa(g,0),xa(An(An(p)),1),p=An(An(p))):(p===av(An(p))&&(p=An(p),this.rotateRight(p)),xa(An(p),0),xa(An(An(p)),1),this.rotateLeft(An(An(p))));this.root_.color=0}},{key:"values",value:function(){var p=new Pe,g=this.getFirstEntry();if(g!==null)for(p.add(g.value);(g=u.successor(g))!==null;)p.add(g.value);return p}},{key:"entrySet",value:function(){var p=new et,g=this.getFirstEntry();if(g!==null)for(p.add(g);(g=u.successor(g))!==null;)p.add(g);return p}},{key:"rotateLeft",value:function(p){if(p!=null){var g=p.right;p.right=g.left,g.left!=null&&(g.left.parent=p),g.parent=p.parent,p.parent==null?this.root_=g:p.parent.left===p?p.parent.left=g:p.parent.right=g,g.left=p,p.parent=g}}},{key:"rotateRight",value:function(p){if(p!=null){var g=p.left;p.left=g.right,g.right!=null&&(g.right.parent=p),g.parent=p.parent,p.parent==null?this.root_=g:p.parent.right===p?p.parent.right=g:p.parent.left=g,g.right=p,p.parent=g}}},{key:"getFirstEntry",value:function(){var p=this.root_;if(p!=null)for(;p.left!=null;)p=p.left;return p}},{key:"size",value:function(){return this.size_}},{key:"containsKey",value:function(p){for(var g=this.root_;g!==null;){var E=p.compareTo(g.key);if(E<0)g=g.left;else{if(!(E>0))return!0;g=g.right}}return!1}}],[{key:"successor",value:function(p){var g;if(p===null)return null;if(p.right!==null){for(g=p.right;g.left!==null;)g=g.left;return g}g=p.parent;for(var E=p;g!==null&&E===g.right;)E=g,g=g.parent;return g}}])})(xF),pw=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"find",value:function(_){return this.nodeMap.get(_)}},{key:"addNode",value:function(){if(arguments[0]instanceof ie){var _=arguments[0],u=this.nodeMap.get(_);return u===null&&(u=this.nodeFact.createNode(_),this.nodeMap.put(_,u)),u}if(arguments[0]instanceof Vf){var p=arguments[0],g=this.nodeMap.get(p.getCoordinate());return g===null?(this.nodeMap.put(p.getCoordinate(),p),p):(g.mergeLabel(p),g)}}},{key:"print",value:function(_){for(var u=this.iterator();u.hasNext();)u.next().print(_)}},{key:"iterator",value:function(){return this.nodeMap.values().iterator()}},{key:"values",value:function(){return this.nodeMap.values()}},{key:"getBoundaryNodes",value:function(_){for(var u=new Pe,p=this.iterator();p.hasNext();){var g=p.next();g.getLabel().getLocation(_)===$.BOUNDARY&&u.add(g)}return u}},{key:"add",value:function(_){var u=_.getCoordinate();this.addNode(u).add(_)}}],[{key:"constructor_",value:function(){this.nodeMap=new cd,this.nodeFact=null;var _=arguments[0];this.nodeFact=_}}])})(),Ts=(function(){function _(){s(this,_)}return o(_,null,[{key:"isNorthern",value:function(u){return u===_.NE||u===_.NW}},{key:"isOpposite",value:function(u,p){return u!==p&&(u-p+4)%4===2}},{key:"commonHalfPlane",value:function(u,p){if(u===p)return u;if((u-p+4)%4===2)return-1;var g=u<p?u:p;return g===0&&(u>p?u:p)===3?3:g}},{key:"isInHalfPlane",value:function(u,p){return p===_.SE?u===_.SE||u===_.SW:u===p||u===p+1}},{key:"quadrant",value:function(){if(typeof arguments[0]=="number"&&typeof arguments[1]=="number"){var u=arguments[0],p=arguments[1];if(u===0&&p===0)throw new R("Cannot compute the quadrant for point ( "+u+", "+p+" )");return u>=0?p>=0?_.NE:_.SE:p>=0?_.NW:_.SW}if(arguments[0]instanceof ie&&arguments[1]instanceof ie){var g=arguments[0],E=arguments[1];if(E.x===g.x&&E.y===g.y)throw new R("Cannot compute the quadrant for two identical points "+g);return E.x>=g.x?E.y>=g.y?_.NE:_.SE:E.y>=g.y?_.NW:_.SW}}}])})();Ts.NE=0,Ts.NW=1,Ts.SW=2,Ts.SE=3;var fw=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"compareDirection",value:function(u){return this._dx===u._dx&&this._dy===u._dy?0:this._quadrant>u._quadrant?1:this._quadrant<u._quadrant?-1:be.index(u._p0,u._p1,this._p1)}},{key:"getDy",value:function(){return this._dy}},{key:"getCoordinate",value:function(){return this._p0}},{key:"setNode",value:function(u){this._node=u}},{key:"print",value:function(u){var p=Math.atan2(this._dy,this._dx),g=this.getClass().getName(),E=g.lastIndexOf("."),B=g.substring(E+1);u.print(" "+B+": "+this._p0+" - "+this._p1+" "+this._quadrant+":"+p+" "+this._label)}},{key:"compareTo",value:function(u){var p=u;return this.compareDirection(p)}},{key:"getDirectedCoordinate",value:function(){return this._p1}},{key:"getDx",value:function(){return this._dx}},{key:"getLabel",value:function(){return this._label}},{key:"getEdge",value:function(){return this._edge}},{key:"getQuadrant",value:function(){return this._quadrant}},{key:"getNode",value:function(){return this._node}},{key:"toString",value:function(){var u=Math.atan2(this._dy,this._dx),p=this.getClass().getName(),g=p.lastIndexOf(".");return" "+p.substring(g+1)+": "+this._p0+" - "+this._p1+" "+this._quadrant+":"+u+" "+this._label}},{key:"computeLabel",value:function(u){}},{key:"init",value:function(u,p){this._p0=u,this._p1=p,this._dx=p.x-u.x,this._dy=p.y-u.y,this._quadrant=Ts.quadrant(this._dx,this._dy),re.isTrue(!(this._dx===0&&this._dy===0),"EdgeEnd with identical endpoints found")}},{key:"interfaces_",get:function(){return[L]}}],[{key:"constructor_",value:function(){if(this._edge=null,this._label=null,this._node=null,this._p0=null,this._p1=null,this._dx=null,this._dy=null,this._quadrant=null,arguments.length===1){var u=arguments[0];this._edge=u}else if(arguments.length===3){var p=arguments[0],g=arguments[1],E=arguments[2];_.constructor_.call(this,p,g,E,null)}else if(arguments.length===4){var B=arguments[0],F=arguments[1],G=arguments[2],Y=arguments[3];_.constructor_.call(this,B),this.init(F,G),this._label=Y}}}])})(),ov=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,[{key:"getNextMin",value:function(){return this._nextMin}},{key:"getDepth",value:function(p){return this._depth[p]}},{key:"setVisited",value:function(p){this._isVisited=p}},{key:"computeDirectedLabel",value:function(){this._label=new Sr(this._edge.getLabel()),this._isForward||this._label.flip()}},{key:"getNext",value:function(){return this._next}},{key:"setDepth",value:function(p,g){if(this._depth[p]!==-999&&this._depth[p]!==g)throw new Ye("assigned depths do not match",this.getCoordinate());this._depth[p]=g}},{key:"isInteriorAreaEdge",value:function(){for(var p=!0,g=0;g<2;g++)this._label.isArea(g)&&this._label.getLocation(g,q.LEFT)===$.INTERIOR&&this._label.getLocation(g,q.RIGHT)===$.INTERIOR||(p=!1);return p}},{key:"setNextMin",value:function(p){this._nextMin=p}},{key:"print",value:function(p){A(u,"print",this,1).call(this,p),p.print(" "+this._depth[q.LEFT]+"/"+this._depth[q.RIGHT]),p.print(" ("+this.getDepthDelta()+")"),this._isInResult&&p.print(" inResult")}},{key:"setMinEdgeRing",value:function(p){this._minEdgeRing=p}},{key:"isLineEdge",value:function(){var p=this._label.isLine(0)||this._label.isLine(1),g=!this._label.isArea(0)||this._label.allPositionsEqual(0,$.EXTERIOR),E=!this._label.isArea(1)||this._label.allPositionsEqual(1,$.EXTERIOR);return p&&g&&E}},{key:"setEdgeRing",value:function(p){this._edgeRing=p}},{key:"getMinEdgeRing",value:function(){return this._minEdgeRing}},{key:"getDepthDelta",value:function(){var p=this._edge.getDepthDelta();return this._isForward||(p=-p),p}},{key:"setInResult",value:function(p){this._isInResult=p}},{key:"getSym",value:function(){return this._sym}},{key:"isForward",value:function(){return this._isForward}},{key:"getEdge",value:function(){return this._edge}},{key:"printEdge",value:function(p){this.print(p),p.print(" "),this._isForward?this._edge.print(p):this._edge.printReverse(p)}},{key:"setSym",value:function(p){this._sym=p}},{key:"setVisitedEdge",value:function(p){this.setVisited(p),this._sym.setVisited(p)}},{key:"setEdgeDepths",value:function(p,g){var E=this.getEdge().getDepthDelta();this._isForward||(E=-E);var B=1;p===q.LEFT&&(B=-1);var F=q.opposite(p),G=g+E*B;this.setDepth(p,g),this.setDepth(F,G)}},{key:"getEdgeRing",value:function(){return this._edgeRing}},{key:"isInResult",value:function(){return this._isInResult}},{key:"setNext",value:function(p){this._next=p}},{key:"isVisited",value:function(){return this._isVisited}}],[{key:"constructor_",value:function(){this._isForward=null,this._isInResult=!1,this._isVisited=!1,this._sym=null,this._next=null,this._nextMin=null,this._edgeRing=null,this._minEdgeRing=null,this._depth=[0,-999,-999];var p=arguments[0],g=arguments[1];if(fw.constructor_.call(this,p),this._isForward=g,g)this.init(p.getCoordinate(0),p.getCoordinate(1));else{var E=p.getNumPoints()-1;this.init(p.getCoordinate(E),p.getCoordinate(E-1))}this.computeDirectedLabel()}},{key:"depthFactor",value:function(p,g){return p===$.EXTERIOR&&g===$.INTERIOR?1:p===$.INTERIOR&&g===$.EXTERIOR?-1:0}}])})(fw),mw=(function(){return o((function _(){s(this,_)}),[{key:"createNode",value:function(_){return new Vf(_,null)}}])})(),gw=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"printEdges",value:function(_){_.println("Edges:");for(var u=0;u<this._edges.size();u++){_.println("edge "+u+":");var p=this._edges.get(u);p.print(_),p.eiList.print(_)}}},{key:"find",value:function(_){return this._nodes.find(_)}},{key:"addNode",value:function(){if(arguments[0]instanceof Vf){var _=arguments[0];return this._nodes.addNode(_)}if(arguments[0]instanceof ie){var u=arguments[0];return this._nodes.addNode(u)}}},{key:"getNodeIterator",value:function(){return this._nodes.iterator()}},{key:"linkResultDirectedEdges",value:function(){for(var _=this._nodes.iterator();_.hasNext();)_.next().getEdges().linkResultDirectedEdges()}},{key:"debugPrintln",value:function(_){xt.out.println(_)}},{key:"isBoundaryNode",value:function(_,u){var p=this._nodes.find(u);if(p===null)return!1;var g=p.getLabel();return g!==null&&g.getLocation(_)===$.BOUNDARY}},{key:"linkAllDirectedEdges",value:function(){for(var _=this._nodes.iterator();_.hasNext();)_.next().getEdges().linkAllDirectedEdges()}},{key:"matchInSameDirection",value:function(_,u,p,g){return!!_.equals(p)&&be.index(_,u,g)===be.COLLINEAR&&Ts.quadrant(_,u)===Ts.quadrant(p,g)}},{key:"getEdgeEnds",value:function(){return this._edgeEndList}},{key:"debugPrint",value:function(_){xt.out.print(_)}},{key:"getEdgeIterator",value:function(){return this._edges.iterator()}},{key:"findEdgeInSameDirection",value:function(_,u){for(var p=0;p<this._edges.size();p++){var g=this._edges.get(p),E=g.getCoordinates();if(this.matchInSameDirection(_,u,E[0],E[1])||this.matchInSameDirection(_,u,E[E.length-1],E[E.length-2]))return g}return null}},{key:"insertEdge",value:function(_){this._edges.add(_)}},{key:"findEdgeEnd",value:function(_){for(var u=this.getEdgeEnds().iterator();u.hasNext();){var p=u.next();if(p.getEdge()===_)return p}return null}},{key:"addEdges",value:function(_){for(var u=_.iterator();u.hasNext();){var p=u.next();this._edges.add(p);var g=new ov(p,!0),E=new ov(p,!1);g.setSym(E),E.setSym(g),this.add(g),this.add(E)}}},{key:"add",value:function(_){this._nodes.add(_),this._edgeEndList.add(_)}},{key:"getNodes",value:function(){return this._nodes.values()}},{key:"findEdge",value:function(_,u){for(var p=0;p<this._edges.size();p++){var g=this._edges.get(p),E=g.getCoordinates();if(_.equals(E[0])&&u.equals(E[1]))return g}return null}}],[{key:"constructor_",value:function(){if(this._edges=new Pe,this._nodes=null,this._edgeEndList=new Pe,arguments.length===0)this._nodes=new pw(new mw);else if(arguments.length===1){var _=arguments[0];this._nodes=new pw(_)}}},{key:"linkResultDirectedEdges",value:function(_){for(var u=_.iterator();u.hasNext();)u.next().getEdges().linkResultDirectedEdges()}}])})(),EF=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"sortShellsAndHoles",value:function(u,p,g){for(var E=u.iterator();E.hasNext();){var B=E.next();B.isHole()?g.add(B):p.add(B)}}},{key:"computePolygons",value:function(u){for(var p=new Pe,g=u.iterator();g.hasNext();){var E=g.next().toPolygon(this._geometryFactory);p.add(E)}return p}},{key:"placeFreeHoles",value:function(u,p){for(var g=p.iterator();g.hasNext();){var E=g.next();if(E.getShell()===null){var B=_.findEdgeRingContaining(E,u);if(B===null)throw new Ye("unable to assign hole to a shell",E.getCoordinate(0));E.setShell(B)}}}},{key:"buildMinimalEdgeRings",value:function(u,p,g){for(var E=new Pe,B=u.iterator();B.hasNext();){var F=B.next();if(F.getMaxNodeDegree()>2){F.linkDirectedEdgesForMinimalEdgeRings();var G=F.buildMinimalRings(),Y=this.findShell(G);Y!==null?(this.placePolygonHoles(Y,G),p.add(Y)):g.addAll(G)}else E.add(F)}return E}},{key:"buildMaximalEdgeRings",value:function(u){for(var p=new Pe,g=u.iterator();g.hasNext();){var E=g.next();if(E.isInResult()&&E.getLabel().isArea()&&E.getEdgeRing()===null){var B=new bF(E,this._geometryFactory);p.add(B),B.setInResult()}}return p}},{key:"placePolygonHoles",value:function(u,p){for(var g=p.iterator();g.hasNext();){var E=g.next();E.isHole()&&E.setShell(u)}}},{key:"getPolygons",value:function(){return this.computePolygons(this._shellList)}},{key:"findShell",value:function(u){for(var p=0,g=null,E=u.iterator();E.hasNext();){var B=E.next();B.isHole()||(g=B,p++)}return re.isTrue(p<=1,"found two shells in MinimalEdgeRing list"),g}},{key:"add",value:function(){if(arguments.length===1){var u=arguments[0];this.add(u.getEdgeEnds(),u.getNodes())}else if(arguments.length===2){var p=arguments[0],g=arguments[1];gw.linkResultDirectedEdges(g);var E=this.buildMaximalEdgeRings(p),B=new Pe,F=this.buildMinimalEdgeRings(E,this._shellList,B);this.sortShellsAndHoles(F,this._shellList,B),this.placeFreeHoles(this._shellList,B)}}}],[{key:"constructor_",value:function(){this._geometryFactory=null,this._shellList=new Pe;var u=arguments[0];this._geometryFactory=u}},{key:"findEdgeRingContaining",value:function(u,p){for(var g=u.getLinearRing(),E=g.getEnvelopeInternal(),B=g.getCoordinateN(0),F=null,G=null,Y=p.iterator();Y.hasNext();){var ae=Y.next(),xe=ae.getLinearRing(),Ie=xe.getEnvelopeInternal();if(!Ie.equals(E)&&Ie.contains(E)){B=In.ptNotInList(g.getCoordinates(),xe.getCoordinates());var Ge=!1;rv.isInRing(B,xe.getCoordinates())&&(Ge=!0),Ge&&(F===null||G.contains(Ie))&&(G=(F=ae).getLinearRing().getEnvelopeInternal())}}return F}}])})(),_w=(function(){return o((function _(){s(this,_)}),[{key:"getBounds",value:function(){}}])})(),no=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"getItem",value:function(){return this._item}},{key:"getBounds",value:function(){return this._bounds}},{key:"interfaces_",get:function(){return[_w,C]}}],[{key:"constructor_",value:function(){this._bounds=null,this._item=null;var _=arguments[0],u=arguments[1];this._bounds=_,this._item=u}}])})(),qf=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"poll",value:function(){if(this.isEmpty())return null;var _=this._items.get(1);return this._items.set(1,this._items.get(this._size)),this._size-=1,this.reorder(1),_}},{key:"size",value:function(){return this._size}},{key:"reorder",value:function(_){for(var u=null,p=this._items.get(_);2*_<=this._size&&((u=2*_)!==this._size&&this._items.get(u+1).compareTo(this._items.get(u))<0&&u++,this._items.get(u).compareTo(p)<0);_=u)this._items.set(_,this._items.get(u));this._items.set(_,p)}},{key:"clear",value:function(){this._size=0,this._items.clear()}},{key:"peek",value:function(){return this.isEmpty()?null:this._items.get(1)}},{key:"isEmpty",value:function(){return this._size===0}},{key:"add",value:function(_){this._items.add(null),this._size+=1;var u=this._size;for(this._items.set(0,_);_.compareTo(this._items.get(Math.trunc(u/2)))<0;u/=2)this._items.set(u,this._items.get(Math.trunc(u/2)));this._items.set(u,_)}}],[{key:"constructor_",value:function(){this._size=null,this._items=null,this._size=0,this._items=new Pe,this._items.add(null)}}])})(),CF=(function(){return o((function _(){s(this,_)}),[{key:"insert",value:function(_,u){}},{key:"remove",value:function(_,u){}},{key:"query",value:function(){}}])})(),Ir=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"getLevel",value:function(){return this._level}},{key:"size",value:function(){return this._childBoundables.size()}},{key:"getChildBoundables",value:function(){return this._childBoundables}},{key:"addChildBoundable",value:function(_){re.isTrue(this._bounds===null),this._childBoundables.add(_)}},{key:"isEmpty",value:function(){return this._childBoundables.isEmpty()}},{key:"getBounds",value:function(){return this._bounds===null&&(this._bounds=this.computeBounds()),this._bounds}},{key:"interfaces_",get:function(){return[_w,C]}}],[{key:"constructor_",value:function(){if(this._childBoundables=new Pe,this._bounds=null,this._level=null,arguments.length!==0){if(arguments.length===1){var _=arguments[0];this._level=_}}}}])})(),Zc={reverseOrder:function(){return{compare:function(_,u){return u.compareTo(_)}}},min:function(_){return Zc.sort(_),_.get(0)},sort:function(_,u){var p=_.toArray();u?le.sort(p,u):le.sort(p);for(var g=_.iterator(),E=0,B=p.length;E<B;E++)g.next(),g.set(p[E])},singletonList:function(_){var u=new Pe;return u.add(_),u}},wF=(function(){function _(){s(this,_)}return o(_,null,[{key:"maxDistance",value:function(u,p,g,E,B,F,G,Y){var ae=_.distance(u,p,B,F);return ae=Math.max(ae,_.distance(u,p,G,Y)),ae=Math.max(ae,_.distance(g,E,B,F)),ae=Math.max(ae,_.distance(g,E,G,Y))}},{key:"distance",value:function(u,p,g,E){var B=g-u,F=E-p;return Math.sqrt(B*B+F*F)}},{key:"maximumDistance",value:function(u,p){var g=Math.min(u.getMinX(),p.getMinX()),E=Math.min(u.getMinY(),p.getMinY()),B=Math.max(u.getMaxX(),p.getMaxX()),F=Math.max(u.getMaxY(),p.getMaxY());return _.distance(g,E,B,F)}},{key:"minMaxDistance",value:function(u,p){var g=u.getMinX(),E=u.getMinY(),B=u.getMaxX(),F=u.getMaxY(),G=p.getMinX(),Y=p.getMinY(),ae=p.getMaxX(),xe=p.getMaxY(),Ie=_.maxDistance(g,E,g,F,G,Y,G,xe);return Ie=Math.min(Ie,_.maxDistance(g,E,g,F,G,Y,ae,Y)),Ie=Math.min(Ie,_.maxDistance(g,E,g,F,ae,xe,G,xe)),Ie=Math.min(Ie,_.maxDistance(g,E,g,F,ae,xe,ae,Y)),Ie=Math.min(Ie,_.maxDistance(g,E,B,E,G,Y,G,xe)),Ie=Math.min(Ie,_.maxDistance(g,E,B,E,G,Y,ae,Y)),Ie=Math.min(Ie,_.maxDistance(g,E,B,E,ae,xe,G,xe)),Ie=Math.min(Ie,_.maxDistance(g,E,B,E,ae,xe,ae,Y)),Ie=Math.min(Ie,_.maxDistance(B,F,g,F,G,Y,G,xe)),Ie=Math.min(Ie,_.maxDistance(B,F,g,F,G,Y,ae,Y)),Ie=Math.min(Ie,_.maxDistance(B,F,g,F,ae,xe,G,xe)),Ie=Math.min(Ie,_.maxDistance(B,F,g,F,ae,xe,ae,Y)),Ie=Math.min(Ie,_.maxDistance(B,F,B,E,G,Y,G,xe)),Ie=Math.min(Ie,_.maxDistance(B,F,B,E,G,Y,ae,Y)),Ie=Math.min(Ie,_.maxDistance(B,F,B,E,ae,xe,G,xe)),Ie=Math.min(Ie,_.maxDistance(B,F,B,E,ae,xe,ae,Y))}}])})(),Jc=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"maximumDistance",value:function(){return wF.maximumDistance(this._boundable1.getBounds(),this._boundable2.getBounds())}},{key:"expandToQueue",value:function(u,p){var g=_.isComposite(this._boundable1),E=_.isComposite(this._boundable2);if(g&&E)return _.area(this._boundable1)>_.area(this._boundable2)?(this.expand(this._boundable1,this._boundable2,!1,u,p),null):(this.expand(this._boundable2,this._boundable1,!0,u,p),null);if(g)return this.expand(this._boundable1,this._boundable2,!1,u,p),null;if(E)return this.expand(this._boundable2,this._boundable1,!0,u,p),null;throw new R("neither boundable is composite")}},{key:"isLeaves",value:function(){return!(_.isComposite(this._boundable1)||_.isComposite(this._boundable2))}},{key:"compareTo",value:function(u){var p=u;return this._distance<p._distance?-1:this._distance>p._distance?1:0}},{key:"expand",value:function(u,p,g,E,B){for(var F=u.getChildBoundables().iterator();F.hasNext();){var G=F.next(),Y=null;(Y=g?new _(p,G,this._itemDistance):new _(G,p,this._itemDistance)).getDistance()<B&&E.add(Y)}}},{key:"getBoundable",value:function(u){return u===0?this._boundable1:this._boundable2}},{key:"getDistance",value:function(){return this._distance}},{key:"distance",value:function(){return this.isLeaves()?this._itemDistance.distance(this._boundable1,this._boundable2):this._boundable1.getBounds().distance(this._boundable2.getBounds())}},{key:"interfaces_",get:function(){return[L]}}],[{key:"constructor_",value:function(){this._boundable1=null,this._boundable2=null,this._distance=null,this._itemDistance=null;var u=arguments[0],p=arguments[1],g=arguments[2];this._boundable1=u,this._boundable2=p,this._itemDistance=g,this._distance=this.distance()}},{key:"area",value:function(u){return u.getBounds().getArea()}},{key:"isComposite",value:function(u){return u instanceof Ir}}])})(),Aw=(function(){return o((function _(){s(this,_)}),[{key:"visitItem",value:function(_){}}])})(),Kc=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"queryInternal",value:function(){if(X(arguments[2],Aw)&&arguments[0]instanceof Object&&arguments[1]instanceof Ir)for(var u=arguments[0],p=arguments[2],g=arguments[1].getChildBoundables(),E=0;E<g.size();E++){var B=g.get(E);this.getIntersectsOp().intersects(B.getBounds(),u)&&(B instanceof Ir?this.queryInternal(u,B,p):B instanceof no?p.visitItem(B.getItem()):re.shouldNeverReachHere())}else if(X(arguments[2],We)&&arguments[0]instanceof Object&&arguments[1]instanceof Ir)for(var F=arguments[0],G=arguments[2],Y=arguments[1].getChildBoundables(),ae=0;ae<Y.size();ae++){var xe=Y.get(ae);this.getIntersectsOp().intersects(xe.getBounds(),F)&&(xe instanceof Ir?this.queryInternal(F,xe,G):xe instanceof no?G.add(xe.getItem()):re.shouldNeverReachHere())}}},{key:"getNodeCapacity",value:function(){return this._nodeCapacity}},{key:"lastNode",value:function(u){return u.get(u.size()-1)}},{key:"size",value:function(){if(arguments.length===0)return this.isEmpty()?0:(this.build(),this.size(this._root));if(arguments.length===1){for(var u=0,p=arguments[0].getChildBoundables().iterator();p.hasNext();){var g=p.next();g instanceof Ir?u+=this.size(g):g instanceof no&&(u+=1)}return u}}},{key:"removeItem",value:function(u,p){for(var g=null,E=u.getChildBoundables().iterator();E.hasNext();){var B=E.next();B instanceof no&&B.getItem()===p&&(g=B)}return g!==null&&(u.getChildBoundables().remove(g),!0)}},{key:"itemsTree",value:function(){if(arguments.length===0){this.build();var u=this.itemsTree(this._root);return u===null?new Pe:u}if(arguments.length===1){for(var p=arguments[0],g=new Pe,E=p.getChildBoundables().iterator();E.hasNext();){var B=E.next();if(B instanceof Ir){var F=this.itemsTree(B);F!==null&&g.add(F)}else B instanceof no?g.add(B.getItem()):re.shouldNeverReachHere()}return g.size()<=0?null:g}}},{key:"insert",value:function(u,p){re.isTrue(!this._built,"Cannot insert items into an STR packed R-tree after it has been built."),this._itemBoundables.add(new no(u,p))}},{key:"boundablesAtLevel",value:function(){if(arguments.length===1){var u=arguments[0],p=new Pe;return this.boundablesAtLevel(u,this._root,p),p}if(arguments.length===3){var g=arguments[0],E=arguments[1],B=arguments[2];if(re.isTrue(g>-2),E.getLevel()===g)return B.add(E),null;for(var F=E.getChildBoundables().iterator();F.hasNext();){var G=F.next();G instanceof Ir?this.boundablesAtLevel(g,G,B):(re.isTrue(G instanceof no),g===-1&&B.add(G))}return null}}},{key:"query",value:function(){if(arguments.length===1){var u=arguments[0];this.build();var p=new Pe;return this.isEmpty()||this.getIntersectsOp().intersects(this._root.getBounds(),u)&&this.queryInternal(u,this._root,p),p}if(arguments.length===2){var g=arguments[0],E=arguments[1];if(this.build(),this.isEmpty())return null;this.getIntersectsOp().intersects(this._root.getBounds(),g)&&this.queryInternal(g,this._root,E)}}},{key:"build",value:function(){if(this._built)return null;this._root=this._itemBoundables.isEmpty()?this.createNode(0):this.createHigherLevels(this._itemBoundables,-1),this._itemBoundables=null,this._built=!0}},{key:"getRoot",value:function(){return this.build(),this._root}},{key:"remove",value:function(){if(arguments.length===2){var u=arguments[0],p=arguments[1];return this.build(),!!this.getIntersectsOp().intersects(this._root.getBounds(),u)&&this.remove(u,this._root,p)}if(arguments.length===3){var g=arguments[0],E=arguments[1],B=arguments[2],F=this.removeItem(E,B);if(F)return!0;for(var G=null,Y=E.getChildBoundables().iterator();Y.hasNext();){var ae=Y.next();if(this.getIntersectsOp().intersects(ae.getBounds(),g)&&ae instanceof Ir&&(F=this.remove(g,ae,B))){G=ae;break}}return G!==null&&G.getChildBoundables().isEmpty()&&E.getChildBoundables().remove(G),F}}},{key:"createHigherLevels",value:function(u,p){re.isTrue(!u.isEmpty());var g=this.createParentBoundables(u,p+1);return g.size()===1?g.get(0):this.createHigherLevels(g,p+1)}},{key:"depth",value:function(){if(arguments.length===0)return this.isEmpty()?0:(this.build(),this.depth(this._root));if(arguments.length===1){for(var u=0,p=arguments[0].getChildBoundables().iterator();p.hasNext();){var g=p.next();if(g instanceof Ir){var E=this.depth(g);E>u&&(u=E)}}return u+1}}},{key:"createParentBoundables",value:function(u,p){re.isTrue(!u.isEmpty());var g=new Pe;g.add(this.createNode(p));var E=new Pe(u);Zc.sort(E,this.getComparator());for(var B=E.iterator();B.hasNext();){var F=B.next();this.lastNode(g).getChildBoundables().size()===this.getNodeCapacity()&&g.add(this.createNode(p)),this.lastNode(g).addChildBoundable(F)}return g}},{key:"isEmpty",value:function(){return this._built?this._root.isEmpty():this._itemBoundables.isEmpty()}},{key:"interfaces_",get:function(){return[C]}}],[{key:"constructor_",value:function(){if(this._root=null,this._built=!1,this._itemBoundables=new Pe,this._nodeCapacity=null,arguments.length===0)_.constructor_.call(this,_.DEFAULT_NODE_CAPACITY);else if(arguments.length===1){var u=arguments[0];re.isTrue(u>1,"Node capacity must be greater than 1"),this._nodeCapacity=u}}},{key:"compareDoubles",value:function(u,p){return u>p?1:u<p?-1:0}}])})();Kc.IntersectsOp=function(){},Kc.DEFAULT_NODE_CAPACITY=10;var SF=(function(){return o((function _(){s(this,_)}),[{key:"distance",value:function(_,u){}}])})(),Ea=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,[{key:"createParentBoundablesFromVerticalSlices",value:function(p,g){re.isTrue(p.length>0);for(var E=new Pe,B=0;B<p.length;B++)E.addAll(this.createParentBoundablesFromVerticalSlice(p[B],g));return E}},{key:"nearestNeighbourK",value:function(){if(arguments.length===2){var p=arguments[0],g=arguments[1];return this.nearestNeighbourK(p,W.POSITIVE_INFINITY,g)}if(arguments.length===3){var E=arguments[0],B=arguments[2],F=arguments[1],G=new qf;G.add(E);for(var Y=new qf;!G.isEmpty()&&F>=0;){var ae=G.poll(),xe=ae.getDistance();if(xe>=F)break;ae.isLeaves()?Y.size()<B?Y.add(ae):(Y.peek().getDistance()>xe&&(Y.poll(),Y.add(ae)),F=Y.peek().getDistance()):ae.expandToQueue(G,F)}return u.getItems(Y)}}},{key:"createNode",value:function(p){return new vw(p)}},{key:"size",value:function(){return arguments.length===0?A(u,"size",this,1).call(this):A(u,"size",this,1).apply(this,arguments)}},{key:"insert",value:function(){if(!(arguments.length===2&&arguments[1]instanceof Object&&arguments[0]instanceof fe))return A(u,"insert",this,1).apply(this,arguments);var p=arguments[0],g=arguments[1];if(p.isNull())return null;A(u,"insert",this,1).call(this,p,g)}},{key:"getIntersectsOp",value:function(){return u.intersectsOp}},{key:"verticalSlices",value:function(p,g){for(var E=Math.trunc(Math.ceil(p.size()/g)),B=new Array(g).fill(null),F=p.iterator(),G=0;G<g;G++){B[G]=new Pe;for(var Y=0;F.hasNext()&&Y<E;){var ae=F.next();B[G].add(ae),Y++}}return B}},{key:"query",value:function(){if(arguments.length===1){var p=arguments[0];return A(u,"query",this,1).call(this,p)}if(arguments.length===2){var g=arguments[0],E=arguments[1];A(u,"query",this,1).call(this,g,E)}}},{key:"getComparator",value:function(){return u.yComparator}},{key:"createParentBoundablesFromVerticalSlice",value:function(p,g){return A(u,"createParentBoundables",this,1).call(this,p,g)}},{key:"remove",value:function(){if(arguments.length===2&&arguments[1]instanceof Object&&arguments[0]instanceof fe){var p=arguments[0],g=arguments[1];return A(u,"remove",this,1).call(this,p,g)}return A(u,"remove",this,1).apply(this,arguments)}},{key:"depth",value:function(){return arguments.length===0?A(u,"depth",this,1).call(this):A(u,"depth",this,1).apply(this,arguments)}},{key:"createParentBoundables",value:function(p,g){re.isTrue(!p.isEmpty());var E=Math.trunc(Math.ceil(p.size()/this.getNodeCapacity())),B=new Pe(p);Zc.sort(B,u.xComparator);var F=this.verticalSlices(B,Math.trunc(Math.ceil(Math.sqrt(E))));return this.createParentBoundablesFromVerticalSlices(F,g)}},{key:"nearestNeighbour",value:function(){if(arguments.length===1){if(X(arguments[0],SF)){var p=arguments[0];if(this.isEmpty())return null;var g=new Jc(this.getRoot(),this.getRoot(),p);return this.nearestNeighbour(g)}if(arguments[0]instanceof Jc){var E=arguments[0],B=W.POSITIVE_INFINITY,F=null,G=new qf;for(G.add(E);!G.isEmpty()&&B>0;){var Y=G.poll(),ae=Y.getDistance();if(ae>=B)break;Y.isLeaves()?(B=ae,F=Y):Y.expandToQueue(G,B)}return F===null?null:[F.getBoundable(0).getItem(),F.getBoundable(1).getItem()]}}else{if(arguments.length===2){var xe=arguments[0],Ie=arguments[1];if(this.isEmpty()||xe.isEmpty())return null;var Ge=new Jc(this.getRoot(),xe.getRoot(),Ie);return this.nearestNeighbour(Ge)}if(arguments.length===3){var ut=arguments[2],Rt=new no(arguments[0],arguments[1]),Ft=new Jc(this.getRoot(),Rt,ut);return this.nearestNeighbour(Ft)[0]}if(arguments.length===4){var vn=arguments[2],pn=arguments[3],Dn=new no(arguments[0],arguments[1]),Ki=new Jc(this.getRoot(),Dn,vn);return this.nearestNeighbourK(Ki,pn)}}}},{key:"isWithinDistance",value:function(){if(arguments.length===2){var p=arguments[0],g=arguments[1],E=W.POSITIVE_INFINITY,B=new qf;for(B.add(p);!B.isEmpty();){var F=B.poll(),G=F.getDistance();if(G>g)return!1;if(F.maximumDistance()<=g)return!0;if(F.isLeaves()){if((E=G)<=g)return!0}else F.expandToQueue(B,E)}return!1}if(arguments.length===3){var Y=arguments[0],ae=arguments[1],xe=arguments[2],Ie=new Jc(this.getRoot(),Y.getRoot(),ae);return this.isWithinDistance(Ie,xe)}}},{key:"interfaces_",get:function(){return[CF,C]}}],[{key:"constructor_",value:function(){if(arguments.length===0)u.constructor_.call(this,u.DEFAULT_NODE_CAPACITY);else if(arguments.length===1){var p=arguments[0];Kc.constructor_.call(this,p)}}},{key:"centreX",value:function(p){return u.avg(p.getMinX(),p.getMaxX())}},{key:"avg",value:function(p,g){return(p+g)/2}},{key:"getItems",value:function(p){for(var g=new Array(p.size()).fill(null),E=0;!p.isEmpty();)g[E]=p.poll().getBoundable(0).getItem(),E++;return g}},{key:"centreY",value:function(p){return u.avg(p.getMinY(),p.getMaxY())}}])})(Kc),vw=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,[{key:"computeBounds",value:function(){for(var p=null,g=this.getChildBoundables().iterator();g.hasNext();){var E=g.next();p===null?p=new fe(E.getBounds()):p.expandToInclude(E.getBounds())}return p}}],[{key:"constructor_",value:function(){var p=arguments[0];Ir.constructor_.call(this,p)}}])})(Ir);Ea.STRtreeNode=vw,Ea.xComparator=new((function(){return o((function _(){s(this,_)}),[{key:"interfaces_",get:function(){return[te]}},{key:"compare",value:function(_,u){return Kc.compareDoubles(Ea.centreX(_.getBounds()),Ea.centreX(u.getBounds()))}}])})()),Ea.yComparator=new((function(){return o((function _(){s(this,_)}),[{key:"interfaces_",get:function(){return[te]}},{key:"compare",value:function(_,u){return Kc.compareDoubles(Ea.centreY(_.getBounds()),Ea.centreY(u.getBounds()))}}])})()),Ea.intersectsOp=new((function(){return o((function _(){s(this,_)}),[{key:"interfaces_",get:function(){return[IntersectsOp]}},{key:"intersects",value:function(_,u){return _.intersects(u)}}])})()),Ea.DEFAULT_NODE_CAPACITY=10;var IF=(function(){function _(){s(this,_)}return o(_,null,[{key:"relativeSign",value:function(u,p){return u<p?-1:u>p?1:0}},{key:"compare",value:function(u,p,g){if(p.equals2D(g))return 0;var E=_.relativeSign(p.x,g.x),B=_.relativeSign(p.y,g.y);switch(u){case 0:return _.compareValue(E,B);case 1:return _.compareValue(B,E);case 2:return _.compareValue(B,-E);case 3:return _.compareValue(-E,B);case 4:return _.compareValue(-E,-B);case 5:return _.compareValue(-B,-E);case 6:return _.compareValue(-B,E);case 7:return _.compareValue(E,-B)}return re.shouldNeverReachHere("invalid octant value"),0}},{key:"compareValue",value:function(u,p){return u<0?-1:u>0?1:p<0?-1:p>0?1:0}}])})(),MF=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"getCoordinate",value:function(){return this.coord}},{key:"print",value:function(_){_.print(this.coord),_.print(" seg # = "+this.segmentIndex)}},{key:"compareTo",value:function(_){var u=_;return this.segmentIndex<u.segmentIndex?-1:this.segmentIndex>u.segmentIndex?1:this.coord.equals2D(u.coord)?0:this._isInterior?u._isInterior?IF.compare(this._segmentOctant,this.coord,u.coord):1:-1}},{key:"isEndPoint",value:function(_){return this.segmentIndex===0&&!this._isInterior||this.segmentIndex===_}},{key:"toString",value:function(){return this.segmentIndex+":"+this.coord.toString()}},{key:"isInterior",value:function(){return this._isInterior}},{key:"interfaces_",get:function(){return[L]}}],[{key:"constructor_",value:function(){this._segString=null,this.coord=null,this.segmentIndex=null,this._segmentOctant=null,this._isInterior=null;var _=arguments[0],u=arguments[1],p=arguments[2],g=arguments[3];this._segString=_,this.coord=new ie(u),this.segmentIndex=p,this._segmentOctant=g,this._isInterior=!u.equals2D(_.getCoordinate(p))}}])})(),TF=(function(){return o((function _(){s(this,_)}),[{key:"hasNext",value:function(){}},{key:"next",value:function(){}},{key:"remove",value:function(){}}])})(),LF=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"getSplitCoordinates",value:function(){var _=new Gn;this.addEndpoints();for(var u=this.iterator(),p=u.next();u.hasNext();){var g=u.next();this.addEdgeCoordinates(p,g,_),p=g}return _.toCoordinateArray()}},{key:"addCollapsedNodes",value:function(){var _=new Pe;this.findCollapsesFromInsertedNodes(_),this.findCollapsesFromExistingVertices(_);for(var u=_.iterator();u.hasNext();){var p=u.next().intValue();this.add(this._edge.getCoordinate(p),p)}}},{key:"createSplitEdgePts",value:function(_,u){var p=u.segmentIndex-_.segmentIndex+2;if(p===2)return[new ie(_.coord),new ie(u.coord)];var g=this._edge.getCoordinate(u.segmentIndex),E=u.isInterior()||!u.coord.equals2D(g);E||p--;var B=new Array(p).fill(null),F=0;B[F++]=new ie(_.coord);for(var G=_.segmentIndex+1;G<=u.segmentIndex;G++)B[F++]=this._edge.getCoordinate(G);return E&&(B[F]=new ie(u.coord)),B}},{key:"print",value:function(_){_.println("Intersections:");for(var u=this.iterator();u.hasNext();)u.next().print(_)}},{key:"findCollapsesFromExistingVertices",value:function(_){for(var u=0;u<this._edge.size()-2;u++){var p=this._edge.getCoordinate(u);this._edge.getCoordinate(u+1);var g=this._edge.getCoordinate(u+2);p.equals2D(g)&&_.add(de.valueOf(u+1))}}},{key:"addEdgeCoordinates",value:function(_,u,p){var g=this.createSplitEdgePts(_,u);p.add(g,!1)}},{key:"iterator",value:function(){return this._nodeMap.values().iterator()}},{key:"addSplitEdges",value:function(_){this.addEndpoints(),this.addCollapsedNodes();for(var u=this.iterator(),p=u.next();u.hasNext();){var g=u.next(),E=this.createSplitEdge(p,g);_.add(E),p=g}}},{key:"findCollapseIndex",value:function(_,u,p){if(!_.coord.equals2D(u.coord))return!1;var g=u.segmentIndex-_.segmentIndex;return u.isInterior()||g--,g===1&&(p[0]=_.segmentIndex+1,!0)}},{key:"findCollapsesFromInsertedNodes",value:function(_){for(var u=new Array(1).fill(null),p=this.iterator(),g=p.next();p.hasNext();){var E=p.next();this.findCollapseIndex(g,E,u)&&_.add(de.valueOf(u[0])),g=E}}},{key:"getEdge",value:function(){return this._edge}},{key:"addEndpoints",value:function(){var _=this._edge.size()-1;this.add(this._edge.getCoordinate(0),0),this.add(this._edge.getCoordinate(_),_)}},{key:"createSplitEdge",value:function(_,u){return new Wl(this.createSplitEdgePts(_,u),this._edge.getData())}},{key:"add",value:function(_,u){var p=new MF(this._edge,_,u,this._edge.getSegmentOctant(u)),g=this._nodeMap.get(p);return g!==null?(re.isTrue(g.coord.equals2D(_),"Found equal nodes with different coordinates"),g):(this._nodeMap.put(p,p),p)}},{key:"checkSplitEdgesCorrectness",value:function(_){var u=this._edge.getCoordinates(),p=_.get(0).getCoordinate(0);if(!p.equals2D(u[0]))throw new J("bad split edge start point at "+p);var g=_.get(_.size()-1).getCoordinates(),E=g[g.length-1];if(!E.equals2D(u[u.length-1]))throw new J("bad split edge end point at "+E)}}],[{key:"constructor_",value:function(){this._nodeMap=new cd,this._edge=null;var _=arguments[0];this._edge=_}}])})(),BF=(function(){function _(){s(this,_)}return o(_,null,[{key:"octant",value:function(){if(typeof arguments[0]=="number"&&typeof arguments[1]=="number"){var u=arguments[0],p=arguments[1];if(u===0&&p===0)throw new R("Cannot compute the octant for point ( "+u+", "+p+" )");var g=Math.abs(u),E=Math.abs(p);return u>=0?p>=0?g>=E?0:1:g>=E?7:6:p>=0?g>=E?3:2:g>=E?4:5}if(arguments[0]instanceof ie&&arguments[1]instanceof ie){var B=arguments[0],F=arguments[1],G=F.x-B.x,Y=F.y-B.y;if(G===0&&Y===0)throw new R("Cannot compute the octant for two identical points "+B);return _.octant(G,Y)}}}])})(),RF=(function(){return o((function _(){s(this,_)}),[{key:"getCoordinates",value:function(){}},{key:"size",value:function(){}},{key:"getCoordinate",value:function(_){}},{key:"isClosed",value:function(){}},{key:"setData",value:function(_){}},{key:"getData",value:function(){}}])})(),kF=(function(){return o((function _(){s(this,_)}),[{key:"addIntersection",value:function(_,u){}},{key:"interfaces_",get:function(){return[RF]}}])})(),Wl=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"getCoordinates",value:function(){return this._pts}},{key:"size",value:function(){return this._pts.length}},{key:"getCoordinate",value:function(u){return this._pts[u]}},{key:"isClosed",value:function(){return this._pts[0].equals(this._pts[this._pts.length-1])}},{key:"getSegmentOctant",value:function(u){return u===this._pts.length-1?-1:this.safeOctant(this.getCoordinate(u),this.getCoordinate(u+1))}},{key:"setData",value:function(u){this._data=u}},{key:"safeOctant",value:function(u,p){return u.equals2D(p)?0:BF.octant(u,p)}},{key:"getData",value:function(){return this._data}},{key:"addIntersection",value:function(){if(arguments.length===2){var u=arguments[0],p=arguments[1];this.addIntersectionNode(u,p)}else if(arguments.length===4){var g=arguments[1],E=arguments[3],B=new ie(arguments[0].getIntersection(E));this.addIntersection(B,g)}}},{key:"toString",value:function(){return sv.toLineString(new Me(this._pts))}},{key:"getNodeList",value:function(){return this._nodeList}},{key:"addIntersectionNode",value:function(u,p){var g=p,E=g+1;if(E<this._pts.length){var B=this._pts[E];u.equals2D(B)&&(g=E)}return this._nodeList.add(u,g)}},{key:"addIntersections",value:function(u,p,g){for(var E=0;E<u.getIntersectionNum();E++)this.addIntersection(u,p,g,E)}},{key:"interfaces_",get:function(){return[kF]}}],[{key:"constructor_",value:function(){this._nodeList=new LF(this),this._pts=null,this._data=null;var u=arguments[0],p=arguments[1];this._pts=u,this._data=p}},{key:"getNodedSubstrings",value:function(){if(arguments.length===1){var u=arguments[0],p=new Pe;return _.getNodedSubstrings(u,p),p}if(arguments.length===2)for(var g=arguments[1],E=arguments[0].iterator();E.hasNext();)E.next().getNodeList().addSplitEdges(g)}}])})(),cr=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"minX",value:function(){return Math.min(this.p0.x,this.p1.x)}},{key:"orientationIndex",value:function(){if(arguments[0]instanceof _){var u=arguments[0],p=be.index(this.p0,this.p1,u.p0),g=be.index(this.p0,this.p1,u.p1);return p>=0&&g>=0||p<=0&&g<=0?Math.max(p,g):0}if(arguments[0]instanceof ie){var E=arguments[0];return be.index(this.p0,this.p1,E)}}},{key:"toGeometry",value:function(u){return u.createLineString([this.p0,this.p1])}},{key:"isVertical",value:function(){return this.p0.x===this.p1.x}},{key:"equals",value:function(u){if(!(u instanceof _))return!1;var p=u;return this.p0.equals(p.p0)&&this.p1.equals(p.p1)}},{key:"intersection",value:function(u){var p=new ql;return p.computeIntersection(this.p0,this.p1,u.p0,u.p1),p.hasIntersection()?p.getIntersection(0):null}},{key:"project",value:function(){if(arguments[0]instanceof ie){var u=arguments[0];if(u.equals(this.p0)||u.equals(this.p1))return new ie(u);var p=this.projectionFactor(u),g=new ie;return g.x=this.p0.x+p*(this.p1.x-this.p0.x),g.y=this.p0.y+p*(this.p1.y-this.p0.y),g}if(arguments[0]instanceof _){var E=arguments[0],B=this.projectionFactor(E.p0),F=this.projectionFactor(E.p1);if(B>=1&&F>=1||B<=0&&F<=0)return null;var G=this.project(E.p0);B<0&&(G=this.p0),B>1&&(G=this.p1);var Y=this.project(E.p1);return F<0&&(Y=this.p0),F>1&&(Y=this.p1),new _(G,Y)}}},{key:"normalize",value:function(){this.p1.compareTo(this.p0)<0&&this.reverse()}},{key:"angle",value:function(){return Math.atan2(this.p1.y-this.p0.y,this.p1.x-this.p0.x)}},{key:"getCoordinate",value:function(u){return u===0?this.p0:this.p1}},{key:"distancePerpendicular",value:function(u){return qe.pointToLinePerpendicular(u,this.p0,this.p1)}},{key:"minY",value:function(){return Math.min(this.p0.y,this.p1.y)}},{key:"midPoint",value:function(){return _.midPoint(this.p0,this.p1)}},{key:"projectionFactor",value:function(u){if(u.equals(this.p0))return 0;if(u.equals(this.p1))return 1;var p=this.p1.x-this.p0.x,g=this.p1.y-this.p0.y,E=p*p+g*g;return E<=0?W.NaN:((u.x-this.p0.x)*p+(u.y-this.p0.y)*g)/E}},{key:"closestPoints",value:function(u){var p=this.intersection(u);if(p!==null)return[p,p];var g=new Array(2).fill(null),E=W.MAX_VALUE,B=null,F=this.closestPoint(u.p0);E=F.distance(u.p0),g[0]=F,g[1]=u.p0;var G=this.closestPoint(u.p1);(B=G.distance(u.p1))<E&&(E=B,g[0]=G,g[1]=u.p1);var Y=u.closestPoint(this.p0);(B=Y.distance(this.p0))<E&&(E=B,g[0]=this.p0,g[1]=Y);var ae=u.closestPoint(this.p1);return(B=ae.distance(this.p1))<E&&(E=B,g[0]=this.p1,g[1]=ae),g}},{key:"closestPoint",value:function(u){var p=this.projectionFactor(u);return p>0&&p<1?this.project(u):this.p0.distance(u)<this.p1.distance(u)?this.p0:this.p1}},{key:"maxX",value:function(){return Math.max(this.p0.x,this.p1.x)}},{key:"getLength",value:function(){return this.p0.distance(this.p1)}},{key:"compareTo",value:function(u){var p=u,g=this.p0.compareTo(p.p0);return g!==0?g:this.p1.compareTo(p.p1)}},{key:"reverse",value:function(){var u=this.p0;this.p0=this.p1,this.p1=u}},{key:"equalsTopo",value:function(u){return this.p0.equals(u.p0)&&this.p1.equals(u.p1)||this.p0.equals(u.p1)&&this.p1.equals(u.p0)}},{key:"lineIntersection",value:function(u){return it.intersection(this.p0,this.p1,u.p0,u.p1)}},{key:"maxY",value:function(){return Math.max(this.p0.y,this.p1.y)}},{key:"pointAlongOffset",value:function(u,p){var g=this.p0.x+u*(this.p1.x-this.p0.x),E=this.p0.y+u*(this.p1.y-this.p0.y),B=this.p1.x-this.p0.x,F=this.p1.y-this.p0.y,G=Math.sqrt(B*B+F*F),Y=0,ae=0;if(p!==0){if(G<=0)throw new IllegalStateException("Cannot compute offset from zero-length line segment");Y=p*B/G,ae=p*F/G}return new ie(g-ae,E+Y)}},{key:"setCoordinates",value:function(){if(arguments.length===1){var u=arguments[0];this.setCoordinates(u.p0,u.p1)}else if(arguments.length===2){var p=arguments[0],g=arguments[1];this.p0.x=p.x,this.p0.y=p.y,this.p1.x=g.x,this.p1.y=g.y}}},{key:"segmentFraction",value:function(u){var p=this.projectionFactor(u);return p<0?p=0:(p>1||W.isNaN(p))&&(p=1),p}},{key:"toString",value:function(){return"LINESTRING( "+this.p0.x+" "+this.p0.y+", "+this.p1.x+" "+this.p1.y+")"}},{key:"isHorizontal",value:function(){return this.p0.y===this.p1.y}},{key:"reflect",value:function(u){var p=this.p1.getY()-this.p0.getY(),g=this.p0.getX()-this.p1.getX(),E=this.p0.getY()*(this.p1.getX()-this.p0.getX())-this.p0.getX()*(this.p1.getY()-this.p0.getY()),B=p*p+g*g,F=p*p-g*g,G=u.getX(),Y=u.getY();return new ie((-F*G-2*p*g*Y-2*p*E)/B,(F*Y-2*p*g*G-2*g*E)/B)}},{key:"distance",value:function(){if(arguments[0]instanceof _){var u=arguments[0];return qe.segmentToSegment(this.p0,this.p1,u.p0,u.p1)}if(arguments[0]instanceof ie){var p=arguments[0];return qe.pointToSegment(p,this.p0,this.p1)}}},{key:"pointAlong",value:function(u){var p=new ie;return p.x=this.p0.x+u*(this.p1.x-this.p0.x),p.y=this.p0.y+u*(this.p1.y-this.p0.y),p}},{key:"hashCode",value:function(){var u=W.doubleToLongBits(this.p0.x);u^=31*W.doubleToLongBits(this.p0.y);var p=Math.trunc(u)^Math.trunc(u>>32),g=W.doubleToLongBits(this.p1.x);return g^=31*W.doubleToLongBits(this.p1.y),p^(Math.trunc(g)^Math.trunc(g>>32))}},{key:"interfaces_",get:function(){return[L,C]}}],[{key:"constructor_",value:function(){if(this.p0=null,this.p1=null,arguments.length===0)_.constructor_.call(this,new ie,new ie);else if(arguments.length===1){var u=arguments[0];_.constructor_.call(this,u.p0,u.p1)}else if(arguments.length===2){var p=arguments[0],g=arguments[1];this.p0=p,this.p1=g}else if(arguments.length===4){var E=arguments[0],B=arguments[1],F=arguments[2],G=arguments[3];_.constructor_.call(this,new ie(E,B),new ie(F,G))}}},{key:"midPoint",value:function(u,p){return new ie((u.x+p.x)/2,(u.y+p.y)/2)}}])})(),NF=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"overlap",value:function(){if(arguments.length!==2){if(arguments.length===4){var _=arguments[1],u=arguments[2],p=arguments[3];arguments[0].getLineSegment(_,this._overlapSeg1),u.getLineSegment(p,this._overlapSeg2),this.overlap(this._overlapSeg1,this._overlapSeg2)}}}}],[{key:"constructor_",value:function(){this._overlapSeg1=new cr,this._overlapSeg2=new cr}}])})(),yw=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"getLineSegment",value:function(_,u){u.p0=this._pts[_],u.p1=this._pts[_+1]}},{key:"computeSelect",value:function(_,u,p,g){var E=this._pts[u],B=this._pts[p];if(p-u==1)return g.select(this,u),null;if(!_.intersects(E,B))return null;var F=Math.trunc((u+p)/2);u<F&&this.computeSelect(_,u,F,g),F<p&&this.computeSelect(_,F,p,g)}},{key:"getCoordinates",value:function(){for(var _=new Array(this._end-this._start+1).fill(null),u=0,p=this._start;p<=this._end;p++)_[u++]=this._pts[p];return _}},{key:"computeOverlaps",value:function(){if(arguments.length===2){var _=arguments[0],u=arguments[1];this.computeOverlaps(this._start,this._end,_,_._start,_._end,u)}else if(arguments.length===6){var p=arguments[0],g=arguments[1],E=arguments[2],B=arguments[3],F=arguments[4],G=arguments[5];if(g-p==1&&F-B==1)return G.overlap(this,p,E,B),null;if(!this.overlaps(p,g,E,B,F))return null;var Y=Math.trunc((p+g)/2),ae=Math.trunc((B+F)/2);p<Y&&(B<ae&&this.computeOverlaps(p,Y,E,B,ae,G),ae<F&&this.computeOverlaps(p,Y,E,ae,F,G)),Y<g&&(B<ae&&this.computeOverlaps(Y,g,E,B,ae,G),ae<F&&this.computeOverlaps(Y,g,E,ae,F,G))}}},{key:"setId",value:function(_){this._id=_}},{key:"select",value:function(_,u){this.computeSelect(_,this._start,this._end,u)}},{key:"getEnvelope",value:function(){if(this._env===null){var _=this._pts[this._start],u=this._pts[this._end];this._env=new fe(_,u)}return this._env}},{key:"overlaps",value:function(_,u,p,g,E){return fe.intersects(this._pts[_],this._pts[u],p._pts[g],p._pts[E])}},{key:"getEndIndex",value:function(){return this._end}},{key:"getStartIndex",value:function(){return this._start}},{key:"getContext",value:function(){return this._context}},{key:"getId",value:function(){return this._id}}],[{key:"constructor_",value:function(){this._pts=null,this._start=null,this._end=null,this._env=null,this._context=null,this._id=null;var _=arguments[0],u=arguments[1],p=arguments[2],g=arguments[3];this._pts=_,this._start=u,this._end=p,this._context=g}}])})(),PF=(function(){function _(){s(this,_)}return o(_,null,[{key:"findChainEnd",value:function(u,p){for(var g=p;g<u.length-1&&u[g].equals2D(u[g+1]);)g++;if(g>=u.length-1)return u.length-1;for(var E=Ts.quadrant(u[g],u[g+1]),B=p+1;B<u.length&&!(!u[B-1].equals2D(u[B])&&Ts.quadrant(u[B-1],u[B])!==E);)B++;return B-1}},{key:"getChains",value:function(){if(arguments.length===1){var u=arguments[0];return _.getChains(u,null)}if(arguments.length===2){var p=arguments[0],g=arguments[1],E=new Pe,B=0;do{var F=_.findChainEnd(p,B),G=new yw(p,B,F,g);E.add(G),B=F}while(B<p.length-1);return E}}}])})(),lv=(function(){return o((function _(){s(this,_)}),[{key:"computeNodes",value:function(_){}},{key:"getNodedSubstrings",value:function(){}}])})(),bw=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"setSegmentIntersector",value:function(_){this._segInt=_}},{key:"interfaces_",get:function(){return[lv]}}],[{key:"constructor_",value:function(){if(this._segInt=null,arguments.length!==0){if(arguments.length===1){var _=arguments[0];this.setSegmentIntersector(_)}}}}])})(),cv=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,[{key:"getMonotoneChains",value:function(){return this._monoChains}},{key:"getNodedSubstrings",value:function(){return Wl.getNodedSubstrings(this._nodedSegStrings)}},{key:"getIndex",value:function(){return this._index}},{key:"add",value:function(p){for(var g=PF.getChains(p.getCoordinates(),p).iterator();g.hasNext();){var E=g.next();E.setId(this._idCounter++),this._index.insert(E.getEnvelope(),E),this._monoChains.add(E)}}},{key:"computeNodes",value:function(p){this._nodedSegStrings=p;for(var g=p.iterator();g.hasNext();)this.add(g.next());this.intersectChains()}},{key:"intersectChains",value:function(){for(var p=new xw(this._segInt),g=this._monoChains.iterator();g.hasNext();)for(var E=g.next(),B=this._index.query(E.getEnvelope()).iterator();B.hasNext();){var F=B.next();if(F.getId()>E.getId()&&(E.computeOverlaps(F,p),this._nOverlaps++),this._segInt.isDone())return null}}}],[{key:"constructor_",value:function(){if(this._monoChains=new Pe,this._index=new Ea,this._idCounter=0,this._nodedSegStrings=null,this._nOverlaps=0,arguments.length!==0){if(arguments.length===1){var p=arguments[0];bw.constructor_.call(this,p)}}}}])})(bw),xw=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,[{key:"overlap",value:function(){if(arguments.length!==4)return A(u,"overlap",this,1).apply(this,arguments);var p=arguments[1],g=arguments[2],E=arguments[3],B=arguments[0].getContext(),F=g.getContext();this._si.processIntersections(B,p,F,E)}}],[{key:"constructor_",value:function(){this._si=null;var p=arguments[0];this._si=p}}])})(NF);cv.SegmentOverlapAction=xw;var jr=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"isDeletable",value:function(u,p,g,E){var B=this._inputLine[u],F=this._inputLine[p],G=this._inputLine[g];return!!this.isConcave(B,F,G)&&!!this.isShallow(B,F,G,E)&&this.isShallowSampled(B,F,u,g,E)}},{key:"deleteShallowConcavities",value:function(){for(var u=1,p=this.findNextNonDeletedIndex(u),g=this.findNextNonDeletedIndex(p),E=!1;g<this._inputLine.length;){var B=!1;this.isDeletable(u,p,g,this._distanceTol)&&(this._isDeleted[p]=_.DELETE,B=!0,E=!0),u=B?g:p,p=this.findNextNonDeletedIndex(u),g=this.findNextNonDeletedIndex(p)}return E}},{key:"isShallowConcavity",value:function(u,p,g,E){return be.index(u,p,g)===this._angleOrientation&&qe.pointToSegment(p,u,g)<E}},{key:"isShallowSampled",value:function(u,p,g,E,B){var F=Math.trunc((E-g)/_.NUM_PTS_TO_CHECK);F<=0&&(F=1);for(var G=g;G<E;G+=F)if(!this.isShallow(u,p,this._inputLine[G],B))return!1;return!0}},{key:"isConcave",value:function(u,p,g){return be.index(u,p,g)===this._angleOrientation}},{key:"simplify",value:function(u){this._distanceTol=Math.abs(u),u<0&&(this._angleOrientation=be.CLOCKWISE),this._isDeleted=new Array(this._inputLine.length).fill(null);var p=!1;do p=this.deleteShallowConcavities();while(p);return this.collapseLine()}},{key:"findNextNonDeletedIndex",value:function(u){for(var p=u+1;p<this._inputLine.length&&this._isDeleted[p]===_.DELETE;)p++;return p}},{key:"isShallow",value:function(u,p,g,E){return qe.pointToSegment(p,u,g)<E}},{key:"collapseLine",value:function(){for(var u=new Gn,p=0;p<this._inputLine.length;p++)this._isDeleted[p]!==_.DELETE&&u.add(this._inputLine[p]);return u.toCoordinateArray()}}],[{key:"constructor_",value:function(){this._inputLine=null,this._distanceTol=null,this._isDeleted=null,this._angleOrientation=be.COUNTERCLOCKWISE;var u=arguments[0];this._inputLine=u}},{key:"simplify",value:function(u,p){return new _(u).simplify(p)}}])})();jr.INIT=0,jr.DELETE=1,jr.KEEP=1,jr.NUM_PTS_TO_CHECK=10;var Ew=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"getCoordinates",value:function(){return this._ptList.toArray(_.COORDINATE_ARRAY_TYPE)}},{key:"setPrecisionModel",value:function(u){this._precisionModel=u}},{key:"addPt",value:function(u){var p=new ie(u);if(this._precisionModel.makePrecise(p),this.isRedundant(p))return null;this._ptList.add(p)}},{key:"reverse",value:function(){}},{key:"addPts",value:function(u,p){if(p)for(var g=0;g<u.length;g++)this.addPt(u[g]);else for(var E=u.length-1;E>=0;E--)this.addPt(u[E])}},{key:"isRedundant",value:function(u){if(this._ptList.size()<1)return!1;var p=this._ptList.get(this._ptList.size()-1);return u.distance(p)<this._minimimVertexDistance}},{key:"toString",value:function(){return new Pt().createLineString(this.getCoordinates()).toString()}},{key:"closeRing",value:function(){if(this._ptList.size()<1)return null;var u=new ie(this._ptList.get(0)),p=this._ptList.get(this._ptList.size()-1);if(u.equals(p))return null;this._ptList.add(u)}},{key:"setMinimumVertexDistance",value:function(u){this._minimimVertexDistance=u}}],[{key:"constructor_",value:function(){this._ptList=null,this._precisionModel=null,this._minimimVertexDistance=0,this._ptList=new Pe}}])})();Ew.COORDINATE_ARRAY_TYPE=new Array(0).fill(null);var hr=(function(){function _(){s(this,_)}return o(_,null,[{key:"toDegrees",value:function(u){return 180*u/Math.PI}},{key:"normalize",value:function(u){for(;u>Math.PI;)u-=_.PI_TIMES_2;for(;u<=-Math.PI;)u+=_.PI_TIMES_2;return u}},{key:"angle",value:function(){if(arguments.length===1){var u=arguments[0];return Math.atan2(u.y,u.x)}if(arguments.length===2){var p=arguments[0],g=arguments[1],E=g.x-p.x,B=g.y-p.y;return Math.atan2(B,E)}}},{key:"isAcute",value:function(u,p,g){var E=u.x-p.x,B=u.y-p.y;return E*(g.x-p.x)+B*(g.y-p.y)>0}},{key:"isObtuse",value:function(u,p,g){var E=u.x-p.x,B=u.y-p.y;return E*(g.x-p.x)+B*(g.y-p.y)<0}},{key:"interiorAngle",value:function(u,p,g){var E=_.angle(p,u),B=_.angle(p,g);return Math.abs(B-E)}},{key:"normalizePositive",value:function(u){if(u<0){for(;u<0;)u+=_.PI_TIMES_2;u>=_.PI_TIMES_2&&(u=0)}else{for(;u>=_.PI_TIMES_2;)u-=_.PI_TIMES_2;u<0&&(u=0)}return u}},{key:"angleBetween",value:function(u,p,g){var E=_.angle(p,u),B=_.angle(p,g);return _.diff(E,B)}},{key:"diff",value:function(u,p){var g=null;return(g=u<p?p-u:u-p)>Math.PI&&(g=2*Math.PI-g),g}},{key:"toRadians",value:function(u){return u*Math.PI/180}},{key:"getTurn",value:function(u,p){var g=Math.sin(p-u);return g>0?_.COUNTERCLOCKWISE:g<0?_.CLOCKWISE:_.NONE}},{key:"angleBetweenOriented",value:function(u,p,g){var E=_.angle(p,u),B=_.angle(p,g)-E;return B<=-Math.PI?B+_.PI_TIMES_2:B>Math.PI?B-_.PI_TIMES_2:B}}])})();hr.PI_TIMES_2=2*Math.PI,hr.PI_OVER_2=Math.PI/2,hr.PI_OVER_4=Math.PI/4,hr.COUNTERCLOCKWISE=be.COUNTERCLOCKWISE,hr.CLOCKWISE=be.CLOCKWISE,hr.NONE=be.COLLINEAR;var hd=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"addNextSegment",value:function(u,p){if(this._s0=this._s1,this._s1=this._s2,this._s2=u,this._seg0.setCoordinates(this._s0,this._s1),this.computeOffsetSegment(this._seg0,this._side,this._distance,this._offset0),this._seg1.setCoordinates(this._s1,this._s2),this.computeOffsetSegment(this._seg1,this._side,this._distance,this._offset1),this._s1.equals(this._s2))return null;var g=be.index(this._s0,this._s1,this._s2),E=g===be.CLOCKWISE&&this._side===q.LEFT||g===be.COUNTERCLOCKWISE&&this._side===q.RIGHT;g===0?this.addCollinear(p):E?this.addOutsideTurn(g,p):this.addInsideTurn(g,p)}},{key:"addLineEndCap",value:function(u,p){var g=new cr(u,p),E=new cr;this.computeOffsetSegment(g,q.LEFT,this._distance,E);var B=new cr;this.computeOffsetSegment(g,q.RIGHT,this._distance,B);var F=p.x-u.x,G=p.y-u.y,Y=Math.atan2(G,F);switch(this._bufParams.getEndCapStyle()){case w.CAP_ROUND:this._segList.addPt(E.p1),this.addDirectedFillet(p,Y+Math.PI/2,Y-Math.PI/2,be.CLOCKWISE,this._distance),this._segList.addPt(B.p1);break;case w.CAP_FLAT:this._segList.addPt(E.p1),this._segList.addPt(B.p1);break;case w.CAP_SQUARE:var ae=new ie;ae.x=Math.abs(this._distance)*Math.cos(Y),ae.y=Math.abs(this._distance)*Math.sin(Y);var xe=new ie(E.p1.x+ae.x,E.p1.y+ae.y),Ie=new ie(B.p1.x+ae.x,B.p1.y+ae.y);this._segList.addPt(xe),this._segList.addPt(Ie)}}},{key:"getCoordinates",value:function(){return this._segList.getCoordinates()}},{key:"addMitreJoin",value:function(u,p,g,E){var B=it.intersection(p.p0,p.p1,g.p0,g.p1);if(B!==null&&(E<=0?1:B.distance(u)/Math.abs(E))<=this._bufParams.getMitreLimit())return this._segList.addPt(B),null;this.addLimitedMitreJoin(p,g,E,this._bufParams.getMitreLimit())}},{key:"addOutsideTurn",value:function(u,p){if(this._offset0.p1.distance(this._offset1.p0)<this._distance*_.OFFSET_SEGMENT_SEPARATION_FACTOR)return this._segList.addPt(this._offset0.p1),null;this._bufParams.getJoinStyle()===w.JOIN_MITRE?this.addMitreJoin(this._s1,this._offset0,this._offset1,this._distance):this._bufParams.getJoinStyle()===w.JOIN_BEVEL?this.addBevelJoin(this._offset0,this._offset1):(p&&this._segList.addPt(this._offset0.p1),this.addCornerFillet(this._s1,this._offset0.p1,this._offset1.p0,u,this._distance),this._segList.addPt(this._offset1.p0))}},{key:"createSquare",value:function(u){this._segList.addPt(new ie(u.x+this._distance,u.y+this._distance)),this._segList.addPt(new ie(u.x+this._distance,u.y-this._distance)),this._segList.addPt(new ie(u.x-this._distance,u.y-this._distance)),this._segList.addPt(new ie(u.x-this._distance,u.y+this._distance)),this._segList.closeRing()}},{key:"addSegments",value:function(u,p){this._segList.addPts(u,p)}},{key:"addFirstSegment",value:function(){this._segList.addPt(this._offset1.p0)}},{key:"addCornerFillet",value:function(u,p,g,E,B){var F=p.x-u.x,G=p.y-u.y,Y=Math.atan2(G,F),ae=g.x-u.x,xe=g.y-u.y,Ie=Math.atan2(xe,ae);E===be.CLOCKWISE?Y<=Ie&&(Y+=2*Math.PI):Y>=Ie&&(Y-=2*Math.PI),this._segList.addPt(p),this.addDirectedFillet(u,Y,Ie,E,B),this._segList.addPt(g)}},{key:"addLastSegment",value:function(){this._segList.addPt(this._offset1.p1)}},{key:"initSideSegments",value:function(u,p,g){this._s1=u,this._s2=p,this._side=g,this._seg1.setCoordinates(u,p),this.computeOffsetSegment(this._seg1,g,this._distance,this._offset1)}},{key:"addLimitedMitreJoin",value:function(u,p,g,E){var B=this._seg0.p1,F=hr.angle(B,this._seg0.p0),G=hr.angleBetweenOriented(this._seg0.p0,B,this._seg1.p1)/2,Y=hr.normalize(F+G),ae=hr.normalize(Y+Math.PI),xe=E*g,Ie=g-xe*Math.abs(Math.sin(G)),Ge=new cr(B,new ie(B.x+xe*Math.cos(ae),B.y+xe*Math.sin(ae))),ut=Ge.pointAlongOffset(1,Ie),Rt=Ge.pointAlongOffset(1,-Ie);this._side===q.LEFT?(this._segList.addPt(ut),this._segList.addPt(Rt)):(this._segList.addPt(Rt),this._segList.addPt(ut))}},{key:"addDirectedFillet",value:function(u,p,g,E,B){var F=E===be.CLOCKWISE?-1:1,G=Math.abs(p-g),Y=Math.trunc(G/this._filletAngleQuantum+.5);if(Y<1)return null;for(var ae=G/Y,xe=new ie,Ie=0;Ie<Y;Ie++){var Ge=p+F*Ie*ae;xe.x=u.x+B*Math.cos(Ge),xe.y=u.y+B*Math.sin(Ge),this._segList.addPt(xe)}}},{key:"computeOffsetSegment",value:function(u,p,g,E){var B=p===q.LEFT?1:-1,F=u.p1.x-u.p0.x,G=u.p1.y-u.p0.y,Y=Math.sqrt(F*F+G*G),ae=B*g*F/Y,xe=B*g*G/Y;E.p0.x=u.p0.x-xe,E.p0.y=u.p0.y+ae,E.p1.x=u.p1.x-xe,E.p1.y=u.p1.y+ae}},{key:"addInsideTurn",value:function(u,p){if(this._li.computeIntersection(this._offset0.p0,this._offset0.p1,this._offset1.p0,this._offset1.p1),this._li.hasIntersection())this._segList.addPt(this._li.getIntersection(0));else if(this._hasNarrowConcaveAngle=!0,this._offset0.p1.distance(this._offset1.p0)<this._distance*_.INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR)this._segList.addPt(this._offset0.p1);else{if(this._segList.addPt(this._offset0.p1),this._closingSegLengthFactor>0){var g=new ie((this._closingSegLengthFactor*this._offset0.p1.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset0.p1.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(g);var E=new ie((this._closingSegLengthFactor*this._offset1.p0.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset1.p0.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(E)}else this._segList.addPt(this._s1);this._segList.addPt(this._offset1.p0)}}},{key:"createCircle",value:function(u){var p=new ie(u.x+this._distance,u.y);this._segList.addPt(p),this.addDirectedFillet(u,0,2*Math.PI,-1,this._distance),this._segList.closeRing()}},{key:"addBevelJoin",value:function(u,p){this._segList.addPt(u.p1),this._segList.addPt(p.p0)}},{key:"init",value:function(u){this._distance=u,this._maxCurveSegmentError=u*(1-Math.cos(this._filletAngleQuantum/2)),this._segList=new Ew,this._segList.setPrecisionModel(this._precisionModel),this._segList.setMinimumVertexDistance(u*_.CURVE_VERTEX_SNAP_DISTANCE_FACTOR)}},{key:"addCollinear",value:function(u){this._li.computeIntersection(this._s0,this._s1,this._s1,this._s2),this._li.getIntersectionNum()>=2&&(this._bufParams.getJoinStyle()===w.JOIN_BEVEL||this._bufParams.getJoinStyle()===w.JOIN_MITRE?(u&&this._segList.addPt(this._offset0.p1),this._segList.addPt(this._offset1.p0)):this.addCornerFillet(this._s1,this._offset0.p1,this._offset1.p0,be.CLOCKWISE,this._distance))}},{key:"closeRing",value:function(){this._segList.closeRing()}},{key:"hasNarrowConcaveAngle",value:function(){return this._hasNarrowConcaveAngle}}],[{key:"constructor_",value:function(){this._maxCurveSegmentError=0,this._filletAngleQuantum=null,this._closingSegLengthFactor=1,this._segList=null,this._distance=0,this._precisionModel=null,this._bufParams=null,this._li=null,this._s0=null,this._s1=null,this._s2=null,this._seg0=new cr,this._seg1=new cr,this._offset0=new cr,this._offset1=new cr,this._side=0,this._hasNarrowConcaveAngle=!1;var u=arguments[0],p=arguments[1],g=arguments[2];this._precisionModel=u,this._bufParams=p,this._li=new ql,this._filletAngleQuantum=Math.PI/2/p.getQuadrantSegments(),p.getQuadrantSegments()>=8&&p.getJoinStyle()===w.JOIN_ROUND&&(this._closingSegLengthFactor=_.MAX_CLOSING_SEG_LEN_FACTOR),this.init(g)}}])})();hd.OFFSET_SEGMENT_SEPARATION_FACTOR=.001,hd.INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR=.001,hd.CURVE_VERTEX_SNAP_DISTANCE_FACTOR=1e-6,hd.MAX_CLOSING_SEG_LEN_FACTOR=80;var DF=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"getOffsetCurve",value:function(u,p){if(this._distance=p,p===0)return null;var g=p<0,E=Math.abs(p),B=this.getSegGen(E);u.length<=1?this.computePointCurve(u[0],B):this.computeOffsetCurve(u,g,B);var F=B.getCoordinates();return g&&In.reverse(F),F}},{key:"computeSingleSidedBufferCurve",value:function(u,p,g){var E=this.simplifyTolerance(this._distance);if(p){g.addSegments(u,!0);var B=jr.simplify(u,-E),F=B.length-1;g.initSideSegments(B[F],B[F-1],q.LEFT),g.addFirstSegment();for(var G=F-2;G>=0;G--)g.addNextSegment(B[G],!0)}else{g.addSegments(u,!1);var Y=jr.simplify(u,E),ae=Y.length-1;g.initSideSegments(Y[0],Y[1],q.LEFT),g.addFirstSegment();for(var xe=2;xe<=ae;xe++)g.addNextSegment(Y[xe],!0)}g.addLastSegment(),g.closeRing()}},{key:"computeRingBufferCurve",value:function(u,p,g){var E=this.simplifyTolerance(this._distance);p===q.RIGHT&&(E=-E);var B=jr.simplify(u,E),F=B.length-1;g.initSideSegments(B[F-1],B[0],p);for(var G=1;G<=F;G++){var Y=G!==1;g.addNextSegment(B[G],Y)}g.closeRing()}},{key:"computeLineBufferCurve",value:function(u,p){var g=this.simplifyTolerance(this._distance),E=jr.simplify(u,g),B=E.length-1;p.initSideSegments(E[0],E[1],q.LEFT);for(var F=2;F<=B;F++)p.addNextSegment(E[F],!0);p.addLastSegment(),p.addLineEndCap(E[B-1],E[B]);var G=jr.simplify(u,-g),Y=G.length-1;p.initSideSegments(G[Y],G[Y-1],q.LEFT);for(var ae=Y-2;ae>=0;ae--)p.addNextSegment(G[ae],!0);p.addLastSegment(),p.addLineEndCap(G[1],G[0]),p.closeRing()}},{key:"computePointCurve",value:function(u,p){switch(this._bufParams.getEndCapStyle()){case w.CAP_ROUND:p.createCircle(u);break;case w.CAP_SQUARE:p.createSquare(u)}}},{key:"getLineCurve",value:function(u,p){if(this._distance=p,this.isLineOffsetEmpty(p))return null;var g=Math.abs(p),E=this.getSegGen(g);if(u.length<=1)this.computePointCurve(u[0],E);else if(this._bufParams.isSingleSided()){var B=p<0;this.computeSingleSidedBufferCurve(u,B,E)}else this.computeLineBufferCurve(u,E);return E.getCoordinates()}},{key:"getBufferParameters",value:function(){return this._bufParams}},{key:"simplifyTolerance",value:function(u){return u*this._bufParams.getSimplifyFactor()}},{key:"getRingCurve",value:function(u,p,g){if(this._distance=g,u.length<=2)return this.getLineCurve(u,g);if(g===0)return _.copyCoordinates(u);var E=this.getSegGen(g);return this.computeRingBufferCurve(u,p,E),E.getCoordinates()}},{key:"computeOffsetCurve",value:function(u,p,g){var E=this.simplifyTolerance(this._distance);if(p){var B=jr.simplify(u,-E),F=B.length-1;g.initSideSegments(B[F],B[F-1],q.LEFT),g.addFirstSegment();for(var G=F-2;G>=0;G--)g.addNextSegment(B[G],!0)}else{var Y=jr.simplify(u,E),ae=Y.length-1;g.initSideSegments(Y[0],Y[1],q.LEFT),g.addFirstSegment();for(var xe=2;xe<=ae;xe++)g.addNextSegment(Y[xe],!0)}g.addLastSegment()}},{key:"isLineOffsetEmpty",value:function(u){return u===0||u<0&&!this._bufParams.isSingleSided()}},{key:"getSegGen",value:function(u){return new hd(this._precisionModel,this._bufParams,u)}}],[{key:"constructor_",value:function(){this._distance=0,this._precisionModel=null,this._bufParams=null;var u=arguments[0],p=arguments[1];this._precisionModel=u,this._bufParams=p}},{key:"copyCoordinates",value:function(u){for(var p=new Array(u.length).fill(null),g=0;g<p.length;g++)p[g]=new ie(u[g]);return p}}])})(),Cw=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"findStabbedSegments",value:function(){if(arguments.length===1){for(var _=arguments[0],u=new Pe,p=this._subgraphs.iterator();p.hasNext();){var g=p.next(),E=g.getEnvelope();_.y<E.getMinY()||_.y>E.getMaxY()||this.findStabbedSegments(_,g.getDirectedEdges(),u)}return u}if(arguments.length===3){if(X(arguments[2],We)&&arguments[0]instanceof ie&&arguments[1]instanceof ov){for(var B=arguments[0],F=arguments[1],G=arguments[2],Y=F.getEdge().getCoordinates(),ae=0;ae<Y.length-1;ae++)if(this._seg.p0=Y[ae],this._seg.p1=Y[ae+1],this._seg.p0.y>this._seg.p1.y&&this._seg.reverse(),!(Math.max(this._seg.p0.x,this._seg.p1.x)<B.x||this._seg.isHorizontal()||B.y<this._seg.p0.y||B.y>this._seg.p1.y||be.index(this._seg.p0,this._seg.p1,B)===be.RIGHT)){var xe=F.getDepth(q.LEFT);this._seg.p0.equals(Y[ae])||(xe=F.getDepth(q.RIGHT));var Ie=new ww(this._seg,xe);G.add(Ie)}}else if(X(arguments[2],We)&&arguments[0]instanceof ie&&X(arguments[1],We))for(var Ge=arguments[0],ut=arguments[2],Rt=arguments[1].iterator();Rt.hasNext();){var Ft=Rt.next();Ft.isForward()&&this.findStabbedSegments(Ge,Ft,ut)}}}},{key:"getDepth",value:function(_){var u=this.findStabbedSegments(_);return u.size()===0?0:Zc.min(u)._leftDepth}}],[{key:"constructor_",value:function(){this._subgraphs=null,this._seg=new cr;var _=arguments[0];this._subgraphs=_}}])})(),ww=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"compareTo",value:function(_){var u=_;if(this._upwardSeg.minX()>=u._upwardSeg.maxX())return 1;if(this._upwardSeg.maxX()<=u._upwardSeg.minX())return-1;var p=this._upwardSeg.orientationIndex(u._upwardSeg);return p!==0||(p=-1*u._upwardSeg.orientationIndex(this._upwardSeg))!==0?p:this._upwardSeg.compareTo(u._upwardSeg)}},{key:"compareX",value:function(_,u){var p=_.p0.compareTo(u.p0);return p!==0?p:_.p1.compareTo(u.p1)}},{key:"toString",value:function(){return this._upwardSeg.toString()}},{key:"interfaces_",get:function(){return[L]}}],[{key:"constructor_",value:function(){this._upwardSeg=null,this._leftDepth=null;var _=arguments[0],u=arguments[1];this._upwardSeg=new cr(_),this._leftDepth=u}}])})();Cw.DepthSegment=ww;var Sw=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,null,[{key:"constructor_",value:function(){S.constructor_.call(this,"Projective point not representable on the Cartesian plane.")}}])})(S),hv=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"getY",value:function(){var u=this.y/this.w;if(W.isNaN(u)||W.isInfinite(u))throw new Sw;return u}},{key:"getX",value:function(){var u=this.x/this.w;if(W.isNaN(u)||W.isInfinite(u))throw new Sw;return u}},{key:"getCoordinate",value:function(){var u=new ie;return u.x=this.getX(),u.y=this.getY(),u}}],[{key:"constructor_",value:function(){if(this.x=null,this.y=null,this.w=null,arguments.length===0)this.x=0,this.y=0,this.w=1;else if(arguments.length===1){var u=arguments[0];this.x=u.x,this.y=u.y,this.w=1}else if(arguments.length===2){if(typeof arguments[0]=="number"&&typeof arguments[1]=="number"){var p=arguments[0],g=arguments[1];this.x=p,this.y=g,this.w=1}else if(arguments[0]instanceof _&&arguments[1]instanceof _){var E=arguments[0],B=arguments[1];this.x=E.y*B.w-B.y*E.w,this.y=B.x*E.w-E.x*B.w,this.w=E.x*B.y-B.x*E.y}else if(arguments[0]instanceof ie&&arguments[1]instanceof ie){var F=arguments[0],G=arguments[1];this.x=F.y-G.y,this.y=G.x-F.x,this.w=F.x*G.y-G.x*F.y}}else if(arguments.length===3){var Y=arguments[0],ae=arguments[1],xe=arguments[2];this.x=Y,this.y=ae,this.w=xe}else if(arguments.length===4){var Ie=arguments[0],Ge=arguments[1],ut=arguments[2],Rt=arguments[3],Ft=Ie.y-Ge.y,vn=Ge.x-Ie.x,pn=Ie.x*Ge.y-Ge.x*Ie.y,Dn=ut.y-Rt.y,Ki=Rt.x-ut.x,ps=ut.x*Rt.y-Rt.x*ut.y;this.x=vn*ps-Ki*pn,this.y=Dn*pn-Ft*ps,this.w=Ft*Ki-Dn*vn}}}])})(),FF=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"area",value:function(){return _.area(this.p0,this.p1,this.p2)}},{key:"signedArea",value:function(){return _.signedArea(this.p0,this.p1,this.p2)}},{key:"interpolateZ",value:function(u){if(u===null)throw new R("Supplied point is null.");return _.interpolateZ(u,this.p0,this.p1,this.p2)}},{key:"longestSideLength",value:function(){return _.longestSideLength(this.p0,this.p1,this.p2)}},{key:"isAcute",value:function(){return _.isAcute(this.p0,this.p1,this.p2)}},{key:"circumcentre",value:function(){return _.circumcentre(this.p0,this.p1,this.p2)}},{key:"area3D",value:function(){return _.area3D(this.p0,this.p1,this.p2)}},{key:"centroid",value:function(){return _.centroid(this.p0,this.p1,this.p2)}},{key:"inCentre",value:function(){return _.inCentre(this.p0,this.p1,this.p2)}}],[{key:"constructor_",value:function(){this.p0=null,this.p1=null,this.p2=null;var u=arguments[0],p=arguments[1],g=arguments[2];this.p0=u,this.p1=p,this.p2=g}},{key:"area",value:function(u,p,g){return Math.abs(((g.x-u.x)*(p.y-u.y)-(p.x-u.x)*(g.y-u.y))/2)}},{key:"signedArea",value:function(u,p,g){return((g.x-u.x)*(p.y-u.y)-(p.x-u.x)*(g.y-u.y))/2}},{key:"det",value:function(u,p,g,E){return u*E-p*g}},{key:"interpolateZ",value:function(u,p,g,E){var B=p.x,F=p.y,G=g.x-B,Y=E.x-B,ae=g.y-F,xe=E.y-F,Ie=G*xe-Y*ae,Ge=u.x-B,ut=u.y-F,Rt=(xe*Ge-Y*ut)/Ie,Ft=(-ae*Ge+G*ut)/Ie;return p.getZ()+Rt*(g.getZ()-p.getZ())+Ft*(E.getZ()-p.getZ())}},{key:"longestSideLength",value:function(u,p,g){var E=u.distance(p),B=p.distance(g),F=g.distance(u),G=E;return B>G&&(G=B),F>G&&(G=F),G}},{key:"circumcentreDD",value:function(u,p,g){var E=ee.valueOf(u.x).subtract(g.x),B=ee.valueOf(u.y).subtract(g.y),F=ee.valueOf(p.x).subtract(g.x),G=ee.valueOf(p.y).subtract(g.y),Y=ee.determinant(E,B,F,G).multiply(2),ae=E.sqr().add(B.sqr()),xe=F.sqr().add(G.sqr()),Ie=ee.determinant(B,ae,G,xe),Ge=ee.determinant(E,ae,F,xe);return new ie(ee.valueOf(g.x).subtract(Ie.divide(Y)).doubleValue(),ee.valueOf(g.y).add(Ge.divide(Y)).doubleValue())}},{key:"isAcute",value:function(u,p,g){return!!hr.isAcute(u,p,g)&&!!hr.isAcute(p,g,u)&&!!hr.isAcute(g,u,p)}},{key:"circumcentre",value:function(u,p,g){var E=g.x,B=g.y,F=u.x-E,G=u.y-B,Y=p.x-E,ae=p.y-B,xe=2*_.det(F,G,Y,ae),Ie=_.det(G,F*F+G*G,ae,Y*Y+ae*ae),Ge=_.det(F,F*F+G*G,Y,Y*Y+ae*ae);return new ie(E-Ie/xe,B+Ge/xe)}},{key:"perpendicularBisector",value:function(u,p){var g=p.x-u.x,E=p.y-u.y;return new hv(new hv(u.x+g/2,u.y+E/2,1),new hv(u.x-E+g/2,u.y+g+E/2,1))}},{key:"angleBisector",value:function(u,p,g){var E=p.distance(u),B=E/(E+p.distance(g)),F=g.x-u.x,G=g.y-u.y;return new ie(u.x+B*F,u.y+B*G)}},{key:"area3D",value:function(u,p,g){var E=p.x-u.x,B=p.y-u.y,F=p.getZ()-u.getZ(),G=g.x-u.x,Y=g.y-u.y,ae=g.getZ()-u.getZ(),xe=B*ae-F*Y,Ie=F*G-E*ae,Ge=E*Y-B*G,ut=xe*xe+Ie*Ie+Ge*Ge;return Math.sqrt(ut)/2}},{key:"centroid",value:function(u,p,g){return new ie((u.x+p.x+g.x)/3,(u.y+p.y+g.y)/3)}},{key:"inCentre",value:function(u,p,g){var E=p.distance(g),B=u.distance(g),F=u.distance(p),G=E+B+F;return new ie((E*u.x+B*p.x+F*g.x)/G,(E*u.y+B*p.y+F*g.y)/G)}}])})(),OF=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"addRingSide",value:function(_,u,p,g,E){if(u===0&&_.length<zt.MINIMUM_VALID_SIZE)return null;var B=g,F=E;_.length>=zt.MINIMUM_VALID_SIZE&&be.isCCW(_)&&(B=E,F=g,p=q.opposite(p));var G=this._curveBuilder.getRingCurve(_,p,u);this.addCurve(G,B,F)}},{key:"addRingBothSides",value:function(_,u){this.addRingSide(_,u,q.LEFT,$.EXTERIOR,$.INTERIOR),this.addRingSide(_,u,q.RIGHT,$.INTERIOR,$.EXTERIOR)}},{key:"addPoint",value:function(_){if(this._distance<=0)return null;var u=_.getCoordinates(),p=this._curveBuilder.getLineCurve(u,this._distance);this.addCurve(p,$.EXTERIOR,$.INTERIOR)}},{key:"addPolygon",value:function(_){var u=this._distance,p=q.LEFT;this._distance<0&&(u=-this._distance,p=q.RIGHT);var g=_.getExteriorRing(),E=In.removeRepeatedPoints(g.getCoordinates());if(this._distance<0&&this.isErodedCompletely(g,this._distance)||this._distance<=0&&E.length<3)return null;this.addRingSide(E,u,p,$.EXTERIOR,$.INTERIOR);for(var B=0;B<_.getNumInteriorRing();B++){var F=_.getInteriorRingN(B),G=In.removeRepeatedPoints(F.getCoordinates());this._distance>0&&this.isErodedCompletely(F,-this._distance)||this.addRingSide(G,u,q.opposite(p),$.INTERIOR,$.EXTERIOR)}}},{key:"isTriangleErodedCompletely",value:function(_,u){var p=new FF(_[0],_[1],_[2]),g=p.inCentre();return qe.pointToSegment(g,p.p0,p.p1)<Math.abs(u)}},{key:"addLineString",value:function(_){if(this._curveBuilder.isLineOffsetEmpty(this._distance))return null;var u=In.removeRepeatedPoints(_.getCoordinates());if(In.isRing(u)&&!this._curveBuilder.getBufferParameters().isSingleSided())this.addRingBothSides(u,this._distance);else{var p=this._curveBuilder.getLineCurve(u,this._distance);this.addCurve(p,$.EXTERIOR,$.INTERIOR)}}},{key:"addCurve",value:function(_,u,p){if(_===null||_.length<2)return null;var g=new Wl(_,new Sr(0,$.BOUNDARY,u,p));this._curveList.add(g)}},{key:"getCurves",value:function(){return this.add(this._inputGeom),this._curveList}},{key:"add",value:function(_){if(_.isEmpty())return null;if(_ instanceof Fe)this.addPolygon(_);else if(_ instanceof zi)this.addLineString(_);else if(_ instanceof Wo)this.addPoint(_);else if(_ instanceof wt)this.addCollection(_);else if(_ instanceof Ut)this.addCollection(_);else if(_ instanceof He)this.addCollection(_);else{if(!(_ instanceof vt))throw new Qe(_.getGeometryType());this.addCollection(_)}}},{key:"isErodedCompletely",value:function(_,u){var p=_.getCoordinates();if(p.length<4)return u<0;if(p.length===4)return this.isTriangleErodedCompletely(p,u);var g=_.getEnvelopeInternal(),E=Math.min(g.getHeight(),g.getWidth());return u<0&&2*Math.abs(u)>E}},{key:"addCollection",value:function(_){for(var u=0;u<_.getNumGeometries();u++){var p=_.getGeometryN(u);this.add(p)}}}],[{key:"constructor_",value:function(){this._inputGeom=null,this._distance=null,this._curveBuilder=null,this._curveList=new Pe;var _=arguments[0],u=arguments[1],p=arguments[2];this._inputGeom=_,this._distance=u,this._curveBuilder=p}}])})(),UF=(function(){return o((function _(){s(this,_)}),[{key:"locate",value:function(_){}}])})(),zF=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"next",value:function(){if(this._atStart)return this._atStart=!1,_.isAtomic(this._parent)&&this._index++,this._parent;if(this._subcollectionIterator!==null){if(this._subcollectionIterator.hasNext())return this._subcollectionIterator.next();this._subcollectionIterator=null}if(this._index>=this._max)throw new Z;var u=this._parent.getGeometryN(this._index++);return u instanceof vt?(this._subcollectionIterator=new _(u),this._subcollectionIterator.next()):u}},{key:"remove",value:function(){throw new Qe(this.getClass().getName())}},{key:"hasNext",value:function(){if(this._atStart)return!0;if(this._subcollectionIterator!==null){if(this._subcollectionIterator.hasNext())return!0;this._subcollectionIterator=null}return!(this._index>=this._max)}},{key:"interfaces_",get:function(){return[TF]}}],[{key:"constructor_",value:function(){this._parent=null,this._atStart=null,this._max=null,this._index=null,this._subcollectionIterator=null;var u=arguments[0];this._parent=u,this._atStart=!0,this._index=0,this._max=u.getNumGeometries()}},{key:"isAtomic",value:function(u){return!(u instanceof vt)}}])})(),QF=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"locate",value:function(u){return _.locate(u,this._geom)}},{key:"interfaces_",get:function(){return[UF]}}],[{key:"constructor_",value:function(){this._geom=null;var u=arguments[0];this._geom=u}},{key:"locatePointInPolygon",value:function(u,p){if(p.isEmpty())return $.EXTERIOR;var g=p.getExteriorRing(),E=_.locatePointInRing(u,g);if(E!==$.INTERIOR)return E;for(var B=0;B<p.getNumInteriorRing();B++){var F=p.getInteriorRingN(B),G=_.locatePointInRing(u,F);if(G===$.BOUNDARY)return $.BOUNDARY;if(G===$.INTERIOR)return $.EXTERIOR}return $.INTERIOR}},{key:"locatePointInRing",value:function(u,p){return p.getEnvelopeInternal().intersects(u)?rv.locateInRing(u,p.getCoordinates()):$.EXTERIOR}},{key:"containsPointInPolygon",value:function(u,p){return $.EXTERIOR!==_.locatePointInPolygon(u,p)}},{key:"locateInGeometry",value:function(u,p){if(p instanceof Fe)return _.locatePointInPolygon(u,p);if(p instanceof vt)for(var g=new zF(p);g.hasNext();){var E=g.next();if(E!==p){var B=_.locateInGeometry(u,E);if(B!==$.EXTERIOR)return B}}return $.EXTERIOR}},{key:"isContained",value:function(u,p){return $.EXTERIOR!==_.locate(u,p)}},{key:"locate",value:function(u,p){return p.isEmpty()?$.EXTERIOR:p.getEnvelopeInternal().intersects(u)?_.locateInGeometry(u,p):$.EXTERIOR}}])})(),GF=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,[{key:"linkResultDirectedEdges",value:function(){this.getResultAreaEdges();for(var p=null,g=null,E=this._SCANNING_FOR_INCOMING,B=0;B<this._resultAreaEdgeList.size();B++){var F=this._resultAreaEdgeList.get(B),G=F.getSym();if(F.getLabel().isArea())switch(p===null&&F.isInResult()&&(p=F),E){case this._SCANNING_FOR_INCOMING:if(!G.isInResult())continue;g=G,E=this._LINKING_TO_OUTGOING;break;case this._LINKING_TO_OUTGOING:if(!F.isInResult())continue;g.setNext(F),E=this._SCANNING_FOR_INCOMING}}if(E===this._LINKING_TO_OUTGOING){if(p===null)throw new Ye("no outgoing dirEdge found",this.getCoordinate());re.isTrue(p.isInResult(),"unable to link last incoming dirEdge"),g.setNext(p)}}},{key:"insert",value:function(p){var g=p;this.insertEdgeEnd(g,g)}},{key:"getRightmostEdge",value:function(){var p=this.getEdges(),g=p.size();if(g<1)return null;var E=p.get(0);if(g===1)return E;var B=p.get(g-1),F=E.getQuadrant(),G=B.getQuadrant();return Ts.isNorthern(F)&&Ts.isNorthern(G)?E:Ts.isNorthern(F)||Ts.isNorthern(G)?E.getDy()!==0?E:B.getDy()!==0?B:(re.shouldNeverReachHere("found two horizontal edges incident on node"),null):B}},{key:"print",value:function(p){xt.out.println("DirectedEdgeStar: "+this.getCoordinate());for(var g=this.iterator();g.hasNext();){var E=g.next();p.print("out "),E.print(p),p.println(),p.print("in "),E.getSym().print(p),p.println()}}},{key:"getResultAreaEdges",value:function(){if(this._resultAreaEdgeList!==null)return this._resultAreaEdgeList;this._resultAreaEdgeList=new Pe;for(var p=this.iterator();p.hasNext();){var g=p.next();(g.isInResult()||g.getSym().isInResult())&&this._resultAreaEdgeList.add(g)}return this._resultAreaEdgeList}},{key:"updateLabelling",value:function(p){for(var g=this.iterator();g.hasNext();){var E=g.next().getLabel();E.setAllLocationsIfNull(0,p.getLocation(0)),E.setAllLocationsIfNull(1,p.getLocation(1))}}},{key:"linkAllDirectedEdges",value:function(){this.getEdges();for(var p=null,g=null,E=this._edgeList.size()-1;E>=0;E--){var B=this._edgeList.get(E),F=B.getSym();g===null&&(g=F),p!==null&&F.setNext(p),p=B}g.setNext(p)}},{key:"computeDepths",value:function(){if(arguments.length===1){var p=arguments[0],g=this.findIndex(p),E=p.getDepth(q.LEFT),B=p.getDepth(q.RIGHT),F=this.computeDepths(g+1,this._edgeList.size(),E);if(this.computeDepths(0,g,F)!==B)throw new Ye("depth mismatch at "+p.getCoordinate())}else if(arguments.length===3){for(var G=arguments[1],Y=arguments[2],ae=arguments[0];ae<G;ae++){var xe=this._edgeList.get(ae);xe.setEdgeDepths(q.RIGHT,Y),Y=xe.getDepth(q.LEFT)}return Y}}},{key:"mergeSymLabels",value:function(){for(var p=this.iterator();p.hasNext();){var g=p.next();g.getLabel().merge(g.getSym().getLabel())}}},{key:"linkMinimalDirectedEdges",value:function(p){for(var g=null,E=null,B=this._SCANNING_FOR_INCOMING,F=this._resultAreaEdgeList.size()-1;F>=0;F--){var G=this._resultAreaEdgeList.get(F),Y=G.getSym();switch(g===null&&G.getEdgeRing()===p&&(g=G),B){case this._SCANNING_FOR_INCOMING:if(Y.getEdgeRing()!==p)continue;E=Y,B=this._LINKING_TO_OUTGOING;break;case this._LINKING_TO_OUTGOING:if(G.getEdgeRing()!==p)continue;E.setNextMin(G),B=this._SCANNING_FOR_INCOMING}}B===this._LINKING_TO_OUTGOING&&(re.isTrue(g!==null,"found null for first outgoing dirEdge"),re.isTrue(g.getEdgeRing()===p,"unable to link last incoming dirEdge"),E.setNextMin(g))}},{key:"getOutgoingDegree",value:function(){if(arguments.length===0){for(var p=0,g=this.iterator();g.hasNext();)g.next().isInResult()&&p++;return p}if(arguments.length===1){for(var E=arguments[0],B=0,F=this.iterator();F.hasNext();)F.next().getEdgeRing()===E&&B++;return B}}},{key:"getLabel",value:function(){return this._label}},{key:"findCoveredLineEdges",value:function(){for(var p=$.NONE,g=this.iterator();g.hasNext();){var E=g.next(),B=E.getSym();if(!E.isLineEdge()){if(E.isInResult()){p=$.INTERIOR;break}if(B.isInResult()){p=$.EXTERIOR;break}}}if(p===$.NONE)return null;for(var F=p,G=this.iterator();G.hasNext();){var Y=G.next(),ae=Y.getSym();Y.isLineEdge()?Y.getEdge().setCovered(F===$.INTERIOR):(Y.isInResult()&&(F=$.EXTERIOR),ae.isInResult()&&(F=$.INTERIOR))}}},{key:"computeLabelling",value:function(p){A(u,"computeLabelling",this,1).call(this,p),this._label=new Sr($.NONE);for(var g=this.iterator();g.hasNext();)for(var E=g.next().getEdge().getLabel(),B=0;B<2;B++){var F=E.getLocation(B);F!==$.INTERIOR&&F!==$.BOUNDARY||this._label.setLocation(B,$.INTERIOR)}}}],[{key:"constructor_",value:function(){this._resultAreaEdgeList=null,this._label=null,this._SCANNING_FOR_INCOMING=1,this._LINKING_TO_OUTGOING=2}}])})((function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"getNextCW",value:function(_){this.getEdges();var u=this._edgeList.indexOf(_),p=u-1;return u===0&&(p=this._edgeList.size()-1),this._edgeList.get(p)}},{key:"propagateSideLabels",value:function(_){for(var u=$.NONE,p=this.iterator();p.hasNext();){var g=p.next().getLabel();g.isArea(_)&&g.getLocation(_,q.LEFT)!==$.NONE&&(u=g.getLocation(_,q.LEFT))}if(u===$.NONE)return null;for(var E=u,B=this.iterator();B.hasNext();){var F=B.next(),G=F.getLabel();if(G.getLocation(_,q.ON)===$.NONE&&G.setLocation(_,q.ON,E),G.isArea(_)){var Y=G.getLocation(_,q.LEFT),ae=G.getLocation(_,q.RIGHT);if(ae!==$.NONE){if(ae!==E)throw new Ye("side location conflict",F.getCoordinate());Y===$.NONE&&re.shouldNeverReachHere("found single null side (at "+F.getCoordinate()+")"),E=Y}else re.isTrue(G.getLocation(_,q.LEFT)===$.NONE,"found single null side"),G.setLocation(_,q.RIGHT,E),G.setLocation(_,q.LEFT,E)}}}},{key:"getCoordinate",value:function(){var _=this.iterator();return _.hasNext()?_.next().getCoordinate():null}},{key:"print",value:function(_){xt.out.println("EdgeEndStar: "+this.getCoordinate());for(var u=this.iterator();u.hasNext();)u.next().print(_)}},{key:"isAreaLabelsConsistent",value:function(_){return this.computeEdgeEndLabels(_.getBoundaryNodeRule()),this.checkAreaLabelsConsistent(0)}},{key:"checkAreaLabelsConsistent",value:function(_){var u=this.getEdges();if(u.size()<=0)return!0;var p=u.size()-1,g=u.get(p).getLabel().getLocation(_,q.LEFT);re.isTrue(g!==$.NONE,"Found unlabelled area edge");for(var E=g,B=this.iterator();B.hasNext();){var F=B.next().getLabel();re.isTrue(F.isArea(_),"Found non-area edge");var G=F.getLocation(_,q.LEFT),Y=F.getLocation(_,q.RIGHT);if(G===Y||Y!==E)return!1;E=G}return!0}},{key:"findIndex",value:function(_){this.iterator();for(var u=0;u<this._edgeList.size();u++)if(this._edgeList.get(u)===_)return u;return-1}},{key:"iterator",value:function(){return this.getEdges().iterator()}},{key:"getEdges",value:function(){return this._edgeList===null&&(this._edgeList=new Pe(this._edgeMap.values())),this._edgeList}},{key:"getLocation",value:function(_,u,p){return this._ptInAreaLocation[_]===$.NONE&&(this._ptInAreaLocation[_]=QF.locate(u,p[_].getGeometry())),this._ptInAreaLocation[_]}},{key:"toString",value:function(){var _=new V;_.append("EdgeEndStar: "+this.getCoordinate()),_.append(`
271
271
  `);for(var u=this.iterator();u.hasNext();){var p=u.next();_.append(p),_.append(`
272
- `)}return _.toString()}},{key:"computeEdgeEndLabels",value:function(_){for(var u=this.iterator();u.hasNext();)u.next().computeLabel(_)}},{key:"computeLabelling",value:function(_){this.computeEdgeEndLabels(_[0].getBoundaryNodeRule()),this.propagateSideLabels(0),this.propagateSideLabels(1);for(var u=[!1,!1],p=this.iterator();p.hasNext();)for(var g=p.next().getLabel(),E=0;E<2;E++)g.isLine(E)&&g.getLocation(E)===$.BOUNDARY&&(u[E]=!0);for(var B=this.iterator();B.hasNext();)for(var F=B.next(),G=F.getLabel(),Y=0;Y<2;Y++)if(G.isAnyNull(Y)){var ae=$.NONE;if(u[Y])ae=$.EXTERIOR;else{var xe=F.getCoordinate();ae=this.getLocation(Y,xe,_)}G.setAllLocationsIfNull(Y,ae)}}},{key:"getDegree",value:function(){return this._edgeMap.size()}},{key:"insertEdgeEnd",value:function(_,u){this._edgeMap.put(_,u),this._edgeList=null}}],[{key:"constructor_",value:function(){this._edgeMap=new cd,this._edgeList=null,this._ptInAreaLocation=[$.NONE,$.NONE]}}])})()),HF=(function(_){function u(){return s(this,u),i(this,u)}return d(u,_),o(u,[{key:"createNode",value:function(p){return new Vf(p,new GF)}}])})(mw),Iw=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"compareTo",value:function(u){var p=u;return _.compareOriented(this._pts,this._orientation,p._pts,p._orientation)}},{key:"interfaces_",get:function(){return[L]}}],[{key:"constructor_",value:function(){this._pts=null,this._orientation=null;var u=arguments[0];this._pts=u,this._orientation=_.orientation(u)}},{key:"orientation",value:function(u){return In.increasingDirection(u)===1}},{key:"compareOriented",value:function(u,p,g,E){for(var B=p?1:-1,F=E?1:-1,G=p?u.length:-1,Y=E?g.length:-1,ae=p?0:u.length-1,xe=E?0:g.length-1;;){var Ie=u[ae].compareTo(g[xe]);if(Ie!==0)return Ie;var Ge=(ae+=B)===G,ut=(xe+=F)===Y;if(Ge&&!ut)return-1;if(!Ge&&ut)return 1;if(Ge&&ut)return 0}}}])})(),$F=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"print",value:function(_){_.print("MULTILINESTRING ( ");for(var u=0;u<this._edges.size();u++){var p=this._edges.get(u);u>0&&_.print(","),_.print("(");for(var g=p.getCoordinates(),E=0;E<g.length;E++)E>0&&_.print(","),_.print(g[E].x+" "+g[E].y);_.println(")")}_.print(") ")}},{key:"addAll",value:function(_){for(var u=_.iterator();u.hasNext();)this.add(u.next())}},{key:"findEdgeIndex",value:function(_){for(var u=0;u<this._edges.size();u++)if(this._edges.get(u).equals(_))return u;return-1}},{key:"iterator",value:function(){return this._edges.iterator()}},{key:"getEdges",value:function(){return this._edges}},{key:"get",value:function(_){return this._edges.get(_)}},{key:"findEqualEdge",value:function(_){var u=new Iw(_.getCoordinates());return this._ocaMap.get(u)}},{key:"add",value:function(_){this._edges.add(_);var u=new Iw(_.getCoordinates());this._ocaMap.put(u,_)}}],[{key:"constructor_",value:function(){this._edges=new Pe,this._ocaMap=new cd}}])})(),Mw=(function(){return o((function _(){s(this,_)}),[{key:"processIntersections",value:function(_,u,p,g){}},{key:"isDone",value:function(){}}])})(),VF=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"isTrivialIntersection",value:function(u,p,g,E){if(u===g&&this._li.getIntersectionNum()===1){if(_.isAdjacentSegments(p,E))return!0;if(u.isClosed()){var B=u.size()-1;if(p===0&&E===B||E===0&&p===B)return!0}}return!1}},{key:"getProperIntersectionPoint",value:function(){return this._properIntersectionPoint}},{key:"hasProperInteriorIntersection",value:function(){return this._hasProperInterior}},{key:"getLineIntersector",value:function(){return this._li}},{key:"hasProperIntersection",value:function(){return this._hasProper}},{key:"processIntersections",value:function(u,p,g,E){if(u===g&&p===E)return null;this.numTests++;var B=u.getCoordinates()[p],F=u.getCoordinates()[p+1],G=g.getCoordinates()[E],Y=g.getCoordinates()[E+1];this._li.computeIntersection(B,F,G,Y),this._li.hasIntersection()&&(this.numIntersections++,this._li.isInteriorIntersection()&&(this.numInteriorIntersections++,this._hasInterior=!0),this.isTrivialIntersection(u,p,g,E)||(this._hasIntersection=!0,u.addIntersections(this._li,p,0),g.addIntersections(this._li,E,1),this._li.isProper()&&(this.numProperIntersections++,this._hasProper=!0,this._hasProperInterior=!0)))}},{key:"hasIntersection",value:function(){return this._hasIntersection}},{key:"isDone",value:function(){return!1}},{key:"hasInteriorIntersection",value:function(){return this._hasInterior}},{key:"interfaces_",get:function(){return[Mw]}}],[{key:"constructor_",value:function(){this._hasIntersection=!1,this._hasProper=!1,this._hasProperInterior=!1,this._hasInterior=!1,this._properIntersectionPoint=null,this._li=null,this._isSelfIntersection=null,this.numIntersections=0,this.numInteriorIntersections=0,this.numProperIntersections=0,this.numTests=0;var u=arguments[0];this._li=u}},{key:"isAdjacentSegments",value:function(u,p){return Math.abs(u-p)===1}}])})(),qF=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"getSegmentIndex",value:function(){return this.segmentIndex}},{key:"getCoordinate",value:function(){return this.coord}},{key:"print",value:function(_){_.print(this.coord),_.print(" seg # = "+this.segmentIndex),_.println(" dist = "+this.dist)}},{key:"compareTo",value:function(_){var u=_;return this.compare(u.segmentIndex,u.dist)}},{key:"isEndPoint",value:function(_){return this.segmentIndex===0&&this.dist===0||this.segmentIndex===_}},{key:"toString",value:function(){return this.coord+" seg # = "+this.segmentIndex+" dist = "+this.dist}},{key:"getDistance",value:function(){return this.dist}},{key:"compare",value:function(_,u){return this.segmentIndex<_?-1:this.segmentIndex>_?1:this.dist<u?-1:this.dist>u?1:0}},{key:"interfaces_",get:function(){return[L]}}],[{key:"constructor_",value:function(){this.coord=null,this.segmentIndex=null,this.dist=null;var _=arguments[0],u=arguments[1],p=arguments[2];this.coord=new ie(_),this.segmentIndex=u,this.dist=p}}])})(),WF=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"print",value:function(_){_.println("Intersections:");for(var u=this.iterator();u.hasNext();)u.next().print(_)}},{key:"iterator",value:function(){return this._nodeMap.values().iterator()}},{key:"addSplitEdges",value:function(_){this.addEndpoints();for(var u=this.iterator(),p=u.next();u.hasNext();){var g=u.next(),E=this.createSplitEdge(p,g);_.add(E),p=g}}},{key:"addEndpoints",value:function(){var _=this.edge.pts.length-1;this.add(this.edge.pts[0],0,0),this.add(this.edge.pts[_],_,0)}},{key:"createSplitEdge",value:function(_,u){var p=u.segmentIndex-_.segmentIndex+2,g=this.edge.pts[u.segmentIndex],E=u.dist>0||!u.coord.equals2D(g);E||p--;var B=new Array(p).fill(null),F=0;B[F++]=new ie(_.coord);for(var G=_.segmentIndex+1;G<=u.segmentIndex;G++)B[F++]=this.edge.pts[G];return E&&(B[F]=u.coord),new Lw(B,new Sr(this.edge._label))}},{key:"add",value:function(_,u,p){var g=new qF(_,u,p),E=this._nodeMap.get(g);return E!==null?E:(this._nodeMap.put(g,g),g)}},{key:"isIntersection",value:function(_){for(var u=this.iterator();u.hasNext();)if(u.next().coord.equals(_))return!0;return!1}}],[{key:"constructor_",value:function(){this._nodeMap=new cd,this.edge=null;var _=arguments[0];this.edge=_}}])})(),YF=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"isIntersects",value:function(){return!this.isDisjoint()}},{key:"isCovers",value:function(){return(_.isTrue(this._matrix[$.INTERIOR][$.INTERIOR])||_.isTrue(this._matrix[$.INTERIOR][$.BOUNDARY])||_.isTrue(this._matrix[$.BOUNDARY][$.INTERIOR])||_.isTrue(this._matrix[$.BOUNDARY][$.BOUNDARY]))&&this._matrix[$.EXTERIOR][$.INTERIOR]===Ne.FALSE&&this._matrix[$.EXTERIOR][$.BOUNDARY]===Ne.FALSE}},{key:"isCoveredBy",value:function(){return(_.isTrue(this._matrix[$.INTERIOR][$.INTERIOR])||_.isTrue(this._matrix[$.INTERIOR][$.BOUNDARY])||_.isTrue(this._matrix[$.BOUNDARY][$.INTERIOR])||_.isTrue(this._matrix[$.BOUNDARY][$.BOUNDARY]))&&this._matrix[$.INTERIOR][$.EXTERIOR]===Ne.FALSE&&this._matrix[$.BOUNDARY][$.EXTERIOR]===Ne.FALSE}},{key:"set",value:function(){if(arguments.length===1)for(var u=arguments[0],p=0;p<u.length;p++){var g=Math.trunc(p/3),E=p%3;this._matrix[g][E]=Ne.toDimensionValue(u.charAt(p))}else if(arguments.length===3){var B=arguments[0],F=arguments[1],G=arguments[2];this._matrix[B][F]=G}}},{key:"isContains",value:function(){return _.isTrue(this._matrix[$.INTERIOR][$.INTERIOR])&&this._matrix[$.EXTERIOR][$.INTERIOR]===Ne.FALSE&&this._matrix[$.EXTERIOR][$.BOUNDARY]===Ne.FALSE}},{key:"setAtLeast",value:function(){if(arguments.length===1)for(var u=arguments[0],p=0;p<u.length;p++){var g=Math.trunc(p/3),E=p%3;this.setAtLeast(g,E,Ne.toDimensionValue(u.charAt(p)))}else if(arguments.length===3){var B=arguments[0],F=arguments[1],G=arguments[2];this._matrix[B][F]<G&&(this._matrix[B][F]=G)}}},{key:"setAtLeastIfValid",value:function(u,p,g){u>=0&&p>=0&&this.setAtLeast(u,p,g)}},{key:"isWithin",value:function(){return _.isTrue(this._matrix[$.INTERIOR][$.INTERIOR])&&this._matrix[$.INTERIOR][$.EXTERIOR]===Ne.FALSE&&this._matrix[$.BOUNDARY][$.EXTERIOR]===Ne.FALSE}},{key:"isTouches",value:function(u,p){return u>p?this.isTouches(p,u):(u===Ne.A&&p===Ne.A||u===Ne.L&&p===Ne.L||u===Ne.L&&p===Ne.A||u===Ne.P&&p===Ne.A||u===Ne.P&&p===Ne.L)&&this._matrix[$.INTERIOR][$.INTERIOR]===Ne.FALSE&&(_.isTrue(this._matrix[$.INTERIOR][$.BOUNDARY])||_.isTrue(this._matrix[$.BOUNDARY][$.INTERIOR])||_.isTrue(this._matrix[$.BOUNDARY][$.BOUNDARY]))}},{key:"isOverlaps",value:function(u,p){return u===Ne.P&&p===Ne.P||u===Ne.A&&p===Ne.A?_.isTrue(this._matrix[$.INTERIOR][$.INTERIOR])&&_.isTrue(this._matrix[$.INTERIOR][$.EXTERIOR])&&_.isTrue(this._matrix[$.EXTERIOR][$.INTERIOR]):u===Ne.L&&p===Ne.L&&this._matrix[$.INTERIOR][$.INTERIOR]===1&&_.isTrue(this._matrix[$.INTERIOR][$.EXTERIOR])&&_.isTrue(this._matrix[$.EXTERIOR][$.INTERIOR])}},{key:"isEquals",value:function(u,p){return u===p&&_.isTrue(this._matrix[$.INTERIOR][$.INTERIOR])&&this._matrix[$.INTERIOR][$.EXTERIOR]===Ne.FALSE&&this._matrix[$.BOUNDARY][$.EXTERIOR]===Ne.FALSE&&this._matrix[$.EXTERIOR][$.INTERIOR]===Ne.FALSE&&this._matrix[$.EXTERIOR][$.BOUNDARY]===Ne.FALSE}},{key:"toString",value:function(){for(var u=new we("123456789"),p=0;p<3;p++)for(var g=0;g<3;g++)u.setCharAt(3*p+g,Ne.toDimensionSymbol(this._matrix[p][g]));return u.toString()}},{key:"setAll",value:function(u){for(var p=0;p<3;p++)for(var g=0;g<3;g++)this._matrix[p][g]=u}},{key:"get",value:function(u,p){return this._matrix[u][p]}},{key:"transpose",value:function(){var u=this._matrix[1][0];return this._matrix[1][0]=this._matrix[0][1],this._matrix[0][1]=u,u=this._matrix[2][0],this._matrix[2][0]=this._matrix[0][2],this._matrix[0][2]=u,u=this._matrix[2][1],this._matrix[2][1]=this._matrix[1][2],this._matrix[1][2]=u,this}},{key:"matches",value:function(u){if(u.length!==9)throw new R("Should be length 9: "+u);for(var p=0;p<3;p++)for(var g=0;g<3;g++)if(!_.matches(this._matrix[p][g],u.charAt(3*p+g)))return!1;return!0}},{key:"add",value:function(u){for(var p=0;p<3;p++)for(var g=0;g<3;g++)this.setAtLeast(p,g,u.get(p,g))}},{key:"isDisjoint",value:function(){return this._matrix[$.INTERIOR][$.INTERIOR]===Ne.FALSE&&this._matrix[$.INTERIOR][$.BOUNDARY]===Ne.FALSE&&this._matrix[$.BOUNDARY][$.INTERIOR]===Ne.FALSE&&this._matrix[$.BOUNDARY][$.BOUNDARY]===Ne.FALSE}},{key:"isCrosses",value:function(u,p){return u===Ne.P&&p===Ne.L||u===Ne.P&&p===Ne.A||u===Ne.L&&p===Ne.A?_.isTrue(this._matrix[$.INTERIOR][$.INTERIOR])&&_.isTrue(this._matrix[$.INTERIOR][$.EXTERIOR]):u===Ne.L&&p===Ne.P||u===Ne.A&&p===Ne.P||u===Ne.A&&p===Ne.L?_.isTrue(this._matrix[$.INTERIOR][$.INTERIOR])&&_.isTrue(this._matrix[$.EXTERIOR][$.INTERIOR]):u===Ne.L&&p===Ne.L&&this._matrix[$.INTERIOR][$.INTERIOR]===0}},{key:"interfaces_",get:function(){return[T]}}],[{key:"constructor_",value:function(){if(this._matrix=null,arguments.length===0)this._matrix=Array(3).fill().map((function(){return Array(3)})),this.setAll(Ne.FALSE);else if(arguments.length===1){if(typeof arguments[0]=="string"){var u=arguments[0];_.constructor_.call(this),this.set(u)}else if(arguments[0]instanceof _){var p=arguments[0];_.constructor_.call(this),this._matrix[$.INTERIOR][$.INTERIOR]=p._matrix[$.INTERIOR][$.INTERIOR],this._matrix[$.INTERIOR][$.BOUNDARY]=p._matrix[$.INTERIOR][$.BOUNDARY],this._matrix[$.INTERIOR][$.EXTERIOR]=p._matrix[$.INTERIOR][$.EXTERIOR],this._matrix[$.BOUNDARY][$.INTERIOR]=p._matrix[$.BOUNDARY][$.INTERIOR],this._matrix[$.BOUNDARY][$.BOUNDARY]=p._matrix[$.BOUNDARY][$.BOUNDARY],this._matrix[$.BOUNDARY][$.EXTERIOR]=p._matrix[$.BOUNDARY][$.EXTERIOR],this._matrix[$.EXTERIOR][$.INTERIOR]=p._matrix[$.EXTERIOR][$.INTERIOR],this._matrix[$.EXTERIOR][$.BOUNDARY]=p._matrix[$.EXTERIOR][$.BOUNDARY],this._matrix[$.EXTERIOR][$.EXTERIOR]=p._matrix[$.EXTERIOR][$.EXTERIOR]}}}},{key:"matches",value:function(){if(Number.isInteger(arguments[0])&&typeof arguments[1]=="string"){var u=arguments[0],p=arguments[1];return p===Ne.SYM_DONTCARE||p===Ne.SYM_TRUE&&(u>=0||u===Ne.TRUE)||p===Ne.SYM_FALSE&&u===Ne.FALSE||p===Ne.SYM_P&&u===Ne.P||p===Ne.SYM_L&&u===Ne.L||p===Ne.SYM_A&&u===Ne.A}if(typeof arguments[0]=="string"&&typeof arguments[1]=="string"){var g=arguments[1];return new _(arguments[0]).matches(g)}}},{key:"isTrue",value:function(u){return u>=0||u===Ne.TRUE}}])})(),jF=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"size",value:function(){return this._size}},{key:"addAll",value:function(u){return u===null||u.length===0?null:(this.ensureCapacity(this._size+u.length),xt.arraycopy(u,0,this._data,this._size,u.length),void(this._size+=u.length))}},{key:"ensureCapacity",value:function(u){if(u<=this._data.length)return null;var p=Math.max(u,2*this._data.length);this._data=le.copyOf(this._data,p)}},{key:"toArray",value:function(){var u=new Array(this._size).fill(null);return xt.arraycopy(this._data,0,u,0,this._size),u}},{key:"add",value:function(u){this.ensureCapacity(this._size+1),this._data[this._size]=u,++this._size}}],[{key:"constructor_",value:function(){if(this._data=null,this._size=0,arguments.length===0)_.constructor_.call(this,10);else if(arguments.length===1){var u=arguments[0];this._data=new Array(u).fill(null)}}}])})(),XF=(function(){function _(){s(this,_)}return o(_,[{key:"getChainStartIndices",value:function(u){var p=0,g=new jF(Math.trunc(u.length/2));g.add(p);do{var E=this.findChainEnd(u,p);g.add(E),p=E}while(p<u.length-1);return g.toArray()}},{key:"findChainEnd",value:function(u,p){for(var g=Ts.quadrant(u[p],u[p+1]),E=p+1;E<u.length&&Ts.quadrant(u[E-1],u[E])===g;)E++;return E-1}},{key:"OLDgetChainStartIndices",value:function(u){var p=0,g=new Pe;g.add(p);do{var E=this.findChainEnd(u,p);g.add(E),p=E}while(p<u.length-1);return _.toIntArray(g)}}],[{key:"toIntArray",value:function(u){for(var p=new Array(u.size()).fill(null),g=0;g<p.length;g++)p[g]=u.get(g).intValue();return p}}])})(),ZF=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"getCoordinates",value:function(){return this.pts}},{key:"getMaxX",value:function(_){var u=this.pts[this.startIndex[_]].x,p=this.pts[this.startIndex[_+1]].x;return u>p?u:p}},{key:"getMinX",value:function(_){var u=this.pts[this.startIndex[_]].x,p=this.pts[this.startIndex[_+1]].x;return u<p?u:p}},{key:"computeIntersectsForChain",value:function(){if(arguments.length===4){var _=arguments[0],u=arguments[1],p=arguments[2],g=arguments[3];this.computeIntersectsForChain(this.startIndex[_],this.startIndex[_+1],u,u.startIndex[p],u.startIndex[p+1],g)}else if(arguments.length===6){var E=arguments[0],B=arguments[1],F=arguments[2],G=arguments[3],Y=arguments[4],ae=arguments[5];if(B-E==1&&Y-G==1)return ae.addIntersections(this.e,E,F.e,G),null;if(!this.overlaps(E,B,F,G,Y))return null;var xe=Math.trunc((E+B)/2),Ie=Math.trunc((G+Y)/2);E<xe&&(G<Ie&&this.computeIntersectsForChain(E,xe,F,G,Ie,ae),Ie<Y&&this.computeIntersectsForChain(E,xe,F,Ie,Y,ae)),xe<B&&(G<Ie&&this.computeIntersectsForChain(xe,B,F,G,Ie,ae),Ie<Y&&this.computeIntersectsForChain(xe,B,F,Ie,Y,ae))}}},{key:"overlaps",value:function(_,u,p,g,E){return fe.intersects(this.pts[_],this.pts[u],p.pts[g],p.pts[E])}},{key:"getStartIndexes",value:function(){return this.startIndex}},{key:"computeIntersects",value:function(_,u){for(var p=0;p<this.startIndex.length-1;p++)for(var g=0;g<_.startIndex.length-1;g++)this.computeIntersectsForChain(p,_,g,u)}}],[{key:"constructor_",value:function(){this.e=null,this.pts=null,this.startIndex=null;var _=arguments[0];this.e=_,this.pts=_.getCoordinates();var u=new XF;this.startIndex=u.getChainStartIndices(this.pts)}}])})(),Tw=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"getDepth",value:function(u,p){return this._depth[u][p]}},{key:"setDepth",value:function(u,p,g){this._depth[u][p]=g}},{key:"isNull",value:function(){if(arguments.length===0){for(var u=0;u<2;u++)for(var p=0;p<3;p++)if(this._depth[u][p]!==_.NULL_VALUE)return!1;return!0}if(arguments.length===1){var g=arguments[0];return this._depth[g][1]===_.NULL_VALUE}if(arguments.length===2){var E=arguments[0],B=arguments[1];return this._depth[E][B]===_.NULL_VALUE}}},{key:"normalize",value:function(){for(var u=0;u<2;u++)if(!this.isNull(u)){var p=this._depth[u][1];this._depth[u][2]<p&&(p=this._depth[u][2]),p<0&&(p=0);for(var g=1;g<3;g++){var E=0;this._depth[u][g]>p&&(E=1),this._depth[u][g]=E}}}},{key:"getDelta",value:function(u){return this._depth[u][q.RIGHT]-this._depth[u][q.LEFT]}},{key:"getLocation",value:function(u,p){return this._depth[u][p]<=0?$.EXTERIOR:$.INTERIOR}},{key:"toString",value:function(){return"A: "+this._depth[0][1]+","+this._depth[0][2]+" B: "+this._depth[1][1]+","+this._depth[1][2]}},{key:"add",value:function(){if(arguments.length===1)for(var u=arguments[0],p=0;p<2;p++)for(var g=1;g<3;g++){var E=u.getLocation(p,g);E!==$.EXTERIOR&&E!==$.INTERIOR||(this.isNull(p,g)?this._depth[p][g]=_.depthAtLocation(E):this._depth[p][g]+=_.depthAtLocation(E))}else if(arguments.length===3){var B=arguments[0],F=arguments[1];arguments[2]===$.INTERIOR&&this._depth[B][F]++}}}],[{key:"constructor_",value:function(){this._depth=Array(2).fill().map((function(){return Array(3)}));for(var u=0;u<2;u++)for(var p=0;p<3;p++)this._depth[u][p]=_.NULL_VALUE}},{key:"depthAtLocation",value:function(u){return u===$.EXTERIOR?0:u===$.INTERIOR?1:_.NULL_VALUE}}])})();Tw.NULL_VALUE=-1;var Lw=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,[{key:"getDepth",value:function(){return this._depth}},{key:"getCollapsedEdge",value:function(){var p=new Array(2).fill(null);return p[0]=this.pts[0],p[1]=this.pts[1],new u(p,Sr.toLineLabel(this._label))}},{key:"isIsolated",value:function(){return this._isIsolated}},{key:"getCoordinates",value:function(){return this.pts}},{key:"setIsolated",value:function(p){this._isIsolated=p}},{key:"setName",value:function(p){this._name=p}},{key:"equals",value:function(p){if(!(p instanceof u))return!1;var g=p;if(this.pts.length!==g.pts.length)return!1;for(var E=!0,B=!0,F=this.pts.length,G=0;G<this.pts.length;G++)if(this.pts[G].equals2D(g.pts[G])||(E=!1),this.pts[G].equals2D(g.pts[--F])||(B=!1),!E&&!B)return!1;return!0}},{key:"getCoordinate",value:function(){if(arguments.length===0)return this.pts.length>0?this.pts[0]:null;if(arguments.length===1){var p=arguments[0];return this.pts[p]}}},{key:"print",value:function(p){p.print("edge "+this._name+": "),p.print("LINESTRING (");for(var g=0;g<this.pts.length;g++)g>0&&p.print(","),p.print(this.pts[g].x+" "+this.pts[g].y);p.print(") "+this._label+" "+this._depthDelta)}},{key:"computeIM",value:function(p){u.updateIM(this._label,p)}},{key:"isCollapsed",value:function(){return!!this._label.isArea()&&this.pts.length===3&&!!this.pts[0].equals(this.pts[2])}},{key:"isClosed",value:function(){return this.pts[0].equals(this.pts[this.pts.length-1])}},{key:"getMaximumSegmentIndex",value:function(){return this.pts.length-1}},{key:"getDepthDelta",value:function(){return this._depthDelta}},{key:"getNumPoints",value:function(){return this.pts.length}},{key:"printReverse",value:function(p){p.print("edge "+this._name+": ");for(var g=this.pts.length-1;g>=0;g--)p.print(this.pts[g]+" ");p.println("")}},{key:"getMonotoneChainEdge",value:function(){return this._mce===null&&(this._mce=new ZF(this)),this._mce}},{key:"getEnvelope",value:function(){if(this._env===null){this._env=new fe;for(var p=0;p<this.pts.length;p++)this._env.expandToInclude(this.pts[p])}return this._env}},{key:"addIntersection",value:function(p,g,E,B){var F=new ie(p.getIntersection(B)),G=g,Y=p.getEdgeDistance(E,B),ae=G+1;if(ae<this.pts.length){var xe=this.pts[ae];F.equals2D(xe)&&(G=ae,Y=0)}this.eiList.add(F,G,Y)}},{key:"toString",value:function(){var p=new we;p.append("edge "+this._name+": "),p.append("LINESTRING (");for(var g=0;g<this.pts.length;g++)g>0&&p.append(","),p.append(this.pts[g].x+" "+this.pts[g].y);return p.append(") "+this._label+" "+this._depthDelta),p.toString()}},{key:"isPointwiseEqual",value:function(p){if(this.pts.length!==p.pts.length)return!1;for(var g=0;g<this.pts.length;g++)if(!this.pts[g].equals2D(p.pts[g]))return!1;return!0}},{key:"setDepthDelta",value:function(p){this._depthDelta=p}},{key:"getEdgeIntersectionList",value:function(){return this.eiList}},{key:"addIntersections",value:function(p,g,E){for(var B=0;B<p.getIntersectionNum();B++)this.addIntersection(p,g,E,B)}}],[{key:"constructor_",value:function(){if(this.pts=null,this._env=null,this.eiList=new WF(this),this._name=null,this._mce=null,this._isIsolated=!0,this._depth=new Tw,this._depthDelta=0,arguments.length===1){var p=arguments[0];u.constructor_.call(this,p,null)}else if(arguments.length===2){var g=arguments[0],E=arguments[1];this.pts=g,this._label=E}}},{key:"updateIM",value:function(){if(!(arguments.length===2&&arguments[1]instanceof YF&&arguments[0]instanceof Sr))return A(u,"updateIM",this).apply(this,arguments);var p=arguments[0],g=arguments[1];g.setAtLeastIfValid(p.getLocation(0,q.ON),p.getLocation(1,q.ON),1),p.isArea()&&(g.setAtLeastIfValid(p.getLocation(0,q.LEFT),p.getLocation(1,q.LEFT),2),g.setAtLeastIfValid(p.getLocation(0,q.RIGHT),p.getLocation(1,q.RIGHT),2))}}])})(hw),Bw=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"setWorkingPrecisionModel",value:function(u){this._workingPrecisionModel=u}},{key:"insertUniqueEdge",value:function(u){var p=this._edgeList.findEqualEdge(u);if(p!==null){var g=p.getLabel(),E=u.getLabel();p.isPointwiseEqual(u)||(E=new Sr(u.getLabel())).flip(),g.merge(E);var B=_.depthDelta(E),F=p.getDepthDelta()+B;p.setDepthDelta(F)}else this._edgeList.add(u),u.setDepthDelta(_.depthDelta(u.getLabel()))}},{key:"buildSubgraphs",value:function(u,p){for(var g=new Pe,E=u.iterator();E.hasNext();){var B=E.next(),F=B.getRightmostCoordinate(),G=new Cw(g).getDepth(F);B.computeDepth(G),B.findResultEdges(),g.add(B),p.add(B.getDirectedEdges(),B.getNodes())}}},{key:"createSubgraphs",value:function(u){for(var p=new Pe,g=u.getNodes().iterator();g.hasNext();){var E=g.next();if(!E.isVisited()){var B=new at;B.create(E),p.add(B)}}return Zc.sort(p,Zc.reverseOrder()),p}},{key:"createEmptyResultGeometry",value:function(){return this._geomFact.createPolygon()}},{key:"getNoder",value:function(u){if(this._workingNoder!==null)return this._workingNoder;var p=new cv,g=new ql;return g.setPrecisionModel(u),p.setSegmentIntersector(new VF(g)),p}},{key:"buffer",value:function(u,p){var g=this._workingPrecisionModel;g===null&&(g=u.getPrecisionModel()),this._geomFact=u.getFactory();var E=new OF(u,p,new DF(g,this._bufParams)).getCurves();if(E.size()<=0)return this.createEmptyResultGeometry();this.computeNodedEdges(E,g),this._graph=new gw(new HF),this._graph.addEdges(this._edgeList.getEdges());var B=this.createSubgraphs(this._graph),F=new EF(this._geomFact);this.buildSubgraphs(B,F);var G=F.getPolygons();return G.size()<=0?this.createEmptyResultGeometry():this._geomFact.buildGeometry(G)}},{key:"computeNodedEdges",value:function(u,p){var g=this.getNoder(p);g.computeNodes(u);for(var E=g.getNodedSubstrings().iterator();E.hasNext();){var B=E.next(),F=B.getCoordinates();if(F.length!==2||!F[0].equals2D(F[1])){var G=B.getData(),Y=new Lw(B.getCoordinates(),new Sr(G));this.insertUniqueEdge(Y)}}}},{key:"setNoder",value:function(u){this._workingNoder=u}}],[{key:"constructor_",value:function(){this._bufParams=null,this._workingPrecisionModel=null,this._workingNoder=null,this._geomFact=null,this._graph=null,this._edgeList=new $F;var u=arguments[0];this._bufParams=u}},{key:"depthDelta",value:function(u){var p=u.getLocation(0,q.LEFT),g=u.getLocation(0,q.RIGHT);return p===$.INTERIOR&&g===$.EXTERIOR?1:p===$.EXTERIOR&&g===$.INTERIOR?-1:0}},{key:"convertSegStrings",value:function(u){for(var p=new Pt,g=new Pe;u.hasNext();){var E=u.next(),B=p.createLineString(E.getCoordinates());g.add(B)}return p.buildGeometry(g)}}])})(),JF=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"rescale",value:function(){if(X(arguments[0],Se))for(var u=arguments[0].iterator();u.hasNext();){var p=u.next();this.rescale(p.getCoordinates())}else if(arguments[0]instanceof Array){for(var g=arguments[0],E=0;E<g.length;E++)g[E].x=g[E].x/this._scaleFactor+this._offsetX,g[E].y=g[E].y/this._scaleFactor+this._offsetY;g.length===2&&g[0].equals2D(g[1])&&xt.out.println(g)}}},{key:"scale",value:function(){if(X(arguments[0],Se)){for(var u=arguments[0],p=new Pe(u.size()),g=u.iterator();g.hasNext();){var E=g.next();p.add(new Wl(this.scale(E.getCoordinates()),E.getData()))}return p}if(arguments[0]instanceof Array){for(var B=arguments[0],F=new Array(B.length).fill(null),G=0;G<B.length;G++)F[G]=new ie(Math.round((B[G].x-this._offsetX)*this._scaleFactor),Math.round((B[G].y-this._offsetY)*this._scaleFactor),B[G].getZ());return In.removeRepeatedPoints(F)}}},{key:"isIntegerPrecision",value:function(){return this._scaleFactor===1}},{key:"getNodedSubstrings",value:function(){var u=this._noder.getNodedSubstrings();return this._isScaled&&this.rescale(u),u}},{key:"computeNodes",value:function(u){var p=u;this._isScaled&&(p=this.scale(u)),this._noder.computeNodes(p)}},{key:"interfaces_",get:function(){return[lv]}}],[{key:"constructor_",value:function(){if(this._noder=null,this._scaleFactor=null,this._offsetX=null,this._offsetY=null,this._isScaled=!1,arguments.length===2){var u=arguments[0],p=arguments[1];_.constructor_.call(this,u,p,0,0)}else if(arguments.length===4){var g=arguments[0],E=arguments[1];this._noder=g,this._scaleFactor=E,this._isScaled=!this.isIntegerPrecision()}}}])})(),Rw=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"checkEndPtVertexIntersections",value:function(){if(arguments.length===0)for(var u=this._segStrings.iterator();u.hasNext();){var p=u.next().getCoordinates();this.checkEndPtVertexIntersections(p[0],this._segStrings),this.checkEndPtVertexIntersections(p[p.length-1],this._segStrings)}else if(arguments.length===2){for(var g=arguments[0],E=arguments[1].iterator();E.hasNext();)for(var B=E.next().getCoordinates(),F=1;F<B.length-1;F++)if(B[F].equals(g))throw new J("found endpt/interior pt intersection at index "+F+" :pt "+g)}}},{key:"checkInteriorIntersections",value:function(){if(arguments.length===0)for(var u=this._segStrings.iterator();u.hasNext();)for(var p=u.next(),g=this._segStrings.iterator();g.hasNext();){var E=g.next();this.checkInteriorIntersections(p,E)}else if(arguments.length===2)for(var B=arguments[0],F=arguments[1],G=B.getCoordinates(),Y=F.getCoordinates(),ae=0;ae<G.length-1;ae++)for(var xe=0;xe<Y.length-1;xe++)this.checkInteriorIntersections(B,ae,F,xe);else if(arguments.length===4){var Ie=arguments[0],Ge=arguments[1],ut=arguments[2],Rt=arguments[3];if(Ie===ut&&Ge===Rt)return null;var Ft=Ie.getCoordinates()[Ge],vn=Ie.getCoordinates()[Ge+1],pn=ut.getCoordinates()[Rt],Dn=ut.getCoordinates()[Rt+1];if(this._li.computeIntersection(Ft,vn,pn,Dn),this._li.hasIntersection()&&(this._li.isProper()||this.hasInteriorIntersection(this._li,Ft,vn)||this.hasInteriorIntersection(this._li,pn,Dn)))throw new J("found non-noded intersection at "+Ft+"-"+vn+" and "+pn+"-"+Dn)}}},{key:"checkValid",value:function(){this.checkEndPtVertexIntersections(),this.checkInteriorIntersections(),this.checkCollapses()}},{key:"checkCollapses",value:function(){if(arguments.length===0)for(var u=this._segStrings.iterator();u.hasNext();){var p=u.next();this.checkCollapses(p)}else if(arguments.length===1)for(var g=arguments[0].getCoordinates(),E=0;E<g.length-2;E++)this.checkCollapse(g[E],g[E+1],g[E+2])}},{key:"hasInteriorIntersection",value:function(u,p,g){for(var E=0;E<u.getIntersectionNum();E++){var B=u.getIntersection(E);if(!B.equals(p)&&!B.equals(g))return!0}return!1}},{key:"checkCollapse",value:function(u,p,g){if(u.equals(g))throw new J("found non-noded collapse at "+_.fact.createLineString([u,p,g]))}}],[{key:"constructor_",value:function(){this._li=new ql,this._segStrings=null;var u=arguments[0];this._segStrings=u}}])})();Rw.fact=new Pt;var uv=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"intersectsScaled",value:function(u,p){var g=Math.min(u.x,p.x),E=Math.max(u.x,p.x),B=Math.min(u.y,p.y),F=Math.max(u.y,p.y),G=this._maxx<g||this._minx>E||this._maxy<B||this._miny>F;if(G)return!1;var Y=this.intersectsToleranceSquare(u,p);return re.isTrue(!(G&&Y),"Found bad envelope test"),Y}},{key:"initCorners",value:function(u){var p=.5;this._minx=u.x-p,this._maxx=u.x+p,this._miny=u.y-p,this._maxy=u.y+p,this._corner[0]=new ie(this._maxx,this._maxy),this._corner[1]=new ie(this._minx,this._maxy),this._corner[2]=new ie(this._minx,this._miny),this._corner[3]=new ie(this._maxx,this._miny)}},{key:"intersects",value:function(u,p){return this._scaleFactor===1?this.intersectsScaled(u,p):(this.copyScaled(u,this._p0Scaled),this.copyScaled(p,this._p1Scaled),this.intersectsScaled(this._p0Scaled,this._p1Scaled))}},{key:"scale",value:function(u){return Math.round(u*this._scaleFactor)}},{key:"getCoordinate",value:function(){return this._originalPt}},{key:"copyScaled",value:function(u,p){p.x=this.scale(u.x),p.y=this.scale(u.y)}},{key:"getSafeEnvelope",value:function(){if(this._safeEnv===null){var u=_.SAFE_ENV_EXPANSION_FACTOR/this._scaleFactor;this._safeEnv=new fe(this._originalPt.x-u,this._originalPt.x+u,this._originalPt.y-u,this._originalPt.y+u)}return this._safeEnv}},{key:"intersectsPixelClosure",value:function(u,p){return this._li.computeIntersection(u,p,this._corner[0],this._corner[1]),!!this._li.hasIntersection()||(this._li.computeIntersection(u,p,this._corner[1],this._corner[2]),!!this._li.hasIntersection()||(this._li.computeIntersection(u,p,this._corner[2],this._corner[3]),!!this._li.hasIntersection()||(this._li.computeIntersection(u,p,this._corner[3],this._corner[0]),!!this._li.hasIntersection())))}},{key:"intersectsToleranceSquare",value:function(u,p){var g=!1,E=!1;return this._li.computeIntersection(u,p,this._corner[0],this._corner[1]),!!this._li.isProper()||(this._li.computeIntersection(u,p,this._corner[1],this._corner[2]),!!this._li.isProper()||(this._li.hasIntersection()&&(g=!0),this._li.computeIntersection(u,p,this._corner[2],this._corner[3]),!!this._li.isProper()||(this._li.hasIntersection()&&(E=!0),this._li.computeIntersection(u,p,this._corner[3],this._corner[0]),!!this._li.isProper()||!(!g||!E)||!!u.equals(this._pt)||!!p.equals(this._pt))))}},{key:"addSnappedNode",value:function(u,p){var g=u.getCoordinate(p),E=u.getCoordinate(p+1);return!!this.intersects(g,E)&&(u.addIntersection(this.getCoordinate(),p),!0)}}],[{key:"constructor_",value:function(){this._li=null,this._pt=null,this._originalPt=null,this._ptScaled=null,this._p0Scaled=null,this._p1Scaled=null,this._scaleFactor=null,this._minx=null,this._maxx=null,this._miny=null,this._maxy=null,this._corner=new Array(4).fill(null),this._safeEnv=null;var u=arguments[0],p=arguments[1],g=arguments[2];if(this._originalPt=u,this._pt=u,this._scaleFactor=p,this._li=g,p<=0)throw new R("Scale factor must be non-zero");p!==1&&(this._pt=new ie(this.scale(u.x),this.scale(u.y)),this._p0Scaled=new ie,this._p1Scaled=new ie),this.initCorners(this._pt)}}])})();uv.SAFE_ENV_EXPANSION_FACTOR=.75;var KF=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"select",value:function(){if(arguments.length!==1){if(arguments.length===2){var _=arguments[1];arguments[0].getLineSegment(_,this.selectedSegment),this.select(this.selectedSegment)}}}}],[{key:"constructor_",value:function(){this.selectedSegment=new cr}}])})(),kw=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"snap",value:function(){if(arguments.length===1){var _=arguments[0];return this.snap(_,null,-1)}if(arguments.length===3){var u=arguments[0],p=arguments[1],g=arguments[2],E=u.getSafeEnvelope(),B=new Nw(u,p,g);return this._index.query(E,new((function(){return o((function F(){s(this,F)}),[{key:"interfaces_",get:function(){return[Aw]}},{key:"visitItem",value:function(F){F.select(E,B)}}])})())),B.isNodeAdded()}}}],[{key:"constructor_",value:function(){this._index=null;var _=arguments[0];this._index=_}}])})(),Nw=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,[{key:"isNodeAdded",value:function(){return this._isNodeAdded}},{key:"select",value:function(){if(!(arguments.length===2&&Number.isInteger(arguments[1])&&arguments[0]instanceof yw))return A(u,"select",this,1).apply(this,arguments);var p=arguments[1],g=arguments[0].getContext();if(this._parentEdge===g&&(p===this._hotPixelVertexIndex||p+1===this._hotPixelVertexIndex))return null;this._isNodeAdded|=this._hotPixel.addSnappedNode(g,p)}}],[{key:"constructor_",value:function(){this._hotPixel=null,this._parentEdge=null,this._hotPixelVertexIndex=null,this._isNodeAdded=!1;var p=arguments[0],g=arguments[1],E=arguments[2];this._hotPixel=p,this._parentEdge=g,this._hotPixelVertexIndex=E}}])})(KF);kw.HotPixelSnapAction=Nw;var eO=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"processIntersections",value:function(_,u,p,g){if(_===p&&u===g)return null;var E=_.getCoordinates()[u],B=_.getCoordinates()[u+1],F=p.getCoordinates()[g],G=p.getCoordinates()[g+1];if(this._li.computeIntersection(E,B,F,G),this._li.hasIntersection()&&this._li.isInteriorIntersection()){for(var Y=0;Y<this._li.getIntersectionNum();Y++)this._interiorIntersections.add(this._li.getIntersection(Y));_.addIntersections(this._li,u,0),p.addIntersections(this._li,g,1)}}},{key:"isDone",value:function(){return!1}},{key:"getInteriorIntersections",value:function(){return this._interiorIntersections}},{key:"interfaces_",get:function(){return[Mw]}}],[{key:"constructor_",value:function(){this._li=null,this._interiorIntersections=null;var _=arguments[0];this._li=_,this._interiorIntersections=new Pe}}])})(),tO=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"checkCorrectness",value:function(_){var u=new Rw(Wl.getNodedSubstrings(_));try{u.checkValid()}catch(p){if(!(p instanceof S))throw p;p.printStackTrace()}}},{key:"getNodedSubstrings",value:function(){return Wl.getNodedSubstrings(this._nodedSegStrings)}},{key:"snapRound",value:function(_,u){var p=this.findInteriorIntersections(_,u);this.computeIntersectionSnaps(p),this.computeVertexSnaps(_)}},{key:"findInteriorIntersections",value:function(_,u){var p=new eO(u);return this._noder.setSegmentIntersector(p),this._noder.computeNodes(_),p.getInteriorIntersections()}},{key:"computeVertexSnaps",value:function(){if(X(arguments[0],Se))for(var _=arguments[0].iterator();_.hasNext();){var u=_.next();this.computeVertexSnaps(u)}else if(arguments[0]instanceof Wl)for(var p=arguments[0],g=p.getCoordinates(),E=0;E<g.length;E++){var B=new uv(g[E],this._scaleFactor,this._li);this._pointSnapper.snap(B,p,E)&&p.addIntersection(g[E],E)}}},{key:"computeNodes",value:function(_){this._nodedSegStrings=_,this._noder=new cv,this._pointSnapper=new kw(this._noder.getIndex()),this.snapRound(_,this._li)}},{key:"computeIntersectionSnaps",value:function(_){for(var u=_.iterator();u.hasNext();){var p=new uv(u.next(),this._scaleFactor,this._li);this._pointSnapper.snap(p)}}},{key:"interfaces_",get:function(){return[lv]}}],[{key:"constructor_",value:function(){this._pm=null,this._li=null,this._scaleFactor=null,this._noder=null,this._pointSnapper=null,this._nodedSegStrings=null;var _=arguments[0];this._pm=_,this._li=new ql,this._li.setPrecisionModel(_),this._scaleFactor=_.getScale()}}])})(),eh=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"bufferFixedPrecision",value:function(u){var p=new JF(new tO(new ct(1)),u.getScale()),g=new Bw(this._bufParams);g.setWorkingPrecisionModel(u),g.setNoder(p),this._resultGeometry=g.buffer(this._argGeom,this._distance)}},{key:"bufferReducedPrecision",value:function(){if(arguments.length===0){for(var u=_.MAX_PRECISION_DIGITS;u>=0;u--){try{this.bufferReducedPrecision(u)}catch(E){if(!(E instanceof Ye))throw E;this._saveException=E}if(this._resultGeometry!==null)return null}throw this._saveException}if(arguments.length===1){var p=arguments[0],g=new ct(_.precisionScaleFactor(this._argGeom,this._distance,p));this.bufferFixedPrecision(g)}}},{key:"computeGeometry",value:function(){if(this.bufferOriginalPrecision(),this._resultGeometry!==null)return null;var u=this._argGeom.getFactory().getPrecisionModel();u.getType()===ct.FIXED?this.bufferFixedPrecision(u):this.bufferReducedPrecision()}},{key:"setQuadrantSegments",value:function(u){this._bufParams.setQuadrantSegments(u)}},{key:"bufferOriginalPrecision",value:function(){try{var u=new Bw(this._bufParams);this._resultGeometry=u.buffer(this._argGeom,this._distance)}catch(p){if(!(p instanceof J))throw p;this._saveException=p}}},{key:"getResultGeometry",value:function(u){return this._distance=u,this.computeGeometry(),this._resultGeometry}},{key:"setEndCapStyle",value:function(u){this._bufParams.setEndCapStyle(u)}}],[{key:"constructor_",value:function(){if(this._argGeom=null,this._distance=null,this._bufParams=new w,this._resultGeometry=null,this._saveException=null,arguments.length===1){var u=arguments[0];this._argGeom=u}else if(arguments.length===2){var p=arguments[0],g=arguments[1];this._argGeom=p,this._bufParams=g}}},{key:"bufferOp",value:function(){if(arguments.length===2){var u=arguments[1];return new _(arguments[0]).getResultGeometry(u)}if(arguments.length===3){if(Number.isInteger(arguments[2])&&arguments[0]instanceof ye&&typeof arguments[1]=="number"){var p=arguments[1],g=arguments[2],E=new _(arguments[0]);return E.setQuadrantSegments(g),E.getResultGeometry(p)}if(arguments[2]instanceof w&&arguments[0]instanceof ye&&typeof arguments[1]=="number"){var B=arguments[1];return new _(arguments[0],arguments[2]).getResultGeometry(B)}}else if(arguments.length===4){var F=arguments[1],G=arguments[2],Y=arguments[3],ae=new _(arguments[0]);return ae.setQuadrantSegments(G),ae.setEndCapStyle(Y),ae.getResultGeometry(F)}}},{key:"precisionScaleFactor",value:function(u,p,g){var E=u.getEnvelopeInternal(),B=me.max(Math.abs(E.getMaxX()),Math.abs(E.getMaxY()),Math.abs(E.getMinX()),Math.abs(E.getMinY()))+2*(p>0?p:0),F=g-Math.trunc(Math.log(B)/Math.log(10)+1);return Math.pow(10,F)}}])})();eh.CAP_ROUND=w.CAP_ROUND,eh.CAP_BUTT=w.CAP_FLAT,eh.CAP_FLAT=w.CAP_FLAT,eh.CAP_SQUARE=w.CAP_SQUARE,eh.MAX_PRECISION_DIGITS=12;var nO=["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon"],Pw=(function(){return o((function _(u){s(this,_),this.geometryFactory=u||new Pt}),[{key:"read",value:function(_){var u,p=(u=typeof _=="string"?JSON.parse(_):_).type;if(!Mr[p])throw new Error("Unknown GeoJSON type: "+u.type);return nO.indexOf(p)!==-1?Mr[p].call(this,u.coordinates):p==="GeometryCollection"?Mr[p].call(this,u.geometries):Mr[p].call(this,u)}},{key:"write",value:function(_){var u=_.getGeometryType();if(!Ca[u])throw new Error("Geometry is not supported");return Ca[u].call(this,_)}}])})(),Mr={Feature:function(_){var u={};for(var p in _)u[p]=_[p];if(_.geometry){if(!Mr[_.geometry.type])throw new Error("Unknown GeoJSON type: "+_.type);u.geometry=this.read(_.geometry)}return _.bbox&&(u.bbox=Mr.bbox.call(this,_.bbox)),u},FeatureCollection:function(_){var u={};if(_.features){u.features=[];for(var p=0;p<_.features.length;++p)u.features.push(this.read(_.features[p]))}return _.bbox&&(u.bbox=this.parse.bbox.call(this,_.bbox)),u},coordinates:function(_){for(var u=[],p=0;p<_.length;++p){var g=_[p];u.push(r(ie,y(g)))}return u},bbox:function(_){return this.geometryFactory.createLinearRing([new ie(_[0],_[1]),new ie(_[2],_[1]),new ie(_[2],_[3]),new ie(_[0],_[3]),new ie(_[0],_[1])])},Point:function(_){var u=r(ie,y(_));return this.geometryFactory.createPoint(u)},MultiPoint:function(_){for(var u=[],p=0;p<_.length;++p)u.push(Mr.Point.call(this,_[p]));return this.geometryFactory.createMultiPoint(u)},LineString:function(_){var u=Mr.coordinates.call(this,_);return this.geometryFactory.createLineString(u)},MultiLineString:function(_){for(var u=[],p=0;p<_.length;++p)u.push(Mr.LineString.call(this,_[p]));return this.geometryFactory.createMultiLineString(u)},Polygon:function(_){for(var u=Mr.coordinates.call(this,_[0]),p=this.geometryFactory.createLinearRing(u),g=[],E=1;E<_.length;++E){var B=_[E],F=Mr.coordinates.call(this,B),G=this.geometryFactory.createLinearRing(F);g.push(G)}return this.geometryFactory.createPolygon(p,g)},MultiPolygon:function(_){for(var u=[],p=0;p<_.length;++p){var g=_[p];u.push(Mr.Polygon.call(this,g))}return this.geometryFactory.createMultiPolygon(u)},GeometryCollection:function(_){for(var u=[],p=0;p<_.length;++p){var g=_[p];u.push(this.read(g))}return this.geometryFactory.createGeometryCollection(u)}},Ca={coordinate:function(_){var u=[_.x,_.y];return _.z&&u.push(_.z),_.m&&u.push(_.m),u},Point:function(_){return{type:"Point",coordinates:Ca.coordinate.call(this,_.getCoordinate())}},MultiPoint:function(_){for(var u=[],p=0;p<_._geometries.length;++p){var g=_._geometries[p],E=Ca.Point.call(this,g);u.push(E.coordinates)}return{type:"MultiPoint",coordinates:u}},LineString:function(_){for(var u=[],p=_.getCoordinates(),g=0;g<p.length;++g){var E=p[g];u.push(Ca.coordinate.call(this,E))}return{type:"LineString",coordinates:u}},MultiLineString:function(_){for(var u=[],p=0;p<_._geometries.length;++p){var g=_._geometries[p],E=Ca.LineString.call(this,g);u.push(E.coordinates)}return{type:"MultiLineString",coordinates:u}},Polygon:function(_){var u=[],p=Ca.LineString.call(this,_._shell);u.push(p.coordinates);for(var g=0;g<_._holes.length;++g){var E=_._holes[g],B=Ca.LineString.call(this,E);u.push(B.coordinates)}return{type:"Polygon",coordinates:u}},MultiPolygon:function(_){for(var u=[],p=0;p<_._geometries.length;++p){var g=_._geometries[p],E=Ca.Polygon.call(this,g);u.push(E.coordinates)}return{type:"MultiPolygon",coordinates:u}},GeometryCollection:function(_){for(var u=[],p=0;p<_._geometries.length;++p){var g=_._geometries[p],E=g.getGeometryType();u.push(Ca[E].call(this,g))}return{type:"GeometryCollection",geometries:u}}};return{BufferOp:eh,GeoJSONReader:(function(){return o((function _(u){s(this,_),this.parser=new Pw(u||new Pt)}),[{key:"read",value:function(_){return this.parser.read(_)}}])})(),GeoJSONWriter:(function(){return o((function _(){s(this,_),this.parser=new Pw(this.geometryFactory)}),[{key:"write",value:function(_){return this.parser.write(_)}}])})()}}))})(zg)),zg.exports}var $Q=Q2(HQ());function Hl(){return new x_}function x_(){this.reset()}x_.prototype={constructor:x_,reset:function(){this.s=this.t=0},add:function(e){CS(tm,e,this.t),CS(this,tm.s,this.s),this.s?this.t+=tm.t:this.s=tm.t},valueOf:function(){return this.s}};var tm=new x_;function CS(e,t,n){var i=e.s=t+n,s=i-t;e.t=t-(i-s)+(n-s)}var Wn=1e-6,gn=Math.PI,Pa=gn/2,wS=gn/4,Ga=gn*2,Yo=180/gn,Pr=gn/180,Yi=Math.abs,VQ=Math.atan,Iu=Math.atan2,hi=Math.cos,ui=Math.sin,Zu=Math.sqrt;function q2(e){return e>1?0:e<-1?gn:Math.acos(e)}function Rc(e){return e>1?Pa:e<-1?-Pa:Math.asin(e)}function qd(){}function E_(e,t){e&&IS.hasOwnProperty(e.type)&&IS[e.type](e,t)}var SS={Feature:function(e,t){E_(e.geometry,t)},FeatureCollection:function(e,t){for(var n=e.features,i=-1,s=n.length;++i<s;)E_(n[i].geometry,t)}},IS={Sphere:function(e,t){t.sphere()},Point:function(e,t){e=e.coordinates,t.point(e[0],e[1],e[2])},MultiPoint:function(e,t){for(var n=e.coordinates,i=-1,s=n.length;++i<s;)e=n[i],t.point(e[0],e[1],e[2])},LineString:function(e,t){ib(e.coordinates,t,0)},MultiLineString:function(e,t){for(var n=e.coordinates,i=-1,s=n.length;++i<s;)ib(n[i],t,0)},Polygon:function(e,t){MS(e.coordinates,t)},MultiPolygon:function(e,t){for(var n=e.coordinates,i=-1,s=n.length;++i<s;)MS(n[i],t)},GeometryCollection:function(e,t){for(var n=e.geometries,i=-1,s=n.length;++i<s;)E_(n[i],t)}};function ib(e,t,n){var i=-1,s=e.length-n,r;for(t.lineStart();++i<s;)r=e[i],t.point(r[0],r[1],r[2]);t.lineEnd()}function MS(e,t){var n=-1,i=e.length;for(t.polygonStart();++n<i;)ib(e[n],t,1);t.polygonEnd()}function qQ(e,t){e&&SS.hasOwnProperty(e.type)?SS[e.type](e,t):E_(e,t)}Hl();Hl();function sb(e){return[Iu(e[1],e[0]),Rc(e[2])]}function Mu(e){var t=e[0],n=e[1],i=hi(n);return[i*hi(t),i*ui(t),ui(n)]}function nm(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function C_(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function Lv(e,t){e[0]+=t[0],e[1]+=t[1],e[2]+=t[2]}function im(e,t){return[e[0]*t,e[1]*t,e[2]*t]}function rb(e){var t=Zu(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);e[0]/=t,e[1]/=t,e[2]/=t}Hl();function W2(e,t){function n(i,s){return i=e(i,s),t(i[0],i[1])}return e.invert&&t.invert&&(n.invert=function(i,s){return i=t.invert(i,s),i&&e.invert(i[0],i[1])}),n}function ab(e,t){return[e>gn?e-Ga:e<-gn?e+Ga:e,t]}ab.invert=ab;function WQ(e,t,n){return(e%=Ga)?t||n?W2(LS(e),BS(t,n)):LS(e):t||n?BS(t,n):ab}function TS(e){return function(t,n){return t+=e,[t>gn?t-Ga:t<-gn?t+Ga:t,n]}}function LS(e){var t=TS(e);return t.invert=TS(-e),t}function BS(e,t){var n=hi(e),i=ui(e),s=hi(t),r=ui(t);function a(o,l){var c=hi(l),h=hi(o)*c,d=ui(o)*c,f=ui(l),m=f*n+h*i;return[Iu(d*s-m*r,h*n-f*i),Rc(m*s+d*r)]}return a.invert=function(o,l){var c=hi(l),h=hi(o)*c,d=ui(o)*c,f=ui(l),m=f*s-d*r;return[Iu(d*s+f*r,h*n+m*i),Rc(m*n-h*i)]},a}function YQ(e,t,n,i,s,r){if(n){var a=hi(t),o=ui(t),l=i*n;s==null?(s=t+i*Ga,r=t-l/2):(s=RS(a,s),r=RS(a,r),(i>0?s<r:s>r)&&(s+=i*Ga));for(var c,h=s;i>0?h>r:h<r;h-=l)c=sb([a,-o*hi(h),-o*ui(h)]),e.point(c[0],c[1])}}function RS(e,t){t=Mu(t),t[0]-=e,rb(t);var n=q2(-t[1]);return((-t[2]<0?-n:n)+Ga-Wn)%Ga}function Y2(){var e=[],t;return{point:function(n,i){t.push([n,i])},lineStart:function(){e.push(t=[])},lineEnd:qd,rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))},result:function(){var n=e;return e=[],t=null,n}}}function jQ(e,t,n,i,s,r){var a=e[0],o=e[1],l=t[0],c=t[1],h=0,d=1,f=l-a,m=c-o,A=n-a;if(!(!f&&A>0)){if(A/=f,f<0){if(A<h)return;A<d&&(d=A)}else if(f>0){if(A>d)return;A>h&&(h=A)}if(A=s-a,!(!f&&A<0)){if(A/=f,f<0){if(A>d)return;A>h&&(h=A)}else if(f>0){if(A<h)return;A<d&&(d=A)}if(A=i-o,!(!m&&A>0)){if(A/=m,m<0){if(A<h)return;A<d&&(d=A)}else if(m>0){if(A>d)return;A>h&&(h=A)}if(A=r-o,!(!m&&A<0)){if(A/=m,m<0){if(A>d)return;A>h&&(h=A)}else if(m>0){if(A<h)return;A<d&&(d=A)}return h>0&&(e[0]=a+h*f,e[1]=o+h*m),d<1&&(t[0]=a+d*f,t[1]=o+d*m),!0}}}}}function Qg(e,t){return Yi(e[0]-t[0])<Wn&&Yi(e[1]-t[1])<Wn}function sm(e,t,n,i){this.x=e,this.z=t,this.o=n,this.e=i,this.v=!1,this.n=this.p=null}function j2(e,t,n,i,s){var r=[],a=[],o,l;if(e.forEach(function(A){if(!((y=A.length-1)<=0)){var y,x=A[0],v=A[y],b;if(Qg(x,v)){for(s.lineStart(),o=0;o<y;++o)s.point((x=A[o])[0],x[1]);s.lineEnd();return}r.push(b=new sm(x,A,null,!0)),a.push(b.o=new sm(x,null,b,!1)),r.push(b=new sm(v,A,null,!1)),a.push(b.o=new sm(v,null,b,!0))}}),!!r.length){for(a.sort(t),kS(r),kS(a),o=0,l=a.length;o<l;++o)a[o].e=n=!n;for(var c=r[0],h,d;;){for(var f=c,m=!0;f.v;)if((f=f.n)===c)return;h=f.z,s.lineStart();do{if(f.v=f.o.v=!0,f.e){if(m)for(o=0,l=h.length;o<l;++o)s.point((d=h[o])[0],d[1]);else i(f.x,f.n.x,1,s);f=f.n}else{if(m)for(h=f.p.z,o=h.length-1;o>=0;--o)s.point((d=h[o])[0],d[1]);else i(f.x,f.p.x,-1,s);f=f.p}f=f.o,h=f.z,m=!m}while(!f.v);s.lineEnd()}}}function kS(e){if(t=e.length){for(var t,n=0,i=e[0],s;++n<t;)i.n=s=e[n],s.p=i,i=s;i.n=s=e[0],s.p=i}}function X2(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function XQ(e){return e.length===1&&(e=ZQ(e)),{left:function(t,n,i,s){for(i==null&&(i=0),s==null&&(s=t.length);i<s;){var r=i+s>>>1;e(t[r],n)<0?i=r+1:s=r}return i},right:function(t,n,i,s){for(i==null&&(i=0),s==null&&(s=t.length);i<s;){var r=i+s>>>1;e(t[r],n)>0?s=r:i=r+1}return i}}}function ZQ(e){return function(t,n){return X2(e(t),n)}}XQ(X2);function Z2(e){for(var t=e.length,n,i=-1,s=0,r,a;++i<t;)s+=e[i].length;for(r=new Array(s);--t>=0;)for(a=e[t],n=a.length;--n>=0;)r[--s]=a[n];return r}var Wd=1e9,rm=-Wd;function JQ(e,t,n,i){function s(c,h){return e<=c&&c<=n&&t<=h&&h<=i}function r(c,h,d,f){var m=0,A=0;if(c==null||(m=a(c,d))!==(A=a(h,d))||l(c,h)<0^d>0)do f.point(m===0||m===3?e:n,m>1?i:t);while((m=(m+d+4)%4)!==A);else f.point(h[0],h[1])}function a(c,h){return Yi(c[0]-e)<Wn?h>0?0:3:Yi(c[0]-n)<Wn?h>0?2:1:Yi(c[1]-t)<Wn?h>0?1:0:h>0?3:2}function o(c,h){return l(c.x,h.x)}function l(c,h){var d=a(c,1),f=a(h,1);return d!==f?d-f:d===0?h[1]-c[1]:d===1?c[0]-h[0]:d===2?c[1]-h[1]:h[0]-c[0]}return function(c){var h=c,d=Y2(),f,m,A,y,x,v,b,w,S,R,k,L={point:T,lineStart:O,lineEnd:N,polygonStart:I,polygonEnd:M};function T(P,U){s(P,U)&&h.point(P,U)}function C(){for(var P=0,U=0,Q=m.length;U<Q;++U)for(var z=m[U],H=1,W=z.length,te=z[0],J,K,re=te[0],ce=te[1];H<W;++H)J=re,K=ce,te=z[H],re=te[0],ce=te[1],K<=i?ce>i&&(re-J)*(i-K)>(ce-K)*(e-J)&&++P:ce<=i&&(re-J)*(i-K)<(ce-K)*(e-J)&&--P;return P}function I(){h=d,f=[],m=[],k=!0}function M(){var P=C(),U=k&&P,Q=(f=Z2(f)).length;(U||Q)&&(c.polygonStart(),U&&(c.lineStart(),r(null,null,1,c),c.lineEnd()),Q&&j2(f,o,P,r,c),c.polygonEnd()),h=c,f=m=A=null}function O(){L.point=D,m&&m.push(A=[]),R=!0,S=!1,b=w=NaN}function N(){f&&(D(y,x),v&&S&&d.rejoin(),f.push(d.result())),L.point=T,S&&h.lineEnd()}function D(P,U){var Q=s(P,U);if(m&&A.push([P,U]),R)y=P,x=U,v=Q,R=!1,Q&&(h.lineStart(),h.point(P,U));else if(Q&&S)h.point(P,U);else{var z=[b=Math.max(rm,Math.min(Wd,b)),w=Math.max(rm,Math.min(Wd,w))],H=[P=Math.max(rm,Math.min(Wd,P)),U=Math.max(rm,Math.min(Wd,U))];jQ(z,H,e,t,n,i)?(S||(h.lineStart(),h.point(z[0],z[1])),h.point(H[0],H[1]),Q||h.lineEnd(),k=!1):Q&&(h.lineStart(),h.point(P,U),k=!1)}b=P,w=U,S=Q}return L}}var Bv=Hl();function KQ(e,t){var n=t[0],i=t[1],s=[ui(n),-hi(n),0],r=0,a=0;Bv.reset();for(var o=0,l=e.length;o<l;++o)if(h=(c=e[o]).length)for(var c,h,d=c[h-1],f=d[0],m=d[1]/2+wS,A=ui(m),y=hi(m),x=0;x<h;++x,f=b,A=S,y=R,d=v){var v=c[x],b=v[0],w=v[1]/2+wS,S=ui(w),R=hi(w),k=b-f,L=k>=0?1:-1,T=L*k,C=T>gn,I=A*S;if(Bv.add(Iu(I*L*ui(T),y*R+I*hi(T))),r+=C?k+L*Ga:k,C^f>=n^b>=n){var M=C_(Mu(d),Mu(v));rb(M);var O=C_(s,M);rb(O);var N=(C^k>=0?-1:1)*Rc(O[2]);(i>N||i===N&&(M[0]||M[1]))&&(a+=C^k>=0?1:-1)}}return(r<-Wn||r<Wn&&Bv<-Wn)^a&1}Hl();function NS(e){return e}Hl();Hl();var Tu=1/0,w_=Tu,Pp=-Tu,S_=Pp,PS={point:e4,lineStart:qd,lineEnd:qd,polygonStart:qd,polygonEnd:qd,result:function(){var e=[[Tu,w_],[Pp,S_]];return Pp=S_=-(w_=Tu=1/0),e}};function e4(e,t){e<Tu&&(Tu=e),e>Pp&&(Pp=e),t<w_&&(w_=t),t>S_&&(S_=t)}Hl();function J2(e,t,n,i){return function(s,r){var a=t(r),o=s.invert(i[0],i[1]),l=Y2(),c=t(l),h=!1,d,f,m,A={point:y,lineStart:v,lineEnd:b,polygonStart:function(){A.point=w,A.lineStart=S,A.lineEnd=R,f=[],d=[]},polygonEnd:function(){A.point=y,A.lineStart=v,A.lineEnd=b,f=Z2(f);var k=KQ(d,o);f.length?(h||(r.polygonStart(),h=!0),j2(f,n4,k,n,r)):k&&(h||(r.polygonStart(),h=!0),r.lineStart(),n(null,null,1,r),r.lineEnd()),h&&(r.polygonEnd(),h=!1),f=d=null},sphere:function(){r.polygonStart(),r.lineStart(),n(null,null,1,r),r.lineEnd(),r.polygonEnd()}};function y(k,L){var T=s(k,L);e(k=T[0],L=T[1])&&r.point(k,L)}function x(k,L){var T=s(k,L);a.point(T[0],T[1])}function v(){A.point=x,a.lineStart()}function b(){A.point=y,a.lineEnd()}function w(k,L){m.push([k,L]);var T=s(k,L);c.point(T[0],T[1])}function S(){c.lineStart(),m=[]}function R(){w(m[0][0],m[0][1]),c.lineEnd();var k=c.clean(),L=l.result(),T,C=L.length,I,M,O;if(m.pop(),d.push(m),m=null,!!C){if(k&1){if(M=L[0],(I=M.length-1)>0){for(h||(r.polygonStart(),h=!0),r.lineStart(),T=0;T<I;++T)r.point((O=M[T])[0],O[1]);r.lineEnd()}return}C>1&&k&2&&L.push(L.pop().concat(L.shift())),f.push(L.filter(t4))}}return A}}function t4(e){return e.length>1}function n4(e,t){return((e=e.x)[0]<0?e[1]-Pa-Wn:Pa-e[1])-((t=t.x)[0]<0?t[1]-Pa-Wn:Pa-t[1])}var DS=J2(function(){return!0},i4,r4,[-gn,-Pa]);function i4(e){var t=NaN,n=NaN,i=NaN,s;return{lineStart:function(){e.lineStart(),s=1},point:function(r,a){var o=r>0?gn:-gn,l=Yi(r-t);Yi(l-gn)<Wn?(e.point(t,n=(n+a)/2>0?Pa:-Pa),e.point(i,n),e.lineEnd(),e.lineStart(),e.point(o,n),e.point(r,n),s=0):i!==o&&l>=gn&&(Yi(t-i)<Wn&&(t-=i*Wn),Yi(r-o)<Wn&&(r-=o*Wn),n=s4(t,n,r,a),e.point(i,n),e.lineEnd(),e.lineStart(),e.point(o,n),s=0),e.point(t=r,n=a),i=o},lineEnd:function(){e.lineEnd(),t=n=NaN},clean:function(){return 2-s}}}function s4(e,t,n,i){var s,r,a=ui(e-n);return Yi(a)>Wn?VQ((ui(t)*(r=hi(i))*ui(n)-ui(i)*(s=hi(t))*ui(e))/(s*r*a)):(t+i)/2}function r4(e,t,n,i){var s;if(e==null)s=n*Pa,i.point(-gn,s),i.point(0,s),i.point(gn,s),i.point(gn,0),i.point(gn,-s),i.point(0,-s),i.point(-gn,-s),i.point(-gn,0),i.point(-gn,s);else if(Yi(e[0]-t[0])>Wn){var r=e[0]<t[0]?gn:-gn;s=n*r/2,i.point(-r,s),i.point(0,s),i.point(r,s)}else i.point(t[0],t[1])}function a4(e,t){var n=hi(e),i=n>0,s=Yi(n)>Wn;function r(h,d,f,m){YQ(m,e,t,f,h,d)}function a(h,d){return hi(h)*hi(d)>n}function o(h){var d,f,m,A,y;return{lineStart:function(){A=m=!1,y=1},point:function(x,v){var b=[x,v],w,S=a(x,v),R=i?S?0:c(x,v):S?c(x+(x<0?gn:-gn),v):0;if(!d&&(A=m=S)&&h.lineStart(),S!==m&&(w=l(d,b),(!w||Qg(d,w)||Qg(b,w))&&(b[0]+=Wn,b[1]+=Wn,S=a(b[0],b[1]))),S!==m)y=0,S?(h.lineStart(),w=l(b,d),h.point(w[0],w[1])):(w=l(d,b),h.point(w[0],w[1]),h.lineEnd()),d=w;else if(s&&d&&i^S){var k;!(R&f)&&(k=l(b,d,!0))&&(y=0,i?(h.lineStart(),h.point(k[0][0],k[0][1]),h.point(k[1][0],k[1][1]),h.lineEnd()):(h.point(k[1][0],k[1][1]),h.lineEnd(),h.lineStart(),h.point(k[0][0],k[0][1])))}S&&(!d||!Qg(d,b))&&h.point(b[0],b[1]),d=b,m=S,f=R},lineEnd:function(){m&&h.lineEnd(),d=null},clean:function(){return y|(A&&m)<<1}}}function l(h,d,f){var m=Mu(h),A=Mu(d),y=[1,0,0],x=C_(m,A),v=nm(x,x),b=x[0],w=v-b*b;if(!w)return!f&&h;var S=n*v/w,R=-n*b/w,k=C_(y,x),L=im(y,S);Lv(L,im(x,R));var T=k,C=nm(L,T),I=nm(T,T),M=C*C-I*(nm(L,L)-1);if(!(M<0)){var O=Zu(M),N=im(T,(-C-O)/I);if(Lv(N,L),N=sb(N),!f)return N;var D=h[0],P=d[0],U=h[1],Q=d[1],z;P<D&&(z=D,D=P,P=z);var H=P-D,W=Yi(H-gn)<Wn,te=W||H<Wn;if(!W&&Q<U&&(z=U,U=Q,Q=z),te?W?U+Q>0^N[1]<(Yi(N[0]-D)<Wn?U:Q):U<=N[1]&&N[1]<=Q:H>gn^(D<=N[0]&&N[0]<=P)){var J=im(T,(-C+O)/I);return Lv(J,L),[N,sb(J)]}}}function c(h,d){var f=i?e:gn-e,m=0;return h<-f?m|=1:h>f&&(m|=2),d<-f?m|=4:d>f&&(m|=8),m}return J2(a,o,r,i?[0,-e]:[-gn,e-gn])}function K2(e){return function(t){var n=new ob;for(var i in e)n[i]=e[i];return n.stream=t,n}}function ob(){}ob.prototype={constructor:ob,point:function(e,t){this.stream.point(e,t)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}};function eR(e,t,n){var i=t[1][0]-t[0][0],s=t[1][1]-t[0][1],r=e.clipExtent&&e.clipExtent();e.scale(150).translate([0,0]),r!=null&&e.clipExtent(null),qQ(n,e.stream(PS));var a=PS.result(),o=Math.min(i/(a[1][0]-a[0][0]),s/(a[1][1]-a[0][1])),l=+t[0][0]+(i-o*(a[1][0]+a[0][0]))/2,c=+t[0][1]+(s-o*(a[1][1]+a[0][1]))/2;return r!=null&&e.clipExtent(r),e.scale(o*150).translate([l,c])}function o4(e,t,n){return eR(e,[[0,0],t],n)}var FS=16,l4=hi(30*Pr);function OS(e,t){return+t?h4(e,t):c4(e)}function c4(e){return K2({point:function(t,n){t=e(t,n),this.stream.point(t[0],t[1])}})}function h4(e,t){function n(i,s,r,a,o,l,c,h,d,f,m,A,y,x){var v=c-i,b=h-s,w=v*v+b*b;if(w>4*t&&y--){var S=a+f,R=o+m,k=l+A,L=Zu(S*S+R*R+k*k),T=Rc(k/=L),C=Yi(Yi(k)-1)<Wn||Yi(r-d)<Wn?(r+d)/2:Iu(R,S),I=e(C,T),M=I[0],O=I[1],N=M-i,D=O-s,P=b*N-v*D;(P*P/w>t||Yi((v*N+b*D)/w-.5)>.3||a*f+o*m+l*A<l4)&&(n(i,s,r,a,o,l,M,O,C,S/=L,R/=L,k,y,x),x.point(M,O),n(M,O,C,S,R,k,c,h,d,f,m,A,y,x))}}return function(i){var s,r,a,o,l,c,h,d,f,m,A,y,x={point:v,lineStart:b,lineEnd:S,polygonStart:function(){i.polygonStart(),x.lineStart=R},polygonEnd:function(){i.polygonEnd(),x.lineStart=b}};function v(T,C){T=e(T,C),i.point(T[0],T[1])}function b(){d=NaN,x.point=w,i.lineStart()}function w(T,C){var I=Mu([T,C]),M=e(T,C);n(d,f,h,m,A,y,d=M[0],f=M[1],h=T,m=I[0],A=I[1],y=I[2],FS,i),i.point(d,f)}function S(){x.point=v,i.lineEnd()}function R(){b(),x.point=k,x.lineEnd=L}function k(T,C){w(s=T,C),r=d,a=f,o=m,l=A,c=y,x.point=w}function L(){n(d,f,h,m,A,y,r,a,s,o,l,c,FS,i),x.lineEnd=S,S()}return x}}var u4=K2({point:function(e,t){this.stream.point(e*Pr,t*Pr)}});function d4(e){return p4(function(){return e})()}function p4(e){var t,n=150,i=480,s=250,r,a,o=0,l=0,c=0,h=0,d=0,f,m,A=null,y=DS,x=null,v,b,w,S=NS,R=.5,k=OS(M,R),L,T;function C(D){return D=m(D[0]*Pr,D[1]*Pr),[D[0]*n+r,a-D[1]*n]}function I(D){return D=m.invert((D[0]-r)/n,(a-D[1])/n),D&&[D[0]*Yo,D[1]*Yo]}function M(D,P){return D=t(D,P),[D[0]*n+r,a-D[1]*n]}C.stream=function(D){return L&&T===D?L:L=u4(y(f,k(S(T=D))))},C.clipAngle=function(D){return arguments.length?(y=+D?a4(A=D*Pr,6*Pr):(A=null,DS),N()):A*Yo},C.clipExtent=function(D){return arguments.length?(S=D==null?(x=v=b=w=null,NS):JQ(x=+D[0][0],v=+D[0][1],b=+D[1][0],w=+D[1][1]),N()):x==null?null:[[x,v],[b,w]]},C.scale=function(D){return arguments.length?(n=+D,O()):n},C.translate=function(D){return arguments.length?(i=+D[0],s=+D[1],O()):[i,s]},C.center=function(D){return arguments.length?(o=D[0]%360*Pr,l=D[1]%360*Pr,O()):[o*Yo,l*Yo]},C.rotate=function(D){return arguments.length?(c=D[0]%360*Pr,h=D[1]%360*Pr,d=D.length>2?D[2]%360*Pr:0,O()):[c*Yo,h*Yo,d*Yo]},C.precision=function(D){return arguments.length?(k=OS(M,R=D*D),N()):Zu(R)},C.fitExtent=function(D,P){return eR(C,D,P)},C.fitSize=function(D,P){return o4(C,D,P)};function O(){m=W2(f=WQ(c,h,d),t);var D=t(o,l);return r=i-D[0]*n,a=s+D[1]*n,N()}function N(){return L=T=null,C}return function(){return t=e.apply(this,arguments),C.invert=t.invert&&I,O()}}function tR(e){return function(t,n){var i=hi(t),s=hi(n),r=e(i*s);return[r*s*ui(t),r*ui(n)]}}function nR(e){return function(t,n){var i=Zu(t*t+n*n),s=e(i),r=ui(s),a=hi(s);return[Iu(t*r,i*a),Rc(i&&n*r/i)]}}var f4=tR(function(e){return Zu(2/(1+e))});f4.invert=nR(function(e){return 2*Rc(e/2)});var iR=tR(function(e){return(e=q2(e))&&e/ui(e)});iR.invert=nR(function(e){return e});function m4(){return d4(iR).scale(79.4188).clipAngle(179.999)}function US(e,t){return[e,t]}US.invert=US;var{BufferOp:g4,GeoJSONReader:_4,GeoJSONWriter:A4}=$Q;function v4(e,t,n){n=n||{};var i=n.units||"kilometers",s=n.steps||8;if(!e)throw new Error("geojson is required");if(typeof n!="object")throw new Error("options must be an object");if(typeof s!="number")throw new Error("steps must be an number");if(t===void 0)throw new Error("radius is required");if(s<=0)throw new Error("steps must be greater than 0");var r=[];switch(e.type){case"GeometryCollection":return Gl(e,function(a){var o=Gg(a,t,i,s);o&&r.push(o)}),Kt(r);case"FeatureCollection":return Po(e,function(a){var o=Gg(a,t,i,s);o&&Po(o,function(l){l&&r.push(l)})}),Kt(r)}return Gg(e,t,i,s)}function Gg(e,t,n,i){var s=e.properties||{},r=e.type==="Feature"?e.geometry:e;if(r.type==="GeometryCollection"){var a=[];return Gl(e,function(f){var m=Gg(f,t,n,i);m&&a.push(m)}),Kt(a)}var o=y4(r),l={type:r.type,coordinates:rR(r.coordinates,o)},c=new _4().read(l),h=SE(M2(t,n),"meters"),d=g4.bufferOp(c,h,i);if(d=new A4().write(d),!sR(d.coordinates))return or({type:d.type,coordinates:aR(d.coordinates,o)},s)}function sR(e){return Array.isArray(e[0])?sR(e[0]):isNaN(e[0])}function rR(e,t){return typeof e[0]!="object"?t(e):e.map(function(n){return rR(n,t)})}function aR(e,t){return typeof e[0]!="object"?t.invert(e):e.map(function(n){return aR(n,t)})}function y4(e){var t=V2(e).geometry.coordinates,n=[-t[0],-t[1]];return m4().rotate(n).scale($i)}function Dp(e,t={}){let n=0,i=0,s=0;return Ql(e,function(r){n+=r[0],i+=r[1],s++},!0),wi([n/s,i/s],t.properties)}function Es(e){if(!e)throw new Error("geojson is required");switch(e.type){case"Feature":return oR(e);case"FeatureCollection":return b4(e);case"Point":case"LineString":case"Polygon":case"MultiPoint":case"MultiLineString":case"MultiPolygon":case"GeometryCollection":return NE(e);default:throw new Error("unknown GeoJSON type")}}function oR(e){const t={type:"Feature"};return Object.keys(e).forEach(n=>{switch(n){case"type":case"properties":case"geometry":return;default:t[n]=e[n]}}),t.properties=lR(e.properties),e.geometry==null?t.geometry=null:t.geometry=NE(e.geometry),t}function lR(e){const t={};return e&&Object.keys(e).forEach(n=>{const i=e[n];typeof i=="object"?i===null?t[n]=null:Array.isArray(i)?t[n]=i.map(s=>s):t[n]=lR(i):t[n]=i}),t}function b4(e){const t={type:"FeatureCollection"};return Object.keys(e).forEach(n=>{switch(n){case"type":case"features":return;default:t[n]=e[n]}}),t.features=e.features.map(n=>oR(n)),t}function NE(e){const t={type:e.type};return e.bbox&&(t.bbox=e.bbox),e.type==="GeometryCollection"?(t.geometries=e.geometries.map(n=>NE(n)),t):(t.coordinates=cR(e.coordinates),t)}function cR(e){const t=e;return typeof t[0]!="object"?t.slice():t.map(n=>cR(n))}var x4=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Rv=Math.ceil,Rr=Math.floor,Zs="[BigNumber Error] ",zS=Zs+"Number primitive has more than 15 significant digits: ",Xr=1e14,Gt=14,kv=9007199254740991,Nv=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],jo=1e7,Qi=1e9;function hR(e){var t,n,i,s=b.prototype={constructor:b,toString:null,valueOf:null},r=new b(1),a=20,o=4,l=-7,c=21,h=-1e7,d=1e7,f=!1,m=1,A=0,y={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:" ",suffix:""},x="0123456789abcdefghijklmnopqrstuvwxyz",v=!0;function b(T,C){var I,M,O,N,D,P,U,Q,z=this;if(!(z instanceof b))return new b(T,C);if(C==null){if(T&&T._isBigNumber===!0){z.s=T.s,!T.c||T.e>d?z.c=z.e=null:T.e<h?z.c=[z.e=0]:(z.e=T.e,z.c=T.c.slice());return}if((P=typeof T=="number")&&T*0==0){if(z.s=1/T<0?(T=-T,-1):1,T===~~T){for(N=0,D=T;D>=10;D/=10,N++);N>d?z.c=z.e=null:(z.e=N,z.c=[T]);return}Q=String(T)}else{if(!x4.test(Q=String(T)))return i(z,Q,P);z.s=Q.charCodeAt(0)==45?(Q=Q.slice(1),-1):1}(N=Q.indexOf("."))>-1&&(Q=Q.replace(".","")),(D=Q.search(/e/i))>0?(N<0&&(N=D),N+=+Q.slice(D+1),Q=Q.substring(0,D)):N<0&&(N=Q.length)}else{if(ri(C,2,x.length,"Base"),C==10&&v)return z=new b(T),k(z,a+z.e+1,o);if(Q=String(T),P=typeof T=="number"){if(T*0!=0)return i(z,Q,P,C);if(z.s=1/T<0?(Q=Q.slice(1),-1):1,b.DEBUG&&Q.replace(/^0\.0*|\./,"").length>15)throw Error(zS+T)}else z.s=Q.charCodeAt(0)===45?(Q=Q.slice(1),-1):1;for(I=x.slice(0,C),N=D=0,U=Q.length;D<U;D++)if(I.indexOf(M=Q.charAt(D))<0){if(M=="."){if(D>N){N=U;continue}}else if(!O&&(Q==Q.toUpperCase()&&(Q=Q.toLowerCase())||Q==Q.toLowerCase()&&(Q=Q.toUpperCase()))){O=!0,D=-1,N=0;continue}return i(z,String(T),P,C)}P=!1,Q=n(Q,C,10,z.s),(N=Q.indexOf("."))>-1?Q=Q.replace(".",""):N=Q.length}for(D=0;Q.charCodeAt(D)===48;D++);for(U=Q.length;Q.charCodeAt(--U)===48;);if(Q=Q.slice(D,++U)){if(U-=D,P&&b.DEBUG&&U>15&&(T>kv||T!==Rr(T)))throw Error(zS+z.s*T);if((N=N-D-1)>d)z.c=z.e=null;else if(N<h)z.c=[z.e=0];else{if(z.e=N,z.c=[],D=(N+1)%Gt,N<0&&(D+=Gt),D<U){for(D&&z.c.push(+Q.slice(0,D)),U-=Gt;D<U;)z.c.push(+Q.slice(D,D+=Gt));D=Gt-(Q=Q.slice(D)).length}else D-=U;for(;D--;Q+="0");z.c.push(+Q)}}else z.c=[z.e=0]}b.clone=hR,b.ROUND_UP=0,b.ROUND_DOWN=1,b.ROUND_CEIL=2,b.ROUND_FLOOR=3,b.ROUND_HALF_UP=4,b.ROUND_HALF_DOWN=5,b.ROUND_HALF_EVEN=6,b.ROUND_HALF_CEIL=7,b.ROUND_HALF_FLOOR=8,b.EUCLID=9,b.config=b.set=function(T){var C,I;if(T!=null)if(typeof T=="object"){if(T.hasOwnProperty(C="DECIMAL_PLACES")&&(I=T[C],ri(I,0,Qi,C),a=I),T.hasOwnProperty(C="ROUNDING_MODE")&&(I=T[C],ri(I,0,8,C),o=I),T.hasOwnProperty(C="EXPONENTIAL_AT")&&(I=T[C],I&&I.pop?(ri(I[0],-Qi,0,C),ri(I[1],0,Qi,C),l=I[0],c=I[1]):(ri(I,-Qi,Qi,C),l=-(c=I<0?-I:I))),T.hasOwnProperty(C="RANGE"))if(I=T[C],I&&I.pop)ri(I[0],-Qi,-1,C),ri(I[1],1,Qi,C),h=I[0],d=I[1];else if(ri(I,-Qi,Qi,C),I)h=-(d=I<0?-I:I);else throw Error(Zs+C+" cannot be zero: "+I);if(T.hasOwnProperty(C="CRYPTO"))if(I=T[C],I===!!I)if(I)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))f=I;else throw f=!I,Error(Zs+"crypto unavailable");else f=I;else throw Error(Zs+C+" not true or false: "+I);if(T.hasOwnProperty(C="MODULO_MODE")&&(I=T[C],ri(I,0,9,C),m=I),T.hasOwnProperty(C="POW_PRECISION")&&(I=T[C],ri(I,0,Qi,C),A=I),T.hasOwnProperty(C="FORMAT"))if(I=T[C],typeof I=="object")y=I;else throw Error(Zs+C+" not an object: "+I);if(T.hasOwnProperty(C="ALPHABET"))if(I=T[C],typeof I=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(I))v=I.slice(0,10)=="0123456789",x=I;else throw Error(Zs+C+" invalid: "+I)}else throw Error(Zs+"Object expected: "+T);return{DECIMAL_PLACES:a,ROUNDING_MODE:o,EXPONENTIAL_AT:[l,c],RANGE:[h,d],CRYPTO:f,MODULO_MODE:m,POW_PRECISION:A,FORMAT:y,ALPHABET:x}},b.isBigNumber=function(T){if(!T||T._isBigNumber!==!0)return!1;if(!b.DEBUG)return!0;var C,I,M=T.c,O=T.e,N=T.s;e:if({}.toString.call(M)=="[object Array]"){if((N===1||N===-1)&&O>=-Qi&&O<=Qi&&O===Rr(O)){if(M[0]===0){if(O===0&&M.length===1)return!0;break e}if(C=(O+1)%Gt,C<1&&(C+=Gt),String(M[0]).length==C){for(C=0;C<M.length;C++)if(I=M[C],I<0||I>=Xr||I!==Rr(I))break e;if(I!==0)return!0}}}else if(M===null&&O===null&&(N===null||N===1||N===-1))return!0;throw Error(Zs+"Invalid BigNumber: "+T)},b.maximum=b.max=function(){return S(arguments,-1)},b.minimum=b.min=function(){return S(arguments,1)},b.random=(function(){var T=9007199254740992,C=Math.random()*T&2097151?function(){return Rr(Math.random()*T)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(I){var M,O,N,D,P,U=0,Q=[],z=new b(r);if(I==null?I=a:ri(I,0,Qi),D=Rv(I/Gt),f)if(crypto.getRandomValues){for(M=crypto.getRandomValues(new Uint32Array(D*=2));U<D;)P=M[U]*131072+(M[U+1]>>>11),P>=9e15?(O=crypto.getRandomValues(new Uint32Array(2)),M[U]=O[0],M[U+1]=O[1]):(Q.push(P%1e14),U+=2);U=D/2}else if(crypto.randomBytes){for(M=crypto.randomBytes(D*=7);U<D;)P=(M[U]&31)*281474976710656+M[U+1]*1099511627776+M[U+2]*4294967296+M[U+3]*16777216+(M[U+4]<<16)+(M[U+5]<<8)+M[U+6],P>=9e15?crypto.randomBytes(7).copy(M,U):(Q.push(P%1e14),U+=7);U=D/7}else throw f=!1,Error(Zs+"crypto unavailable");if(!f)for(;U<D;)P=C(),P<9e15&&(Q[U++]=P%1e14);for(D=Q[--U],I%=Gt,D&&I&&(P=Nv[Gt-I],Q[U]=Rr(D/P)*P);Q[U]===0;Q.pop(),U--);if(U<0)Q=[N=0];else{for(N=-1;Q[0]===0;Q.splice(0,1),N-=Gt);for(U=1,P=Q[0];P>=10;P/=10,U++);U<Gt&&(N-=Gt-U)}return z.e=N,z.c=Q,z}})(),b.sum=function(){for(var T=1,C=arguments,I=new b(C[0]);T<C.length;)I=I.plus(C[T++]);return I},n=(function(){var T="0123456789";function C(I,M,O,N){for(var D,P=[0],U,Q=0,z=I.length;Q<z;){for(U=P.length;U--;P[U]*=M);for(P[0]+=N.indexOf(I.charAt(Q++)),D=0;D<P.length;D++)P[D]>O-1&&(P[D+1]==null&&(P[D+1]=0),P[D+1]+=P[D]/O|0,P[D]%=O)}return P.reverse()}return function(I,M,O,N,D){var P,U,Q,z,H,W,te,J,K=I.indexOf("."),re=a,ce=o;for(K>=0&&(z=A,A=0,I=I.replace(".",""),J=new b(M),W=J.pow(I.length-K),A=z,J.c=C(io(Tr(W.c),W.e,"0"),10,O,T),J.e=J.c.length),te=C(I,M,O,D?(P=x,T):(P=T,x)),Q=z=te.length;te[--z]==0;te.pop());if(!te[0])return P.charAt(0);if(K<0?--Q:(W.c=te,W.e=Q,W.s=N,W=t(W,J,re,ce,O),te=W.c,H=W.r,Q=W.e),U=Q+re+1,K=te[U],z=O/2,H=H||U<0||te[U+1]!=null,H=ce<4?(K!=null||H)&&(ce==0||ce==(W.s<0?3:2)):K>z||K==z&&(ce==4||H||ce==6&&te[U-1]&1||ce==(W.s<0?8:7)),U<1||!te[0])I=H?io(P.charAt(1),-re,P.charAt(0)):P.charAt(0);else{if(te.length=U,H)for(--O;++te[--U]>O;)te[U]=0,U||(++Q,te=[1].concat(te));for(z=te.length;!te[--z];);for(K=0,I="";K<=z;I+=P.charAt(te[K++]));I=io(I,Q,P.charAt(0))}return I}})(),t=(function(){function T(M,O,N){var D,P,U,Q,z=0,H=M.length,W=O%jo,te=O/jo|0;for(M=M.slice();H--;)U=M[H]%jo,Q=M[H]/jo|0,D=te*U+Q*W,P=W*U+D%jo*jo+z,z=(P/N|0)+(D/jo|0)+te*Q,M[H]=P%N;return z&&(M=[z].concat(M)),M}function C(M,O,N,D){var P,U;if(N!=D)U=N>D?1:-1;else for(P=U=0;P<N;P++)if(M[P]!=O[P]){U=M[P]>O[P]?1:-1;break}return U}function I(M,O,N,D){for(var P=0;N--;)M[N]-=P,P=M[N]<O[N]?1:0,M[N]=P*D+M[N]-O[N];for(;!M[0]&&M.length>1;M.splice(0,1));}return function(M,O,N,D,P){var U,Q,z,H,W,te,J,K,re,ce,oe,ge,ie,fe,ye,$,Se,Z=M.s==O.s?1:-1,Qe=M.c,Le=O.c;if(!Qe||!Qe[0]||!Le||!Le[0])return new b(!M.s||!O.s||(Qe?Le&&Qe[0]==Le[0]:!Le)?NaN:Qe&&Qe[0]==0||!Le?Z*0:Z/0);for(K=new b(Z),re=K.c=[],Q=M.e-O.e,Z=N+Q+1,P||(P=Xr,Q=kr(M.e/Gt)-kr(O.e/Gt),Z=Z/Gt|0),z=0;Le[z]==(Qe[z]||0);z++);if(Le[z]>(Qe[z]||0)&&Q--,Z<0)re.push(1),H=!0;else{for(fe=Qe.length,$=Le.length,z=0,Z+=2,W=Rr(P/(Le[0]+1)),W>1&&(Le=T(Le,W,P),Qe=T(Qe,W,P),$=Le.length,fe=Qe.length),ie=$,ce=Qe.slice(0,$),oe=ce.length;oe<$;ce[oe++]=0);Se=Le.slice(),Se=[0].concat(Se),ye=Le[0],Le[1]>=P/2&&ye++;do{if(W=0,U=C(Le,ce,$,oe),U<0){if(ge=ce[0],$!=oe&&(ge=ge*P+(ce[1]||0)),W=Rr(ge/ye),W>1)for(W>=P&&(W=P-1),te=T(Le,W,P),J=te.length,oe=ce.length;C(te,ce,J,oe)==1;)W--,I(te,$<J?Se:Le,J,P),J=te.length,U=1;else W==0&&(U=W=1),te=Le.slice(),J=te.length;if(J<oe&&(te=[0].concat(te)),I(ce,te,oe,P),oe=ce.length,U==-1)for(;C(Le,ce,$,oe)<1;)W++,I(ce,$<oe?Se:Le,oe,P),oe=ce.length}else U===0&&(W++,ce=[0]);re[z++]=W,ce[0]?ce[oe++]=Qe[ie]||0:(ce=[Qe[ie]],oe=1)}while((ie++<fe||ce[0]!=null)&&Z--);H=ce[0]!=null,re[0]||re.splice(0,1)}if(P==Xr){for(z=1,Z=re[0];Z>=10;Z/=10,z++);k(K,N+(K.e=z+Q*Gt-1)+1,D,H)}else K.e=Q,K.r=+H;return K}})();function w(T,C,I,M){var O,N,D,P,U;if(I==null?I=o:ri(I,0,8),!T.c)return T.toString();if(O=T.c[0],D=T.e,C==null)U=Tr(T.c),U=M==1||M==2&&(D<=l||D>=c)?om(U,D):io(U,D,"0");else if(T=k(new b(T),C,I),N=T.e,U=Tr(T.c),P=U.length,M==1||M==2&&(C<=N||N<=l)){for(;P<C;U+="0",P++);U=om(U,N)}else if(C-=D+(M===2&&N>D),U=io(U,N,"0"),N+1>P){if(--C>0)for(U+=".";C--;U+="0");}else if(C+=N-P,C>0)for(N+1==P&&(U+=".");C--;U+="0");return T.s<0&&O?"-"+U:U}function S(T,C){for(var I,M,O=1,N=new b(T[0]);O<T.length;O++)M=new b(T[O]),(!M.s||(I=Jl(N,M))===C||I===0&&N.s===C)&&(N=M);return N}function R(T,C,I){for(var M=1,O=C.length;!C[--O];C.pop());for(O=C[0];O>=10;O/=10,M++);return(I=M+I*Gt-1)>d?T.c=T.e=null:I<h?T.c=[T.e=0]:(T.e=I,T.c=C),T}i=(function(){var T=/^(-?)0([xbo])(?=\w[\w.]*$)/i,C=/^([^.]+)\.$/,I=/^\.([^.]+)$/,M=/^-?(Infinity|NaN)$/,O=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(N,D,P,U){var Q,z=P?D:D.replace(O,"");if(M.test(z))N.s=isNaN(z)?null:z<0?-1:1;else{if(!P&&(z=z.replace(T,function(H,W,te){return Q=(te=te.toLowerCase())=="x"?16:te=="b"?2:8,!U||U==Q?W:H}),U&&(Q=U,z=z.replace(C,"$1").replace(I,"0.$1")),D!=z))return new b(z,Q);if(b.DEBUG)throw Error(Zs+"Not a"+(U?" base "+U:"")+" number: "+D);N.s=null}N.c=N.e=null}})();function k(T,C,I,M){var O,N,D,P,U,Q,z,H=T.c,W=Nv;if(H){e:{for(O=1,P=H[0];P>=10;P/=10,O++);if(N=C-O,N<0)N+=Gt,D=C,U=H[Q=0],z=Rr(U/W[O-D-1]%10);else if(Q=Rv((N+1)/Gt),Q>=H.length)if(M){for(;H.length<=Q;H.push(0));U=z=0,O=1,N%=Gt,D=N-Gt+1}else break e;else{for(U=P=H[Q],O=1;P>=10;P/=10,O++);N%=Gt,D=N-Gt+O,z=D<0?0:Rr(U/W[O-D-1]%10)}if(M=M||C<0||H[Q+1]!=null||(D<0?U:U%W[O-D-1]),M=I<4?(z||M)&&(I==0||I==(T.s<0?3:2)):z>5||z==5&&(I==4||M||I==6&&(N>0?D>0?U/W[O-D]:0:H[Q-1])%10&1||I==(T.s<0?8:7)),C<1||!H[0])return H.length=0,M?(C-=T.e+1,H[0]=W[(Gt-C%Gt)%Gt],T.e=-C||0):H[0]=T.e=0,T;if(N==0?(H.length=Q,P=1,Q--):(H.length=Q+1,P=W[Gt-N],H[Q]=D>0?Rr(U/W[O-D]%W[D])*P:0),M)for(;;)if(Q==0){for(N=1,D=H[0];D>=10;D/=10,N++);for(D=H[0]+=P,P=1;D>=10;D/=10,P++);N!=P&&(T.e++,H[0]==Xr&&(H[0]=1));break}else{if(H[Q]+=P,H[Q]!=Xr)break;H[Q--]=0,P=1}for(N=H.length;H[--N]===0;H.pop());}T.e>d?T.c=T.e=null:T.e<h&&(T.c=[T.e=0])}return T}function L(T){var C,I=T.e;return I===null?T.toString():(C=Tr(T.c),C=I<=l||I>=c?om(C,I):io(C,I,"0"),T.s<0?"-"+C:C)}return s.absoluteValue=s.abs=function(){var T=new b(this);return T.s<0&&(T.s=1),T},s.comparedTo=function(T,C){return Jl(this,new b(T,C))},s.decimalPlaces=s.dp=function(T,C){var I,M,O,N=this;if(T!=null)return ri(T,0,Qi),C==null?C=o:ri(C,0,8),k(new b(N),T+N.e+1,C);if(!(I=N.c))return null;if(M=((O=I.length-1)-kr(this.e/Gt))*Gt,O=I[O])for(;O%10==0;O/=10,M--);return M<0&&(M=0),M},s.dividedBy=s.div=function(T,C){return t(this,new b(T,C),a,o)},s.dividedToIntegerBy=s.idiv=function(T,C){return t(this,new b(T,C),0,1)},s.exponentiatedBy=s.pow=function(T,C){var I,M,O,N,D,P,U,Q,z,H=this;if(T=new b(T),T.c&&!T.isInteger())throw Error(Zs+"Exponent not an integer: "+L(T));if(C!=null&&(C=new b(C)),P=T.e>14,!H.c||!H.c[0]||H.c[0]==1&&!H.e&&H.c.length==1||!T.c||!T.c[0])return z=new b(Math.pow(+L(H),P?T.s*(2-am(T)):+L(T))),C?z.mod(C):z;if(U=T.s<0,C){if(C.c?!C.c[0]:!C.s)return new b(NaN);M=!U&&H.isInteger()&&C.isInteger(),M&&(H=H.mod(C))}else{if(T.e>9&&(H.e>0||H.e<-1||(H.e==0?H.c[0]>1||P&&H.c[1]>=24e7:H.c[0]<8e13||P&&H.c[0]<=9999975e7)))return N=H.s<0&&am(T)?-0:0,H.e>-1&&(N=1/N),new b(U?1/N:N);A&&(N=Rv(A/Gt+2))}for(P?(I=new b(.5),U&&(T.s=1),Q=am(T)):(O=Math.abs(+L(T)),Q=O%2),z=new b(r);;){if(Q){if(z=z.times(H),!z.c)break;N?z.c.length>N&&(z.c.length=N):M&&(z=z.mod(C))}if(O){if(O=Rr(O/2),O===0)break;Q=O%2}else if(T=T.times(I),k(T,T.e+1,1),T.e>14)Q=am(T);else{if(O=+L(T),O===0)break;Q=O%2}H=H.times(H),N?H.c&&H.c.length>N&&(H.c.length=N):M&&(H=H.mod(C))}return M?z:(U&&(z=r.div(z)),C?z.mod(C):N?k(z,A,o,D):z)},s.integerValue=function(T){var C=new b(this);return T==null?T=o:ri(T,0,8),k(C,C.e+1,T)},s.isEqualTo=s.eq=function(T,C){return Jl(this,new b(T,C))===0},s.isFinite=function(){return!!this.c},s.isGreaterThan=s.gt=function(T,C){return Jl(this,new b(T,C))>0},s.isGreaterThanOrEqualTo=s.gte=function(T,C){return(C=Jl(this,new b(T,C)))===1||C===0},s.isInteger=function(){return!!this.c&&kr(this.e/Gt)>this.c.length-2},s.isLessThan=s.lt=function(T,C){return Jl(this,new b(T,C))<0},s.isLessThanOrEqualTo=s.lte=function(T,C){return(C=Jl(this,new b(T,C)))===-1||C===0},s.isNaN=function(){return!this.s},s.isNegative=function(){return this.s<0},s.isPositive=function(){return this.s>0},s.isZero=function(){return!!this.c&&this.c[0]==0},s.minus=function(T,C){var I,M,O,N,D=this,P=D.s;if(T=new b(T,C),C=T.s,!P||!C)return new b(NaN);if(P!=C)return T.s=-C,D.plus(T);var U=D.e/Gt,Q=T.e/Gt,z=D.c,H=T.c;if(!U||!Q){if(!z||!H)return z?(T.s=-C,T):new b(H?D:NaN);if(!z[0]||!H[0])return H[0]?(T.s=-C,T):new b(z[0]?D:o==3?-0:0)}if(U=kr(U),Q=kr(Q),z=z.slice(),P=U-Q){for((N=P<0)?(P=-P,O=z):(Q=U,O=H),O.reverse(),C=P;C--;O.push(0));O.reverse()}else for(M=(N=(P=z.length)<(C=H.length))?P:C,P=C=0;C<M;C++)if(z[C]!=H[C]){N=z[C]<H[C];break}if(N&&(O=z,z=H,H=O,T.s=-T.s),C=(M=H.length)-(I=z.length),C>0)for(;C--;z[I++]=0);for(C=Xr-1;M>P;){if(z[--M]<H[M]){for(I=M;I&&!z[--I];z[I]=C);--z[I],z[M]+=Xr}z[M]-=H[M]}for(;z[0]==0;z.splice(0,1),--Q);return z[0]?R(T,z,Q):(T.s=o==3?-1:1,T.c=[T.e=0],T)},s.modulo=s.mod=function(T,C){var I,M,O=this;return T=new b(T,C),!O.c||!T.s||T.c&&!T.c[0]?new b(NaN):!T.c||O.c&&!O.c[0]?new b(O):(m==9?(M=T.s,T.s=1,I=t(O,T,0,3),T.s=M,I.s*=M):I=t(O,T,0,m),T=O.minus(I.times(T)),!T.c[0]&&m==1&&(T.s=O.s),T)},s.multipliedBy=s.times=function(T,C){var I,M,O,N,D,P,U,Q,z,H,W,te,J,K,re,ce=this,oe=ce.c,ge=(T=new b(T,C)).c;if(!oe||!ge||!oe[0]||!ge[0])return!ce.s||!T.s||oe&&!oe[0]&&!ge||ge&&!ge[0]&&!oe?T.c=T.e=T.s=null:(T.s*=ce.s,!oe||!ge?T.c=T.e=null:(T.c=[0],T.e=0)),T;for(M=kr(ce.e/Gt)+kr(T.e/Gt),T.s*=ce.s,U=oe.length,H=ge.length,U<H&&(J=oe,oe=ge,ge=J,O=U,U=H,H=O),O=U+H,J=[];O--;J.push(0));for(K=Xr,re=jo,O=H;--O>=0;){for(I=0,W=ge[O]%re,te=ge[O]/re|0,D=U,N=O+D;N>O;)Q=oe[--D]%re,z=oe[D]/re|0,P=te*Q+z*W,Q=W*Q+P%re*re+J[N]+I,I=(Q/K|0)+(P/re|0)+te*z,J[N--]=Q%K;J[N]=I}return I?++M:J.splice(0,1),R(T,J,M)},s.negated=function(){var T=new b(this);return T.s=-T.s||null,T},s.plus=function(T,C){var I,M=this,O=M.s;if(T=new b(T,C),C=T.s,!O||!C)return new b(NaN);if(O!=C)return T.s=-C,M.minus(T);var N=M.e/Gt,D=T.e/Gt,P=M.c,U=T.c;if(!N||!D){if(!P||!U)return new b(O/0);if(!P[0]||!U[0])return U[0]?T:new b(P[0]?M:O*0)}if(N=kr(N),D=kr(D),P=P.slice(),O=N-D){for(O>0?(D=N,I=U):(O=-O,I=P),I.reverse();O--;I.push(0));I.reverse()}for(O=P.length,C=U.length,O-C<0&&(I=U,U=P,P=I,C=O),O=0;C;)O=(P[--C]=P[C]+U[C]+O)/Xr|0,P[C]=Xr===P[C]?0:P[C]%Xr;return O&&(P=[O].concat(P),++D),R(T,P,D)},s.precision=s.sd=function(T,C){var I,M,O,N=this;if(T!=null&&T!==!!T)return ri(T,1,Qi),C==null?C=o:ri(C,0,8),k(new b(N),T,C);if(!(I=N.c))return null;if(O=I.length-1,M=O*Gt+1,O=I[O]){for(;O%10==0;O/=10,M--);for(O=I[0];O>=10;O/=10,M++);}return T&&N.e+1>M&&(M=N.e+1),M},s.shiftedBy=function(T){return ri(T,-kv,kv),this.times("1e"+T)},s.squareRoot=s.sqrt=function(){var T,C,I,M,O,N=this,D=N.c,P=N.s,U=N.e,Q=a+4,z=new b("0.5");if(P!==1||!D||!D[0])return new b(!P||P<0&&(!D||D[0])?NaN:D?N:1/0);if(P=Math.sqrt(+L(N)),P==0||P==1/0?(C=Tr(D),(C.length+U)%2==0&&(C+="0"),P=Math.sqrt(+C),U=kr((U+1)/2)-(U<0||U%2),P==1/0?C="5e"+U:(C=P.toExponential(),C=C.slice(0,C.indexOf("e")+1)+U),I=new b(C)):I=new b(P+""),I.c[0]){for(U=I.e,P=U+Q,P<3&&(P=0);;)if(O=I,I=z.times(O.plus(t(N,O,Q,1))),Tr(O.c).slice(0,P)===(C=Tr(I.c)).slice(0,P))if(I.e<U&&--P,C=C.slice(P-3,P+1),C=="9999"||!M&&C=="4999"){if(!M&&(k(O,O.e+a+2,0),O.times(O).eq(N))){I=O;break}Q+=4,P+=4,M=1}else{(!+C||!+C.slice(1)&&C.charAt(0)=="5")&&(k(I,I.e+a+2,1),T=!I.times(I).eq(N));break}}return k(I,I.e+a+1,o,T)},s.toExponential=function(T,C){return T!=null&&(ri(T,0,Qi),T++),w(this,T,C,1)},s.toFixed=function(T,C){return T!=null&&(ri(T,0,Qi),T=T+this.e+1),w(this,T,C)},s.toFormat=function(T,C,I){var M,O=this;if(I==null)T!=null&&C&&typeof C=="object"?(I=C,C=null):T&&typeof T=="object"?(I=T,T=C=null):I=y;else if(typeof I!="object")throw Error(Zs+"Argument not an object: "+I);if(M=O.toFixed(T,C),O.c){var N,D=M.split("."),P=+I.groupSize,U=+I.secondaryGroupSize,Q=I.groupSeparator||"",z=D[0],H=D[1],W=O.s<0,te=W?z.slice(1):z,J=te.length;if(U&&(N=P,P=U,U=N,J-=N),P>0&&J>0){for(N=J%P||P,z=te.substr(0,N);N<J;N+=P)z+=Q+te.substr(N,P);U>0&&(z+=Q+te.slice(N)),W&&(z="-"+z)}M=H?z+(I.decimalSeparator||"")+((U=+I.fractionGroupSize)?H.replace(new RegExp("\\d{"+U+"}\\B","g"),"$&"+(I.fractionGroupSeparator||"")):H):z}return(I.prefix||"")+M+(I.suffix||"")},s.toFraction=function(T){var C,I,M,O,N,D,P,U,Q,z,H,W,te=this,J=te.c;if(T!=null&&(P=new b(T),!P.isInteger()&&(P.c||P.s!==1)||P.lt(r)))throw Error(Zs+"Argument "+(P.isInteger()?"out of range: ":"not an integer: ")+L(P));if(!J)return new b(te);for(C=new b(r),Q=I=new b(r),M=U=new b(r),W=Tr(J),N=C.e=W.length-te.e-1,C.c[0]=Nv[(D=N%Gt)<0?Gt+D:D],T=!T||P.comparedTo(C)>0?N>0?C:Q:P,D=d,d=1/0,P=new b(W),U.c[0]=0;z=t(P,C,0,1),O=I.plus(z.times(M)),O.comparedTo(T)!=1;)I=M,M=O,Q=U.plus(z.times(O=Q)),U=O,C=P.minus(z.times(O=C)),P=O;return O=t(T.minus(I),M,0,1),U=U.plus(O.times(Q)),I=I.plus(O.times(M)),U.s=Q.s=te.s,N=N*2,H=t(Q,M,N,o).minus(te).abs().comparedTo(t(U,I,N,o).minus(te).abs())<1?[Q,M]:[U,I],d=D,H},s.toNumber=function(){return+L(this)},s.toPrecision=function(T,C){return T!=null&&ri(T,1,Qi),w(this,T,C,2)},s.toString=function(T){var C,I=this,M=I.s,O=I.e;return O===null?M?(C="Infinity",M<0&&(C="-"+C)):C="NaN":(T==null?C=O<=l||O>=c?om(Tr(I.c),O):io(Tr(I.c),O,"0"):T===10&&v?(I=k(new b(I),a+O+1,o),C=io(Tr(I.c),I.e,"0")):(ri(T,2,x.length,"Base"),C=n(io(Tr(I.c),O,"0"),10,T,M,!0)),M<0&&I.c[0]&&(C="-"+C)),C},s.valueOf=s.toJSON=function(){return L(this)},s._isBigNumber=!0,s[Symbol.toStringTag]="BigNumber",s[Symbol.for("nodejs.util.inspect.custom")]=s.valueOf,e!=null&&b.set(e),b}function kr(e){var t=e|0;return e>0||e===t?t:t-1}function Tr(e){for(var t,n,i=1,s=e.length,r=e[0]+"";i<s;){for(t=e[i++]+"",n=Gt-t.length;n--;t="0"+t);r+=t}for(s=r.length;r.charCodeAt(--s)===48;);return r.slice(0,s+1||1)}function Jl(e,t){var n,i,s=e.c,r=t.c,a=e.s,o=t.s,l=e.e,c=t.e;if(!a||!o)return null;if(n=s&&!s[0],i=r&&!r[0],n||i)return n?i?0:-o:a;if(a!=o)return a;if(n=a<0,i=l==c,!s||!r)return i?0:!s^n?1:-1;if(!i)return l>c^n?1:-1;for(o=(l=s.length)<(c=r.length)?l:c,a=0;a<o;a++)if(s[a]!=r[a])return s[a]>r[a]^n?1:-1;return l==c?0:l>c^n?1:-1}function ri(e,t,n,i){if(e<t||e>n||e!==Rr(e))throw Error(Zs+(i||"Argument")+(typeof e=="number"?e<t||e>n?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function am(e){var t=e.c.length-1;return kr(e.e/Gt)==t&&e.c[t]%2!=0}function om(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function io(e,t,n){var i,s;if(t<0){for(s=n+".";++t;s+=n);e=s+e}else if(i=e.length,++t>i){for(s=n,t-=i;--t;s+=n);e+=s}else t<i&&(e=e.slice(0,t)+"."+e.slice(t));return e}var Da=hR(),E4=class{key;left=null;right=null;constructor(e){this.key=e}},fd=class extends E4{constructor(e){super(e)}},C4=class{size=0;modificationCount=0;splayCount=0;splay(e){const t=this.root;if(t==null)return this.compare(e,e),-1;let n=null,i=null,s=null,r=null,a=t;const o=this.compare;let l;for(;;)if(l=o(a.key,e),l>0){let c=a.left;if(c==null||(l=o(c.key,e),l>0&&(a.left=c.right,c.right=a,a=c,c=a.left,c==null)))break;n==null?i=a:n.left=a,n=a,a=c}else if(l<0){let c=a.right;if(c==null||(l=o(c.key,e),l<0&&(a.right=c.left,c.left=a,a=c,c=a.right,c==null)))break;s==null?r=a:s.right=a,s=a,a=c}else break;return s!=null&&(s.right=a.left,a.left=r),n!=null&&(n.left=a.right,a.right=i),this.root!==a&&(this.root=a,this.splayCount++),l}splayMin(e){let t=e,n=t.left;for(;n!=null;){const i=n;t.left=i.right,i.right=t,t=i,n=t.left}return t}splayMax(e){let t=e,n=t.right;for(;n!=null;){const i=n;t.right=i.left,i.left=t,t=i,n=t.right}return t}_delete(e){if(this.root==null||this.splay(e)!=0)return null;let t=this.root;const n=t,i=t.left;if(this.size--,i==null)this.root=t.right;else{const s=t.right;t=this.splayMax(i),t.right=s,this.root=t}return this.modificationCount++,n}addNewRoot(e,t){this.size++,this.modificationCount++;const n=this.root;if(n==null){this.root=e;return}t<0?(e.left=n,e.right=n.right,n.right=null):(e.right=n,e.left=n.left,n.left=null),this.root=e}_first(){const e=this.root;return e==null?null:(this.root=this.splayMin(e),this.root)}_last(){const e=this.root;return e==null?null:(this.root=this.splayMax(e),this.root)}clear(){this.root=null,this.size=0,this.modificationCount++}has(e){return this.validKey(e)&&this.splay(e)==0}defaultCompare(){return(e,t)=>e<t?-1:e>t?1:0}wrap(){return{getRoot:()=>this.root,setRoot:e=>{this.root=e},getSize:()=>this.size,getModificationCount:()=>this.modificationCount,getSplayCount:()=>this.splayCount,setSplayCount:e=>{this.splayCount=e},splay:e=>this.splay(e),has:e=>this.has(e)}}},I_=class Yd extends C4{root=null;compare;validKey;constructor(t,n){super(),this.compare=t??this.defaultCompare(),this.validKey=n??(i=>i!=null&&i!=null)}delete(t){return this.validKey(t)?this._delete(t)!=null:!1}deleteAll(t){for(const n of t)this.delete(n)}forEach(t){const n=this[Symbol.iterator]();let i;for(;i=n.next(),!i.done;)t(i.value,i.value,this)}add(t){const n=this.splay(t);return n!=0&&this.addNewRoot(new fd(t),n),this}addAndReturn(t){const n=this.splay(t);return n!=0&&this.addNewRoot(new fd(t),n),this.root.key}addAll(t){for(const n of t)this.add(n)}isEmpty(){return this.root==null}isNotEmpty(){return this.root!=null}single(){if(this.size==0)throw"Bad state: No element";if(this.size>1)throw"Bad state: Too many element";return this.root.key}first(){if(this.size==0)throw"Bad state: No element";return this._first().key}last(){if(this.size==0)throw"Bad state: No element";return this._last().key}lastBefore(t){if(t==null)throw"Invalid arguments(s)";if(this.root==null)return null;if(this.splay(t)<0)return this.root.key;let n=this.root.left;if(n==null)return null;let i=n.right;for(;i!=null;)n=i,i=n.right;return n.key}firstAfter(t){if(t==null)throw"Invalid arguments(s)";if(this.root==null)return null;if(this.splay(t)>0)return this.root.key;let n=this.root.right;if(n==null)return null;let i=n.left;for(;i!=null;)n=i,i=n.left;return n.key}retainAll(t){const n=new Yd(this.compare,this.validKey),i=this.modificationCount;for(const s of t){if(i!=this.modificationCount)throw"Concurrent modification during iteration.";this.validKey(s)&&this.splay(s)==0&&n.add(this.root.key)}n.size!=this.size&&(this.root=n.root,this.size=n.size,this.modificationCount++)}lookup(t){return!this.validKey(t)||this.splay(t)!=0?null:this.root.key}intersection(t){const n=new Yd(this.compare,this.validKey);for(const i of this)t.has(i)&&n.add(i);return n}difference(t){const n=new Yd(this.compare,this.validKey);for(const i of this)t.has(i)||n.add(i);return n}union(t){const n=this.clone();return n.addAll(t),n}clone(){const t=new Yd(this.compare,this.validKey);return t.size=this.size,t.root=this.copyNode(this.root),t}copyNode(t){if(t==null)return null;function n(s,r){let a,o;do{if(a=s.left,o=s.right,a!=null){const l=new fd(a.key);r.left=l,n(a,l)}if(o!=null){const l=new fd(o.key);r.right=l,s=o,r=l}}while(o!=null)}const i=new fd(t.key);return n(t,i),i}toSet(){return this.clone()}entries(){return new S4(this.wrap())}keys(){return this[Symbol.iterator]()}values(){return this[Symbol.iterator]()}[Symbol.iterator](){return new w4(this.wrap())}[Symbol.toStringTag]="[object Set]"},uR=class{tree;path=new Array;modificationCount=null;splayCount;constructor(e){this.tree=e,this.splayCount=e.getSplayCount()}[Symbol.iterator](){return this}next(){return this.moveNext()?{done:!1,value:this.current()}:{done:!0,value:null}}current(){if(!this.path.length)return null;const e=this.path[this.path.length-1];return this.getValue(e)}rebuildPath(e){this.path.splice(0,this.path.length),this.tree.splay(e),this.path.push(this.tree.getRoot()),this.splayCount=this.tree.getSplayCount()}findLeftMostDescendent(e){for(;e!=null;)this.path.push(e),e=e.left}moveNext(){if(this.modificationCount!=this.tree.getModificationCount()){if(this.modificationCount==null){this.modificationCount=this.tree.getModificationCount();let n=this.tree.getRoot();for(;n!=null;)this.path.push(n),n=n.left;return this.path.length>0}throw"Concurrent modification during iteration."}if(!this.path.length)return!1;this.splayCount!=this.tree.getSplayCount()&&this.rebuildPath(this.path[this.path.length-1].key);let e=this.path[this.path.length-1],t=e.right;if(t!=null){for(;t!=null;)this.path.push(t),t=t.left;return!0}for(this.path.pop();this.path.length&&this.path[this.path.length-1].right===e;)e=this.path.pop();return this.path.length>0}},w4=class extends uR{getValue(e){return e.key}},S4=class extends uR{getValue(e){return[e.key,e.key]}},dR=e=>()=>e,lb=e=>{const t=e?(n,i)=>i.minus(n).abs().isLessThanOrEqualTo(e):dR(!1);return(n,i)=>t(n,i)?0:n.comparedTo(i)};function I4(e){const t=e?(n,i,s,r,a)=>n.exponentiatedBy(2).isLessThanOrEqualTo(r.minus(i).exponentiatedBy(2).plus(a.minus(s).exponentiatedBy(2)).times(e)):dR(!1);return(n,i,s)=>{const r=n.x,a=n.y,o=s.x,l=s.y,c=a.minus(l).times(i.x.minus(o)).minus(r.minus(o).times(i.y.minus(l)));return t(c,r,a,o,l)?0:c.comparedTo(0)}}var M4=e=>e,T4=e=>{if(e){const t=new I_(lb(e)),n=new I_(lb(e)),i=(r,a)=>a.addAndReturn(r),s=r=>({x:i(r.x,t),y:i(r.y,n)});return s({x:new Da(0),y:new Da(0)}),s}return M4},cb=e=>({set:t=>{Fo=cb(t)},reset:()=>cb(e),compare:lb(e),snap:T4(e),orient:I4(e)}),Fo=cb(),md=(e,t)=>e.ll.x.isLessThanOrEqualTo(t.x)&&t.x.isLessThanOrEqualTo(e.ur.x)&&e.ll.y.isLessThanOrEqualTo(t.y)&&t.y.isLessThanOrEqualTo(e.ur.y),hb=(e,t)=>{if(t.ur.x.isLessThan(e.ll.x)||e.ur.x.isLessThan(t.ll.x)||t.ur.y.isLessThan(e.ll.y)||e.ur.y.isLessThan(t.ll.y))return null;const n=e.ll.x.isLessThan(t.ll.x)?t.ll.x:e.ll.x,i=e.ur.x.isLessThan(t.ur.x)?e.ur.x:t.ur.x,s=e.ll.y.isLessThan(t.ll.y)?t.ll.y:e.ll.y,r=e.ur.y.isLessThan(t.ur.y)?e.ur.y:t.ur.y;return{ll:{x:n,y:s},ur:{x:i,y:r}}},Hg=(e,t)=>e.x.times(t.y).minus(e.y.times(t.x)),pR=(e,t)=>e.x.times(t.x).plus(e.y.times(t.y)),M_=e=>pR(e,e).sqrt(),L4=(e,t,n)=>{const i={x:t.x.minus(e.x),y:t.y.minus(e.y)},s={x:n.x.minus(e.x),y:n.y.minus(e.y)};return Hg(s,i).div(M_(s)).div(M_(i))},B4=(e,t,n)=>{const i={x:t.x.minus(e.x),y:t.y.minus(e.y)},s={x:n.x.minus(e.x),y:n.y.minus(e.y)};return pR(s,i).div(M_(s)).div(M_(i))},QS=(e,t,n)=>t.y.isZero()?null:{x:e.x.plus(t.x.div(t.y).times(n.minus(e.y))),y:n},GS=(e,t,n)=>t.x.isZero()?null:{x:n,y:e.y.plus(t.y.div(t.x).times(n.minus(e.x)))},R4=(e,t,n,i)=>{if(t.x.isZero())return GS(n,i,e.x);if(i.x.isZero())return GS(e,t,n.x);if(t.y.isZero())return QS(n,i,e.y);if(i.y.isZero())return QS(e,t,n.y);const s=Hg(t,i);if(s.isZero())return null;const r={x:n.x.minus(e.x),y:n.y.minus(e.y)},a=Hg(r,t).div(s),o=Hg(r,i).div(s),l=e.x.plus(o.times(t.x)),c=n.x.plus(a.times(i.x)),h=e.y.plus(o.times(t.y)),d=n.y.plus(a.times(i.y));return{x:l.plus(c).div(2),y:h.plus(d).div(2)}},Ma=class fR{point;isLeft;segment;otherSE;consumedBy;static compare(t,n){const i=fR.comparePoints(t.point,n.point);return i!==0?i:(t.point!==n.point&&t.link(n),t.isLeft!==n.isLeft?t.isLeft?1:-1:T_.compare(t.segment,n.segment))}static comparePoints(t,n){return t.x.isLessThan(n.x)?-1:t.x.isGreaterThan(n.x)?1:t.y.isLessThan(n.y)?-1:t.y.isGreaterThan(n.y)?1:0}constructor(t,n){t.events===void 0?t.events=[this]:t.events.push(this),this.point=t,this.isLeft=n}link(t){if(t.point===this.point)throw new Error("Tried to link already linked events");const n=t.point.events;for(let i=0,s=n.length;i<s;i++){const r=n[i];this.point.events.push(r),r.point=this.point}this.checkForConsuming()}checkForConsuming(){const t=this.point.events.length;for(let n=0;n<t;n++){const i=this.point.events[n];if(i.segment.consumedBy===void 0)for(let s=n+1;s<t;s++){const r=this.point.events[s];r.consumedBy===void 0&&i.otherSE.point.events===r.otherSE.point.events&&i.segment.consume(r.segment)}}}getAvailableLinkedEvents(){const t=[];for(let n=0,i=this.point.events.length;n<i;n++){const s=this.point.events[n];s!==this&&!s.segment.ringOut&&s.segment.isInResult()&&t.push(s)}return t}getLeftmostComparator(t){const n=new Map,i=s=>{const r=s.otherSE;n.set(s,{sine:L4(this.point,t.point,r.point),cosine:B4(this.point,t.point,r.point)})};return(s,r)=>{n.has(s)||i(s),n.has(r)||i(r);const{sine:a,cosine:o}=n.get(s),{sine:l,cosine:c}=n.get(r);return a.isGreaterThanOrEqualTo(0)&&l.isGreaterThanOrEqualTo(0)?o.isLessThan(c)?1:o.isGreaterThan(c)?-1:0:a.isLessThan(0)&&l.isLessThan(0)?o.isLessThan(c)?-1:o.isGreaterThan(c)?1:0:l.isLessThan(a)?-1:l.isGreaterThan(a)?1:0}}},k4=class ub{events;poly;_isExteriorRing;_enclosingRing;static factory(t){const n=[];for(let i=0,s=t.length;i<s;i++){const r=t[i];if(!r.isInResult()||r.ringOut)continue;let a=null,o=r.leftSE,l=r.rightSE;const c=[o],h=o.point,d=[];for(;a=o,o=l,c.push(o),o.point!==h;)for(;;){const f=o.getAvailableLinkedEvents();if(f.length===0){const y=c[0].point,x=c[c.length-1].point;throw new Error(`Unable to complete output ring starting at [${y.x}, ${y.y}]. Last matching segment found ends at [${x.x}, ${x.y}].`)}if(f.length===1){l=f[0].otherSE;break}let m=null;for(let y=0,x=d.length;y<x;y++)if(d[y].point===o.point){m=y;break}if(m!==null){const y=d.splice(m)[0],x=c.splice(y.index);x.unshift(x[0].otherSE),n.push(new ub(x.reverse()));continue}d.push({index:c.length,point:o.point});const A=o.getLeftmostComparator(a);l=f.sort(A)[0].otherSE;break}n.push(new ub(c))}return n}constructor(t){this.events=t;for(let n=0,i=t.length;n<i;n++)t[n].segment.ringOut=this;this.poly=null}getGeom(){let t=this.events[0].point;const n=[t];for(let c=1,h=this.events.length-1;c<h;c++){const d=this.events[c].point,f=this.events[c+1].point;Fo.orient(d,t,f)!==0&&(n.push(d),t=d)}if(n.length===1)return null;const i=n[0],s=n[1];Fo.orient(i,t,s)===0&&n.shift(),n.push(n[0]);const r=this.isExteriorRing()?1:-1,a=this.isExteriorRing()?0:n.length-1,o=this.isExteriorRing()?n.length:-1,l=[];for(let c=a;c!=o;c+=r)l.push([n[c].x.toNumber(),n[c].y.toNumber()]);return l}isExteriorRing(){if(this._isExteriorRing===void 0){const t=this.enclosingRing();this._isExteriorRing=t?!t.isExteriorRing():!0}return this._isExteriorRing}enclosingRing(){return this._enclosingRing===void 0&&(this._enclosingRing=this._calcEnclosingRing()),this._enclosingRing}_calcEnclosingRing(){let t=this.events[0];for(let s=1,r=this.events.length;s<r;s++){const a=this.events[s];Ma.compare(t,a)>0&&(t=a)}let n=t.segment.prevInResult(),i=n?n.prevInResult():null;for(;;){if(!n)return null;if(!i)return n.ringOut;if(i.ringOut!==n.ringOut)return i.ringOut?.enclosingRing()!==n.ringOut?n.ringOut:n.ringOut?.enclosingRing();n=i.prevInResult(),i=n?n.prevInResult():null}}},HS=class{exteriorRing;interiorRings;constructor(e){this.exteriorRing=e,e.poly=this,this.interiorRings=[]}addInterior(e){this.interiorRings.push(e),e.poly=this}getGeom(){const e=this.exteriorRing.getGeom();if(e===null)return null;const t=[e];for(let n=0,i=this.interiorRings.length;n<i;n++){const s=this.interiorRings[n].getGeom();s!==null&&t.push(s)}return t}},N4=class{rings;polys;constructor(e){this.rings=e,this.polys=this._composePolys(e)}getGeom(){const e=[];for(let t=0,n=this.polys.length;t<n;t++){const i=this.polys[t].getGeom();i!==null&&e.push(i)}return e}_composePolys(e){const t=[];for(let n=0,i=e.length;n<i;n++){const s=e[n];if(!s.poly)if(s.isExteriorRing())t.push(new HS(s));else{const r=s.enclosingRing();r?.poly||t.push(new HS(r)),r?.poly?.addInterior(s)}}return t}},P4=class{queue;tree;segments;constructor(e,t=T_.compare){this.queue=e,this.tree=new I_(t),this.segments=[]}process(e){const t=e.segment,n=[];if(e.consumedBy)return e.isLeft?this.queue.delete(e.otherSE):this.tree.delete(t),n;e.isLeft&&this.tree.add(t);let i=t,s=t;do i=this.tree.lastBefore(i);while(i!=null&&i.consumedBy!=null);do s=this.tree.firstAfter(s);while(s!=null&&s.consumedBy!=null);if(e.isLeft){let r=null;if(i){const o=i.getIntersection(t);if(o!==null&&(t.isAnEndpoint(o)||(r=o),!i.isAnEndpoint(o))){const l=this._splitSafely(i,o);for(let c=0,h=l.length;c<h;c++)n.push(l[c])}}let a=null;if(s){const o=s.getIntersection(t);if(o!==null&&(t.isAnEndpoint(o)||(a=o),!s.isAnEndpoint(o))){const l=this._splitSafely(s,o);for(let c=0,h=l.length;c<h;c++)n.push(l[c])}}if(r!==null||a!==null){let o=null;r===null?o=a:a===null?o=r:o=Ma.comparePoints(r,a)<=0?r:a,this.queue.delete(t.rightSE),n.push(t.rightSE);const l=t.split(o);for(let c=0,h=l.length;c<h;c++)n.push(l[c])}n.length>0?(this.tree.delete(t),n.push(e)):(this.segments.push(t),t.prev=i)}else{if(i&&s){const r=i.getIntersection(s);if(r!==null){if(!i.isAnEndpoint(r)){const a=this._splitSafely(i,r);for(let o=0,l=a.length;o<l;o++)n.push(a[o])}if(!s.isAnEndpoint(r)){const a=this._splitSafely(s,r);for(let o=0,l=a.length;o<l;o++)n.push(a[o])}}}this.tree.delete(t)}return n}_splitSafely(e,t){this.tree.delete(e);const n=e.rightSE;this.queue.delete(n);const i=e.split(t);return i.push(n),e.consumedBy===void 0&&this.tree.add(e),i}},D4=class{type;numMultiPolys;run(e,t,n){jd.type=e;const i=[new VS(t,!0)];for(let o=0,l=n.length;o<l;o++)i.push(new VS(n[o],!1));if(jd.numMultiPolys=i.length,jd.type==="difference"){const o=i[0];let l=1;for(;l<i.length;)hb(i[l].bbox,o.bbox)!==null?l++:i.splice(l,1)}if(jd.type==="intersection")for(let o=0,l=i.length;o<l;o++){const c=i[o];for(let h=o+1,d=i.length;h<d;h++)if(hb(c.bbox,i[h].bbox)===null)return[]}const s=new I_(Ma.compare);for(let o=0,l=i.length;o<l;o++){const c=i[o].getSweepEvents();for(let h=0,d=c.length;h<d;h++)s.add(c[h])}const r=new P4(s);let a=null;for(s.size!=0&&(a=s.first(),s.delete(a));a;){const o=r.process(a);for(let l=0,c=o.length;l<c;l++){const h=o[l];h.consumedBy===void 0&&s.add(h)}s.size!=0?(a=s.first(),s.delete(a)):a=null}return Fo.reset(),new N4(k4.factory(r.segments)).getGeom()}},jd=new D4,Fp=jd,F4=0,T_=class $g{id;leftSE;rightSE;rings;windings;ringOut;consumedBy;prev;_prevInResult;_beforeState;_afterState;_isInResult;static compare(t,n){const i=t.leftSE.point.x,s=n.leftSE.point.x,r=t.rightSE.point.x,a=n.rightSE.point.x;if(a.isLessThan(i))return 1;if(r.isLessThan(s))return-1;const o=t.leftSE.point.y,l=n.leftSE.point.y,c=t.rightSE.point.y,h=n.rightSE.point.y;if(i.isLessThan(s)){if(l.isLessThan(o)&&l.isLessThan(c))return 1;if(l.isGreaterThan(o)&&l.isGreaterThan(c))return-1;const d=t.comparePoint(n.leftSE.point);if(d<0)return 1;if(d>0)return-1;const f=n.comparePoint(t.rightSE.point);return f!==0?f:-1}if(i.isGreaterThan(s)){if(o.isLessThan(l)&&o.isLessThan(h))return-1;if(o.isGreaterThan(l)&&o.isGreaterThan(h))return 1;const d=n.comparePoint(t.leftSE.point);if(d!==0)return d;const f=t.comparePoint(n.rightSE.point);return f<0?1:f>0?-1:1}if(o.isLessThan(l))return-1;if(o.isGreaterThan(l))return 1;if(r.isLessThan(a)){const d=n.comparePoint(t.rightSE.point);if(d!==0)return d}if(r.isGreaterThan(a)){const d=t.comparePoint(n.rightSE.point);if(d<0)return 1;if(d>0)return-1}if(!r.eq(a)){const d=c.minus(o),f=r.minus(i),m=h.minus(l),A=a.minus(s);if(d.isGreaterThan(f)&&m.isLessThan(A))return 1;if(d.isLessThan(f)&&m.isGreaterThan(A))return-1}return r.isGreaterThan(a)?1:r.isLessThan(a)||c.isLessThan(h)?-1:c.isGreaterThan(h)?1:t.id<n.id?-1:t.id>n.id?1:0}constructor(t,n,i,s){this.id=++F4,this.leftSE=t,t.segment=this,t.otherSE=n,this.rightSE=n,n.segment=this,n.otherSE=t,this.rings=i,this.windings=s}static fromRing(t,n,i){let s,r,a;const o=Ma.comparePoints(t,n);if(o<0)s=t,r=n,a=1;else if(o>0)s=n,r=t,a=-1;else throw new Error(`Tried to create degenerate segment at [${t.x}, ${t.y}]`);return new $g(new Ma(s,!0),new Ma(r,!1),[i],[a])}replaceRightSE(t){this.rightSE=t,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const t=this.leftSE.point.y,n=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:t.isLessThan(n)?t:n},ur:{x:this.rightSE.point.x,y:t.isGreaterThan(n)?t:n}}}vector(){return{x:this.rightSE.point.x.minus(this.leftSE.point.x),y:this.rightSE.point.y.minus(this.leftSE.point.y)}}isAnEndpoint(t){return t.x.eq(this.leftSE.point.x)&&t.y.eq(this.leftSE.point.y)||t.x.eq(this.rightSE.point.x)&&t.y.eq(this.rightSE.point.y)}comparePoint(t){return Fo.orient(this.leftSE.point,t,this.rightSE.point)}getIntersection(t){const n=this.bbox(),i=t.bbox(),s=hb(n,i);if(s===null)return null;const r=this.leftSE.point,a=this.rightSE.point,o=t.leftSE.point,l=t.rightSE.point,c=md(n,o)&&this.comparePoint(o)===0,h=md(i,r)&&t.comparePoint(r)===0,d=md(n,l)&&this.comparePoint(l)===0,f=md(i,a)&&t.comparePoint(a)===0;if(h&&c)return f&&!d?a:!f&&d?l:null;if(h)return d&&r.x.eq(l.x)&&r.y.eq(l.y)?null:r;if(c)return f&&a.x.eq(o.x)&&a.y.eq(o.y)?null:o;if(f&&d)return null;if(f)return a;if(d)return l;const m=R4(r,this.vector(),o,t.vector());return m===null||!md(s,m)?null:Fo.snap(m)}split(t){const n=[],i=t.events!==void 0,s=new Ma(t,!0),r=new Ma(t,!1),a=this.rightSE;this.replaceRightSE(r),n.push(r),n.push(s);const o=new $g(s,a,this.rings.slice(),this.windings.slice());return Ma.comparePoints(o.leftSE.point,o.rightSE.point)>0&&o.swapEvents(),Ma.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),i&&(s.checkForConsuming(),r.checkForConsuming()),n}swapEvents(){const t=this.rightSE;this.rightSE=this.leftSE,this.leftSE=t,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let n=0,i=this.windings.length;n<i;n++)this.windings[n]*=-1}consume(t){let n=this,i=t;for(;n.consumedBy;)n=n.consumedBy;for(;i.consumedBy;)i=i.consumedBy;const s=$g.compare(n,i);if(s!==0){if(s>0){const r=n;n=i,i=r}if(n.prev===i){const r=n;n=i,i=r}for(let r=0,a=i.rings.length;r<a;r++){const o=i.rings[r],l=i.windings[r],c=n.rings.indexOf(o);c===-1?(n.rings.push(o),n.windings.push(l)):n.windings[c]+=l}i.rings=null,i.windings=null,i.consumedBy=n,i.leftSE.consumedBy=n.leftSE,i.rightSE.consumedBy=n.rightSE}}prevInResult(){return this._prevInResult!==void 0?this._prevInResult:(this.prev?this.prev.isInResult()?this._prevInResult=this.prev:this._prevInResult=this.prev.prevInResult():this._prevInResult=null,this._prevInResult)}beforeState(){if(this._beforeState!==void 0)return this._beforeState;if(!this.prev)this._beforeState={rings:[],windings:[],multiPolys:[]};else{const t=this.prev.consumedBy||this.prev;this._beforeState=t.afterState()}return this._beforeState}afterState(){if(this._afterState!==void 0)return this._afterState;const t=this.beforeState();this._afterState={rings:t.rings.slice(0),windings:t.windings.slice(0),multiPolys:[]};const n=this._afterState.rings,i=this._afterState.windings,s=this._afterState.multiPolys;for(let o=0,l=this.rings.length;o<l;o++){const c=this.rings[o],h=this.windings[o],d=n.indexOf(c);d===-1?(n.push(c),i.push(h)):i[d]+=h}const r=[],a=[];for(let o=0,l=n.length;o<l;o++){if(i[o]===0)continue;const c=n[o],h=c.poly;if(a.indexOf(h)===-1)if(c.isExterior)r.push(h);else{a.indexOf(h)===-1&&a.push(h);const d=r.indexOf(c.poly);d!==-1&&r.splice(d,1)}}for(let o=0,l=r.length;o<l;o++){const c=r[o].multiPoly;s.indexOf(c)===-1&&s.push(c)}return this._afterState}isInResult(){if(this.consumedBy)return!1;if(this._isInResult!==void 0)return this._isInResult;const t=this.beforeState().multiPolys,n=this.afterState().multiPolys;switch(Fp.type){case"union":{const i=t.length===0,s=n.length===0;this._isInResult=i!==s;break}case"intersection":{let i,s;t.length<n.length?(i=t.length,s=n.length):(i=n.length,s=t.length),this._isInResult=s===Fp.numMultiPolys&&i<s;break}case"xor":{const i=Math.abs(t.length-n.length);this._isInResult=i%2===1;break}case"difference":{const i=s=>s.length===1&&s[0].isSubject;this._isInResult=i(t)!==i(n);break}}return this._isInResult}},$S=class{poly;isExterior;segments;bbox;constructor(e,t,n){if(!Array.isArray(e)||e.length===0)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=t,this.isExterior=n,this.segments=[],typeof e[0][0]!="number"||typeof e[0][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const i=Fo.snap({x:new Da(e[0][0]),y:new Da(e[0][1])});this.bbox={ll:{x:i.x,y:i.y},ur:{x:i.x,y:i.y}};let s=i;for(let r=1,a=e.length;r<a;r++){if(typeof e[r][0]!="number"||typeof e[r][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const o=Fo.snap({x:new Da(e[r][0]),y:new Da(e[r][1])});o.x.eq(s.x)&&o.y.eq(s.y)||(this.segments.push(T_.fromRing(s,o,this)),o.x.isLessThan(this.bbox.ll.x)&&(this.bbox.ll.x=o.x),o.y.isLessThan(this.bbox.ll.y)&&(this.bbox.ll.y=o.y),o.x.isGreaterThan(this.bbox.ur.x)&&(this.bbox.ur.x=o.x),o.y.isGreaterThan(this.bbox.ur.y)&&(this.bbox.ur.y=o.y),s=o)}(!i.x.eq(s.x)||!i.y.eq(s.y))&&this.segments.push(T_.fromRing(s,i,this))}getSweepEvents(){const e=[];for(let t=0,n=this.segments.length;t<n;t++){const i=this.segments[t];e.push(i.leftSE),e.push(i.rightSE)}return e}},O4=class{multiPoly;exteriorRing;interiorRings;bbox;constructor(e,t){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");this.exteriorRing=new $S(e[0],this,!0),this.bbox={ll:{x:this.exteriorRing.bbox.ll.x,y:this.exteriorRing.bbox.ll.y},ur:{x:this.exteriorRing.bbox.ur.x,y:this.exteriorRing.bbox.ur.y}},this.interiorRings=[];for(let n=1,i=e.length;n<i;n++){const s=new $S(e[n],this,!1);s.bbox.ll.x.isLessThan(this.bbox.ll.x)&&(this.bbox.ll.x=s.bbox.ll.x),s.bbox.ll.y.isLessThan(this.bbox.ll.y)&&(this.bbox.ll.y=s.bbox.ll.y),s.bbox.ur.x.isGreaterThan(this.bbox.ur.x)&&(this.bbox.ur.x=s.bbox.ur.x),s.bbox.ur.y.isGreaterThan(this.bbox.ur.y)&&(this.bbox.ur.y=s.bbox.ur.y),this.interiorRings.push(s)}this.multiPoly=t}getSweepEvents(){const e=this.exteriorRing.getSweepEvents();for(let t=0,n=this.interiorRings.length;t<n;t++){const i=this.interiorRings[t].getSweepEvents();for(let s=0,r=i.length;s<r;s++)e.push(i[s])}return e}},VS=class{isSubject;polys;bbox;constructor(e,t){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");try{typeof e[0][0][0]=="number"&&(e=[e])}catch{}this.polys=[],this.bbox={ll:{x:new Da(Number.POSITIVE_INFINITY),y:new Da(Number.POSITIVE_INFINITY)},ur:{x:new Da(Number.NEGATIVE_INFINITY),y:new Da(Number.NEGATIVE_INFINITY)}};for(let n=0,i=e.length;n<i;n++){const s=new O4(e[n],this);s.bbox.ll.x.isLessThan(this.bbox.ll.x)&&(this.bbox.ll.x=s.bbox.ll.x),s.bbox.ll.y.isLessThan(this.bbox.ll.y)&&(this.bbox.ll.y=s.bbox.ll.y),s.bbox.ur.x.isGreaterThan(this.bbox.ur.x)&&(this.bbox.ur.x=s.bbox.ur.x),s.bbox.ur.y.isGreaterThan(this.bbox.ur.y)&&(this.bbox.ur.y=s.bbox.ur.y),this.polys.push(s)}this.isSubject=t}getSweepEvents(){const e=[];for(let t=0,n=this.polys.length;t<n;t++){const i=this.polys[t].getSweepEvents();for(let s=0,r=i.length;s<r;s++)e.push(i[s])}return e}},U4=(e,...t)=>Fp.run("union",e,t),z4=(e,...t)=>Fp.run("intersection",e,t),Q4=(e,...t)=>Fp.run("difference",e,t);Fo.set;function mR(e){const t=[];if(Gl(e,s=>{t.push(s.coordinates)}),t.length<2)throw new Error("Must have at least two features");const n=e.features[0].properties||{},i=Q4(t[0],...t.slice(1));return i.length===0?null:i.length===1?Hr(i[0],n):mA(i,n)}function G4(e,t,n={}){const i=Si(e),s=Si(t);return s[0]+=s[0]-i[0]>180?-360:i[0]-s[0]>180?360:0,T2(H4(i,s),"meters",n.units)}function H4(e,t,n){n=n===void 0?$i:Number(n);const i=n,s=e[1]*Math.PI/180,r=t[1]*Math.PI/180,a=r-s;let o=Math.abs(t[0]-e[0])*Math.PI/180;o>Math.PI&&(o-=2*Math.PI);const l=Math.log(Math.tan(r/2+Math.PI/4)/Math.tan(s/2+Math.PI/4)),c=Math.abs(l)>1e-11?a/l:Math.cos(s);return Math.sqrt(a*a+c*c*o*o)*i}function gR(e,t,n,i={}){const s=t<0;let r=T2(Math.abs(t),i.units,"meters");s&&(r=-Math.abs(r));const a=Si(e),o=$4(a,r,n);return o[0]+=o[0]-a[0]>180?-360:a[0]-o[0]>180?360:0,wi(o,i.properties)}function $4(e,t,n,i){i=i===void 0?$i:Number(i);const s=t/i,r=e[0]*Math.PI/180,a=Qs(e[1]),o=Qs(n),l=s*Math.cos(o);let c=a+l;Math.abs(c)>Math.PI/2&&(c=c>0?Math.PI-c:-Math.PI-c);const h=Math.log(Math.tan(c/2+Math.PI/4)/Math.tan(a/2+Math.PI/4)),d=Math.abs(h)>1e-11?l/h:Math.cos(a);return[((r+s*Math.sin(o)/d)*180/Math.PI+540)%360-180,c*180/Math.PI]}function V4(e,t={}){const n=[];if(Gl(e,s=>{n.push(s.coordinates)}),n.length<2)throw new Error("Must specify at least 2 geometries");const i=z4(n[0],...n.slice(1));return i.length===0?null:i.length===1?Hr(i[0],t.properties):mA(i,t.properties)}function q4(e,t,n){if(n=n||{},!bf(n))throw new Error("options is invalid");const i=n.origin||"centroid",s=n.mutate||!1;if(!e)throw new Error("geojson required");if(typeof t!="number"||t<=0)throw new Error("invalid factor");const r=Array.isArray(i)||typeof i=="object";return s!==!0&&(e=Es(e)),e.type==="FeatureCollection"&&!r?(Po(e,function(a,o){e.features[o]=qS(a,t,i)}),e):qS(e,t,i)}function qS(e,t,n){const i=v_(e)==="Point",s=W4(e,n);return t===1||i||(Ql(e,function(r){const a=G4(s,r),o=fz(s,r),l=as(gR(s,a*t,o));r[0]=l[0],r[1]=l[1],r.length===3&&(r[2]*=t)}),delete e.bbox),e}function W4(e,t){if(t==null&&(t="centroid"),Array.isArray(t)||typeof t=="object")return Si(t);const n=e.bbox?e.bbox:si(e,{recompute:!0}),i=n[0],s=n[1],r=n[2],a=n[3];switch(t){case"sw":case"southwest":case"westsouth":case"bottomleft":return wi([i,s]);case"se":case"southeast":case"eastsouth":case"bottomright":return wi([r,s]);case"nw":case"northwest":case"westnorth":case"topleft":return wi([i,a]);case"ne":case"northeast":case"eastnorth":case"topright":return wi([r,a]);case"center":return V2(e);case void 0:case null:case"centroid":return Dp(e);default:throw new Error("invalid origin")}}function Y4(e,t){var n=e[0]-t[0],i=e[1]-t[1];return n*n+i*i}function j4(e,t,n){var i=t[0],s=t[1],r=n[0]-i,a=n[1]-s;if(r!==0||a!==0){var o=((e[0]-i)*r+(e[1]-s)*a)/(r*r+a*a);o>1?(i=n[0],s=n[1]):o>0&&(i+=r*o,s+=a*o)}return r=e[0]-i,a=e[1]-s,r*r+a*a}function X4(e,t){for(var n=e[0],i=[n],s,r=1,a=e.length;r<a;r++)s=e[r],Y4(s,n)>t&&(i.push(s),n=s);return n!==s&&i.push(s),i}function db(e,t,n,i,s){for(var r=i,a,o=t+1;o<n;o++){var l=j4(e[o],e[t],e[n]);l>r&&(a=o,r=l)}r>i&&(a-t>1&&db(e,t,a,i,s),s.push(e[a]),n-a>1&&db(e,a,n,i,s))}function Z4(e,t){var n=e.length-1,i=[e[0]];return db(e,0,n,t,i),i.push(e[n]),i}function L_(e,t,n){if(e.length<=2)return e;var i=t!==void 0?t*t:1;return e=n?e:X4(e,i),e=Z4(e,i),e}function pb(e,t={}){var n,i,s;if(t=t??{},!bf(t))throw new Error("options is invalid");const r=(n=t.tolerance)!=null?n:1,a=(i=t.highQuality)!=null?i:!1,o=(s=t.mutate)!=null?s:!1;if(!e)throw new Error("geojson is required");if(r&&r<0)throw new Error("invalid tolerance");return o!==!0&&(e=Es(e)),Gl(e,function(l){J4(l,r,a)}),e}function J4(e,t,n){const i=e.type;if(i==="Point"||i==="MultiPoint")return e;if(z2(e,{mutate:!0}),i!=="GeometryCollection")switch(i){case"LineString":e.coordinates=L_(e.coordinates,t,n);break;case"MultiLineString":e.coordinates=e.coordinates.map(s=>L_(s,t,n));break;case"Polygon":e.coordinates=WS(e.coordinates,t,n);break;case"MultiPolygon":e.coordinates=e.coordinates.map(s=>WS(s,t,n))}return e}function WS(e,t,n){return e.map(function(i){if(i.length<4)throw new Error("invalid polygon");let s=t,r=L_(i,s,n);for(;!YS(r)&&s>=Number.EPSILON;)s-=s*.01,r=L_(i,s,n);return YS(r)?((r[r.length-1][0]!==r[0][0]||r[r.length-1][1]!==r[0][1])&&r.push(r[0]),r):i})}function YS(e){return e.length<3?!1:!(e.length===3&&e[2][0]===e[0][0]&&e[2][1]===e[0][1])}function fb(e,t,n,i){if(i=i||{},!bf(i))throw new Error("options is invalid");var s=i.units,r=i.zTranslation,a=i.mutate;if(!e)throw new Error("geojson is required");if(t==null||isNaN(t))throw new Error("distance is required");if(r&&typeof r!="number"&&isNaN(r))throw new Error("zTranslation is not a number");if(r=r!==void 0?r:0,t===0&&r===0)return e;if(n==null||isNaN(n))throw new Error("direction is required");return t<0&&(t=-t,n=n+180),(a===!1||a===void 0)&&(e=Es(e)),Ql(e,function(o){var l=as(gR(o,t,n,{units:s}));o[0]=l[0],o[1]=l[1],r&&o.length===3&&(o[2]+=r)}),e}function K4(e,t={}){const n=[];if(Gl(e,s=>{n.push(s.coordinates)}),n.length<2)throw new Error("Must have at least 2 geometries");const i=U4(n[0],...n.slice(1));return i.length===0?null:i.length===1?Hr(i[0],t.properties):mA(i,t.properties)}function eG(e,t){if(e.geometry.type!=="Polygon")throw new Error("The input feature must be a Polygon");for(var n=e.geometry.coordinates,i=[],s={},r=[],a=0;a<n.length;a++)for(var o=0;o<n[a].length-1;o++)r.push(f(a,o));var l=new IE;l.load(r);for(var c=0;c<n.length;c++)for(var h=0;h<n[c].length-1;h++)l.search(f(c,h)).forEach(function(m){var A=m.ring,y=m.edge;d(c,h,A,y)});return i;function d(m,A,y,x){var v=n[m][A],b=n[m][A+1],w=n[y][x],S=n[y][x+1],R=tG(v,b,w,S);if(R!==null){var k,L;if(b[0]!==v[0]?k=(R[0]-v[0])/(b[0]-v[0]):k=(R[1]-v[1])/(b[1]-v[1]),S[0]!==w[0]?L=(R[0]-w[0])/(S[0]-w[0]):L=(R[1]-w[1])/(S[1]-w[1]),!(k>=1||k<=0||L>=1||L<=0)){var T=R,C=!s[T.toString()];C&&(s[T.toString()]=!0),t&&i.push(t(R,m,A,v,b,k,y,x,w,S,L,C))}}}function f(m,A){var y=n[m][A],x=n[m][A+1],v,b,w,S;return y[0]<x[0]?(v=y[0],b=x[0]):(v=x[0],b=y[0]),y[1]<x[1]?(w=y[1],S=x[1]):(w=x[1],S=y[1]),{minX:v,minY:w,maxX:b,maxY:S,ring:m,edge:A}}}function tG(e,t,n,i){if(Xd(e,n)||Xd(e,i)||Xd(t,n)||Xd(i,n))return null;var s=e[0],r=e[1],a=t[0],o=t[1],l=n[0],c=n[1],h=i[0],d=i[1],f=(s-a)*(c-d)-(r-o)*(l-h);return f===0?null:[((s*o-r*a)*(l-h)-(s-a)*(l*d-c*h))/f,((s*o-r*a)*(c-d)-(r-o)*(l*d-c*h))/f]}function Xd(e,t){if(!e||!t||e.length!==t.length)return!1;for(var n=0,i=e.length;n<i;n++)if(e[n]instanceof Array&&t[n]instanceof Array){if(!Xd(e[n],t[n]))return!1}else if(e[n]!==t[n])return!1;return!0}function nG(e){if(e.type!="Feature")throw new Error("The input must a geojson object of type Feature");if(e.geometry===void 0||e.geometry==null)throw new Error("The input must a geojson object with a non-empty geometry");if(e.geometry.type!="Polygon")throw new Error("The input must be a geojson Polygon");for(var t=e.geometry.coordinates.length,n=[],v=0;v<t;v++){var i=e.geometry.coordinates[v];Zd(i[0],i[i.length-1])||i.push(i[0]);for(var s=0;s<i.length-1;s++)n.push(i[s])}if(!sG(n))throw new Error("The input polygon may not have duplicate vertices (except for the first and last vertex of each ring)");var r=n.length,a=eG(e,function(K,re,ce,oe,ge,ie,fe,ye,$,Se,Z,Qe){return[K,re,ce,oe,ge,ie,fe,ye,$,Se,Z,Qe]}),o=a.length;if(o==0){for(var k=[],v=0;v<t;v++)k.push(Hr([e.geometry.coordinates[v]],{parent:-1,winding:iG(e.geometry.coordinates[v])}));let K=Kt(k);return H(K),W(K),K}for(var l=[],c=[],v=0;v<t;v++){l.push([]);for(var s=0;s<e.geometry.coordinates[v].length-1;s++)l[v].push([new jS(e.geometry.coordinates[v][ou(s+1,e.geometry.coordinates[v].length-1)],1,[v,s],[v,ou(s+1,e.geometry.coordinates[v].length-1)],void 0)]),c.push(new XS(e.geometry.coordinates[v][s],[v,ou(s-1,e.geometry.coordinates[v].length-1)],[v,s],void 0,void 0,!1,!0))}for(var v=0;v<o;v++)l[a[v][1]][a[v][2]].push(new jS(a[v][0],a[v][5],[a[v][1],a[v][2]],[a[v][6],a[v][7]],void 0)),a[v][11]&&c.push(new XS(a[v][0],[a[v][1],a[v][2]],[a[v][6],a[v][7]],void 0,void 0,!0,!0));for(var h=c.length,v=0;v<l.length;v++)for(var s=0;s<l[v].length;s++)l[v][s].sort(function(re,ce){return re.param<ce.param?-1:1});for(var d=[],v=0;v<h;v++)d.push({minX:c[v].coord[0],minY:c[v].coord[1],maxX:c[v].coord[0],maxY:c[v].coord[1],index:v});var f=new IE;f.load(d);for(var v=0;v<l.length;v++)for(var s=0;s<l[v].length;s++)for(var m=0;m<l[v][s].length;m++){let re;m==l[v][s].length-1?re=l[v][ou(s+1,e.geometry.coordinates[v].length-1)][0].coord:re=l[v][s][m+1].coord;var A=f.search({minX:re[0],minY:re[1],maxX:re[0],maxY:re[1]})[0];l[v][s][m].nxtIsectAlongEdgeIn=A.index}for(var v=0;v<l.length;v++)for(var s=0;s<l[v].length;s++)for(var m=0;m<l[v][s].length;m++){let ce=l[v][s][m].coord;var A=f.search({minX:ce[0],minY:ce[1],maxX:ce[0],maxY:ce[1]})[0],y=A.index;y<r?c[y].nxtIsectAlongRingAndEdge2=l[v][s][m].nxtIsectAlongEdgeIn:Zd(c[y].ringAndEdge1,l[v][s][m].ringAndEdgeIn)?c[y].nxtIsectAlongRingAndEdge1=l[v][s][m].nxtIsectAlongEdgeIn:c[y].nxtIsectAlongRingAndEdge2=l[v][s][m].nxtIsectAlongEdgeIn}for(var x=[],v=0,s=0;s<t;s++){for(var b=v,m=0;m<e.geometry.coordinates[s].length-1;m++)c[v].coord[0]<c[b].coord[0]&&(b=v),v++;for(var w=c[b].nxtIsectAlongRingAndEdge2,m=0;m<c.length;m++)if(c[m].nxtIsectAlongRingAndEdge1==b||c[m].nxtIsectAlongRingAndEdge2==b){var S=m;break}var R=Vg([c[S].coord,c[b].coord,c[w].coord],!0)?1:-1;x.push({isect:b,parent:-1,winding:R})}x.sort(function(J,K){return c[J.isect].coord>c[K.isect].coord?-1:1});for(var k=[];x.length>0;){var L=x.pop(),T=L.isect,C=L.parent,I=L.winding,M=k.length,O=[c[T].coord],N=T;if(c[T].ringAndEdge1Walkable)var D=c[T].ringAndEdge1,P=c[T].nxtIsectAlongRingAndEdge1;else var D=c[T].ringAndEdge2,P=c[T].nxtIsectAlongRingAndEdge2;for(;!Zd(c[T].coord,c[P].coord);){O.push(c[P].coord);for(var U=void 0,v=0;v<x.length;v++)if(x[v].isect==P){U=v;break}if(U!=null&&x.splice(U,1),Zd(D,c[P].ringAndEdge1)){if(D=c[P].ringAndEdge2,c[P].ringAndEdge2Walkable=!1,c[P].ringAndEdge1Walkable){var Q={isect:P};Vg([c[N].coord,c[P].coord,c[c[P].nxtIsectAlongRingAndEdge2].coord],I==1)?(Q.parent=C,Q.winding=-I):(Q.parent=M,Q.winding=I),x.push(Q)}N=P,P=c[P].nxtIsectAlongRingAndEdge2}else{if(D=c[P].ringAndEdge1,c[P].ringAndEdge1Walkable=!1,c[P].ringAndEdge2Walkable){var Q={isect:P};Vg([c[N].coord,c[P].coord,c[c[P].nxtIsectAlongRingAndEdge1].coord],I==1)?(Q.parent=C,Q.winding=-I):(Q.parent=M,Q.winding=I),x.push(Q)}N=P,P=c[P].nxtIsectAlongRingAndEdge1}}O.push(c[P].coord),k.push(Hr([O],{index:M,parent:C,winding:I,netWinding:void 0}))}let z=Kt(k);H(z),W(z);function H(J){for(var K=[],re=0;re<J.features.length;re++)J.features[re].properties.parent==-1&&K.push(re);if(K.length>1)for(var re=0;re<K.length;re++){for(var ce=-1,oe=1/0,ge=0;ge<J.features.length;ge++)K[re]!=ge&&Ii(J.features[K[re]].geometry.coordinates[0][0],J.features[ge],{ignoreBoundary:!0})&&y_(J.features[ge])<oe&&(ce=ge);J.features[K[re]].properties.parent=ce}}function W(J){for(var K=0;K<J.features.length;K++)if(J.features[K].properties.parent==-1){var re=J.features[K].properties.winding;J.features[K].properties.netWinding=re,te(J,K,re)}}function te(J,K,re){for(var ce=0;ce<J.features.length;ce++)if(J.features[ce].properties.parent==K){var oe=re+J.features[ce].properties.winding;J.features[ce].properties.netWinding=oe,te(J,ce,oe)}}return z}var jS=class{constructor(e,t,n,i,s){this.coord=e,this.param=t,this.ringAndEdgeIn=n,this.ringAndEdgeOut=i,this.nxtIsectAlongEdgeIn=s}},XS=class{constructor(e,t,n,i,s,r,a){this.coord=e,this.ringAndEdge1=t,this.ringAndEdge2=n,this.nxtIsectAlongRingAndEdge1=i,this.nxtIsectAlongRingAndEdge2=s,this.ringAndEdge1Walkable=r,this.ringAndEdge2Walkable=a}};function Vg(e,t){if(typeof t>"u"&&(t=!0),e.length!=3)throw new Error("This function requires an array of three points [x,y]");return(e[1][0]-e[0][0])*(e[2][1]-e[0][1])-(e[1][1]-e[0][1])*(e[2][0]-e[0][0])>=0==t}function iG(e){for(var t=0,n=0;n<e.length-1;n++)e[n][0]<e[t][0]&&(t=n);if(Vg([e[ou(t-1,e.length-1)],e[t],e[ou(t+1,e.length-1)]],!0))var i=1;else var i=-1;return i}function Zd(e,t){if(!e||!t||e.length!=t.length)return!1;for(var n=0,i=e.length;n<i;n++)if(e[n]instanceof Array&&t[n]instanceof Array){if(!Zd(e[n],t[n]))return!1}else if(e[n]!=t[n])return!1;return!0}function ou(e,t){return(e%t+t)%t}function sG(e){for(var t={},n=1,i=0,s=e.length;i<s;++i){if(Object.prototype.hasOwnProperty.call(t,e[i].toString())){n=0;break}t[e[i].toString()]=1}return n}function rG(e){var t=[];return Do(e,function(n){n.geometry.type==="Polygon"&&Po(nG(n),function(i){t.push(Hr(i.geometry.coordinates,n.properties))})}),Kt(t)}var aG=class{undoStack=[];redoStack=[];maxSize;isExecuting=!1;onHistoryChange;constructor(e=50,t){this.maxSize=e,this.onHistoryChange=t}record(e){if(!this.isExecuting){for(this.undoStack.push(e);this.undoStack.length>this.maxSize;)this.undoStack.shift();this.redoStack=[],this.notifyChange()}}undo(){if(!this.canUndo())return!1;const e=this.undoStack.pop();this.isExecuting=!0;try{e.undo()}finally{this.isExecuting=!1}return this.redoStack.push(e),this.notifyChange(),!0}redo(){if(!this.canRedo())return!1;const e=this.redoStack.pop();this.isExecuting=!0;try{e.execute()}finally{this.isExecuting=!1}return this.undoStack.push(e),this.notifyChange(),!0}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}isExecutingCommand(){return this.isExecuting}getState(){return{canUndo:this.canUndo(),canRedo:this.canRedo(),undoCount:this.undoStack.length,redoCount:this.redoStack.length}}clear(){this.undoStack=[],this.redoStack=[],this.notifyChange()}getUndoDescription(){return this.undoStack.length===0?null:this.undoStack[this.undoStack.length-1].description}getRedoDescription(){return this.redoStack.length===0?null:this.redoStack[this.redoStack.length-1].description}notifyChange(){this.onHistoryChange&&this.onHistoryChange(this.canUndo(),this.canRedo())}},ZS=class{description;type="create";feature;featureId=null;context;constructor(e,t){this.feature=Es(e),this.context=t,this.featureId=this.extractFeatureId(e);const n=e.geometry?.type||"feature";this.description=`Create ${n}`}execute(){const e=this.context.featuresApi.importGeoJsonFeature(this.feature);e&&(this.featureId=String(e.id),this.context.onFeatureCreate?.(this.feature))}undo(){if(!this.featureId)return;const e=[];try{this.context.featuresApi.forEach(t=>{const n=String(t.id),i=this.getGeomanFeature(t),s=i?this.extractFeatureId(i):null;(n===this.featureId||s===this.featureId)&&e.push(t)}),e.forEach(t=>{try{this.context.featuresApi.delete(t)}catch{try{t.delete()}catch{}}}),e.length>0&&this.featureId&&this.context.onFeatureDelete?.(this.featureId)}catch{}}extractFeatureId(e){const t=e.properties,n=e.id??t?.__gm_id??t?.id;return n!=null?String(n):null}getGeomanFeature(e){if(!e)return null;if(typeof e.getGeoJson=="function")try{return e.getGeoJson()}catch{return null}return e.geoJson??null}},oG=class{description;type="edit";oldFeature;newFeature;featureId;context;constructor(e,t,n){this.oldFeature=Es(e),this.newFeature=Es(t),this.context=n,this.featureId=this.extractFeatureId(t)||this.extractFeatureId(e);const i=t.geometry?.type||"feature";this.description=`Edit ${i}`}execute(){this.updateFeatureGeometry(this.newFeature)}undo(){this.updateFeatureGeometry(this.oldFeature)}updateFeatureGeometry(e){if(this.featureId)try{this.context.featuresApi.forEach(t=>{const n=String(t.id),i=this.getGeomanFeature(t),s=i?this.extractFeatureId(i):null;(n===this.featureId||s===this.featureId)&&(t.updateGeometry?t.updateGeometry(e.geometry):t.updateGeoJsonGeometry&&t.updateGeoJsonGeometry(e.geometry))})}catch{this.deleteAndReimport(e)}}deleteAndReimport(e){if(!this.featureId)return;const t=[];try{this.context.featuresApi.forEach(i=>{const s=String(i.id),r=this.getGeomanFeature(i),a=r?this.extractFeatureId(r):null;(s===this.featureId||a===this.featureId)&&t.push(i)}),t.forEach(i=>{try{this.context.featuresApi.delete(i)}catch{try{i.delete()}catch{}}})}catch{}const n=this.context.featuresApi.importGeoJsonFeature(e);n&&(this.featureId=String(n.id))}extractFeatureId(e){const t=e.properties,n=e.id??t?.__gm_id??t?.id;return n!=null?String(n):null}getGeomanFeature(e){if(!e)return null;if(typeof e.getGeoJson=="function")try{return e.getGeoJson()}catch{return null}return e.geoJson??null}},JS=class{description;type="delete";feature;featureId;context;constructor(e,t){this.feature=Es(e),this.context=t,this.featureId=this.extractFeatureId(e);const n=e.geometry?.type||"feature";this.description=`Delete ${n}`}execute(){if(!this.featureId)return;const e=[];try{this.context.featuresApi.forEach(t=>{const n=String(t.id),i=this.getGeomanFeature(t),s=i?this.extractFeatureId(i):null;(n===this.featureId||s===this.featureId)&&e.push(t)}),e.forEach(t=>{try{this.context.featuresApi.delete(t)}catch{try{t.delete()}catch{}}}),e.length>0&&this.featureId&&this.context.onFeatureDelete?.(this.featureId)}catch{}}undo(){const e=this.context.featuresApi.importGeoJsonFeature(this.feature);e&&(this.featureId=String(e.id),this.context.onFeatureCreate?.(this.feature))}extractFeatureId(e){const t=e.properties,n=e.id??t?.__gm_id??t?.id;return n!=null?String(n):null}getGeomanFeature(e){if(!e)return null;if(typeof e.getGeoJson=="function")try{return e.getGeoJson()}catch{return null}return e.geoJson??null}},lG=class{description;type="composite";commands;constructor(e,t){this.commands=e,this.description=t}execute(){for(const e of this.commands)e.execute()}undo(){for(let e=this.commands.length-1;e>=0;e--)this.commands[e].undo()}getCommandCount(){return this.commands.length}},cG=["polygon","line","rectangle","circle","marker"],hG=["select","drag","change","rotate","cut","delete","scale","copy","split","union","difference","simplify","lasso"],Pv=["select","scale","copy","split","union","difference","simplify","lasso"],uG=["snapping","measurements"],dG=["open","save"],pG={position:"top-left",collapsed:!1,drawModes:cG,editModes:hG,helperModes:uG,fileModes:dG,toolbarOrientation:"vertical",showLabels:!1,simplifyTolerance:.001,snappingEnabled:!0,measurementsEnabled:!1,hideGeomanControl:!0,saveFilename:"features.geojson",onFeatureCreate:()=>{},onFeatureEdit:()=>{},onFeatureDelete:()=>{},onSelectionChange:()=>{},onModeChange:()=>{},onGeoJsonLoad:()=>{},onGeoJsonSave:()=>{},showFeatureProperties:!0,fitBoundsOnLoad:!0,columns:2,enableHistory:!0,maxHistorySize:50,onHistoryChange:()=>{},enableAttributeEditing:!1,attributeSchema:void 0,onAttributeChange:()=>{},attributePanelPosition:"right",attributePanelWidth:300,attributePanelMaxHeight:"80vh",attributePanelTop:10,attributePanelSideOffset:10,attributePanelTitle:"Feature Properties"},rt="geo-editor",gt={LASSO_SOURCE:"geo-editor-lasso-source",LASSO_LAYER:"geo-editor-lasso-layer",LASSO_LINE_LAYER:"geo-editor-lasso-line-layer",SCALE_HANDLES_SOURCE:"geo-editor-scale-handles-source",SCALE_HANDLES_LAYER:"geo-editor-scale-handles-layer",SPLIT_LINE_SOURCE:"geo-editor-split-line-source",SPLIT_LINE_LAYER:"geo-editor-split-line-layer",SELECTION_SOURCE:"geo-editor-selection-source",SELECTION_FILL_LAYER:"geo-editor-selection-fill-layer",SELECTION_LINE_LAYER:"geo-editor-selection-line-layer",SELECTION_CIRCLE_LAYER:"geo-editor-selection-circle-layer",FREEHAND_SOURCE:"geo-editor-freehand-source",FREEHAND_FILL_LAYER:"geo-editor-freehand-fill-layer",FREEHAND_LINE_LAYER:"geo-editor-freehand-line-layer"},sh={handleSize:10,handleColor:"#3388ff",handleBorderColor:"#ffffff",handleBorderWidth:2,minScale:.1,maxScale:10},Dv={tolerance:.001,highQuality:!1,mutate:!1},KS={offset:[5e-4,5e-4],generateNewIds:!0};function Oo(){return`feature_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}function _R(e){return e.geometry.type==="Polygon"||e.geometry.type==="MultiPolygon"}function fG(e){return e.geometry.type==="LineString"||e.geometry.type==="MultiLineString"}function e1(e,t,n){return Math.min(Math.max(e,t),n)}function gd(e){return gz(e).length}var mG=class{options;constructor(e={}){this.options={offset:e.offset??KS.offset,generateNewIds:e.generateNewIds??KS.generateNewIds}}copy(e,t){const n=Es(e),i=t??this.options.offset;return this.options.generateNewIds&&(n.id=Oo(),n.properties&&(n.properties={...n.properties,id:n.id})),i[0]!==0||i[1]!==0?fb(n,Math.sqrt(i[0]**2+i[1]**2)*111,Math.atan2(i[0],i[1])*180/Math.PI,{units:"kilometers"}):n}copyMultiple(e,t){return e.map(n=>this.copy(n,t))}copyToLocation(e,t){if(e.length===0)return[];const n=Dp(Kt(e)).geometry.coordinates,i=t[0]-n[0],s=t[1]-n[1];return e.map(r=>{const a=Es(r);return this.options.generateNewIds&&(a.id=Oo(),a.properties&&(a.properties={...a.properties,id:a.id})),fb(a,Math.sqrt(i**2+s**2)*111,Math.atan2(i,s)*180/Math.PI,{units:"kilometers"})})}setOffset(e){this.options.offset=e}getOffset(){return this.options.offset}},gG=class{defaultOptions;constructor(e){this.defaultOptions={tolerance:e?.tolerance??Dv.tolerance,highQuality:e?.highQuality??Dv.highQuality,mutate:e?.mutate??Dv.mutate}}simplify(e,t){return pb(e,{...this.defaultOptions,...t})}simplifyWithStats(e,t){const n={...this.defaultOptions,...t},i=gd(e),s=pb(e,n),r=gd(s);return{result:s,original:e,verticesBefore:i,verticesAfter:r,reductionPercent:i>0?(i-r)/i*100:0}}getSimplificationStats(e,t){const n=gd(e),i=gd(this.simplify(e,{tolerance:t}));return{before:n,after:i,reduction:n>0?(n-i)/n*100:0}}previewTolerances(e,t){const n=new Map;for(const i of t)n.set(i,this.simplifyWithStats(e,{tolerance:i}));return n}getSuggestedTolerances(e){const t=gd(e),n=[1e-4,5e-4,.001,.005,.01];return t>1e3?[.001,.005,.01,.05,.1]:t>100?[5e-4,.001,.005,.01,.05]:n}findOptimalTolerance(e,t){const n=[1e-5,5e-5,1e-4,5e-4,.001,.005,.01,.05,.1];let i=n[0],s=this.simplifyWithStats(e,{tolerance:i}),r=Math.abs(s.reductionPercent-t);for(const a of n.slice(1)){const o=this.simplifyWithStats(e,{tolerance:a}),l=Math.abs(o.reductionPercent-t);l<r&&(r=l,i=a,s=o)}return{tolerance:i,result:s}}setDefaultTolerance(e){this.defaultOptions.tolerance=e}getDefaultTolerance(){return this.defaultOptions.tolerance}},_G=class{union(e,t){if(e.length===0)return{result:null,originals:[],success:!1,error:"No features provided"};if(e.length===1){const n=Es(e[0]);return n.id=Oo(),t?.properties&&(n.properties={...n.properties,...t.properties}),{result:n,originals:e,success:!0}}try{const n=K4(Kt(e));return n&&(n.id=Oo(),t?.properties&&(n.properties={...n.properties,...t.properties})),{result:n,originals:e,success:n!==null,error:n===null?"Union operation returned null":void 0}}catch(n){return{result:null,originals:e,success:!1,error:`Union operation failed: ${n instanceof Error?n.message:"Unknown error"}`}}}canMerge(e){if(e.length<2)return{canMerge:!1,reason:"Need at least 2 polygons to merge"};for(const t of e)if(t.geometry.type!=="Polygon"&&t.geometry.type!=="MultiPolygon")return{canMerge:!1,reason:"All features must be polygons"};return{canMerge:!0}}hasOverlap(e){for(let t=0;t<e.length;t++)for(let n=t+1;n<e.length;n++)try{if(G2(e[t],e[n])||kE(e[t],e[n]))return!0}catch{}return!1}getCombinedArea(e){return e.reduce((t,n)=>{try{return t+y_(n)}catch{return t}},0)}getUnionArea(e){const t=this.union(e);if(t.success&&t.result)try{return y_(t.result)}catch{return null}return null}},AG=class{difference(e,t,n){if(t.length===0){const i=Es(e);return i.id=Oo(),{result:i,base:e,subtracted:[],success:!0}}try{let i=Es(e);for(const s of t){if(!i)break;i=mR(Kt([i,s]))}return i&&(i.id=Oo(),n?.properties&&(i.properties={...i.properties,...n.properties})),{result:i,base:e,subtracted:t,success:!0}}catch(i){return{result:null,base:e,subtracted:t,success:!1,error:`Difference operation failed: ${i instanceof Error?i.message:"Unknown error"}`}}}canSubtract(e,t){if(e.geometry.type!=="Polygon"&&e.geometry.type!=="MultiPolygon")return{canSubtract:!1,overlap:!1,reason:"Base must be a polygon"};if(t.geometry.type!=="Polygon"&&t.geometry.type!=="MultiPolygon")return{canSubtract:!1,overlap:!1,reason:"Subtract feature must be a polygon"};try{return G2(e,t)||_S(e,t)||kE(e,t)?{canSubtract:!0,overlap:!0}:{canSubtract:!1,overlap:!1,reason:"Polygons do not overlap"}}catch{return{canSubtract:!1,overlap:!1,reason:"Could not determine overlap"}}}getSubtractedArea(e,t){try{const n=V4(Kt([e,t]));return n?y_(n):0}catch{return null}}preview(e,t){return this.difference(e,t).result}createHole(e,t){try{return _S(e,t)?this.difference(e,[t]).result:(console.warn("Hole must be completely inside the polygon"),null)}catch{return null}}},vG=class{map=null;options;activeFeature=null;originalFeature=null;handles=[];activeHandle=null;startPoint=null;onScaleCallback=null;constructor(e={}){this.options={maintainAspectRatio:e.maintainAspectRatio??!0,scaleFromCenter:e.scaleFromCenter??!0,minScale:e.minScale??sh.minScale,maxScale:e.maxScale??sh.maxScale}}init(e){this.map=e}scale(e,t,n){const i=q4(e,e1(t,this.options.minScale,this.options.maxScale),{origin:n||Dp(e).geometry.coordinates});return i.id=e.id||Oo(),i.properties={...e.properties},i}scaleFromHandle(e,t,n,i){const s=si(e),r=Dp(e).geometry.coordinates,a=this.distanceFromCenter(n,r);let o=this.distanceFromCenter(i,r)/a;o=e1(o,this.options.minScale,this.options.maxScale);let l;return this.options.scaleFromCenter?l=r:l=this.getOppositeCorner(s,t),this.scale(e,o,l)}createHandles(e){const[t,n,i,s]=si(e),r=(t+i)/2,a=(n+s)/2;return this.handles=[{position:"nw",coordinates:[t,s]},{position:"n",coordinates:[r,s]},{position:"ne",coordinates:[i,s]},{position:"e",coordinates:[i,a]},{position:"se",coordinates:[i,n]},{position:"s",coordinates:[r,n]},{position:"sw",coordinates:[t,n]},{position:"w",coordinates:[t,a]}],this.handles}startScale(e,t,n,i){this.activeFeature=Es(e),this.originalFeature=Es(e),this.activeHandle=t,this.startPoint=n,this.onScaleCallback=i||null,this.showHandles(e)}showHandlesForFeature(e){this.showHandles(e)}updateScale(e){if(!this.activeFeature||!this.originalFeature||!this.activeHandle||!this.startPoint)return null;const t=this.scaleFromHandle(this.originalFeature,this.activeHandle,this.startPoint,e);this.activeFeature=t,this.updateHandlePositions(t);const n=si(this.originalFeature),i=si(t),s=(i[2]-i[0])/(n[2]-n[0]);return this.onScaleCallback&&this.onScaleCallback(t,s),t}endScale(){if(!this.activeFeature||!this.originalFeature)return null;const e=si(this.originalFeature),t=si(this.activeFeature),n=(t[2]-t[0])/(e[2]-e[0]),i={feature:this.activeFeature,factor:n};return this.hideHandles(),this.activeFeature=null,this.originalFeature=null,this.activeHandle=null,this.startPoint=null,this.onScaleCallback=null,i}cancelScale(){this.hideHandles(),this.activeFeature=null,this.originalFeature=null,this.activeHandle=null,this.startPoint=null,this.onScaleCallback=null}showHandles(e){if(!this.map)return;const t=this.createHandles(e).map(n=>wi(n.coordinates,{position:n.position}));if(!this.map.getSource(gt.SCALE_HANDLES_SOURCE))this.map.addSource(gt.SCALE_HANDLES_SOURCE,{type:"geojson",data:Kt(t)}),this.map.addLayer({id:gt.SCALE_HANDLES_LAYER,type:"circle",source:gt.SCALE_HANDLES_SOURCE,paint:{"circle-radius":sh.handleSize/2,"circle-color":sh.handleColor,"circle-stroke-color":sh.handleBorderColor,"circle-stroke-width":sh.handleBorderWidth}});else{const n=this.map.getSource(gt.SCALE_HANDLES_SOURCE);n&&n.setData(Kt(t))}}updateHandlePositions(e){if(!this.map)return;const t=this.createHandles(e).map(i=>wi(i.coordinates,{position:i.position})),n=this.map.getSource(gt.SCALE_HANDLES_SOURCE);n&&n.setData(Kt(t))}hideHandles(){this.map&&(this.map.getLayer(gt.SCALE_HANDLES_LAYER)&&this.map.removeLayer(gt.SCALE_HANDLES_LAYER),this.map.getSource(gt.SCALE_HANDLES_SOURCE)&&this.map.removeSource(gt.SCALE_HANDLES_SOURCE))}distanceFromCenter(e,t){return Math.sqrt(Math.pow(e[0]-t[0],2)+Math.pow(e[1]-t[1],2))}getOppositeCorner(e,t){const[n,i,s,r]=e,a=(n+s)/2,o=(i+r)/2;return{nw:[s,i],n:[a,i],ne:[n,i],e:[n,o],se:[n,r],s:[a,r],sw:[s,r],w:[s,o]}[t]}getHandleAtPoint(e,t=1e-4){for(const n of this.handles)if(this.distanceFromCenter(e,n.coordinates)<t)return n.position;return null}destroy(){this.cancelScale(),this.map=null}},yG=class{map=null;isDrawing=!1;points=[];options;onCompleteCallback=null;dragPanEnabled=null;boxZoomEnabled=null;doubleClickZoomEnabled=null;handleMouseDown=null;handleMouseMove=null;handleMouseUp=null;constructor(e={}){this.options={mode:e.mode??"intersects"}}init(e){this.map=e}enable(e){this.map&&(this.onCompleteCallback=e||null,this.disableMapInteractions(),this.setupLassoLayers(),this.attachEventListeners(),this.map.getCanvas().style.cursor="crosshair")}disable(){this.removeEventListeners(),this.clearLasso(),this.isDrawing=!1,this.points=[],this.onCompleteCallback=null,this.restoreMapInteractions(),this.map&&(this.map.getCanvas().style.cursor="")}selectWithinLasso(e,t){return t.filter(n=>{try{return this.options.mode==="contains"?RQ(n,e):kE(n,e)}catch{return!1}})}buildLassoPolygon(){if(this.points.length<3)return null;const e=[...this.points,this.points[0]];try{return Hr([e])}catch{return null}}setMode(e){this.options.mode=e}isActive(){return this.isDrawing}setupLassoLayers(){this.map&&(this.map.getSource(gt.LASSO_SOURCE)||this.map.addSource(gt.LASSO_SOURCE,{type:"geojson",data:Kt([])}),this.map.getLayer(gt.LASSO_LAYER)||this.map.addLayer({id:gt.LASSO_LAYER,type:"fill",source:gt.LASSO_SOURCE,paint:{"fill-color":"#3388ff","fill-opacity":.2}}),this.map.getLayer(gt.LASSO_LINE_LAYER)||this.map.addLayer({id:gt.LASSO_LINE_LAYER,type:"line",source:gt.LASSO_SOURCE,paint:{"line-color":"#3388ff","line-width":2,"line-dasharray":[2,2]}}))}attachEventListeners(){this.map&&(this.handleMouseDown=e=>{e.preventDefault(),this.isDrawing=!0,this.points=[[e.lngLat.lng,e.lngLat.lat]],this.updateLassoVisualization()},this.handleMouseMove=e=>{this.isDrawing&&(e.preventDefault(),this.points.push([e.lngLat.lng,e.lngLat.lat]),this.updateLassoVisualization())},this.handleMouseUp=()=>{this.isDrawing&&(this.isDrawing=!1,this.completeLasso())},this.map.on("mousedown",this.handleMouseDown),this.map.on("mousemove",this.handleMouseMove),this.map.on("mouseup",this.handleMouseUp))}removeEventListeners(){this.map&&(this.handleMouseDown&&this.map.off("mousedown",this.handleMouseDown),this.handleMouseMove&&this.map.off("mousemove",this.handleMouseMove),this.handleMouseUp&&this.map.off("mouseup",this.handleMouseUp),this.handleMouseDown=null,this.handleMouseMove=null,this.handleMouseUp=null)}updateLassoVisualization(){if(!this.map||this.points.length<2)return;const e=this.map.getSource(gt.LASSO_SOURCE);if(!e)return;const t=[...this.points];if(t.length>=3){t.push(t[0]);const n=Hr([t]);e.setData(Kt([n]))}else{const n=xs(t);e.setData(Kt([n]))}}completeLasso(){const e=this.buildLassoPolygon();if(e&&this.onCompleteCallback){const t={selected:[],lasso:e};this.onCompleteCallback(t)}setTimeout(()=>{this.clearLasso(),this.points=[]},100)}clearLasso(){if(!this.map)return;const e=this.map.getSource(gt.LASSO_SOURCE);e&&e.setData(Kt([]))}disableMapInteractions(){this.map&&(this.dragPanEnabled=this.map.dragPan.isEnabled(),this.dragPanEnabled&&this.map.dragPan.disable(),this.map.boxZoom&&(this.boxZoomEnabled=this.map.boxZoom.isEnabled(),this.boxZoomEnabled&&this.map.boxZoom.disable()),this.map.doubleClickZoom&&(this.doubleClickZoomEnabled=this.map.doubleClickZoom.isEnabled(),this.doubleClickZoomEnabled&&this.map.doubleClickZoom.disable()))}restoreMapInteractions(){this.map&&(this.dragPanEnabled&&this.map.dragPan.enable(),this.boxZoomEnabled&&this.map.boxZoom&&this.map.boxZoom.enable(),this.doubleClickZoomEnabled&&this.map.doubleClickZoom&&this.map.doubleClickZoom.enable(),this.dragPanEnabled=null,this.boxZoomEnabled=null,this.doubleClickZoomEnabled=null)}removeLayers(){this.map&&(this.map.getLayer(gt.LASSO_LINE_LAYER)&&this.map.removeLayer(gt.LASSO_LINE_LAYER),this.map.getLayer(gt.LASSO_LAYER)&&this.map.removeLayer(gt.LASSO_LAYER),this.map.getSource(gt.LASSO_SOURCE)&&this.map.removeSource(gt.LASSO_SOURCE))}destroy(){this.disable(),this.removeLayers(),this.map=null}},bG=class{map=null;isDrawing=!1;splitLinePoints=[];targetFeature=null;onCompleteCallback=null;handleClick=null;handleMouseMove=null;handleDblClick=null;constructor(){}init(e){this.map=e}splitPolygon(e,t,n){try{if(ju(b_(e),t).features.length<2)return{original:e,parts:[],success:!1,error:"Splitting line must intersect polygon at least twice"};if(!this.clipLineToBbox(t,si(e)))return{original:e,parts:[],success:!1,error:"Could not clip splitting line to polygon"};const i=this.performPolygonSplit(e,t);return i.length===0?{original:e,parts:[],success:!1,error:"Split operation produced no valid parts"}:(i.forEach(s=>{s.id=Oo(),s.properties={...e.properties}}),{original:e,parts:i,success:!0})}catch(i){return{original:e,parts:[],success:!1,error:`Split operation failed: ${i instanceof Error?i.message:"Unknown error"}`}}}splitLine(e,t){try{const n=TE(e,t);return n.features.length<=1?{original:e,parts:[],success:!1,error:"Splitter does not intersect the line"}:{original:e,parts:n.features.map(i=>{const s=i;return s.id=Oo(),s.properties={...e.properties},s}),success:!0}}catch(n){return{original:e,parts:[],success:!1,error:`Split operation failed: ${n instanceof Error?n.message:"Unknown error"}`}}}startSplit(e,t){this.map&&(this.targetFeature=e,this.onCompleteCallback=t,this.splitLinePoints=[],this.isDrawing=!0,this.setupSplitLineLayers(),this.attachEventListeners(),this.map.getCanvas().style.cursor="crosshair")}cancelSplit(){this.cleanup(),this.targetFeature=null,this.onCompleteCallback=null}isActive(){return this.isDrawing}performPolygonSplit(e,t){try{const n=v4(t,1e-5,{units:"degrees"});if(!n)return[];const i=mR(Kt([e,n]));if(!i)return[];if(i.geometry.type==="MultiPolygon")return i.geometry.coordinates.map(r=>Hr(r));const s=rG(i);return s.features.length>1?s.features:[i]}catch{return[]}}clipLineToBbox(e,t){try{return xz(e,t)}catch{return null}}setupSplitLineLayers(){this.map&&(this.map.getSource(gt.SPLIT_LINE_SOURCE)||this.map.addSource(gt.SPLIT_LINE_SOURCE,{type:"geojson",data:Kt([])}),this.map.getLayer(gt.SPLIT_LINE_LAYER)||this.map.addLayer({id:gt.SPLIT_LINE_LAYER,type:"line",source:gt.SPLIT_LINE_SOURCE,paint:{"line-color":"#ff4444","line-width":3,"line-dasharray":[3,3]}}))}attachEventListeners(){this.map&&(this.handleClick=e=>{this.splitLinePoints.push([e.lngLat.lng,e.lngLat.lat]),this.updateSplitLineVisualization()},this.handleMouseMove=e=>{if(this.splitLinePoints.length===0)return;const t=[...this.splitLinePoints,[e.lngLat.lng,e.lngLat.lat]];this.updateSplitLineVisualization(t)},this.handleDblClick=e=>{e.preventDefault(),this.completeSplit()},this.map.on("click",this.handleClick),this.map.on("mousemove",this.handleMouseMove),this.map.on("dblclick",this.handleDblClick))}removeEventListeners(){this.map&&(this.handleClick&&this.map.off("click",this.handleClick),this.handleMouseMove&&this.map.off("mousemove",this.handleMouseMove),this.handleDblClick&&this.map.off("dblclick",this.handleDblClick),this.handleClick=null,this.handleMouseMove=null,this.handleDblClick=null)}updateSplitLineVisualization(e){if(!this.map)return;const t=this.map.getSource(gt.SPLIT_LINE_SOURCE);if(!t)return;const n=e||this.splitLinePoints;if(n.length<2){t.setData(Kt([]));return}const i=xs(n);t.setData(Kt([i]))}completeSplit(){if(!this.targetFeature||!this.onCompleteCallback||this.splitLinePoints.length<2){this.cleanup();return}const e=xs(this.splitLinePoints);let t;this.targetFeature.geometry.type==="Polygon"?t=this.splitPolygon(this.targetFeature,e):t=this.splitLine(this.targetFeature,e),this.onCompleteCallback(t),this.cleanup()}cleanup(){this.removeEventListeners(),this.clearSplitLine(),this.isDrawing=!1,this.splitLinePoints=[],this.map&&(this.map.getCanvas().style.cursor="")}clearSplitLine(){if(!this.map)return;const e=this.map.getSource(gt.SPLIT_LINE_SOURCE);e&&e.setData(Kt([]))}removeLayers(){this.map&&(this.map.getLayer(gt.SPLIT_LINE_LAYER)&&this.map.removeLayer(gt.SPLIT_LINE_LAYER),this.map.getSource(gt.SPLIT_LINE_SOURCE)&&this.map.removeSource(gt.SPLIT_LINE_SOURCE))}destroy(){this.cancelSplit(),this.removeLayers(),this.map=null}},xG=class{map=null;isDrawing=!1;points=[];options;onCompleteCallback=null;dragPanEnabled=null;boxZoomEnabled=null;doubleClickZoomEnabled=null;handleMouseDown=null;handleMouseMove=null;handleMouseUp=null;constructor(e={}){this.options={type:e.type??"polygon",simplifyTolerance:e.simplifyTolerance??1e-5,minPoints:e.minPoints??(e.type==="line"?2:3)}}init(e){this.map=e}enable(e){this.map&&(this.onCompleteCallback=e||null,this.disableMapInteractions(),this.setupFreehandLayers(),this.attachEventListeners(),this.map.getCanvas().style.cursor="crosshair")}disable(){this.removeEventListeners(),this.clearFreehand(),this.isDrawing=!1,this.points=[],this.onCompleteCallback=null,this.restoreMapInteractions(),this.map&&(this.map.getCanvas().style.cursor="")}setType(e){this.options.type=e,this.options.minPoints=e==="line"?2:3}isActive(){return this.isDrawing}buildFeature(){if(this.points.length<this.options.minPoints)return null;try{let e=this.removeDuplicatePoints(this.points);if(e.length<this.options.minPoints)return null;if(e.length>10&&(e=pb(xs(e),{tolerance:this.options.simplifyTolerance,highQuality:!0}).geometry.coordinates),e=this.removeDuplicatePoints(e),this.options.type==="polygon"){if(e.length<3)return null;for(;e.length>3&&this.arePointsEqual(e[0],e[e.length-1]);)e=e.slice(0,-1);if(e.length<3)return null;const t=e.map(i=>[i[0],i[1]]),n=[t[0][0],t[0][1]];return z2(Hr([[...t,n]]))}else return e.length<2?null:xs(e.map(t=>[t[0],t[1]]))}catch(e){return console.warn("FreehandFeature: Error building feature:",e),null}}removeDuplicatePoints(e){if(e.length<=1)return e;const t=[e[0]];for(let n=1;n<e.length;n++)this.arePointsEqual(e[n],e[n-1])||t.push(e[n]);return t}arePointsEqual(e,t){return Math.abs(e[0]-t[0])<1e-7&&Math.abs(e[1]-t[1])<1e-7}setupFreehandLayers(){this.map&&(this.map.getSource(gt.FREEHAND_SOURCE)||this.map.addSource(gt.FREEHAND_SOURCE,{type:"geojson",data:Kt([])}),this.map.getLayer(gt.FREEHAND_FILL_LAYER)||this.map.addLayer({id:gt.FREEHAND_FILL_LAYER,type:"fill",source:gt.FREEHAND_SOURCE,filter:["==",["geometry-type"],"Polygon"],paint:{"fill-color":"#3388ff","fill-opacity":.2}}),this.map.getLayer(gt.FREEHAND_LINE_LAYER)||this.map.addLayer({id:gt.FREEHAND_LINE_LAYER,type:"line",source:gt.FREEHAND_SOURCE,paint:{"line-color":"#3388ff","line-width":3}}))}attachEventListeners(){this.map&&(this.handleMouseDown=e=>{e.preventDefault(),this.isDrawing=!0,this.points=[[e.lngLat.lng,e.lngLat.lat]],this.updateFreehandVisualization()},this.handleMouseMove=e=>{this.isDrawing&&(e.preventDefault(),this.points.push([e.lngLat.lng,e.lngLat.lat]),this.updateFreehandVisualization())},this.handleMouseUp=()=>{this.isDrawing&&(this.isDrawing=!1,this.completeFreehand())},this.map.on("mousedown",this.handleMouseDown),this.map.on("mousemove",this.handleMouseMove),this.map.on("mouseup",this.handleMouseUp))}removeEventListeners(){this.map&&(this.handleMouseDown&&this.map.off("mousedown",this.handleMouseDown),this.handleMouseMove&&this.map.off("mousemove",this.handleMouseMove),this.handleMouseUp&&this.map.off("mouseup",this.handleMouseUp),this.handleMouseDown=null,this.handleMouseMove=null,this.handleMouseUp=null)}updateFreehandVisualization(){if(!this.map||this.points.length<2)return;const e=this.map.getSource(gt.FREEHAND_SOURCE);if(!e)return;const t=[...this.points];if(this.options.type==="polygon"&&t.length>=3){const n=Hr([[...t,t[0]]]);e.setData(Kt([n]))}else{const n=xs(t);e.setData(Kt([n]))}}completeFreehand(){const e=this.buildFeature(),t={feature:e,success:e!==null,error:e?void 0:`Need at least ${this.options.minPoints} points`};this.onCompleteCallback&&this.onCompleteCallback(t),setTimeout(()=>{this.clearFreehand(),this.points=[]},100)}clearFreehand(){if(!this.map)return;const e=this.map.getSource(gt.FREEHAND_SOURCE);e&&e.setData(Kt([]))}disableMapInteractions(){this.map&&(this.dragPanEnabled=this.map.dragPan.isEnabled(),this.dragPanEnabled&&this.map.dragPan.disable(),this.map.boxZoom&&(this.boxZoomEnabled=this.map.boxZoom.isEnabled(),this.boxZoomEnabled&&this.map.boxZoom.disable()),this.map.doubleClickZoom&&(this.doubleClickZoomEnabled=this.map.doubleClickZoom.isEnabled(),this.doubleClickZoomEnabled&&this.map.doubleClickZoom.disable()))}restoreMapInteractions(){this.map&&(this.dragPanEnabled&&this.map.dragPan.enable(),this.boxZoomEnabled&&this.map.boxZoom&&this.map.boxZoom.enable(),this.doubleClickZoomEnabled&&this.map.doubleClickZoom&&this.map.doubleClickZoom.enable(),this.dragPanEnabled=null,this.boxZoomEnabled=null,this.doubleClickZoomEnabled=null)}removeLayers(){this.map&&(this.map.getLayer(gt.FREEHAND_LINE_LAYER)&&this.map.removeLayer(gt.FREEHAND_LINE_LAYER),this.map.getLayer(gt.FREEHAND_FILL_LAYER)&&this.map.removeLayer(gt.FREEHAND_FILL_LAYER),this.map.getSource(gt.FREEHAND_SOURCE)&&this.map.removeSource(gt.FREEHAND_SOURCE))}destroy(){this.disable(),this.removeLayers(),this.map=null}};function lm(e){return e.filter(_R)}var mb=class{map;geoman=null;container;options;state;copyFeature;simplifyFeature;unionFeature;differenceFeature;scaleFeature;lassoFeature;splitFeature;freehandFeature;boundKeyHandler=null;boundClickHandler=null;boundScaleMouseDown=null;boundScaleMouseMove=null;boundScaleMouseUp=null;isSelectMode=!1;pendingOperation=null;snappingEnabled=!1;lastCreatedFeature=null;lastEditedFeature=null;lastDeletedFeature=null;lastDeletedFeatureId=null;isScaling=!1;scaleTargetFeature=null;scaleTargetGeomanData=null;scaleStartFeature=null;scaleDragPanEnabled=null;isMultiDragging=!1;multiDragStartPoint=null;multiDragOriginalFeatures=[];multiDragGeomanData=[];multiDragPanEnabled=null;boundMultiDragMouseDown=null;boundMultiDragMouseMove=null;boundMultiDragMouseUp=null;toolbar=null;fileInput=null;propertiesPopup=null;historyManager=null;pendingEditFeature=null;isPerformingCompositeOperation=!1;attributePanel=null;attributePanelVisible=!1;currentEditingFeature=null;currentEditingGeomanData=null;isNewFeature=!1;originalProperties=null;boundStyleDataHandler=null;_eventHandlers=new globalThis.Map;constructor(e={}){this.options={...pG,...e},this.state={activeDrawMode:null,activeEditMode:null,selectedFeatures:[],isDrawing:!1,isEditing:!1,clipboard:[],collapsed:this.options.collapsed},this.snappingEnabled=this.options.snappingEnabled,this.copyFeature=new mG,this.simplifyFeature=new gG({tolerance:this.options.simplifyTolerance}),this.unionFeature=new _G,this.differenceFeature=new AG,this.scaleFeature=new vG,this.lassoFeature=new yG,this.splitFeature=new bG,this.freehandFeature=new xG,this.options.enableHistory!==!1&&(this.historyManager=new aG(this.options.maxHistorySize,(t,n)=>{this.updateHistoryButtonStates(t,n),this.options.onHistoryChange?.(t,n)}))}onAdd(e){return this.map=e,this.scaleFeature.init(e),this.lassoFeature.init(e),this.splitFeature.init(e),this.freehandFeature.init(e),this.container=document.createElement("div"),this.container.className=`maplibregl-ctrl maplibregl-ctrl-group ${rt}-control`,this.createToolbar(),this.setupFileInput(),this.setupKeyboardShortcuts(),this.setupSelectionHandler(),this.setupScaleHandler(),this.setupMultiDragHandler(),this.setupVertexMarkerStyleListener(),this.setupGeomanEvents(),this.options.enableAttributeEditing&&this.createAttributePanel(),this.geoman||this._autoInitGeoman(),this.container}onRemove(){this.removeKeyboardShortcuts(),this.removeSelectionHandler(),this.removeScaleHandler(),this.removeMultiDragHandler(),this.removeVertexMarkerStyleListener(),this.disableAllModes(),this.hideFeaturePropertiesPopup(),this.hideAttributePanel(),this.removeAttributePanel(),this.scaleFeature.destroy(),this.lassoFeature.destroy(),this.splitFeature.destroy(),this.freehandFeature.destroy(),this.fileInput&&this.fileInput.parentNode&&(this.fileInput.parentNode.removeChild(this.fileInput),this.fileInput=null),this.container.parentNode&&this.container.parentNode.removeChild(this.container),this.map=void 0}setGeoman(e){this.geoman=e,this.setupGeomanEvents(),this.applySnappingState(),this.options.hideGeomanControl&&this.hideGeomanControl()}_autoInitGeoman(){Promise.resolve().then(()=>require("./maplibre-geoman.es-DQDIjwS6.cjs")).then(({Geoman:e})=>{if(this.map&&!this.geoman){const t=new e(this.map);t.addControls=async()=>{},t.removeControls=()=>{},this.setGeoman(t)}}).catch(()=>{})}hideGeomanControl(){if(this.geoman)try{this.geoman.removeControls()}catch{[".maplibregl-ctrl.geoman-controls",".gm-control",".maplibregl-ctrl-group.geoman",'[class*="geoman"]'].forEach(e=>{document.querySelectorAll(e).forEach(t=>{t.classList.contains("geo-editor-control")||(t.style.display="none")})})}}setupSelectionHandler(){this.boundClickHandler=e=>{if(!this.isSelectMode&&!this.pendingOperation||!this.geoman)return;const t=this.findFeatureByMouseEvent(e)||this.findFeatureAtPoint(e.lngLat.lng,e.lngLat.lat);if(t){const{feature:n,geomanData:i}=t;this.pendingOperation?(n.geometry.type==="Polygon"||n.geometry.type==="MultiPolygon")&&this.addToSelection(n,i):e.originalEvent.shiftKey?this.toggleFeatureSelection(n,i):this.selectFeatures([n],[i])}else!e.originalEvent.shiftKey&&!this.pendingOperation&&this.clearSelection()},this.map.on("click",this.boundClickHandler)}getClickToleranceKm(){const e=this.map.getZoom();return 40075/(512*Math.pow(2,e))*15}findFeatureAtPoint(e,t){if(!this.geoman)return null;const n=wi([e,t]);let i=null;const s=this.getClickToleranceKm();let r=[];const a=new Map;try{let o=0;this.geoman.features.forEach(l=>{const c=this.getGeomanFeature(l);if(!l||!c||!c.geometry){o++;return}const h=String(l.id??c.id??`feature-${o}`);r.push(c),a.set(h,l),a.set(`idx-${o}`,l),o++})}catch{try{r=(this.geoman.features.getAll().features||[]).filter(o=>o&&o.geometry)}catch{return null}}for(let o=0;o<r.length;o++){const l=r[o];if(!l||!l.geometry)continue;const c=String(l.id??`feature-${o}`),h=a.get(c)||a.get(`idx-${o}`);try{let d=!1;if(l.geometry.type==="Point")d=dp(n,wi(l.geometry.coordinates),{units:"kilometers"})<s;else if(l.geometry.type==="Polygon"||l.geometry.type==="MultiPolygon")d=Ii(n,l);else if(l.geometry.type==="LineString"||l.geometry.type==="MultiLineString"){const f=au(l,n);d=f.properties.dist!==void 0&&f.properties.dist<s}if(d){const f=h||this.findGeomanDataForFeature(l);if(f){i={feature:l,geomanData:f};break}}}catch{}}return i}findFeatureByMouseEvent(e){if(!this.geoman||!e.originalEvent)return null;try{const t=this.geoman.features.getFeatureByMouseEvent({event:e}),n=this.getGeomanFeature(t);if(n&&t)return{feature:n,geomanData:t}}catch{}return null}findGeomanDataForFeature(e){if(!this.geoman)return null;let t=null;const n=this.getGeomanIdFromFeature(e);try{this.geoman.features.forEach(i=>{if(t)return;const s=this.getGeomanFeature(i);s&&(n&&String(s.id)===n||n&&this.getGeomanIdFromFeature(s)===n||JSON.stringify(s.geometry)===JSON.stringify(e.geometry))&&(t=i)})}catch{}return t}getGeomanIdFromFeature(e){const t=e.properties,n=e.id??t?.__gm_id??t?.id;return n!=null?String(n):null}getGeomanFeature(e){if(!e)return null;if(typeof e.getGeoJson=="function")try{return e.getGeoJson()}catch{return null}return e.geoJson??null}removeSelectionHandler(){this.boundClickHandler&&(this.map.off("click",this.boundClickHandler),this.boundClickHandler=null)}setupScaleHandler(){this.boundScaleMouseDown=e=>{if(this.state.activeEditMode!=="scale")return;const t=this.getScaleHandleFromEvent(e);!t||!this.scaleTargetFeature||!this.scaleTargetGeomanData||(e.preventDefault(),this.isScaling=!0,this.scaleStartFeature=this.scaleTargetFeature,this.disableScaleDragPan(),this.scaleFeature.startScale(this.scaleTargetFeature,t,[e.lngLat.lng,e.lngLat.lat],(n,i)=>{this.applyScaledFeature(n),this.emitEvent("gm:scale",{feature:n,scaleFactor:i})}),this.emitEvent("gm:scalestart",{feature:this.scaleTargetFeature}))},this.boundScaleMouseMove=e=>{if(!this.isScaling)return;const t=this.scaleFeature.updateScale([e.lngLat.lng,e.lngLat.lat]);t&&this.applyScaledFeature(t)},this.boundScaleMouseUp=()=>{if(!this.isScaling)return;this.isScaling=!1;const e=this.scaleFeature.endScale();this.restoreScaleDragPan(),e&&(this.applyScaledFeature(e.feature),this.scaleStartFeature&&this.options.onFeatureEdit?.(e.feature,this.scaleStartFeature),this.lastEditedFeature=e.feature,this.logSelectedFeatureCollection("edited",e.feature),this.scaleFeature.showHandlesForFeature(e.feature),this.bringScaleHandlesToFront(),this.emitEvent("gm:scaleend",{feature:e.feature,scaleFactor:e.factor})),this.scaleStartFeature=null},this.map.on("mousedown",this.boundScaleMouseDown),this.map.on("mousemove",this.boundScaleMouseMove),this.map.on("mouseup",this.boundScaleMouseUp)}removeScaleHandler(){this.boundScaleMouseDown&&(this.map.off("mousedown",this.boundScaleMouseDown),this.boundScaleMouseDown=null),this.boundScaleMouseMove&&(this.map.off("mousemove",this.boundScaleMouseMove),this.boundScaleMouseMove=null),this.boundScaleMouseUp&&(this.map.off("mouseup",this.boundScaleMouseUp),this.boundScaleMouseUp=null)}setupMultiDragHandler(){this.boundMultiDragMouseDown=e=>{if(this.state.activeEditMode!=="drag"||this.state.selectedFeatures.length<2)return;const t=this.findFeatureByMouseEvent(e)||this.findFeatureAtPoint(e.lngLat.lng,e.lngLat.lat);if(!t)return;const n=this.getGeomanIdFromFeature(t.feature);this.state.selectedFeatures.some(i=>this.getGeomanIdFromFeature(i.feature)===n)&&(e.preventDefault(),this.isMultiDragging=!0,this.multiDragStartPoint=[e.lngLat.lng,e.lngLat.lat],this.multiDragOriginalFeatures=this.state.selectedFeatures.map(i=>Es(i.feature)),this.multiDragGeomanData=this.state.selectedFeatures.map(i=>i.geomanData??this.findGeomanDataForFeature(i.feature)),this.disableMultiDragPan())},this.boundMultiDragMouseMove=e=>{if(!this.isMultiDragging||!this.multiDragStartPoint)return;const t=this.multiDragStartPoint,n=[e.lngLat.lng,e.lngLat.lat],i=dp(wi(t),wi(n),{units:"kilometers"}),s=L2(wi(t),wi(n)),r=[];this.multiDragOriginalFeatures.forEach((a,o)=>{const l=fb(a,i,s,{units:"kilometers"}),c=this.multiDragGeomanData[o];c?.updateGeometry?c.updateGeometry(l.geometry):c?.updateGeoJsonGeometry&&c.updateGeoJsonGeometry(l.geometry),r.push(l)}),this.state.selectedFeatures=this.state.selectedFeatures.map((a,o)=>({...a,feature:r[o]??a.feature})),this.updateSelectionHighlight()},this.boundMultiDragMouseUp=()=>{this.isMultiDragging&&(this.isMultiDragging=!1,this.restoreMultiDragPan(),this.state.selectedFeatures.length>0&&(this.state.selectedFeatures.forEach((e,t)=>{const n=this.multiDragOriginalFeatures[t];n&&this.options.onFeatureEdit?.(e.feature,n)}),this.lastEditedFeature=this.state.selectedFeatures[this.state.selectedFeatures.length-1]?.feature??null,this.logSelectedFeatureCollection("edited",this.lastEditedFeature)),this.multiDragStartPoint=null,this.multiDragOriginalFeatures=[],this.multiDragGeomanData=[])},this.map.on("mousedown",this.boundMultiDragMouseDown),this.map.on("mousemove",this.boundMultiDragMouseMove),this.map.on("mouseup",this.boundMultiDragMouseUp)}removeMultiDragHandler(){this.boundMultiDragMouseDown&&(this.map.off("mousedown",this.boundMultiDragMouseDown),this.boundMultiDragMouseDown=null),this.boundMultiDragMouseMove&&(this.map.off("mousemove",this.boundMultiDragMouseMove),this.boundMultiDragMouseMove=null),this.boundMultiDragMouseUp&&(this.map.off("mouseup",this.boundMultiDragMouseUp),this.boundMultiDragMouseUp=null)}disableMultiDragPan(){this.multiDragPanEnabled=this.map.dragPan.isEnabled(),this.multiDragPanEnabled&&this.map.dragPan.disable()}restoreMultiDragPan(){this.multiDragPanEnabled&&this.map.dragPan.enable(),this.multiDragPanEnabled=null}getScaleHandleFromEvent(e){if(!this.map.getLayer(gt.SCALE_HANDLES_LAYER))return null;const t=this.map.queryRenderedFeatures(e.point,{layers:[gt.SCALE_HANDLES_LAYER]});if(!t.length)return null;const n=t[0].properties?.position;return typeof n=="string"?n:null}disableScaleDragPan(){this.scaleDragPanEnabled=this.map.dragPan.isEnabled(),this.scaleDragPanEnabled&&this.map.dragPan.disable()}restoreScaleDragPan(){this.scaleDragPanEnabled&&this.map.dragPan.enable(),this.scaleDragPanEnabled=null}applyScaledFeature(e){if(this.scaleTargetGeomanData?.updateGeometry?this.scaleTargetGeomanData.updateGeometry(e.geometry):this.scaleTargetGeomanData?.updateGeoJsonGeometry&&this.scaleTargetGeomanData.updateGeoJsonGeometry(e.geometry),this.state.selectedFeatures.length>0){const t=this.state.selectedFeatures[0];this.state.selectedFeatures[0]={...t,id:String(this.scaleTargetGeomanData?.id??e.id??t.id),feature:e,geomanData:this.scaleTargetGeomanData??t.geomanData},this.scaleTargetFeature=e}this.updateSelectionHighlight(),this.bringScaleHandlesToFront()}bringScaleHandlesToFront(){if(this.map.getLayer(gt.SCALE_HANDLES_LAYER))try{this.map.moveLayer(gt.SCALE_HANDLES_LAYER)}catch{}}logSelectedFeatureCollection(e,t){const n=t?this.getGeomanIdFromFeature(t):null;console.log("GeoEditor",{action:e,featureId:n,feature:t,selection:this.getSelectedFeatureCollection()})}extractFeatureFromEvent(e){if(!e||typeof e!="object")return null;const t=e;if(typeof t.getGeoJson=="function")try{return t.getGeoJson()}catch{return null}return t.geoJson?t.geoJson:"geometry"in t?t:null}toggleFeatureSelection(e,t){const n=t??this.findGeomanDataForFeature(e),i=String(n?.id??e.id);this.state.selectedFeatures.some(s=>s.id===i)?this.removeFromSelection(i):this.addToSelection(e,n??void 0)}enableSelectMode(){this.disableAllModes(),this.isSelectMode=!0,this.map.getCanvas().style.cursor="pointer",this.updateToolbarState()}disableSelectMode(){this.isSelectMode=!1,this.map.getCanvas().style.cursor=""}getState(){return{...this.state}}getSelectedFeatures(){return this.state.selectedFeatures.map(e=>e.feature)}getSelectedFeatureCollection(){return{type:"FeatureCollection",features:this.getSelectedFeatures()}}getFeatures(){if(this.geoman)try{return this.geoman.features.getAll()}catch{const e=[];return this.geoman.features.forEach(t=>{const n=this.getGeomanFeature(t);n&&e.push(n)}),{type:"FeatureCollection",features:e}}return{type:"FeatureCollection",features:[]}}getAllFeatureCollection(){return this.getFeatures()}getLastCreatedFeature(){return this.lastCreatedFeature}getLastEditedFeature(){return this.lastEditedFeature}getLastDeletedFeature(){return this.lastDeletedFeature}getLastDeletedFeatureId(){return this.lastDeletedFeatureId}enableDrawMode(e){this.disableAllModes(),e==="freehand"?this.enableFreehandMode():this.geoman&&(this.geoman.enableDraw(e),setTimeout(()=>this.applyVertexMarkerStyles(),50)),this.state.activeDrawMode=e,this.state.isDrawing=!0,this.options.onModeChange?.(e),this.updateToolbarState()}applyVertexMarkerStyles(){if(!this.map)return;const e=this.map.getStyle();if(!(!e||!e.layers))for(const t of e.layers){const n=t.id.toLowerCase();if(t.type==="circle"&&(n.includes("gm-")||n.includes("geoman")||n.includes("marker")||n.includes("vertex")||n.includes("handle")||n.includes("temp")))try{this.map.getLayer(t.id)&&(this.map.setPaintProperty(t.id,"circle-opacity",.5),this.map.setPaintProperty(t.id,"circle-stroke-opacity",.8))}catch{}}}setupVertexMarkerStyleListener(){this.map&&(this.boundStyleDataHandler=()=>{this.state.isDrawing&&this.applyVertexMarkerStyles()},this.map.on("styledata",this.boundStyleDataHandler))}removeVertexMarkerStyleListener(){this.map&&this.boundStyleDataHandler&&(this.map.off("styledata",this.boundStyleDataHandler),this.boundStyleDataHandler=null)}enableFreehandMode(){this.freehandFeature.enable(e=>{e.success&&e.feature&&this.geoman&&this.geoman.features.importGeoJsonFeature(e.feature)&&(this.options.onFeatureCreate?.(e.feature),this.emitEvent("gm:create",{feature:e.feature}))})}disableFreehandMode(){this.freehandFeature.disable()}enableEditMode(e){if(this.disableAllModes(),Pv.includes(e))this.enableAdvancedEditMode(e);else if(this.geoman)switch(e){case"drag":this.state.selectedFeatures.length<2&&this.geoman.enableGlobalDragMode();break;case"change":this.geoman.enableGlobalEditMode();break;case"rotate":this.geoman.enableGlobalRotateMode();break;case"cut":this.geoman.enableGlobalCutMode();break;case"delete":if(this.state.selectedFeatures.length>0){this.deleteSelectedFeatures();return}this.geoman.enableGlobalRemovalMode();break}this.state.activeEditMode=e,this.state.isEditing=!0,this.options.onModeChange?.(e),this.updateToolbarState()}disableAllModes(){this.geoman&&this.geoman.disableAllModes(),this.scaleFeature.cancelScale(),this.lassoFeature.disable(),this.splitFeature.cancelSplit(),this.disableFreehandMode(),this.disableSelectMode(),this.restoreScaleDragPan(),this.restoreMultiDragPan(),this.isMultiDragging=!1,this.multiDragStartPoint=null,this.multiDragOriginalFeatures=[],this.multiDragGeomanData=[],this.isScaling=!1,this.scaleTargetFeature=null,this.scaleTargetGeomanData=null,this.scaleStartFeature=null,this.pendingOperation=null,this.map.getCanvas().style.cursor="",this.state.activeDrawMode=null,this.state.activeEditMode=null,this.state.isDrawing=!1,this.state.isEditing=!1,this.updateToolbarState(),this.applySnappingState()}enableAdvancedEditMode(e){switch(e){case"select":this.enableSelectMode();break;case"scale":this.enableScaleMode();break;case"copy":this.enableCopyMode();break;case"split":this.enableSplitMode();break;case"union":this.enableUnionMode();break;case"difference":this.enableDifferenceMode();break;case"simplify":this.executeSimplify();break;case"lasso":this.enableLassoMode();break}}enableUnionMode(){if(lm(this.getSelectedFeatures()).length>=2){this.executeUnion();return}this.pendingOperation="union",this.map.getCanvas().style.cursor="pointer"}enableDifferenceMode(){if(lm(this.getSelectedFeatures()).length>=2){this.executeDifference();return}this.pendingOperation="difference",this.map.getCanvas().style.cursor="pointer"}executePendingOperation(){this.pendingOperation&&(this.pendingOperation==="union"?this.executeUnion():this.pendingOperation==="difference"&&this.executeDifference(),this.pendingOperation=null)}cancelPendingOperation(){this.pendingOperation=null,this.clearSelection(),this.map.getCanvas().style.cursor="",this.updateToolbarState()}setupSelectionHighlight(){if(this.map)if(!this.map.getSource(gt.SELECTION_SOURCE))this.map.addSource(gt.SELECTION_SOURCE,{type:"geojson",data:{type:"FeatureCollection",features:[]}}),this.map.addLayer({id:gt.SELECTION_FILL_LAYER,type:"fill",source:gt.SELECTION_SOURCE,filter:["match",["geometry-type"],["Polygon","MultiPolygon"],!0,!1],paint:{"fill-color":"#ffff00","fill-opacity":.3}}),this.map.addLayer({id:gt.SELECTION_LINE_LAYER,type:"line",source:gt.SELECTION_SOURCE,paint:{"line-color":"#ff9900","line-width":5,"line-opacity":1,"line-dasharray":[3,2]}}),this.map.addLayer({id:gt.SELECTION_CIRCLE_LAYER,type:"circle",source:gt.SELECTION_SOURCE,filter:["==",["geometry-type"],"Point"],paint:{"circle-radius":12,"circle-color":"#ffff00","circle-opacity":.5,"circle-stroke-color":"#ff9900","circle-stroke-width":3,"circle-stroke-opacity":1}});else try{this.map.getLayer(gt.SELECTION_FILL_LAYER)&&(this.map.setFilter(gt.SELECTION_FILL_LAYER,["match",["geometry-type"],["Polygon","MultiPolygon"],!0,!1]),this.map.moveLayer(gt.SELECTION_FILL_LAYER)),this.map.getLayer(gt.SELECTION_LINE_LAYER)&&this.map.moveLayer(gt.SELECTION_LINE_LAYER),this.map.getLayer(gt.SELECTION_CIRCLE_LAYER)&&this.map.moveLayer(gt.SELECTION_CIRCLE_LAYER)}catch{}}updateSelectionHighlight(){if(!this.map)return;this.setupSelectionHighlight();const e=this.map.getSource(gt.SELECTION_SOURCE);if(e){const t=this.getSelectedFeatures();e.setData({type:"FeatureCollection",features:t})}}selectFeatures(e,t){const n=t&&t.length?t:e.map(s=>this.findGeomanDataForFeature(s)),i=Date.now();this.state.selectedFeatures=e.map((s,r)=>({id:String(n?.[r]?.id??s.id??`${i}-${r}`),feature:s,layerId:"default",geomanData:n?.[r]??void 0})),this.updateSelectionHighlight(),this.options.onSelectionChange?.(e),this.logSelectedFeatureCollection("selected"),e.length===1&&this.isSelectMode?this.options.enableAttributeEditing?this.showAttributePanel(e[0],n?.[0]??void 0,!1):this.options.showFeatureProperties&&this.showFeaturePropertiesPopup(e[0]):(this.hideAttributePanel(),this.hideFeaturePropertiesPopup())}addToSelection(e,t){const n=t??this.findGeomanDataForFeature(e),i=String(n?.id??e.id);this.state.selectedFeatures.some(s=>s.id===i)||(this.state.selectedFeatures.push({id:i,feature:e,layerId:"default",geomanData:n??void 0}),this.updateSelectionHighlight(),this.options.onSelectionChange?.(this.getSelectedFeatures()),this.logSelectedFeatureCollection("selected"))}removeFromSelection(e){this.state.selectedFeatures=this.state.selectedFeatures.filter(t=>t.id!==e),this.updateSelectionHighlight(),this.options.onSelectionChange?.(this.getSelectedFeatures()),this.logSelectedFeatureCollection("selected")}clearSelection(){this.state.selectedFeatures=[],this.updateSelectionHighlight(),this.hideFeaturePropertiesPopup(),this.hideAttributePanel(),this.options.onSelectionChange?.([]),this.logSelectedFeatureCollection("selected")}showFeaturePropertiesPopup(e){if(!this.options.showFeatureProperties||!e.properties||Object.keys(e.properties).length===0)return;this.hideFeaturePropertiesPopup();const t=Dp(e).geometry.coordinates,n=this.formatPropertiesHtml(e.properties);this.propertiesPopup=new fi.default.Popup({maxWidth:"300px",closeButton:!0,closeOnClick:!1,className:"geo-editor-properties-popup"}).setLngLat(t).setHTML(n).addTo(this.map)}hideFeaturePropertiesPopup(){this.propertiesPopup&&(this.propertiesPopup.remove(),this.propertiesPopup=null)}formatPropertiesHtml(e){const t=Object.entries(e).filter(([n])=>!n.startsWith("__"));return t.length===0?'<div class="geo-editor-popup-empty">No properties</div>':`<table class="geo-editor-popup-table"><tbody>${t.map(([n,i])=>{const s=i==null?"<em>null</em>":typeof i=="object"?this.escapeHtml(JSON.stringify(i)):this.escapeHtml(String(i));return`<tr><td class="geo-editor-popup-key">${this.escapeHtml(n)}</td><td class="geo-editor-popup-value">${s}</td></tr>`}).join("")}</tbody></table>`}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}createAttributePanel(){if(this.attributePanel)return;const e=this.options.attributePanelPosition,t=this.options.attributePanelWidth,n=this.options.attributePanelMaxHeight,i=this.options.attributePanelTop,s=this.options.attributePanelSideOffset;this.attributePanel=document.createElement("div"),this.attributePanel.className=`${rt}-attribute-panel ${rt}-attribute-panel--${e} ${rt}-attribute-panel--hidden`,this.attributePanel.style.width=`${t}px`,this.attributePanel.style.maxHeight=typeof n=="number"?`${n}px`:n,this.attributePanel.style.top=`${i}px`,e==="right"?this.attributePanel.style.right=`${s}px`:this.attributePanel.style.left=`${s}px`;const r=document.createElement("div");r.className=`${rt}-attribute-panel-header`;const a=document.createElement("h3");a.className=`${rt}-attribute-panel-title`,a.textContent=this.options.attributePanelTitle,r.appendChild(a);const o=document.createElement("button");o.className=`${rt}-attribute-panel-close`,o.innerHTML='<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M1 1l12 12M13 1L1 13"/></svg>',o.title="Close",o.addEventListener("click",()=>this.hideAttributePanel()),r.appendChild(o),this.attributePanel.appendChild(r);const l=document.createElement("div");l.className=`${rt}-attribute-panel-body`,l.setAttribute("data-panel-body","true"),this.attributePanel.appendChild(l);const c=document.createElement("div");c.className=`${rt}-attribute-panel-footer`;const h=document.createElement("button");h.className=`${rt}-btn ${rt}-btn--secondary`,h.textContent="Cancel",h.addEventListener("click",()=>this.hideAttributePanel()),c.appendChild(h);const d=document.createElement("button");d.className=`${rt}-btn ${rt}-btn--primary`,d.textContent="Save",d.setAttribute("data-save-btn","true"),d.addEventListener("click",()=>this.saveAttributeChanges()),c.appendChild(d),this.attributePanel.appendChild(c),this.map.getContainer().appendChild(this.attributePanel)}removeAttributePanel(){this.attributePanel&&this.attributePanel.parentNode&&(this.attributePanel.parentNode.removeChild(this.attributePanel),this.attributePanel=null)}showAttributePanel(e,t,n=!1){this.attributePanel&&(this.currentEditingFeature=e,this.currentEditingGeomanData=t??null,this.isNewFeature=n,this.originalProperties=e.properties?{...e.properties}:{},this.buildAttributeForm(e),this.attributePanel.classList.remove(`${rt}-attribute-panel--hidden`),this.attributePanelVisible=!0,this.hideFeaturePropertiesPopup())}hideAttributePanel(){this.attributePanel&&(this.attributePanel.classList.add(`${rt}-attribute-panel--hidden`),this.attributePanelVisible=!1,this.currentEditingFeature=null,this.currentEditingGeomanData=null,this.isNewFeature=!1,this.originalProperties=null)}toggleAttributePanel(){this.attributePanelVisible?this.hideAttributePanel():this.currentEditingFeature&&this.showAttributePanel(this.currentEditingFeature,this.currentEditingGeomanData??void 0,this.isNewFeature)}getSchemaFieldsForGeometry(e){const t=this.options.attributeSchema;if(!t)return[];const n=[];return e==="Polygon"||e==="MultiPolygon"?t.polygon&&n.push(...t.polygon):e==="LineString"||e==="MultiLineString"?t.line&&n.push(...t.line):(e==="Point"||e==="MultiPoint")&&t.point&&n.push(...t.point),t.common&&n.push(...t.common),n}getExtraProperties(e){const t=e.properties||{},n=this.getSchemaFieldsForGeometry(e.geometry.type),i=new Set(n.map(r=>r.name)),s={};for(const[r,a]of Object.entries(t))!r.startsWith("__")&&!i.has(r)&&(s[r]=a);return s}buildAttributeForm(e){if(!this.attributePanel)return;const t=this.attributePanel.querySelector("[data-panel-body]");if(!t)return;t.innerHTML="";const n=e.geometry.type,i=this.getSchemaFieldsForGeometry(n),s=e.properties||{},r=this.attributePanel.querySelector(`.${rt}-attribute-panel-header`);if(r){const l=r.querySelector(`.${rt}-attribute-geometry-badge`);l&&l.remove();const c=document.createElement("span");c.className=`${rt}-attribute-geometry-badge`,c.textContent=this.getGeometryDisplayName(n);const h=r.querySelector(`.${rt}-attribute-panel-title`);h&&h.appendChild(c)}if(i.length>0)i.forEach(l=>{const c=s[l.name],h=this.createFormField(l,c);t.appendChild(h)});else{const l=document.createElement("div");l.className=`${rt}-attribute-empty`,l.textContent="No attribute schema defined",t.appendChild(l)}const a=this.getExtraProperties(e),o=Object.keys(a);if(o.length>0){const l=document.createElement("div");l.className=`${rt}-attribute-extra-section`;const c=document.createElement("div");c.className=`${rt}-attribute-extra-section-title`,c.textContent="Other Properties",l.appendChild(c),o.forEach(h=>{const d=this.createReadOnlyField(h,a[h]);l.appendChild(d)}),t.appendChild(l)}}getGeometryDisplayName(e){return{Point:"Point",MultiPoint:"Multi-Point",LineString:"Line",MultiLineString:"Multi-Line",Polygon:"Polygon",MultiPolygon:"Multi-Polygon",GeometryCollection:"Collection"}[e]||e}createFormField(e,t){const n=document.createElement("div");n.className=`${rt}-attribute-form-group`;const i=document.createElement("label");i.className=`${rt}-attribute-label`,e.required&&i.classList.add(`${rt}-attribute-label--required`),i.textContent=e.label||e.name,i.setAttribute("for",`attr-${e.name}`),n.appendChild(i);const s=this.createInputForFieldType(e,t);return n.appendChild(s),n}createInputForFieldType(e,t){const n=`attr-${e.name}`;switch(e.type){case"boolean":{const i=document.createElement("div");i.className=`${rt}-attribute-checkbox-wrapper`;const s=document.createElement("input");s.type="checkbox",s.id=n,s.name=e.name,s.className=`${rt}-attribute-checkbox`,s.checked=t===!0||t==="true",s.disabled=e.readOnly??!1,i.appendChild(s);const r=document.createElement("label");return r.className=`${rt}-attribute-checkbox-label`,r.setAttribute("for",n),r.textContent=e.label||e.name,i.appendChild(r),i}case"select":{const i=document.createElement("select");if(i.id=n,i.name=e.name,i.className=`${rt}-attribute-select`,i.disabled=e.readOnly??!1,!e.required){const s=document.createElement("option");s.value="",s.textContent="-- Select --",i.appendChild(s)}return e.options&&e.options.forEach(s=>{const r=document.createElement("option");r.value=String(s.value),r.textContent=s.label,String(t)===String(s.value)&&(r.selected=!0),i.appendChild(r)}),i}case"textarea":{const i=document.createElement("textarea");return i.id=n,i.name=e.name,i.className=`${rt}-attribute-textarea`,i.value=t!=null?String(t):"",i.placeholder=e.placeholder||"",i.disabled=e.readOnly??!1,i}case"number":{const i=document.createElement("input");return i.type="number",i.id=n,i.name=e.name,i.className=`${rt}-attribute-input`,i.value=t!=null?String(t):"",i.placeholder=e.placeholder||"",i.disabled=e.readOnly??!1,e.min!==void 0&&(i.min=String(e.min)),e.max!==void 0&&(i.max=String(e.max)),e.step!==void 0&&(i.step=String(e.step)),i}case"date":{const i=document.createElement("input");return i.type="date",i.id=n,i.name=e.name,i.className=`${rt}-attribute-input`,i.value=t!=null?String(t):"",i.disabled=e.readOnly??!1,i}case"color":{const i=document.createElement("input");return i.type="color",i.id=n,i.name=e.name,i.className=`${rt}-attribute-input`,i.value=t!=null?String(t):"#000000",i.disabled=e.readOnly??!1,i}default:{const i=document.createElement("input");return i.type="text",i.id=n,i.name=e.name,i.className=`${rt}-attribute-input`,i.value=t!=null?String(t):"",i.placeholder=e.placeholder||"",i.disabled=e.readOnly??!1,i}}}createReadOnlyField(e,t){const n=document.createElement("div");n.className=`${rt}-attribute-form-group`;const i=document.createElement("label");i.className=`${rt}-attribute-label`,i.textContent=e,n.appendChild(i);const s=document.createElement("div");return s.className=`${rt}-attribute-readonly`,t==null?(s.classList.add(`${rt}-attribute-readonly-null`),s.textContent="null"):typeof t=="object"?s.textContent=JSON.stringify(t):s.textContent=String(t),n.appendChild(s),n}collectFormValues(){if(!this.attributePanel||!this.currentEditingFeature)return{};const e=this.attributePanel.querySelector("[data-panel-body]");if(!e)return{};const t={};return this.getSchemaFieldsForGeometry(this.currentEditingFeature.geometry.type).forEach(n=>{const i=e.querySelector(`[name="${n.name}"]`);if(i)if(n.type==="boolean")t[n.name]=i.checked;else if(n.type==="number"){const s=i.value.trim();t[n.name]=s!==""?parseFloat(s):null}else t[n.name]=i.value||null}),t}validateFormValues(e){if(!this.currentEditingFeature)return{valid:!0,errors:{}};const t=this.getSchemaFieldsForGeometry(this.currentEditingFeature.geometry.type),n={};return t.forEach(i=>{if(i.required){const s=e[i.name];(s==null||s==="")&&(n[i.name]=`${i.label||i.name} is required`)}}),{valid:Object.keys(n).length===0,errors:n}}showValidationErrors(e){if(!this.attributePanel)return;const t=this.attributePanel.querySelector("[data-panel-body]");t&&(t.querySelectorAll(`.${rt}-attribute-error`).forEach(n=>n.remove()),t.querySelectorAll(`.${rt}-attribute-input--error, .${rt}-attribute-select--error, .${rt}-attribute-textarea--error`).forEach(n=>{n.classList.remove(`${rt}-attribute-input--error`),n.classList.remove(`${rt}-attribute-select--error`),n.classList.remove(`${rt}-attribute-textarea--error`)}),Object.entries(e).forEach(([n,i])=>{const s=t.querySelector(`[name="${n}"]`);if(s){s.classList.add(`${rt}-attribute-input--error`);const r=document.createElement("div");r.className=`${rt}-attribute-error`,r.textContent=i,s.parentNode?.appendChild(r)}}))}applyDefaultValues(e){const t=this.getSchemaFieldsForGeometry(e.geometry.type);t.length!==0&&(e.properties||(e.properties={}),t.forEach(n=>{n.defaultValue!==void 0&&e.properties[n.name]===void 0&&(e.properties[n.name]=n.defaultValue)}))}saveAttributeChanges(){if(!this.currentEditingFeature)return;const e=this.collectFormValues(),t=this.validateFormValues(e);if(!t.valid){this.showValidationErrors(t.errors);return}const n={...this.currentEditingFeature.properties,...e};this.currentEditingFeature.properties=n,this.currentEditingGeomanData&&this.updateFeatureProperties(this.currentEditingGeomanData,n);const i={feature:this.currentEditingFeature,previousProperties:this.originalProperties??{},newProperties:n,isNewFeature:this.isNewFeature};this.options.onAttributeChange?.(i),this.hideAttributePanel()}updateFeatureProperties(e,t){const n=e.getGeoJson?e.getGeoJson():e.geoJson;n&&(n.properties=t)}openAttributeEditor(e){if(!this.options.enableAttributeEditing){console.warn("Attribute editing is not enabled");return}const t=this.findGeomanDataForFeature(e);this.showAttributePanel(e,t??void 0,!1)}closeAttributeEditor(){this.hideAttributePanel()}setAttributeSchema(e){this.options.attributeSchema=e,this.attributePanelVisible&&this.currentEditingFeature&&this.buildAttributeForm(this.currentEditingFeature)}getAttributeSchema(){return this.options.attributeSchema}enableScaleMode(){this.scaleTargetFeature=null,this.scaleTargetGeomanData=null;const e=this.getSelectedFeatures();if(e.length===0){console.warn("Select a feature to scale");return}const t=this.findGeomanDataForFeature(e[0]);if(!t){console.warn("Selected feature is not managed by Geoman");return}this.scaleTargetFeature=e[0],this.scaleTargetGeomanData=t,this.scaleFeature.showHandlesForFeature(e[0]),this.bringScaleHandlesToFront(),this.state.selectedFeatures.length>0&&(this.state.selectedFeatures[0]={...this.state.selectedFeatures[0],id:String(t.id),geomanData:t}),this.map.getCanvas().style.cursor="nwse-resize"}enableCopyMode(){this.copySelectedFeatures()}enableSplitMode(){const e=this.getSelectedFeatures();if(e.length===0){console.warn("Select a polygon or line to split");return}const t=e[0];if(!_R(t)&&!fG(t)){console.warn("Can only split polygons and lines");return}this.splitFeature.startSplit(t,n=>{this.handleSplitResult(n)})}enableLassoMode(){this.lassoFeature.enable(e=>{this.handleLassoResult(e)})}executeUnion(){const e=lm(this.getSelectedFeatures());if(e.length<2){console.warn("Select at least 2 polygons to merge");return}const t=this.unionFeature.union(e);this.handleUnionResult(t)}executeDifference(){const e=lm(this.getSelectedFeatures());if(e.length<2){console.warn("Select at least 2 polygons (first is base, rest are subtracted)");return}const[t,...n]=e,i=this.differenceFeature.difference(t,n);this.handleDifferenceResult(i)}executeSimplify(){let e=this.getSelectedFeatures();if(e.length===0&&this.lastCreatedFeature&&(e=[this.lastCreatedFeature]),e.length===0){console.warn("Select a feature to simplify");return}const t=e.map(i=>this.getSimplifyResult(i)).filter(i=>!!i),n=t.length>1;if(t.length===0){console.warn("Simplify: no vertices removed with current tolerance");return}t.forEach(i=>{this.applySimplifyResult(i,{clearSelection:!n,disableModes:!n}),this.logSelectedFeatureCollection("edited",i.result)}),n&&(this.clearSelection(),this.disableAllModes())}getSimplifyResult(e){const t=this.simplifyFeature.simplifyWithStats(e);if(t.verticesAfter<t.verticesBefore)return t;const n=this.simplifyFeature.getSuggestedTolerances(e);for(const i of n){if(i===this.options.simplifyTolerance)continue;const s=this.simplifyFeature.simplifyWithStats(e,{tolerance:i});if(s.verticesAfter<s.verticesBefore)return s}return null}copySelectedFeatures(){const e=this.getSelectedFeatures();if(e.length===0){console.warn("No features selected to copy");return}this.state.clipboard=this.copyFeature.copyMultiple(e),this.emitEvent("gm:copy",{features:e})}pasteFeatures(){if(this.state.clipboard.length===0){console.warn("Clipboard is empty");return}const e=this.copyFeature.copyMultiple(this.state.clipboard);this.geoman&&e.forEach(t=>{this.geoman?.features.importGeoJsonFeature(t),this.options.onFeatureCreate?.(t),this.lastCreatedFeature=t}),this.emitEvent("gm:paste",{features:e})}deleteFeatureById(e){if(this.geoman)try{const t=[];this.geoman.features.forEach(n=>{const i=this.getGeomanFeature(n),s=i?.properties;(String(n.id)===e||String(i?.id)===e||String(s?.__gm_id)===e)&&t.push(n)}),t.forEach(n=>{this.deleteGeomanFeatureData(n)})}catch{}}deleteSelectedFeatures(){const e=this.state.selectedFeatures;e.length!==0&&(e.forEach(t=>{const n=t.geomanData??this.findGeomanDataForFeature(t.feature);this.deleteGeomanFeatureData(n,t.id),this.options.onFeatureDelete?.(t.id),this.lastDeletedFeature=t.feature,this.lastDeletedFeatureId=t.id,this.logSelectedFeatureCollection("deleted",t.feature)}),this.clearSelection())}deleteGeomanFeatureData(e,t){if(this.geoman){if(e){try{this.geoman.features.delete(e);return}catch{}try{e.delete();return}catch{}}t&&this.deleteFeatureById(t)}}deleteGeomanFeatures(e){e.forEach(t=>{const n=this.findGeomanDataForFeature(t),i=this.getGeomanIdFromFeature(t);this.deleteGeomanFeatureData(n,i??void 0),i&&this.options.onFeatureDelete?.(i),this.lastDeletedFeature=t,this.lastDeletedFeatureId=i??null,this.logSelectedFeatureCollection("deleted",t)})}clearGeomanTemporaryFeatures(){if(this.geoman)try{if(typeof this.geoman.features.tmpForEach=="function"){this.geoman.features.tmpForEach(e=>{try{e.delete()}catch{}});return}this.geoman.features.forEach(e=>{if(e.temporary)try{e.delete()}catch{}})}catch{}}handleSplitResult(e){if(!e.success){console.warn("Split failed:",e.error);return}this.recordCompositeOperation([e.original],e.parts,"Split"),this.isPerformingCompositeOperation=!0;try{this.deleteGeomanFeatures([e.original]),this.clearGeomanTemporaryFeatures(),this.clearSelection(),this.geoman&&e.parts.forEach(t=>{this.geoman?.features.importGeoJsonFeature(t),this.options.onFeatureCreate?.(t),this.lastCreatedFeature=t,this.logSelectedFeatureCollection("created",t)})}finally{this.isPerformingCompositeOperation=!1}this.emitEvent("gm:split",e),this.disableAllModes()}handleUnionResult(e){if(!e.success||!e.result){console.warn("Union failed:",e.error);return}this.recordCompositeOperation(e.originals,[e.result],"Union"),this.isPerformingCompositeOperation=!0;try{this.deleteGeomanFeatures(e.originals),this.clearGeomanTemporaryFeatures(),this.clearSelection(),this.geoman&&(this.geoman.features.importGeoJsonFeature(e.result),this.options.onFeatureCreate?.(e.result),this.lastCreatedFeature=e.result,this.logSelectedFeatureCollection("created",e.result))}finally{this.isPerformingCompositeOperation=!1}this.emitEvent("gm:union",e),this.disableAllModes()}handleDifferenceResult(e){if(!e.success){console.warn("Difference failed:",e.error);return}const t=[e.base,...e.subtracted],n=e.result?[e.result]:[];this.recordCompositeOperation(t,n,"Difference"),this.isPerformingCompositeOperation=!0;try{this.deleteGeomanFeatures([e.base,...e.subtracted]),this.clearGeomanTemporaryFeatures(),this.clearSelection(),e.result&&this.geoman&&(this.geoman.features.importGeoJsonFeature(e.result),this.options.onFeatureCreate?.(e.result),this.lastCreatedFeature=e.result,this.logSelectedFeatureCollection("created",e.result))}finally{this.isPerformingCompositeOperation=!1}this.emitEvent("gm:difference",e),this.disableAllModes()}applySimplifyResult(e,t){this.recordCompositeOperation([e.original],[e.result],"Simplify"),this.isPerformingCompositeOperation=!0;try{this.deleteGeomanFeatures([e.original]),this.clearGeomanTemporaryFeatures(),this.geoman&&(e.result.id=this.getGeomanIdFromFeature(e.original)??e.result.id,this.geoman.features.importGeoJsonFeature(e.result),this.options.onFeatureEdit?.(e.result,e.original),this.lastEditedFeature=e.result)}finally{this.isPerformingCompositeOperation=!1}this.emitEvent("gm:simplify",e),t.clearSelection&&this.clearSelection(),t.disableModes&&this.disableAllModes()}handleLassoResult(e){const t=this.getFeatures().features,n=this.lassoFeature.selectWithinLasso(e.lasso,t);this.selectFeatures(n),this.emitEvent("gm:lassoend",{...e,selected:n}),this.disableAllModes()}createToolbar(){this.toolbar=document.createElement("div"),this.toolbar.className=`${rt}-toolbar ${rt}-toolbar--${this.options.toolbarOrientation}`,this.options.toolbarOrientation==="vertical"&&this.options.columns>1&&this.toolbar.classList.add(`${rt}-toolbar--columns-${this.options.columns}`),this.state.collapsed&&this.toolbar.classList.add(`${rt}-toolbar--collapsed`);const e=this.createCollapseButton();this.toolbar.appendChild(e);const t=document.createElement("div");if(t.className=`${rt}-tools-wrapper`,this.options.drawModes.length>0){const r=this.createToolGroup("Draw",this.options.drawModes,"draw");t.appendChild(r)}const n=this.options.editModes.filter(r=>!Pv.includes(r));if(n.length>0){const r=this.createToolGroup("Edit",n,"edit");t.appendChild(r)}const i=this.options.editModes.filter(r=>Pv.includes(r));if(i.length>0){const r=this.createToolGroup("Advanced",i,"edit");t.appendChild(r)}if(this.historyManager){const r=this.createHistoryToolsGroup();t.appendChild(r)}if(this.options.helperModes.includes("snapping")){const r=this.createHelperToolsGroup();t.appendChild(r)}if(this.options.fileModes&&this.options.fileModes.length>0){const r=this.createFileToolsGroup();t.appendChild(r)}const s=this.createResetToolsGroup();t.appendChild(s),this.toolbar.appendChild(t),this.state.collapsed&&(t.style.display="none"),this.container.appendChild(this.toolbar)}createCollapseButton(){const e=document.createElement("button");e.className=`${rt}-tool-button ${rt}-collapse-btn`,e.title=this.state.collapsed?"Expand toolbar":"Collapse toolbar";const t='<svg viewBox="0 0 24 24" width="18" height="18"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 0 0 0-1.41l-2.34-2.34a1 1 0 0 0-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z" fill="currentColor"/></svg>',n='<svg viewBox="0 0 24 24" width="18" height="18"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" fill="currentColor"/></svg>';return e.innerHTML=this.state.collapsed?t:n,e.addEventListener("click",()=>{this.toggleCollapse(),e.innerHTML=this.state.collapsed?t:n,e.title=this.state.collapsed?"Expand toolbar":"Collapse toolbar"}),e}toggleCollapse(){if(this.state.collapsed=!this.state.collapsed,this.toolbar){this.toolbar.classList.toggle(`${rt}-toolbar--collapsed`,this.state.collapsed);const e=this.toolbar.querySelector(`.${rt}-tools-wrapper`);e&&(e.style.display=this.state.collapsed?"none":"")}this._emitControlEvent(this.state.collapsed?"collapse":"expand")}isCollapsed(){return this.state.collapsed}setCollapsed(e){this.state.collapsed!==e&&this.toggleCollapse()}expand(){this.setCollapsed(!1)}collapse(){this.setCollapsed(!0)}on(e,t){this._eventHandlers.has(e)||this._eventHandlers.set(e,new Set),this._eventHandlers.get(e).add(t)}off(e,t){this._eventHandlers.get(e)?.delete(t)}_emitControlEvent(e,t){const n=this._eventHandlers.get(e);n&&n.forEach(i=>i(t))}createHelperToolsGroup(){const e=document.createElement("div");if(e.className=`${rt}-tool-group`,this.options.showLabels){const i=document.createElement("div");i.className=`${rt}-tool-group-label`,i.textContent="Helper",e.appendChild(i)}const t=document.createElement("div");t.className=`${rt}-tool-buttons`;const n=document.createElement("button");return n.className=`${rt}-tool-button`,n.dataset.helper="snapping",n.title="Toggle Snapping",n.innerHTML='<svg viewBox="0 0 24 24" width="18" height="18"><path d="M7 3h4v6H7V3zm6 0h4v6h-4V3zM7 9h4v3a3 3 0 0 0 6 0V9h4v3a7 7 0 0 1-14 0V9z" fill="currentColor"/></svg>',this.snappingEnabled&&n.classList.add(`${rt}-tool-button--active`),n.addEventListener("click",i=>{i.stopPropagation(),this.toggleSnapping(),n.classList.toggle(`${rt}-tool-button--active`,this.snappingEnabled)}),t.appendChild(n),e.appendChild(t),e}createResetToolsGroup(){const e=document.createElement("div");if(e.className=`${rt}-tool-group`,this.options.showLabels){const i=document.createElement("div");i.className=`${rt}-tool-group-label`,i.textContent="Reset",e.appendChild(i)}const t=document.createElement("div");t.className=`${rt}-tool-buttons`;const n=document.createElement("button");return n.className=`${rt}-tool-button`,n.title="Clear selection and disable tools",n.innerHTML='<svg viewBox="0 0 24 24" width="18" height="18"><path d="M12 5a7 7 0 1 1-6.32 4H3l3.5-3.5L10 9H7.74A5 5 0 1 0 12 7v2l3-3-3-3v2z" fill="currentColor"/></svg>',n.addEventListener("click",()=>{this.disableAllModes(),this.clearSelection(),this.updateToolbarState()}),t.appendChild(n),e.appendChild(t),e}createFileToolsGroup(){const e=document.createElement("div");if(e.className=`${rt}-tool-group`,this.options.showLabels){const n=document.createElement("div");n.className=`${rt}-tool-group-label`,n.textContent="File",e.appendChild(n)}const t=document.createElement("div");if(t.className=`${rt}-tool-buttons`,this.options.fileModes.includes("open")){const n=document.createElement("button");n.className=`${rt}-tool-button`,n.dataset.file="open",n.title="Open GeoJSON file",n.innerHTML='<svg viewBox="0 0 24 24" width="18" height="18"><path d="M20 6h-8l-2-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 12H4V8h16v10z" fill="currentColor"/></svg>',n.addEventListener("click",()=>this.openFileDialog()),t.appendChild(n)}if(this.options.fileModes.includes("save")){const n=document.createElement("button");n.className=`${rt}-tool-button`,n.dataset.file="save",n.title="Save GeoJSON file",n.innerHTML='<svg viewBox="0 0 24 24" width="18" height="18"><path d="M17 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm2 16H5V5h11.17L19 7.83V19zm-7-7c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3zM6 6h9v4H6V6z" fill="currentColor"/></svg>',n.addEventListener("click",()=>this.saveGeoJson()),t.appendChild(n)}return e.appendChild(t),e}setupFileInput(){this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept=".geojson,.json,application/geo+json,application/json",this.fileInput.style.display="none",this.fileInput.addEventListener("change",e=>this.handleFileSelect(e)),document.body.appendChild(this.fileInput)}openFileDialog(){this.fileInput&&this.fileInput.click()}handleFileSelect(e){const t=e.target,n=t.files?.[0];if(!n)return;const i=new FileReader;i.onload=s=>{try{const r=s.target?.result,a=JSON.parse(r);this.loadGeoJson(a,n.name)}catch(r){console.error("GeoEditor: Failed to parse GeoJSON file:",r);const a={filename:n.name,message:r instanceof Error?r.message:String(r),error:r};this.emitEvent("gm:geojsonloaderror",a)}},i.readAsText(n),t.value=""}loadGeoJson(e,t="loaded.geojson"){if(!this.geoman)throw new Error("Geoman not initialized");try{this.geoman.features.deleteAll()}catch{this.geoman.features.forEach(r=>{try{r.delete()}catch{}})}this.clearSelection();let n;if(e.type==="Feature")n={type:"FeatureCollection",features:[e]};else if(e.type==="FeatureCollection")n=e;else throw new Error("Invalid GeoJSON: expected Feature or FeatureCollection");const i=this.geoman.features.importGeoJson(n),s={features:n.features,count:i.success,filename:t};return this.options.fitBoundsOnLoad&&n.features.length>0&&this.fitBoundsToFeatures(n),this.options.onGeoJsonLoad?.(s),this.emitEvent("gm:geojsonload",s),console.log(`GeoEditor: Loaded ${s.count} features from ${t}`),s}fitBoundsToFeatures(e){if(!(!e.features||e.features.length===0))try{const t=si(e);if(!this.isValidBBox(t)){console.warn("GeoEditor: Invalid bounding box for loaded features");return}const n=[[t[0],t[1]],[t[2],t[3]]];this.map.fitBounds(n,{padding:50,maxZoom:18,duration:500})}catch(t){console.warn("GeoEditor: Failed to fit bounds to features:",t)}}isValidBBox(e){return e.every(t=>isFinite(t)&&!isNaN(t))&&e[0]<=e[2]&&e[1]<=e[3]}fitToAllFeatures(){const e=this.getFeatures();if(e.features.length===0){console.warn("GeoEditor: No features to fit bounds to");return}this.fitBoundsToFeatures(e)}saveGeoJson(e){const t=this.getFeatures(),n=e||this.options.saveFilename||"features.geojson",i=new Blob([JSON.stringify(t,null,2)],{type:"application/geo+json"}),s=URL.createObjectURL(i),r=document.createElement("a");r.href=s,r.download=n,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(s);const a={featureCollection:t,count:t.features.length,filename:n};return this.options.onGeoJsonSave?.(a),this.emitEvent("gm:geojsonsave",a),console.log(`GeoEditor: Saved ${a.count} features to ${n}`),a}toggleSnapping(){this.snappingEnabled=!this.snappingEnabled,this.applySnappingState()}isSnappingEnabled(){return this.snappingEnabled}setSnapping(e){this.snappingEnabled=e,this.applySnappingState()}applySnappingState(){if(this.geoman)try{if(typeof this.geoman.enableMode=="function"){this.snappingEnabled?this.geoman.enableMode("helper","snapping"):this.geoman.disableMode("helper","snapping");return}const e=this.geoman;typeof e.setGlobalOptions=="function"?e.setGlobalOptions({snapping:this.snappingEnabled}):typeof e.enableSnapping=="function"&&this.snappingEnabled?e.enableSnapping():typeof e.disableSnapping=="function"&&!this.snappingEnabled&&e.disableSnapping()}catch{console.info("Snapping toggle: Geoman version does not support snapping.")}}createToolGroup(e,t,n){const i=document.createElement("div");if(i.className=`${rt}-tool-group`,this.options.showLabels){const r=document.createElement("div");r.className=`${rt}-tool-group-label`,r.textContent=e,i.appendChild(r)}const s=document.createElement("div");return s.className=`${rt}-tool-buttons`,t.forEach(r=>{const a=this.createToolButton(r,n);s.appendChild(a)}),i.appendChild(s),i}createToolButton(e,t){const n=document.createElement("button");return n.className=`${rt}-tool-button`,n.dataset.mode=e,n.dataset.type=t,n.title=this.getModeLabel(e),n.innerHTML=this.getModeIcon(e),n.addEventListener("click",()=>{t==="draw"?this.enableDrawMode(e):this.enableEditMode(e)}),n}updateToolbarState(){this.container.querySelectorAll(`.${rt}-tool-button`).forEach(e=>{const t=e,n=t.dataset.mode,i=t.dataset.type;if(t.dataset.helper)return;let s=!1;i==="draw"?s=n===this.state.activeDrawMode:i==="edit"&&(n==="select"?s=this.isSelectMode:n==="union"?s=this.pendingOperation==="union":n==="difference"?s=this.pendingOperation==="difference":s=n===this.state.activeEditMode),t.classList.toggle(`${rt}-tool-button--active`,s);const r=t.querySelector("svg");r&&r.querySelectorAll("path, polygon, rect, circle, ellipse, line, text").forEach(a=>{const o=a;o.style.fill="",o.style.stroke=""})})}getModeLabel(e){return{marker:"Marker",circle:"Circle",circle_marker:"Circle Marker",ellipse:"Ellipse",text_marker:"Text",line:"Line",rectangle:"Rectangle",polygon:"Polygon",freehand:"Freehand",select:"Select (click features)",drag:"Drag",change:"Edit",rotate:"Rotate",cut:"Cut",delete:"Delete",scale:"Scale",copy:"Copy",split:"Split",union:"Union (select 2+ polygons)",difference:"Difference (select 2+ polygons)",simplify:"Simplify",lasso:"Lasso Select"}[e]||e}getModeIcon(e){return{polygon:'<svg viewBox="0 0 24 24" width="18" height="18"><polygon points="12,2 22,8 18,22 6,22 2,8" fill="none" stroke="currentColor" stroke-width="2"/></svg>',line:'<svg viewBox="0 0 24 24" width="18" height="18"><line x1="4" y1="20" x2="20" y2="4" stroke="currentColor" stroke-width="2"/></svg>',rectangle:'<svg viewBox="0 0 24 24" width="18" height="18"><rect x="3" y="5" width="18" height="14" fill="none" stroke="currentColor" stroke-width="2"/></svg>',circle:'<svg viewBox="0 0 24 24" width="18" height="18"><circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="2"/></svg>',marker:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7z" fill="none" stroke="currentColor" stroke-width="2"/></svg>',select:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M4 3l6 14 2-6 6-2L4 3z" fill="currentColor"/><path d="M12.5 13.5l4.5 4.5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>',drag:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M10 9h4V6h3l-5-5-5 5h3v3zm-1 1H6V7l-5 5 5 5v-3h3v-4zm14 2l-5-5v3h-3v4h3v3l5-5zm-9 3h-4v3H7l5 5 5-5h-3v-3z" fill="currentColor"/></svg>',change:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a.996.996 0 0 0 0-1.41l-2.34-2.34a.996.996 0 0 0-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z" fill="currentColor"/></svg>',rotate:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M17.65 6.35A7.958 7.958 0 0 0 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08A5.99 5.99 0 0 1 12 18c-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z" fill="currentColor"/></svg>',cut:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M9.64 7.64c.23-.5.36-1.05.36-1.64 0-2.21-1.79-4-4-4S2 3.79 2 6s1.79 4 4 4c.59 0 1.14-.13 1.64-.36L10 12l-2.36 2.36C7.14 14.13 6.59 14 6 14c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4c0-.59-.13-1.14-.36-1.64L12 14l7 7h3v-1L9.64 7.64z" fill="currentColor"/></svg>',delete:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z" fill="currentColor"/></svg>',scale:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M21 15h2v2h-2v-2zm0-4h2v2h-2v-2zm2 8h-2v2c1 0 2-1 2-2zM13 3h2v2h-2V3zm8 4h2v2h-2V7zm0-4v2h2c0-1-1-2-2-2zM1 7h2v2H1V7zm16-4h2v2h-2V3zm0 16h2v2h-2v-2zM3 3C2 3 1 4 1 5h2V3zm6 0h2v2H9V3zM5 3h2v2H5V3zm-4 8v8c0 1.1.9 2 2 2h12V11H1z" fill="currentColor"/></svg>',copy:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z" fill="currentColor"/></svg>',split:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M14 4l2.29 2.29-2.88 2.88 1.42 1.42 2.88-2.88L20 10V4h-6zm-4 0H4v6l2.29-2.29 4.71 4.7V20h2v-8.41l-5.29-5.3L10 4z" fill="currentColor"/></svg>',union:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M4 4h7v7H4V4zm9 0h7v7h-7V4zm-9 9h7v7H4v-7zm9 0h7v7h-7v-7z" fill="currentColor"/></svg>',difference:'<svg viewBox="0 0 24 24" width="18" height="18"><rect x="4" y="4" width="10" height="10" fill="none" stroke="currentColor" stroke-width="2"/><rect x="10" y="10" width="10" height="10" fill="none" stroke="currentColor" stroke-width="2"/><path d="M13 7h6v2h-6z" fill="currentColor"/></svg>',simplify:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M4 17l5-5 3 3 6-6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M5 6h14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>',lasso:'<svg viewBox="0 0 24 24" width="18" height="18"><ellipse cx="12" cy="10" rx="8" ry="6" fill="none" stroke="currentColor" stroke-width="2" stroke-dasharray="4 2"/><circle cx="12" cy="18" r="3" fill="currentColor"/></svg>',freehand:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25z" fill="none" stroke="currentColor" stroke-width="2"/></svg>',circle_marker:'<svg viewBox="0 0 24 24" width="18" height="18"><circle cx="12" cy="12" r="4" fill="currentColor"/></svg>',ellipse:'<svg viewBox="0 0 24 24" width="18" height="18"><ellipse cx="12" cy="12" rx="10" ry="6" fill="none" stroke="currentColor" stroke-width="2"/></svg>',text_marker:'<svg viewBox="0 0 24 24" width="18" height="18"><text x="12" y="16" text-anchor="middle" font-size="14" fill="currentColor">T</text></svg>'}[e]||`<span>${e[0].toUpperCase()}</span>`}setupKeyboardShortcuts(){this.boundKeyHandler=e=>{const t=e.target instanceof HTMLInputElement||e.target instanceof HTMLTextAreaElement||e.target instanceof HTMLElement&&e.target.isContentEditable;if((e.ctrlKey||e.metaKey)&&e.key==="z"&&!e.shiftKey){this.undo(),e.preventDefault();return}if((e.ctrlKey||e.metaKey)&&(e.key==="y"||e.key==="z"&&e.shiftKey||e.key==="Z"&&e.shiftKey)){this.redo(),e.preventDefault();return}(e.ctrlKey||e.metaKey)&&e.key==="c"&&(this.copySelectedFeatures(),e.preventDefault()),(e.ctrlKey||e.metaKey)&&e.key==="v"&&(this.pasteFeatures(),e.preventDefault()),(e.key==="Delete"||e.key==="Backspace")&&!t&&!(e.target instanceof Element&&e.target.closest(".geo-editor-attribute-panel"))&&(this.deleteSelectedFeatures(),e.preventDefault()),e.key==="Enter"&&this.pendingOperation&&(this.executePendingOperation(),e.preventDefault()),e.key==="Escape"&&(this.pendingOperation?this.cancelPendingOperation():(this.disableAllModes(),this.clearSelection()))},document.addEventListener("keydown",this.boundKeyHandler)}removeKeyboardShortcuts(){this.boundKeyHandler&&(document.removeEventListener("keydown",this.boundKeyHandler),this.boundKeyHandler=null)}setupGeomanEvents(){this.geoman&&this.geoman.setGlobalEventsListener(e=>{const t=e.name??e.type??"",n=this.extractFeatureFromEvent(e.feature),i=e.action??"";if((t==="gm:create"||e.type==="gm:create")&&n&&(this.lastCreatedFeature=n,this.options.onFeatureCreate?.(n),this.logSelectedFeatureCollection("created",n),this.recordCreateOperation(n),this.options.enableAttributeEditing)){this.applyDefaultValues(n);const s=this.findGeomanDataForFeature(n);this.showAttributePanel(n,s??void 0,!0)}i==="feature_edit_start"&&n&&(this.pendingEditFeature=Es(n)),i==="feature_edit_end"&&n&&(this.lastEditedFeature=n,this.logSelectedFeatureCollection("edited",n),this.pendingEditFeature&&(this.recordEditOperation(this.pendingEditFeature,n),this.pendingEditFeature=null)),i==="feature_removed"&&n&&(this.lastDeletedFeature=n,this.lastDeletedFeatureId=this.getGeomanIdFromFeature(n),this.logSelectedFeatureCollection("deleted",n),this.recordDeleteOperation(n)),(t.includes("modetoggled")||e.type?.includes("modetoggled"))&&this.updateToolbarState()})}emitEvent(e,t){const n=new CustomEvent(e,{detail:t});this.map.getContainer().dispatchEvent(n)}undo(){return this.historyManager?this.historyManager.undo():!1}redo(){return this.historyManager?this.historyManager.redo():!1}canUndo(){return this.historyManager?.canUndo()??!1}canRedo(){return this.historyManager?.canRedo()??!1}clearHistory(){this.historyManager?.clear()}getHistoryState(){return this.historyManager?.getState()??null}getCommandContext(){return this.geoman?{featuresApi:this.geoman.features,onFeatureCreate:this.options.onFeatureCreate,onFeatureDelete:this.options.onFeatureDelete,onFeatureEdit:this.options.onFeatureEdit}:null}recordCreateOperation(e){if(!this.historyManager||this.historyManager.isExecutingCommand()||this.isPerformingCompositeOperation)return;const t=this.getCommandContext();if(!t)return;const n=new ZS(e,t);this.historyManager.record(n)}recordEditOperation(e,t){if(!this.historyManager||this.historyManager.isExecutingCommand()||this.isPerformingCompositeOperation)return;const n=this.getCommandContext();if(!n)return;const i=new oG(e,t,n);this.historyManager.record(i)}recordDeleteOperation(e){if(!this.historyManager||this.historyManager.isExecutingCommand()||this.isPerformingCompositeOperation)return;const t=this.getCommandContext();if(!t)return;const n=new JS(e,t);this.historyManager.record(n)}recordCompositeOperation(e,t,n){if(!this.historyManager||this.historyManager.isExecutingCommand())return;const i=this.getCommandContext();if(!i)return;const s=[];for(const a of e)s.push(new JS(a,i));for(const a of t)s.push(new ZS(a,i));const r=new lG(s,n);this.historyManager.record(r)}updateHistoryButtonStates(e,t){const n=this.container.querySelector('[data-history="undo"]'),i=this.container.querySelector('[data-history="redo"]');n&&(n.disabled=!e),i&&(i.disabled=!t)}createHistoryToolsGroup(){const e=document.createElement("div");if(e.className=`${rt}-tool-group`,this.options.showLabels){const s=document.createElement("div");s.className=`${rt}-tool-group-label`,s.textContent="History",e.appendChild(s)}const t=document.createElement("div");t.className=`${rt}-tool-buttons`;const n=document.createElement("button");n.className=`${rt}-tool-button`,n.dataset.history="undo",n.title="Undo (Ctrl+Z)",n.disabled=!0,n.innerHTML='<svg viewBox="0 0 24 24" width="18" height="18"><path d="M12.5 8c-2.65 0-5.05 1.04-6.93 2.75L2.5 7.69v7.81h7.81l-3.12-3.12c1.36-1.2 3.13-1.88 5.04-1.88 3.31 0 6.13 2.04 7.31 4.94l2.33-.91C20.32 10.93 16.73 8 12.5 8z" fill="currentColor"/></svg>',n.addEventListener("click",()=>this.undo()),t.appendChild(n);const i=document.createElement("button");return i.className=`${rt}-tool-button`,i.dataset.history="redo",i.title="Redo (Ctrl+Y)",i.disabled=!0,i.innerHTML='<svg viewBox="0 0 24 24" width="18" height="18"><path d="M18.43 10.75C16.55 9.04 14.15 8 11.5 8c-4.23 0-7.82 2.93-9.37 6.53l2.33.91c1.18-2.9 4-4.94 7.31-4.94 1.91 0 3.68.68 5.04 1.88l-3.12 3.12h7.81V7.69l-3.07 3.06z" fill="currentColor"/></svg>',i.addEventListener("click",()=>this.redo()),t.appendChild(i),e.appendChild(t),e}getPanelElement(){return this.attributePanel??null}},Fv="geo-editor-features",AR=class{type="geo-editor";_control;_changeCallbacks=[];_visible=!0;_opacity=1;_hasFeatures=!1;constructor(e){this._control=e,this._setupEventListeners()}_setupEventListeners(){}getLayerIds(){const e=this._control.getFeatures(),t=e&&e.features&&e.features.length>0;return t&&!this._hasFeatures?(this._hasFeatures=!0,this._changeCallbacks.forEach(n=>n("add",Fv))):!t&&this._hasFeatures&&(this._hasFeatures=!1,this._changeCallbacks.forEach(n=>n("remove",Fv))),t?[Fv]:[]}getLayerState(e){const t=this._control.getFeatures();return!t||!t.features||t.features.length===0?null:{visible:this._visible,opacity:this._opacity,name:this.getName(e),isCustomLayer:!0,customLayerType:"geo-editor"}}setVisibility(e,t){this._visible=t;const n=this._control.map;if(!n)return;const i=n.getStyle();if(i?.layers)for(const s of i.layers)s.source&&typeof s.source=="string"&&s.source.startsWith("geoman")&&n.setLayoutProperty(s.id,"visibility",t?"visible":"none")}setOpacity(e,t){this._opacity=t;const n=this._control.map;if(!n)return;const i=n.getStyle();if(i?.layers)for(const s of i.layers)s.source&&typeof s.source=="string"&&s.source.startsWith("geoman")&&(s.type==="fill"?n.setPaintProperty(s.id,"fill-opacity",t*.3):s.type==="line"?n.setPaintProperty(s.id,"line-opacity",t):s.type==="circle"&&n.setPaintProperty(s.id,"circle-opacity",t))}getName(e){return"Drawn Features"}getSymbolType(e){return"fill"}removeLayer(e){const t=this._control.geoman;t?.features&&t.features.forEach(n=>{n.delete()}),this._hasFeatures=!1}onLayerChange(e){return this._changeCallbacks.push(e),()=>{const t=this._changeCallbacks.indexOf(e);t>=0&&this._changeCallbacks.splice(t,1)}}destroy(){this._changeCallbacks=[]}},EG=Object.defineProperty,CG=(e,t,n)=>t in e?EG(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,oi=(e,t,n)=>CG(e,typeof t!="symbol"?t+"":t,n),wG="https://planetarycomputer.microsoft.com/api/stac/v1",SG=class{constructor(e=wG){oi(this,"baseUrl"),oi(this,"abortController",null),this.baseUrl=e.replace(/\/$/,"")}async getCollections(){return(await this.fetch("/collections")).collections}async getCollection(e){return this.fetch(`/collections/${encodeURIComponent(e)}`)}async search(e){var t;return(t=this.abortController)==null||t.abort(),this.abortController=new AbortController,(await this.fetch("/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:this.abortController.signal})).features}async searchWithContext(e){var t;return(t=this.abortController)==null||t.abort(),this.abortController=new AbortController,this.fetch("/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:this.abortController.signal})}async getCollectionItems(e,t=50){return(await this.fetch(`/collections/${encodeURIComponent(e)}/items?limit=${t}`)).features}async getItem(e,t){return this.fetch(`/collections/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}`)}cancelPending(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null}getBaseUrl(){return this.baseUrl}async fetch(e,t){const n=`${this.baseUrl}${e}`;try{const i=await fetch(n,t);if(!i.ok){const s=await i.text();throw new Error(`STAC API error: ${i.status} ${i.statusText} - ${s}`)}return i.json()}catch(i){throw i instanceof Error&&i.name==="AbortError"?new Error("Request was cancelled"):i}}},IG="https://planetarycomputer.microsoft.com/api/data/v1",MG=class{constructor(e=IG){oi(this,"baseUrl"),this.baseUrl=e.replace(/\/$/,"")}getItemTileUrl(e,t,n={}){const i=this.buildQueryString(n),s=i?`?${i}`:"";return`${this.baseUrl}/item/tiles/WebMercatorQuad/{z}/{x}/{y}@1x?collection=${encodeURIComponent(e)}&item=${encodeURIComponent(t)}${s?"&"+i:""}`}getCollectionTileUrl(e,t={},n){const i=this.buildQueryString(t),s=n?this.buildSearchParams(n):"",r=[`collection=${encodeURIComponent(e)}`,i,s].filter(Boolean).join("&");return`${this.baseUrl}/mosaic/tiles/WebMercatorQuad/{z}/{x}/{y}@1x?${r}`}async registerMosaic(e,t={}){const n=await fetch(`${this.baseUrl}/mosaic/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({collections:e.collections,filter:e.filter,"filter-lang":e["filter-lang"]||"cql2-json",sortby:e.sortby})});if(!n.ok)throw new Error(`Failed to register mosaic: ${n.statusText}`);const i=await n.json(),s=i.id||i.searchid,r=this.buildQueryString(t);return{searchId:s,tileUrl:`${this.baseUrl}/mosaic/tiles/WebMercatorQuad/{z}/{x}/{y}@1x?searchid=${s}${r?"&"+r:""}`}}async getItemInfo(e,t,n){const i=n?.length?`&assets=${n.join(",")}`:"",s=await fetch(`${this.baseUrl}/item/info?collection=${encodeURIComponent(e)}&item=${encodeURIComponent(t)}${i}`);if(!s.ok)throw new Error(`Failed to get item info: ${s.statusText}`);return s.json()}async getItemStatistics(e,t,n){const i=n?.length?`&assets=${n.join(",")}`:"",s=await fetch(`${this.baseUrl}/item/statistics?collection=${encodeURIComponent(e)}&item=${encodeURIComponent(t)}${i}`);if(!s.ok)throw new Error(`Failed to get item statistics: ${s.statusText}`);return s.json()}getBaseUrl(){return this.baseUrl}buildQueryString(e){var t;const n=new URLSearchParams;return(t=e.assets)!=null&&t.length&&e.assets.forEach(i=>n.append("assets",i)),e.expression&&n.set("expression",e.expression),e.rescale&&n.set("rescale",e.rescale),e.colormap_name&&n.set("colormap_name",e.colormap_name),e.colormap&&n.set("colormap",JSON.stringify(e.colormap)),e.nodata!==void 0&&n.set("nodata",String(e.nodata)),e.resampling&&n.set("resampling",e.resampling),e.return_mask!==void 0&&n.set("return_mask",String(e.return_mask)),e.tile_size&&n.set("tile_size",String(e.tile_size)),e.asset_bidx&&Object.entries(e.asset_bidx).forEach(([i,s])=>{n.append("asset_bidx",`${i}|${s}`)}),n.toString()}buildSearchParams(e){const t=[];return e.datetime&&t.push(`datetime=${encodeURIComponent(e.datetime)}`),e.bbox&&t.push(`bbox=${e.bbox.join(",")}`),t.join("&")}},TG="https://planetarycomputer.microsoft.com/api/sas/v1/token",LG=class{constructor(e=300*1e3){oi(this,"cache",new Map),oi(this,"bufferMs"),this.bufferMs=e}async getToken(e){const t=this.cache.get(e),n=new Date;if(t&&t.expiry.getTime()-n.getTime()>this.bufferMs)return t.token;const i=await fetch(`${TG}/${encodeURIComponent(e)}`);if(!i.ok)throw new Error(`Failed to get SAS token for ${e}: ${i.statusText}`);const s=await i.json(),r=s.token,a=new Date(s["msft:expiry"]);return this.cache.set(e,{token:r,expiry:a}),r}async signUrl(e,t){const n=await this.getToken(t);return`${e}${e.includes("?")?"&":"?"}${n}`}hasValidToken(e){const t=this.cache.get(e);if(!t)return!1;const n=new Date;return t.expiry.getTime()-n.getTime()>this.bufferMs}clearCache(){this.cache.clear()}clearToken(e){this.cache.delete(e)}},BG=[{name:"true-color",label:"True Color",description:"Natural color composite (RGB)",params:{assets:["visual"]}},{name:"false-color",label:"False Color (Vegetation)",description:"NIR-Red-Green composite for vegetation analysis",params:{assets:["B08","B04","B03"],rescale:"0,3000"}},{name:"ndvi",label:"NDVI",description:"Normalized Difference Vegetation Index",params:{expression:"(B08-B04)/(B08+B04)",rescale:"-1,1",colormap_name:"rdylgn"}},{name:"ndwi",label:"NDWI",description:"Normalized Difference Water Index",params:{expression:"(B03-B08)/(B03+B08)",rescale:"-1,1",colormap_name:"blues"}},{name:"swir",label:"SWIR Composite",description:"SWIR-NIR-Red for geology and moisture",params:{assets:["B12","B08","B04"],rescale:"0,3000"}}],RG=[{name:"true-color",label:"True Color",description:"Natural color composite (RGB)",params:{assets:["red","green","blue"],rescale:"0,20000"}},{name:"false-color",label:"False Color (Vegetation)",description:"NIR-Red-Green composite",params:{assets:["nir08","red","green"],rescale:"0,20000"}},{name:"ndvi",label:"NDVI",description:"Normalized Difference Vegetation Index",params:{expression:"(nir08-red)/(nir08+red)",rescale:"-1,1",colormap_name:"rdylgn"}},{name:"thermal",label:"Thermal",description:"Land surface temperature",params:{assets:["lwir11"],rescale:"290,320",colormap_name:"magma"}}],kG=[{name:"rgb",label:"RGB",description:"Natural color",params:{assets:["image"],asset_bidx:{image:"1,2,3"}}},{name:"cir",label:"Color Infrared",description:"NIR-Red-Green composite",params:{assets:["image"],asset_bidx:{image:"4,1,2"}}},{name:"ndvi",label:"NDVI",description:"Vegetation index from NAIP",params:{expression:"(image_b4-image_b1)/(image_b4+image_b1)",rescale:"-1,1",colormap_name:"rdylgn"}}],t1=[{name:"elevation",label:"Elevation",description:"Color-coded elevation",params:{assets:["data"],colormap_name:"terrain",rescale:"0,4000"}},{name:"hillshade",label:"Hillshade",description:"Shaded relief visualization",params:{assets:["data"],colormap_name:"gray",rescale:"0,255"}}],NG=[{collectionId:"sentinel-2-l2a",defaultPreset:"true-color",presets:BG},{collectionId:"landsat-c2-l2",defaultPreset:"true-color",presets:RG},{collectionId:"naip",defaultPreset:"rgb",presets:kG},{collectionId:"cop-dem-glo-30",defaultPreset:"elevation",presets:t1},{collectionId:"cop-dem-glo-90",defaultPreset:"elevation",presets:t1}];function vR(e){return NG.find(t=>t.collectionId===e)}function n1(e){const t=vR(e);return t?.presets??[]}function i1(e){const t=vR(e);if(t)return t.presets.find(n=>n.name===t.defaultPreset)}function s1(e=""){const t=Date.now().toString(36),n=Math.random().toString(36).substring(2,8);return e?`${e}-${t}-${n}`:`${t}-${n}`}function r1(e){if(!e)return"Unknown";try{return new Date(e).toLocaleDateString()}catch{return e}}function a1(e){return e.datetime||e.start_datetime||e.end_datetime||null}function PG(e,t){return e.length<=t?e:e.substring(0,t)+"..."}function DG(e){const[t,n,i,s]=e;return`${t.toFixed(2)}, ${n.toFixed(2)}, ${i.toFixed(2)}, ${s.toFixed(2)}`}var FG=class{constructor(e,t){oi(this,"map"),oi(this,"tilerClient"),oi(this,"layers",new Map),this.map=e,this.tilerClient=t}addItemLayer(e,t){const n=`${e.id.replace(/[^a-zA-Z0-9-_]/g,"-").slice(0,50)}-${s1().slice(-6)}`,i=`${n}-source`,s=e.collection||"";let r=t?.renderParams||{},a=t?.presetName;if(!t?.renderParams&&!t?.assets&&s){const h=i1(s);h&&(r=h.params,a=h.name)}const o=t?.assets||r.assets||this.getDefaultAssets(e);r={...r,assets:o};const l=this.tilerClient.getItemTileUrl(s,e.id,r);this.map.addSource(i,{type:"raster",tiles:[l],tileSize:256,bounds:e.bbox,attribution:"Microsoft Planetary Computer"}),this.map.addLayer({id:n,type:"raster",source:i,paint:{"raster-opacity":1}});const c={id:n,type:"item",sourceId:i,item:e,collection:void 0,visible:!0,opacity:1,assets:o,renderParams:r,presetName:a};return this.layers.set(n,c),c}addCollectionLayer(e,t){const n=`${(e.title||e.id).replace(/[^a-zA-Z0-9-_]/g,"-").slice(0,50)}-${s1().slice(-6)}`,i=`${n}-source`;let s=t?.renderParams||{},r=t?.presetName;if(!t?.renderParams&&!t?.assets){const h=i1(e.id);h&&(s=h.params,r=h.name)}const a=t?.assets||s.assets||this.getDefaultCollectionAssets(e);s={...s,assets:a};const o=this.tilerClient.getCollectionTileUrl(e.id,s),l=t?.bbox||this.getCollectionBounds(e);this.map.addSource(i,{type:"raster",tiles:[o],tileSize:256,bounds:l,attribution:"Microsoft Planetary Computer"}),this.map.addLayer({id:n,type:"raster",source:i,paint:{"raster-opacity":1}});const c={id:n,type:"collection",sourceId:i,collection:e,visible:!0,opacity:1,assets:a,renderParams:s,presetName:r};return this.layers.set(n,c),c}removeLayer(e){const t=this.layers.get(e);t&&(this.map.getLayer(e)&&this.map.removeLayer(e),this.map.getSource(t.sourceId)&&this.map.removeSource(t.sourceId),this.layers.delete(e))}updateLayer(e,t){const n=this.layers.get(e);n&&(t.visible!==void 0&&this.map.setLayoutProperty(e,"visibility",t.visible?"visible":"none"),t.opacity!==void 0&&this.map.setPaintProperty(e,"raster-opacity",t.opacity),(t.renderParams||t.assets)&&this.updateLayerSource(e,t),this.layers.set(e,{...n,...t}))}getLayer(e){return this.layers.get(e)}getLayers(){return Array.from(this.layers.values())}removeAllLayers(){for(const e of this.layers.keys())this.removeLayer(e)}zoomToLayer(e){var t;const n=this.layers.get(e);if(!n)return;let i;(t=n.item)!=null&&t.bbox?i=n.item.bbox:n.collection&&(i=this.getCollectionBounds(n.collection)),i&&this.map.fitBounds([[i[0],i[1]],[i[2],i[3]]],{padding:50})}getMap(){return this.map}updateLayerSource(e,t){var n;const i=this.layers.get(e);if(!i)return;const s={...i.renderParams,...t.renderParams},r=t.assets||i.assets;let a;if(i.type==="item"&&i.item){const h=i.item.collection||"";a=this.tilerClient.getItemTileUrl(h,i.item.id,{...s,assets:r})}else if(i.type==="collection"&&i.collection)a=this.tilerClient.getCollectionTileUrl(i.collection.id,{...s,assets:r});else return;const o=this.map.getLayoutProperty(e,"visibility"),l=this.map.getPaintProperty(e,"raster-opacity");this.map.removeLayer(e),this.map.removeSource(i.sourceId);const c=((n=i.item)==null?void 0:n.bbox)||(i.collection?this.getCollectionBounds(i.collection):void 0);this.map.addSource(i.sourceId,{type:"raster",tiles:[a],tileSize:256,bounds:c,attribution:"Microsoft Planetary Computer"}),this.map.addLayer({id:e,type:"raster",source:i.sourceId,layout:{visibility:o},paint:{"raster-opacity":l??1}})}getDefaultAssets(e){for(const i of["visual","data","image","cog_default"])if(e.assets[i])return[i];for(const[i,s]of Object.entries(e.assets)){const r=s.type||"";if(r.includes("tiff")||r.includes("geotiff")||r.includes("cog"))return[i]}const t=["thumbnail","overview","metadata","tilejson","rendered_preview"],n=Object.keys(e.assets).find(i=>!t.some(s=>i.toLowerCase().includes(s)));return n?[n]:[]}getDefaultCollectionAssets(e){const t=e.item_assets||{};for(const s of["visual","data","image","cog_default"])if(t[s])return[s];for(const[s,r]of Object.entries(t)){const a=r.type||"";if(a.includes("tiff")||a.includes("geotiff")||a.includes("cog"))return[s]}const n=["thumbnail","overview","metadata","tilejson","rendered_preview"],i=Object.keys(t).find(s=>!n.some(r=>s.toLowerCase().includes(r)));return i?[i]:[]}getCollectionBounds(e){var t,n,i;const s=(i=(n=(t=e.extent)==null?void 0:t.spatial)==null?void 0:n.bbox)==null?void 0:i[0];if(s&&s.length>=4)return[s[0],s[1],s[2],s[3]]}},OG={collapsed:!0,position:"top-right",title:"Planetary Computer",panelWidth:380,maxHeight:500,className:"",stacApiUrl:"https://planetarycomputer.microsoft.com/api/stac/v1",tilerApiUrl:"https://planetarycomputer.microsoft.com/api/data/v1",defaultCollections:[],enableBboxSelector:!0,maxSearchResults:50,autoLoadCollections:!0},gb=class{constructor(e){oi(this,"_map"),oi(this,"_mapContainer"),oi(this,"_container"),oi(this,"_panel"),oi(this,"_contentEl"),oi(this,"_options"),oi(this,"_state"),oi(this,"_eventHandlers",new globalThis.Map),oi(this,"_stacClient"),oi(this,"_tilerClient"),oi(this,"_sasManager"),oi(this,"_layerManager"),oi(this,"_resizeHandler",null),oi(this,"_mapResizeHandler",null),oi(this,"_clickOutsideHandler",null),this._options={...OG,...e},this._state=this._getInitialState(),this._stacClient=new SG(this._options.stacApiUrl),this._tilerClient=new MG(this._options.tilerApiUrl),this._sasManager=new LG}onAdd(e){return this._map=e,this._mapContainer=e.getContainer(),this._layerManager=new FG(e,this._tilerClient),this._container=this._createContainer(),this._panel=this._createPanel(),this._mapContainer.appendChild(this._panel),this._setupEventListeners(),this._state.collapsed||(this._panel.classList.add("expanded"),requestAnimationFrame(()=>this._updatePanelPosition())),this._options.autoLoadCollections&&this._loadCollections(),this._container}onRemove(){var e,t,n,i,s;this._resizeHandler&&(window.removeEventListener("resize",this._resizeHandler),this._resizeHandler=null),this._mapResizeHandler&&this._map&&(this._map.off("resize",this._mapResizeHandler),this._mapResizeHandler=null),this._clickOutsideHandler&&(document.removeEventListener("click",this._clickOutsideHandler),this._clickOutsideHandler=null),this._stacClient.cancelPending(),this._sasManager.clearCache(),(e=this._layerManager)==null||e.removeAllLayers(),(n=(t=this._panel)==null?void 0:t.parentNode)==null||n.removeChild(this._panel),(s=(i=this._container)==null?void 0:i.parentNode)==null||s.removeChild(this._container),this._map=void 0,this._eventHandlers.clear()}getState(){return{...this._state}}toggle(){this._state.collapsed=!this._state.collapsed,this._updatePanelVisibility(),this._emit(this._state.collapsed?"collapse":"expand"),this._emit("statechange")}expand(){this._state.collapsed&&this.toggle()}collapse(){this._state.collapsed||this.toggle()}async loadCollections(){return this._loadCollections()}async search(e){const t={...this._state.searchParams,...e,limit:this._options.maxSearchResults};this._state.searchParams=t,this._state.searchLoading=!0,this._state.error=null,this._emit("search:start"),this._emit("statechange");try{const n=await this._stacClient.search(t);return this._state.searchResults=n,this._state.activeView="results",this._emit("search:complete"),this._emit("search"),n}catch(n){const i=n instanceof Error?n.message:"Search failed";throw this._state.error=i,this._emit("search:error"),this._emit("error"),n}finally{this._state.searchLoading=!1,this._emit("statechange"),this._renderContent()}}addItemLayer(e,t){if(!this._layerManager)throw new Error("Control not added to map");const n=this._layerManager.addItemLayer(e,t);return this._state.activeLayers.push(n),this._emit("layer:add"),this._emit("statechange"),this._renderContent(),n}addCollectionLayer(e,t){if(!this._layerManager)throw new Error("Control not added to map");const n=this._layerManager.addCollectionLayer(e,t);return this._state.activeLayers.push(n),this._emit("layer:add"),this._emit("statechange"),this._renderContent(),n}removeLayer(e){var t;(t=this._layerManager)==null||t.removeLayer(e),this._state.activeLayers=this._state.activeLayers.filter(n=>n.id!==e),this._emit("layer:remove"),this._emit("statechange"),this._renderContent()}updateLayer(e,t){var n;(n=this._layerManager)==null||n.updateLayer(e,t);const i=this._state.activeLayers.findIndex(s=>s.id===e);i>=0&&(this._state.activeLayers[i]={...this._state.activeLayers[i],...t}),this._emit("layer:update"),this._emit("statechange")}zoomToLayer(e){var t;(t=this._layerManager)==null||t.zoomToLayer(e)}async getDownloadUrl(e,t){const n=e.assets[t];if(!n)throw new Error(`Asset '${t}' not found`);const i=e.collection||"";return this._sasManager.signUrl(n.href,i)}selectCollection(e){this._state.selectedCollection=e,this._state.searchParams=e?{collections:[e.id]}:{},this._state.activeView=e?"search":"collections",this._state.searchResults=[],this._emit("collection:select"),this._emit("statechange"),this._renderContent()}selectItem(e){this._state.selectedItem=e,this._state.activeView=e?"item":"results",this._emit("item:select"),this._emit("statechange"),this._renderContent()}setView(e){this._state.activeView=e,this._emit("statechange"),this._renderContent()}on(e,t){this._eventHandlers.has(e)||this._eventHandlers.set(e,new Set),this._eventHandlers.get(e).add(t)}off(e,t){var n;(n=this._eventHandlers.get(e))==null||n.delete(t)}getMap(){return this._map}getContainer(){return this._container}_getInitialState(){return{collapsed:this._options.collapsed,panelWidth:this._options.panelWidth,activeView:"collections",collections:[],collectionsLoading:!1,selectedCollection:null,searchParams:{},searchResults:[],searchLoading:!1,selectedItem:null,activeLayers:[],error:null,bboxSelectorActive:!1,drawnBbox:null}}_emit(e,t){const n=this._eventHandlers.get(e);if(n){const i={type:e,state:this.getState(),data:t};n.forEach(s=>s(i))}}_createContainer(){const e=document.createElement("div");e.className=`maplibregl-ctrl maplibregl-ctrl-group pc-control${this._options.className?` ${this._options.className}`:""}`;const t=document.createElement("button");return t.className="pc-control-toggle",t.type="button",t.setAttribute("aria-label",this._options.title),t.innerHTML=`
272
+ `)}return _.toString()}},{key:"computeEdgeEndLabels",value:function(_){for(var u=this.iterator();u.hasNext();)u.next().computeLabel(_)}},{key:"computeLabelling",value:function(_){this.computeEdgeEndLabels(_[0].getBoundaryNodeRule()),this.propagateSideLabels(0),this.propagateSideLabels(1);for(var u=[!1,!1],p=this.iterator();p.hasNext();)for(var g=p.next().getLabel(),E=0;E<2;E++)g.isLine(E)&&g.getLocation(E)===$.BOUNDARY&&(u[E]=!0);for(var B=this.iterator();B.hasNext();)for(var F=B.next(),G=F.getLabel(),Y=0;Y<2;Y++)if(G.isAnyNull(Y)){var ae=$.NONE;if(u[Y])ae=$.EXTERIOR;else{var xe=F.getCoordinate();ae=this.getLocation(Y,xe,_)}G.setAllLocationsIfNull(Y,ae)}}},{key:"getDegree",value:function(){return this._edgeMap.size()}},{key:"insertEdgeEnd",value:function(_,u){this._edgeMap.put(_,u),this._edgeList=null}}],[{key:"constructor_",value:function(){this._edgeMap=new cd,this._edgeList=null,this._ptInAreaLocation=[$.NONE,$.NONE]}}])})()),HF=(function(_){function u(){return s(this,u),i(this,u)}return d(u,_),o(u,[{key:"createNode",value:function(p){return new Vf(p,new GF)}}])})(mw),Iw=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"compareTo",value:function(u){var p=u;return _.compareOriented(this._pts,this._orientation,p._pts,p._orientation)}},{key:"interfaces_",get:function(){return[L]}}],[{key:"constructor_",value:function(){this._pts=null,this._orientation=null;var u=arguments[0];this._pts=u,this._orientation=_.orientation(u)}},{key:"orientation",value:function(u){return In.increasingDirection(u)===1}},{key:"compareOriented",value:function(u,p,g,E){for(var B=p?1:-1,F=E?1:-1,G=p?u.length:-1,Y=E?g.length:-1,ae=p?0:u.length-1,xe=E?0:g.length-1;;){var Ie=u[ae].compareTo(g[xe]);if(Ie!==0)return Ie;var Ge=(ae+=B)===G,ut=(xe+=F)===Y;if(Ge&&!ut)return-1;if(!Ge&&ut)return 1;if(Ge&&ut)return 0}}}])})(),$F=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"print",value:function(_){_.print("MULTILINESTRING ( ");for(var u=0;u<this._edges.size();u++){var p=this._edges.get(u);u>0&&_.print(","),_.print("(");for(var g=p.getCoordinates(),E=0;E<g.length;E++)E>0&&_.print(","),_.print(g[E].x+" "+g[E].y);_.println(")")}_.print(") ")}},{key:"addAll",value:function(_){for(var u=_.iterator();u.hasNext();)this.add(u.next())}},{key:"findEdgeIndex",value:function(_){for(var u=0;u<this._edges.size();u++)if(this._edges.get(u).equals(_))return u;return-1}},{key:"iterator",value:function(){return this._edges.iterator()}},{key:"getEdges",value:function(){return this._edges}},{key:"get",value:function(_){return this._edges.get(_)}},{key:"findEqualEdge",value:function(_){var u=new Iw(_.getCoordinates());return this._ocaMap.get(u)}},{key:"add",value:function(_){this._edges.add(_);var u=new Iw(_.getCoordinates());this._ocaMap.put(u,_)}}],[{key:"constructor_",value:function(){this._edges=new Pe,this._ocaMap=new cd}}])})(),Mw=(function(){return o((function _(){s(this,_)}),[{key:"processIntersections",value:function(_,u,p,g){}},{key:"isDone",value:function(){}}])})(),VF=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"isTrivialIntersection",value:function(u,p,g,E){if(u===g&&this._li.getIntersectionNum()===1){if(_.isAdjacentSegments(p,E))return!0;if(u.isClosed()){var B=u.size()-1;if(p===0&&E===B||E===0&&p===B)return!0}}return!1}},{key:"getProperIntersectionPoint",value:function(){return this._properIntersectionPoint}},{key:"hasProperInteriorIntersection",value:function(){return this._hasProperInterior}},{key:"getLineIntersector",value:function(){return this._li}},{key:"hasProperIntersection",value:function(){return this._hasProper}},{key:"processIntersections",value:function(u,p,g,E){if(u===g&&p===E)return null;this.numTests++;var B=u.getCoordinates()[p],F=u.getCoordinates()[p+1],G=g.getCoordinates()[E],Y=g.getCoordinates()[E+1];this._li.computeIntersection(B,F,G,Y),this._li.hasIntersection()&&(this.numIntersections++,this._li.isInteriorIntersection()&&(this.numInteriorIntersections++,this._hasInterior=!0),this.isTrivialIntersection(u,p,g,E)||(this._hasIntersection=!0,u.addIntersections(this._li,p,0),g.addIntersections(this._li,E,1),this._li.isProper()&&(this.numProperIntersections++,this._hasProper=!0,this._hasProperInterior=!0)))}},{key:"hasIntersection",value:function(){return this._hasIntersection}},{key:"isDone",value:function(){return!1}},{key:"hasInteriorIntersection",value:function(){return this._hasInterior}},{key:"interfaces_",get:function(){return[Mw]}}],[{key:"constructor_",value:function(){this._hasIntersection=!1,this._hasProper=!1,this._hasProperInterior=!1,this._hasInterior=!1,this._properIntersectionPoint=null,this._li=null,this._isSelfIntersection=null,this.numIntersections=0,this.numInteriorIntersections=0,this.numProperIntersections=0,this.numTests=0;var u=arguments[0];this._li=u}},{key:"isAdjacentSegments",value:function(u,p){return Math.abs(u-p)===1}}])})(),qF=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"getSegmentIndex",value:function(){return this.segmentIndex}},{key:"getCoordinate",value:function(){return this.coord}},{key:"print",value:function(_){_.print(this.coord),_.print(" seg # = "+this.segmentIndex),_.println(" dist = "+this.dist)}},{key:"compareTo",value:function(_){var u=_;return this.compare(u.segmentIndex,u.dist)}},{key:"isEndPoint",value:function(_){return this.segmentIndex===0&&this.dist===0||this.segmentIndex===_}},{key:"toString",value:function(){return this.coord+" seg # = "+this.segmentIndex+" dist = "+this.dist}},{key:"getDistance",value:function(){return this.dist}},{key:"compare",value:function(_,u){return this.segmentIndex<_?-1:this.segmentIndex>_?1:this.dist<u?-1:this.dist>u?1:0}},{key:"interfaces_",get:function(){return[L]}}],[{key:"constructor_",value:function(){this.coord=null,this.segmentIndex=null,this.dist=null;var _=arguments[0],u=arguments[1],p=arguments[2];this.coord=new ie(_),this.segmentIndex=u,this.dist=p}}])})(),WF=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"print",value:function(_){_.println("Intersections:");for(var u=this.iterator();u.hasNext();)u.next().print(_)}},{key:"iterator",value:function(){return this._nodeMap.values().iterator()}},{key:"addSplitEdges",value:function(_){this.addEndpoints();for(var u=this.iterator(),p=u.next();u.hasNext();){var g=u.next(),E=this.createSplitEdge(p,g);_.add(E),p=g}}},{key:"addEndpoints",value:function(){var _=this.edge.pts.length-1;this.add(this.edge.pts[0],0,0),this.add(this.edge.pts[_],_,0)}},{key:"createSplitEdge",value:function(_,u){var p=u.segmentIndex-_.segmentIndex+2,g=this.edge.pts[u.segmentIndex],E=u.dist>0||!u.coord.equals2D(g);E||p--;var B=new Array(p).fill(null),F=0;B[F++]=new ie(_.coord);for(var G=_.segmentIndex+1;G<=u.segmentIndex;G++)B[F++]=this.edge.pts[G];return E&&(B[F]=u.coord),new Lw(B,new Sr(this.edge._label))}},{key:"add",value:function(_,u,p){var g=new qF(_,u,p),E=this._nodeMap.get(g);return E!==null?E:(this._nodeMap.put(g,g),g)}},{key:"isIntersection",value:function(_){for(var u=this.iterator();u.hasNext();)if(u.next().coord.equals(_))return!0;return!1}}],[{key:"constructor_",value:function(){this._nodeMap=new cd,this.edge=null;var _=arguments[0];this.edge=_}}])})(),YF=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"isIntersects",value:function(){return!this.isDisjoint()}},{key:"isCovers",value:function(){return(_.isTrue(this._matrix[$.INTERIOR][$.INTERIOR])||_.isTrue(this._matrix[$.INTERIOR][$.BOUNDARY])||_.isTrue(this._matrix[$.BOUNDARY][$.INTERIOR])||_.isTrue(this._matrix[$.BOUNDARY][$.BOUNDARY]))&&this._matrix[$.EXTERIOR][$.INTERIOR]===Ne.FALSE&&this._matrix[$.EXTERIOR][$.BOUNDARY]===Ne.FALSE}},{key:"isCoveredBy",value:function(){return(_.isTrue(this._matrix[$.INTERIOR][$.INTERIOR])||_.isTrue(this._matrix[$.INTERIOR][$.BOUNDARY])||_.isTrue(this._matrix[$.BOUNDARY][$.INTERIOR])||_.isTrue(this._matrix[$.BOUNDARY][$.BOUNDARY]))&&this._matrix[$.INTERIOR][$.EXTERIOR]===Ne.FALSE&&this._matrix[$.BOUNDARY][$.EXTERIOR]===Ne.FALSE}},{key:"set",value:function(){if(arguments.length===1)for(var u=arguments[0],p=0;p<u.length;p++){var g=Math.trunc(p/3),E=p%3;this._matrix[g][E]=Ne.toDimensionValue(u.charAt(p))}else if(arguments.length===3){var B=arguments[0],F=arguments[1],G=arguments[2];this._matrix[B][F]=G}}},{key:"isContains",value:function(){return _.isTrue(this._matrix[$.INTERIOR][$.INTERIOR])&&this._matrix[$.EXTERIOR][$.INTERIOR]===Ne.FALSE&&this._matrix[$.EXTERIOR][$.BOUNDARY]===Ne.FALSE}},{key:"setAtLeast",value:function(){if(arguments.length===1)for(var u=arguments[0],p=0;p<u.length;p++){var g=Math.trunc(p/3),E=p%3;this.setAtLeast(g,E,Ne.toDimensionValue(u.charAt(p)))}else if(arguments.length===3){var B=arguments[0],F=arguments[1],G=arguments[2];this._matrix[B][F]<G&&(this._matrix[B][F]=G)}}},{key:"setAtLeastIfValid",value:function(u,p,g){u>=0&&p>=0&&this.setAtLeast(u,p,g)}},{key:"isWithin",value:function(){return _.isTrue(this._matrix[$.INTERIOR][$.INTERIOR])&&this._matrix[$.INTERIOR][$.EXTERIOR]===Ne.FALSE&&this._matrix[$.BOUNDARY][$.EXTERIOR]===Ne.FALSE}},{key:"isTouches",value:function(u,p){return u>p?this.isTouches(p,u):(u===Ne.A&&p===Ne.A||u===Ne.L&&p===Ne.L||u===Ne.L&&p===Ne.A||u===Ne.P&&p===Ne.A||u===Ne.P&&p===Ne.L)&&this._matrix[$.INTERIOR][$.INTERIOR]===Ne.FALSE&&(_.isTrue(this._matrix[$.INTERIOR][$.BOUNDARY])||_.isTrue(this._matrix[$.BOUNDARY][$.INTERIOR])||_.isTrue(this._matrix[$.BOUNDARY][$.BOUNDARY]))}},{key:"isOverlaps",value:function(u,p){return u===Ne.P&&p===Ne.P||u===Ne.A&&p===Ne.A?_.isTrue(this._matrix[$.INTERIOR][$.INTERIOR])&&_.isTrue(this._matrix[$.INTERIOR][$.EXTERIOR])&&_.isTrue(this._matrix[$.EXTERIOR][$.INTERIOR]):u===Ne.L&&p===Ne.L&&this._matrix[$.INTERIOR][$.INTERIOR]===1&&_.isTrue(this._matrix[$.INTERIOR][$.EXTERIOR])&&_.isTrue(this._matrix[$.EXTERIOR][$.INTERIOR])}},{key:"isEquals",value:function(u,p){return u===p&&_.isTrue(this._matrix[$.INTERIOR][$.INTERIOR])&&this._matrix[$.INTERIOR][$.EXTERIOR]===Ne.FALSE&&this._matrix[$.BOUNDARY][$.EXTERIOR]===Ne.FALSE&&this._matrix[$.EXTERIOR][$.INTERIOR]===Ne.FALSE&&this._matrix[$.EXTERIOR][$.BOUNDARY]===Ne.FALSE}},{key:"toString",value:function(){for(var u=new we("123456789"),p=0;p<3;p++)for(var g=0;g<3;g++)u.setCharAt(3*p+g,Ne.toDimensionSymbol(this._matrix[p][g]));return u.toString()}},{key:"setAll",value:function(u){for(var p=0;p<3;p++)for(var g=0;g<3;g++)this._matrix[p][g]=u}},{key:"get",value:function(u,p){return this._matrix[u][p]}},{key:"transpose",value:function(){var u=this._matrix[1][0];return this._matrix[1][0]=this._matrix[0][1],this._matrix[0][1]=u,u=this._matrix[2][0],this._matrix[2][0]=this._matrix[0][2],this._matrix[0][2]=u,u=this._matrix[2][1],this._matrix[2][1]=this._matrix[1][2],this._matrix[1][2]=u,this}},{key:"matches",value:function(u){if(u.length!==9)throw new R("Should be length 9: "+u);for(var p=0;p<3;p++)for(var g=0;g<3;g++)if(!_.matches(this._matrix[p][g],u.charAt(3*p+g)))return!1;return!0}},{key:"add",value:function(u){for(var p=0;p<3;p++)for(var g=0;g<3;g++)this.setAtLeast(p,g,u.get(p,g))}},{key:"isDisjoint",value:function(){return this._matrix[$.INTERIOR][$.INTERIOR]===Ne.FALSE&&this._matrix[$.INTERIOR][$.BOUNDARY]===Ne.FALSE&&this._matrix[$.BOUNDARY][$.INTERIOR]===Ne.FALSE&&this._matrix[$.BOUNDARY][$.BOUNDARY]===Ne.FALSE}},{key:"isCrosses",value:function(u,p){return u===Ne.P&&p===Ne.L||u===Ne.P&&p===Ne.A||u===Ne.L&&p===Ne.A?_.isTrue(this._matrix[$.INTERIOR][$.INTERIOR])&&_.isTrue(this._matrix[$.INTERIOR][$.EXTERIOR]):u===Ne.L&&p===Ne.P||u===Ne.A&&p===Ne.P||u===Ne.A&&p===Ne.L?_.isTrue(this._matrix[$.INTERIOR][$.INTERIOR])&&_.isTrue(this._matrix[$.EXTERIOR][$.INTERIOR]):u===Ne.L&&p===Ne.L&&this._matrix[$.INTERIOR][$.INTERIOR]===0}},{key:"interfaces_",get:function(){return[T]}}],[{key:"constructor_",value:function(){if(this._matrix=null,arguments.length===0)this._matrix=Array(3).fill().map((function(){return Array(3)})),this.setAll(Ne.FALSE);else if(arguments.length===1){if(typeof arguments[0]=="string"){var u=arguments[0];_.constructor_.call(this),this.set(u)}else if(arguments[0]instanceof _){var p=arguments[0];_.constructor_.call(this),this._matrix[$.INTERIOR][$.INTERIOR]=p._matrix[$.INTERIOR][$.INTERIOR],this._matrix[$.INTERIOR][$.BOUNDARY]=p._matrix[$.INTERIOR][$.BOUNDARY],this._matrix[$.INTERIOR][$.EXTERIOR]=p._matrix[$.INTERIOR][$.EXTERIOR],this._matrix[$.BOUNDARY][$.INTERIOR]=p._matrix[$.BOUNDARY][$.INTERIOR],this._matrix[$.BOUNDARY][$.BOUNDARY]=p._matrix[$.BOUNDARY][$.BOUNDARY],this._matrix[$.BOUNDARY][$.EXTERIOR]=p._matrix[$.BOUNDARY][$.EXTERIOR],this._matrix[$.EXTERIOR][$.INTERIOR]=p._matrix[$.EXTERIOR][$.INTERIOR],this._matrix[$.EXTERIOR][$.BOUNDARY]=p._matrix[$.EXTERIOR][$.BOUNDARY],this._matrix[$.EXTERIOR][$.EXTERIOR]=p._matrix[$.EXTERIOR][$.EXTERIOR]}}}},{key:"matches",value:function(){if(Number.isInteger(arguments[0])&&typeof arguments[1]=="string"){var u=arguments[0],p=arguments[1];return p===Ne.SYM_DONTCARE||p===Ne.SYM_TRUE&&(u>=0||u===Ne.TRUE)||p===Ne.SYM_FALSE&&u===Ne.FALSE||p===Ne.SYM_P&&u===Ne.P||p===Ne.SYM_L&&u===Ne.L||p===Ne.SYM_A&&u===Ne.A}if(typeof arguments[0]=="string"&&typeof arguments[1]=="string"){var g=arguments[1];return new _(arguments[0]).matches(g)}}},{key:"isTrue",value:function(u){return u>=0||u===Ne.TRUE}}])})(),jF=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"size",value:function(){return this._size}},{key:"addAll",value:function(u){return u===null||u.length===0?null:(this.ensureCapacity(this._size+u.length),xt.arraycopy(u,0,this._data,this._size,u.length),void(this._size+=u.length))}},{key:"ensureCapacity",value:function(u){if(u<=this._data.length)return null;var p=Math.max(u,2*this._data.length);this._data=le.copyOf(this._data,p)}},{key:"toArray",value:function(){var u=new Array(this._size).fill(null);return xt.arraycopy(this._data,0,u,0,this._size),u}},{key:"add",value:function(u){this.ensureCapacity(this._size+1),this._data[this._size]=u,++this._size}}],[{key:"constructor_",value:function(){if(this._data=null,this._size=0,arguments.length===0)_.constructor_.call(this,10);else if(arguments.length===1){var u=arguments[0];this._data=new Array(u).fill(null)}}}])})(),XF=(function(){function _(){s(this,_)}return o(_,[{key:"getChainStartIndices",value:function(u){var p=0,g=new jF(Math.trunc(u.length/2));g.add(p);do{var E=this.findChainEnd(u,p);g.add(E),p=E}while(p<u.length-1);return g.toArray()}},{key:"findChainEnd",value:function(u,p){for(var g=Ts.quadrant(u[p],u[p+1]),E=p+1;E<u.length&&Ts.quadrant(u[E-1],u[E])===g;)E++;return E-1}},{key:"OLDgetChainStartIndices",value:function(u){var p=0,g=new Pe;g.add(p);do{var E=this.findChainEnd(u,p);g.add(E),p=E}while(p<u.length-1);return _.toIntArray(g)}}],[{key:"toIntArray",value:function(u){for(var p=new Array(u.size()).fill(null),g=0;g<p.length;g++)p[g]=u.get(g).intValue();return p}}])})(),ZF=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"getCoordinates",value:function(){return this.pts}},{key:"getMaxX",value:function(_){var u=this.pts[this.startIndex[_]].x,p=this.pts[this.startIndex[_+1]].x;return u>p?u:p}},{key:"getMinX",value:function(_){var u=this.pts[this.startIndex[_]].x,p=this.pts[this.startIndex[_+1]].x;return u<p?u:p}},{key:"computeIntersectsForChain",value:function(){if(arguments.length===4){var _=arguments[0],u=arguments[1],p=arguments[2],g=arguments[3];this.computeIntersectsForChain(this.startIndex[_],this.startIndex[_+1],u,u.startIndex[p],u.startIndex[p+1],g)}else if(arguments.length===6){var E=arguments[0],B=arguments[1],F=arguments[2],G=arguments[3],Y=arguments[4],ae=arguments[5];if(B-E==1&&Y-G==1)return ae.addIntersections(this.e,E,F.e,G),null;if(!this.overlaps(E,B,F,G,Y))return null;var xe=Math.trunc((E+B)/2),Ie=Math.trunc((G+Y)/2);E<xe&&(G<Ie&&this.computeIntersectsForChain(E,xe,F,G,Ie,ae),Ie<Y&&this.computeIntersectsForChain(E,xe,F,Ie,Y,ae)),xe<B&&(G<Ie&&this.computeIntersectsForChain(xe,B,F,G,Ie,ae),Ie<Y&&this.computeIntersectsForChain(xe,B,F,Ie,Y,ae))}}},{key:"overlaps",value:function(_,u,p,g,E){return fe.intersects(this.pts[_],this.pts[u],p.pts[g],p.pts[E])}},{key:"getStartIndexes",value:function(){return this.startIndex}},{key:"computeIntersects",value:function(_,u){for(var p=0;p<this.startIndex.length-1;p++)for(var g=0;g<_.startIndex.length-1;g++)this.computeIntersectsForChain(p,_,g,u)}}],[{key:"constructor_",value:function(){this.e=null,this.pts=null,this.startIndex=null;var _=arguments[0];this.e=_,this.pts=_.getCoordinates();var u=new XF;this.startIndex=u.getChainStartIndices(this.pts)}}])})(),Tw=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"getDepth",value:function(u,p){return this._depth[u][p]}},{key:"setDepth",value:function(u,p,g){this._depth[u][p]=g}},{key:"isNull",value:function(){if(arguments.length===0){for(var u=0;u<2;u++)for(var p=0;p<3;p++)if(this._depth[u][p]!==_.NULL_VALUE)return!1;return!0}if(arguments.length===1){var g=arguments[0];return this._depth[g][1]===_.NULL_VALUE}if(arguments.length===2){var E=arguments[0],B=arguments[1];return this._depth[E][B]===_.NULL_VALUE}}},{key:"normalize",value:function(){for(var u=0;u<2;u++)if(!this.isNull(u)){var p=this._depth[u][1];this._depth[u][2]<p&&(p=this._depth[u][2]),p<0&&(p=0);for(var g=1;g<3;g++){var E=0;this._depth[u][g]>p&&(E=1),this._depth[u][g]=E}}}},{key:"getDelta",value:function(u){return this._depth[u][q.RIGHT]-this._depth[u][q.LEFT]}},{key:"getLocation",value:function(u,p){return this._depth[u][p]<=0?$.EXTERIOR:$.INTERIOR}},{key:"toString",value:function(){return"A: "+this._depth[0][1]+","+this._depth[0][2]+" B: "+this._depth[1][1]+","+this._depth[1][2]}},{key:"add",value:function(){if(arguments.length===1)for(var u=arguments[0],p=0;p<2;p++)for(var g=1;g<3;g++){var E=u.getLocation(p,g);E!==$.EXTERIOR&&E!==$.INTERIOR||(this.isNull(p,g)?this._depth[p][g]=_.depthAtLocation(E):this._depth[p][g]+=_.depthAtLocation(E))}else if(arguments.length===3){var B=arguments[0],F=arguments[1];arguments[2]===$.INTERIOR&&this._depth[B][F]++}}}],[{key:"constructor_",value:function(){this._depth=Array(2).fill().map((function(){return Array(3)}));for(var u=0;u<2;u++)for(var p=0;p<3;p++)this._depth[u][p]=_.NULL_VALUE}},{key:"depthAtLocation",value:function(u){return u===$.EXTERIOR?0:u===$.INTERIOR?1:_.NULL_VALUE}}])})();Tw.NULL_VALUE=-1;var Lw=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,[{key:"getDepth",value:function(){return this._depth}},{key:"getCollapsedEdge",value:function(){var p=new Array(2).fill(null);return p[0]=this.pts[0],p[1]=this.pts[1],new u(p,Sr.toLineLabel(this._label))}},{key:"isIsolated",value:function(){return this._isIsolated}},{key:"getCoordinates",value:function(){return this.pts}},{key:"setIsolated",value:function(p){this._isIsolated=p}},{key:"setName",value:function(p){this._name=p}},{key:"equals",value:function(p){if(!(p instanceof u))return!1;var g=p;if(this.pts.length!==g.pts.length)return!1;for(var E=!0,B=!0,F=this.pts.length,G=0;G<this.pts.length;G++)if(this.pts[G].equals2D(g.pts[G])||(E=!1),this.pts[G].equals2D(g.pts[--F])||(B=!1),!E&&!B)return!1;return!0}},{key:"getCoordinate",value:function(){if(arguments.length===0)return this.pts.length>0?this.pts[0]:null;if(arguments.length===1){var p=arguments[0];return this.pts[p]}}},{key:"print",value:function(p){p.print("edge "+this._name+": "),p.print("LINESTRING (");for(var g=0;g<this.pts.length;g++)g>0&&p.print(","),p.print(this.pts[g].x+" "+this.pts[g].y);p.print(") "+this._label+" "+this._depthDelta)}},{key:"computeIM",value:function(p){u.updateIM(this._label,p)}},{key:"isCollapsed",value:function(){return!!this._label.isArea()&&this.pts.length===3&&!!this.pts[0].equals(this.pts[2])}},{key:"isClosed",value:function(){return this.pts[0].equals(this.pts[this.pts.length-1])}},{key:"getMaximumSegmentIndex",value:function(){return this.pts.length-1}},{key:"getDepthDelta",value:function(){return this._depthDelta}},{key:"getNumPoints",value:function(){return this.pts.length}},{key:"printReverse",value:function(p){p.print("edge "+this._name+": ");for(var g=this.pts.length-1;g>=0;g--)p.print(this.pts[g]+" ");p.println("")}},{key:"getMonotoneChainEdge",value:function(){return this._mce===null&&(this._mce=new ZF(this)),this._mce}},{key:"getEnvelope",value:function(){if(this._env===null){this._env=new fe;for(var p=0;p<this.pts.length;p++)this._env.expandToInclude(this.pts[p])}return this._env}},{key:"addIntersection",value:function(p,g,E,B){var F=new ie(p.getIntersection(B)),G=g,Y=p.getEdgeDistance(E,B),ae=G+1;if(ae<this.pts.length){var xe=this.pts[ae];F.equals2D(xe)&&(G=ae,Y=0)}this.eiList.add(F,G,Y)}},{key:"toString",value:function(){var p=new we;p.append("edge "+this._name+": "),p.append("LINESTRING (");for(var g=0;g<this.pts.length;g++)g>0&&p.append(","),p.append(this.pts[g].x+" "+this.pts[g].y);return p.append(") "+this._label+" "+this._depthDelta),p.toString()}},{key:"isPointwiseEqual",value:function(p){if(this.pts.length!==p.pts.length)return!1;for(var g=0;g<this.pts.length;g++)if(!this.pts[g].equals2D(p.pts[g]))return!1;return!0}},{key:"setDepthDelta",value:function(p){this._depthDelta=p}},{key:"getEdgeIntersectionList",value:function(){return this.eiList}},{key:"addIntersections",value:function(p,g,E){for(var B=0;B<p.getIntersectionNum();B++)this.addIntersection(p,g,E,B)}}],[{key:"constructor_",value:function(){if(this.pts=null,this._env=null,this.eiList=new WF(this),this._name=null,this._mce=null,this._isIsolated=!0,this._depth=new Tw,this._depthDelta=0,arguments.length===1){var p=arguments[0];u.constructor_.call(this,p,null)}else if(arguments.length===2){var g=arguments[0],E=arguments[1];this.pts=g,this._label=E}}},{key:"updateIM",value:function(){if(!(arguments.length===2&&arguments[1]instanceof YF&&arguments[0]instanceof Sr))return A(u,"updateIM",this).apply(this,arguments);var p=arguments[0],g=arguments[1];g.setAtLeastIfValid(p.getLocation(0,q.ON),p.getLocation(1,q.ON),1),p.isArea()&&(g.setAtLeastIfValid(p.getLocation(0,q.LEFT),p.getLocation(1,q.LEFT),2),g.setAtLeastIfValid(p.getLocation(0,q.RIGHT),p.getLocation(1,q.RIGHT),2))}}])})(hw),Bw=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"setWorkingPrecisionModel",value:function(u){this._workingPrecisionModel=u}},{key:"insertUniqueEdge",value:function(u){var p=this._edgeList.findEqualEdge(u);if(p!==null){var g=p.getLabel(),E=u.getLabel();p.isPointwiseEqual(u)||(E=new Sr(u.getLabel())).flip(),g.merge(E);var B=_.depthDelta(E),F=p.getDepthDelta()+B;p.setDepthDelta(F)}else this._edgeList.add(u),u.setDepthDelta(_.depthDelta(u.getLabel()))}},{key:"buildSubgraphs",value:function(u,p){for(var g=new Pe,E=u.iterator();E.hasNext();){var B=E.next(),F=B.getRightmostCoordinate(),G=new Cw(g).getDepth(F);B.computeDepth(G),B.findResultEdges(),g.add(B),p.add(B.getDirectedEdges(),B.getNodes())}}},{key:"createSubgraphs",value:function(u){for(var p=new Pe,g=u.getNodes().iterator();g.hasNext();){var E=g.next();if(!E.isVisited()){var B=new at;B.create(E),p.add(B)}}return Zc.sort(p,Zc.reverseOrder()),p}},{key:"createEmptyResultGeometry",value:function(){return this._geomFact.createPolygon()}},{key:"getNoder",value:function(u){if(this._workingNoder!==null)return this._workingNoder;var p=new cv,g=new ql;return g.setPrecisionModel(u),p.setSegmentIntersector(new VF(g)),p}},{key:"buffer",value:function(u,p){var g=this._workingPrecisionModel;g===null&&(g=u.getPrecisionModel()),this._geomFact=u.getFactory();var E=new OF(u,p,new DF(g,this._bufParams)).getCurves();if(E.size()<=0)return this.createEmptyResultGeometry();this.computeNodedEdges(E,g),this._graph=new gw(new HF),this._graph.addEdges(this._edgeList.getEdges());var B=this.createSubgraphs(this._graph),F=new EF(this._geomFact);this.buildSubgraphs(B,F);var G=F.getPolygons();return G.size()<=0?this.createEmptyResultGeometry():this._geomFact.buildGeometry(G)}},{key:"computeNodedEdges",value:function(u,p){var g=this.getNoder(p);g.computeNodes(u);for(var E=g.getNodedSubstrings().iterator();E.hasNext();){var B=E.next(),F=B.getCoordinates();if(F.length!==2||!F[0].equals2D(F[1])){var G=B.getData(),Y=new Lw(B.getCoordinates(),new Sr(G));this.insertUniqueEdge(Y)}}}},{key:"setNoder",value:function(u){this._workingNoder=u}}],[{key:"constructor_",value:function(){this._bufParams=null,this._workingPrecisionModel=null,this._workingNoder=null,this._geomFact=null,this._graph=null,this._edgeList=new $F;var u=arguments[0];this._bufParams=u}},{key:"depthDelta",value:function(u){var p=u.getLocation(0,q.LEFT),g=u.getLocation(0,q.RIGHT);return p===$.INTERIOR&&g===$.EXTERIOR?1:p===$.EXTERIOR&&g===$.INTERIOR?-1:0}},{key:"convertSegStrings",value:function(u){for(var p=new Pt,g=new Pe;u.hasNext();){var E=u.next(),B=p.createLineString(E.getCoordinates());g.add(B)}return p.buildGeometry(g)}}])})(),JF=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"rescale",value:function(){if(X(arguments[0],Se))for(var u=arguments[0].iterator();u.hasNext();){var p=u.next();this.rescale(p.getCoordinates())}else if(arguments[0]instanceof Array){for(var g=arguments[0],E=0;E<g.length;E++)g[E].x=g[E].x/this._scaleFactor+this._offsetX,g[E].y=g[E].y/this._scaleFactor+this._offsetY;g.length===2&&g[0].equals2D(g[1])&&xt.out.println(g)}}},{key:"scale",value:function(){if(X(arguments[0],Se)){for(var u=arguments[0],p=new Pe(u.size()),g=u.iterator();g.hasNext();){var E=g.next();p.add(new Wl(this.scale(E.getCoordinates()),E.getData()))}return p}if(arguments[0]instanceof Array){for(var B=arguments[0],F=new Array(B.length).fill(null),G=0;G<B.length;G++)F[G]=new ie(Math.round((B[G].x-this._offsetX)*this._scaleFactor),Math.round((B[G].y-this._offsetY)*this._scaleFactor),B[G].getZ());return In.removeRepeatedPoints(F)}}},{key:"isIntegerPrecision",value:function(){return this._scaleFactor===1}},{key:"getNodedSubstrings",value:function(){var u=this._noder.getNodedSubstrings();return this._isScaled&&this.rescale(u),u}},{key:"computeNodes",value:function(u){var p=u;this._isScaled&&(p=this.scale(u)),this._noder.computeNodes(p)}},{key:"interfaces_",get:function(){return[lv]}}],[{key:"constructor_",value:function(){if(this._noder=null,this._scaleFactor=null,this._offsetX=null,this._offsetY=null,this._isScaled=!1,arguments.length===2){var u=arguments[0],p=arguments[1];_.constructor_.call(this,u,p,0,0)}else if(arguments.length===4){var g=arguments[0],E=arguments[1];this._noder=g,this._scaleFactor=E,this._isScaled=!this.isIntegerPrecision()}}}])})(),Rw=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"checkEndPtVertexIntersections",value:function(){if(arguments.length===0)for(var u=this._segStrings.iterator();u.hasNext();){var p=u.next().getCoordinates();this.checkEndPtVertexIntersections(p[0],this._segStrings),this.checkEndPtVertexIntersections(p[p.length-1],this._segStrings)}else if(arguments.length===2){for(var g=arguments[0],E=arguments[1].iterator();E.hasNext();)for(var B=E.next().getCoordinates(),F=1;F<B.length-1;F++)if(B[F].equals(g))throw new J("found endpt/interior pt intersection at index "+F+" :pt "+g)}}},{key:"checkInteriorIntersections",value:function(){if(arguments.length===0)for(var u=this._segStrings.iterator();u.hasNext();)for(var p=u.next(),g=this._segStrings.iterator();g.hasNext();){var E=g.next();this.checkInteriorIntersections(p,E)}else if(arguments.length===2)for(var B=arguments[0],F=arguments[1],G=B.getCoordinates(),Y=F.getCoordinates(),ae=0;ae<G.length-1;ae++)for(var xe=0;xe<Y.length-1;xe++)this.checkInteriorIntersections(B,ae,F,xe);else if(arguments.length===4){var Ie=arguments[0],Ge=arguments[1],ut=arguments[2],Rt=arguments[3];if(Ie===ut&&Ge===Rt)return null;var Ft=Ie.getCoordinates()[Ge],vn=Ie.getCoordinates()[Ge+1],pn=ut.getCoordinates()[Rt],Dn=ut.getCoordinates()[Rt+1];if(this._li.computeIntersection(Ft,vn,pn,Dn),this._li.hasIntersection()&&(this._li.isProper()||this.hasInteriorIntersection(this._li,Ft,vn)||this.hasInteriorIntersection(this._li,pn,Dn)))throw new J("found non-noded intersection at "+Ft+"-"+vn+" and "+pn+"-"+Dn)}}},{key:"checkValid",value:function(){this.checkEndPtVertexIntersections(),this.checkInteriorIntersections(),this.checkCollapses()}},{key:"checkCollapses",value:function(){if(arguments.length===0)for(var u=this._segStrings.iterator();u.hasNext();){var p=u.next();this.checkCollapses(p)}else if(arguments.length===1)for(var g=arguments[0].getCoordinates(),E=0;E<g.length-2;E++)this.checkCollapse(g[E],g[E+1],g[E+2])}},{key:"hasInteriorIntersection",value:function(u,p,g){for(var E=0;E<u.getIntersectionNum();E++){var B=u.getIntersection(E);if(!B.equals(p)&&!B.equals(g))return!0}return!1}},{key:"checkCollapse",value:function(u,p,g){if(u.equals(g))throw new J("found non-noded collapse at "+_.fact.createLineString([u,p,g]))}}],[{key:"constructor_",value:function(){this._li=new ql,this._segStrings=null;var u=arguments[0];this._segStrings=u}}])})();Rw.fact=new Pt;var uv=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"intersectsScaled",value:function(u,p){var g=Math.min(u.x,p.x),E=Math.max(u.x,p.x),B=Math.min(u.y,p.y),F=Math.max(u.y,p.y),G=this._maxx<g||this._minx>E||this._maxy<B||this._miny>F;if(G)return!1;var Y=this.intersectsToleranceSquare(u,p);return re.isTrue(!(G&&Y),"Found bad envelope test"),Y}},{key:"initCorners",value:function(u){var p=.5;this._minx=u.x-p,this._maxx=u.x+p,this._miny=u.y-p,this._maxy=u.y+p,this._corner[0]=new ie(this._maxx,this._maxy),this._corner[1]=new ie(this._minx,this._maxy),this._corner[2]=new ie(this._minx,this._miny),this._corner[3]=new ie(this._maxx,this._miny)}},{key:"intersects",value:function(u,p){return this._scaleFactor===1?this.intersectsScaled(u,p):(this.copyScaled(u,this._p0Scaled),this.copyScaled(p,this._p1Scaled),this.intersectsScaled(this._p0Scaled,this._p1Scaled))}},{key:"scale",value:function(u){return Math.round(u*this._scaleFactor)}},{key:"getCoordinate",value:function(){return this._originalPt}},{key:"copyScaled",value:function(u,p){p.x=this.scale(u.x),p.y=this.scale(u.y)}},{key:"getSafeEnvelope",value:function(){if(this._safeEnv===null){var u=_.SAFE_ENV_EXPANSION_FACTOR/this._scaleFactor;this._safeEnv=new fe(this._originalPt.x-u,this._originalPt.x+u,this._originalPt.y-u,this._originalPt.y+u)}return this._safeEnv}},{key:"intersectsPixelClosure",value:function(u,p){return this._li.computeIntersection(u,p,this._corner[0],this._corner[1]),!!this._li.hasIntersection()||(this._li.computeIntersection(u,p,this._corner[1],this._corner[2]),!!this._li.hasIntersection()||(this._li.computeIntersection(u,p,this._corner[2],this._corner[3]),!!this._li.hasIntersection()||(this._li.computeIntersection(u,p,this._corner[3],this._corner[0]),!!this._li.hasIntersection())))}},{key:"intersectsToleranceSquare",value:function(u,p){var g=!1,E=!1;return this._li.computeIntersection(u,p,this._corner[0],this._corner[1]),!!this._li.isProper()||(this._li.computeIntersection(u,p,this._corner[1],this._corner[2]),!!this._li.isProper()||(this._li.hasIntersection()&&(g=!0),this._li.computeIntersection(u,p,this._corner[2],this._corner[3]),!!this._li.isProper()||(this._li.hasIntersection()&&(E=!0),this._li.computeIntersection(u,p,this._corner[3],this._corner[0]),!!this._li.isProper()||!(!g||!E)||!!u.equals(this._pt)||!!p.equals(this._pt))))}},{key:"addSnappedNode",value:function(u,p){var g=u.getCoordinate(p),E=u.getCoordinate(p+1);return!!this.intersects(g,E)&&(u.addIntersection(this.getCoordinate(),p),!0)}}],[{key:"constructor_",value:function(){this._li=null,this._pt=null,this._originalPt=null,this._ptScaled=null,this._p0Scaled=null,this._p1Scaled=null,this._scaleFactor=null,this._minx=null,this._maxx=null,this._miny=null,this._maxy=null,this._corner=new Array(4).fill(null),this._safeEnv=null;var u=arguments[0],p=arguments[1],g=arguments[2];if(this._originalPt=u,this._pt=u,this._scaleFactor=p,this._li=g,p<=0)throw new R("Scale factor must be non-zero");p!==1&&(this._pt=new ie(this.scale(u.x),this.scale(u.y)),this._p0Scaled=new ie,this._p1Scaled=new ie),this.initCorners(this._pt)}}])})();uv.SAFE_ENV_EXPANSION_FACTOR=.75;var KF=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"select",value:function(){if(arguments.length!==1){if(arguments.length===2){var _=arguments[1];arguments[0].getLineSegment(_,this.selectedSegment),this.select(this.selectedSegment)}}}}],[{key:"constructor_",value:function(){this.selectedSegment=new cr}}])})(),kw=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"snap",value:function(){if(arguments.length===1){var _=arguments[0];return this.snap(_,null,-1)}if(arguments.length===3){var u=arguments[0],p=arguments[1],g=arguments[2],E=u.getSafeEnvelope(),B=new Nw(u,p,g);return this._index.query(E,new((function(){return o((function F(){s(this,F)}),[{key:"interfaces_",get:function(){return[Aw]}},{key:"visitItem",value:function(F){F.select(E,B)}}])})())),B.isNodeAdded()}}}],[{key:"constructor_",value:function(){this._index=null;var _=arguments[0];this._index=_}}])})(),Nw=(function(_){function u(){var p;return s(this,u),p=i(this,u),u.constructor_.apply(p,arguments),p}return d(u,_),o(u,[{key:"isNodeAdded",value:function(){return this._isNodeAdded}},{key:"select",value:function(){if(!(arguments.length===2&&Number.isInteger(arguments[1])&&arguments[0]instanceof yw))return A(u,"select",this,1).apply(this,arguments);var p=arguments[1],g=arguments[0].getContext();if(this._parentEdge===g&&(p===this._hotPixelVertexIndex||p+1===this._hotPixelVertexIndex))return null;this._isNodeAdded|=this._hotPixel.addSnappedNode(g,p)}}],[{key:"constructor_",value:function(){this._hotPixel=null,this._parentEdge=null,this._hotPixelVertexIndex=null,this._isNodeAdded=!1;var p=arguments[0],g=arguments[1],E=arguments[2];this._hotPixel=p,this._parentEdge=g,this._hotPixelVertexIndex=E}}])})(KF);kw.HotPixelSnapAction=Nw;var eO=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"processIntersections",value:function(_,u,p,g){if(_===p&&u===g)return null;var E=_.getCoordinates()[u],B=_.getCoordinates()[u+1],F=p.getCoordinates()[g],G=p.getCoordinates()[g+1];if(this._li.computeIntersection(E,B,F,G),this._li.hasIntersection()&&this._li.isInteriorIntersection()){for(var Y=0;Y<this._li.getIntersectionNum();Y++)this._interiorIntersections.add(this._li.getIntersection(Y));_.addIntersections(this._li,u,0),p.addIntersections(this._li,g,1)}}},{key:"isDone",value:function(){return!1}},{key:"getInteriorIntersections",value:function(){return this._interiorIntersections}},{key:"interfaces_",get:function(){return[Mw]}}],[{key:"constructor_",value:function(){this._li=null,this._interiorIntersections=null;var _=arguments[0];this._li=_,this._interiorIntersections=new Pe}}])})(),tO=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"checkCorrectness",value:function(_){var u=new Rw(Wl.getNodedSubstrings(_));try{u.checkValid()}catch(p){if(!(p instanceof S))throw p;p.printStackTrace()}}},{key:"getNodedSubstrings",value:function(){return Wl.getNodedSubstrings(this._nodedSegStrings)}},{key:"snapRound",value:function(_,u){var p=this.findInteriorIntersections(_,u);this.computeIntersectionSnaps(p),this.computeVertexSnaps(_)}},{key:"findInteriorIntersections",value:function(_,u){var p=new eO(u);return this._noder.setSegmentIntersector(p),this._noder.computeNodes(_),p.getInteriorIntersections()}},{key:"computeVertexSnaps",value:function(){if(X(arguments[0],Se))for(var _=arguments[0].iterator();_.hasNext();){var u=_.next();this.computeVertexSnaps(u)}else if(arguments[0]instanceof Wl)for(var p=arguments[0],g=p.getCoordinates(),E=0;E<g.length;E++){var B=new uv(g[E],this._scaleFactor,this._li);this._pointSnapper.snap(B,p,E)&&p.addIntersection(g[E],E)}}},{key:"computeNodes",value:function(_){this._nodedSegStrings=_,this._noder=new cv,this._pointSnapper=new kw(this._noder.getIndex()),this.snapRound(_,this._li)}},{key:"computeIntersectionSnaps",value:function(_){for(var u=_.iterator();u.hasNext();){var p=new uv(u.next(),this._scaleFactor,this._li);this._pointSnapper.snap(p)}}},{key:"interfaces_",get:function(){return[lv]}}],[{key:"constructor_",value:function(){this._pm=null,this._li=null,this._scaleFactor=null,this._noder=null,this._pointSnapper=null,this._nodedSegStrings=null;var _=arguments[0];this._pm=_,this._li=new ql,this._li.setPrecisionModel(_),this._scaleFactor=_.getScale()}}])})(),eh=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"bufferFixedPrecision",value:function(u){var p=new JF(new tO(new ct(1)),u.getScale()),g=new Bw(this._bufParams);g.setWorkingPrecisionModel(u),g.setNoder(p),this._resultGeometry=g.buffer(this._argGeom,this._distance)}},{key:"bufferReducedPrecision",value:function(){if(arguments.length===0){for(var u=_.MAX_PRECISION_DIGITS;u>=0;u--){try{this.bufferReducedPrecision(u)}catch(E){if(!(E instanceof Ye))throw E;this._saveException=E}if(this._resultGeometry!==null)return null}throw this._saveException}if(arguments.length===1){var p=arguments[0],g=new ct(_.precisionScaleFactor(this._argGeom,this._distance,p));this.bufferFixedPrecision(g)}}},{key:"computeGeometry",value:function(){if(this.bufferOriginalPrecision(),this._resultGeometry!==null)return null;var u=this._argGeom.getFactory().getPrecisionModel();u.getType()===ct.FIXED?this.bufferFixedPrecision(u):this.bufferReducedPrecision()}},{key:"setQuadrantSegments",value:function(u){this._bufParams.setQuadrantSegments(u)}},{key:"bufferOriginalPrecision",value:function(){try{var u=new Bw(this._bufParams);this._resultGeometry=u.buffer(this._argGeom,this._distance)}catch(p){if(!(p instanceof J))throw p;this._saveException=p}}},{key:"getResultGeometry",value:function(u){return this._distance=u,this.computeGeometry(),this._resultGeometry}},{key:"setEndCapStyle",value:function(u){this._bufParams.setEndCapStyle(u)}}],[{key:"constructor_",value:function(){if(this._argGeom=null,this._distance=null,this._bufParams=new w,this._resultGeometry=null,this._saveException=null,arguments.length===1){var u=arguments[0];this._argGeom=u}else if(arguments.length===2){var p=arguments[0],g=arguments[1];this._argGeom=p,this._bufParams=g}}},{key:"bufferOp",value:function(){if(arguments.length===2){var u=arguments[1];return new _(arguments[0]).getResultGeometry(u)}if(arguments.length===3){if(Number.isInteger(arguments[2])&&arguments[0]instanceof ye&&typeof arguments[1]=="number"){var p=arguments[1],g=arguments[2],E=new _(arguments[0]);return E.setQuadrantSegments(g),E.getResultGeometry(p)}if(arguments[2]instanceof w&&arguments[0]instanceof ye&&typeof arguments[1]=="number"){var B=arguments[1];return new _(arguments[0],arguments[2]).getResultGeometry(B)}}else if(arguments.length===4){var F=arguments[1],G=arguments[2],Y=arguments[3],ae=new _(arguments[0]);return ae.setQuadrantSegments(G),ae.setEndCapStyle(Y),ae.getResultGeometry(F)}}},{key:"precisionScaleFactor",value:function(u,p,g){var E=u.getEnvelopeInternal(),B=me.max(Math.abs(E.getMaxX()),Math.abs(E.getMaxY()),Math.abs(E.getMinX()),Math.abs(E.getMinY()))+2*(p>0?p:0),F=g-Math.trunc(Math.log(B)/Math.log(10)+1);return Math.pow(10,F)}}])})();eh.CAP_ROUND=w.CAP_ROUND,eh.CAP_BUTT=w.CAP_FLAT,eh.CAP_FLAT=w.CAP_FLAT,eh.CAP_SQUARE=w.CAP_SQUARE,eh.MAX_PRECISION_DIGITS=12;var nO=["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon"],Pw=(function(){return o((function _(u){s(this,_),this.geometryFactory=u||new Pt}),[{key:"read",value:function(_){var u,p=(u=typeof _=="string"?JSON.parse(_):_).type;if(!Mr[p])throw new Error("Unknown GeoJSON type: "+u.type);return nO.indexOf(p)!==-1?Mr[p].call(this,u.coordinates):p==="GeometryCollection"?Mr[p].call(this,u.geometries):Mr[p].call(this,u)}},{key:"write",value:function(_){var u=_.getGeometryType();if(!Ca[u])throw new Error("Geometry is not supported");return Ca[u].call(this,_)}}])})(),Mr={Feature:function(_){var u={};for(var p in _)u[p]=_[p];if(_.geometry){if(!Mr[_.geometry.type])throw new Error("Unknown GeoJSON type: "+_.type);u.geometry=this.read(_.geometry)}return _.bbox&&(u.bbox=Mr.bbox.call(this,_.bbox)),u},FeatureCollection:function(_){var u={};if(_.features){u.features=[];for(var p=0;p<_.features.length;++p)u.features.push(this.read(_.features[p]))}return _.bbox&&(u.bbox=this.parse.bbox.call(this,_.bbox)),u},coordinates:function(_){for(var u=[],p=0;p<_.length;++p){var g=_[p];u.push(r(ie,y(g)))}return u},bbox:function(_){return this.geometryFactory.createLinearRing([new ie(_[0],_[1]),new ie(_[2],_[1]),new ie(_[2],_[3]),new ie(_[0],_[3]),new ie(_[0],_[1])])},Point:function(_){var u=r(ie,y(_));return this.geometryFactory.createPoint(u)},MultiPoint:function(_){for(var u=[],p=0;p<_.length;++p)u.push(Mr.Point.call(this,_[p]));return this.geometryFactory.createMultiPoint(u)},LineString:function(_){var u=Mr.coordinates.call(this,_);return this.geometryFactory.createLineString(u)},MultiLineString:function(_){for(var u=[],p=0;p<_.length;++p)u.push(Mr.LineString.call(this,_[p]));return this.geometryFactory.createMultiLineString(u)},Polygon:function(_){for(var u=Mr.coordinates.call(this,_[0]),p=this.geometryFactory.createLinearRing(u),g=[],E=1;E<_.length;++E){var B=_[E],F=Mr.coordinates.call(this,B),G=this.geometryFactory.createLinearRing(F);g.push(G)}return this.geometryFactory.createPolygon(p,g)},MultiPolygon:function(_){for(var u=[],p=0;p<_.length;++p){var g=_[p];u.push(Mr.Polygon.call(this,g))}return this.geometryFactory.createMultiPolygon(u)},GeometryCollection:function(_){for(var u=[],p=0;p<_.length;++p){var g=_[p];u.push(this.read(g))}return this.geometryFactory.createGeometryCollection(u)}},Ca={coordinate:function(_){var u=[_.x,_.y];return _.z&&u.push(_.z),_.m&&u.push(_.m),u},Point:function(_){return{type:"Point",coordinates:Ca.coordinate.call(this,_.getCoordinate())}},MultiPoint:function(_){for(var u=[],p=0;p<_._geometries.length;++p){var g=_._geometries[p],E=Ca.Point.call(this,g);u.push(E.coordinates)}return{type:"MultiPoint",coordinates:u}},LineString:function(_){for(var u=[],p=_.getCoordinates(),g=0;g<p.length;++g){var E=p[g];u.push(Ca.coordinate.call(this,E))}return{type:"LineString",coordinates:u}},MultiLineString:function(_){for(var u=[],p=0;p<_._geometries.length;++p){var g=_._geometries[p],E=Ca.LineString.call(this,g);u.push(E.coordinates)}return{type:"MultiLineString",coordinates:u}},Polygon:function(_){var u=[],p=Ca.LineString.call(this,_._shell);u.push(p.coordinates);for(var g=0;g<_._holes.length;++g){var E=_._holes[g],B=Ca.LineString.call(this,E);u.push(B.coordinates)}return{type:"Polygon",coordinates:u}},MultiPolygon:function(_){for(var u=[],p=0;p<_._geometries.length;++p){var g=_._geometries[p],E=Ca.Polygon.call(this,g);u.push(E.coordinates)}return{type:"MultiPolygon",coordinates:u}},GeometryCollection:function(_){for(var u=[],p=0;p<_._geometries.length;++p){var g=_._geometries[p],E=g.getGeometryType();u.push(Ca[E].call(this,g))}return{type:"GeometryCollection",geometries:u}}};return{BufferOp:eh,GeoJSONReader:(function(){return o((function _(u){s(this,_),this.parser=new Pw(u||new Pt)}),[{key:"read",value:function(_){return this.parser.read(_)}}])})(),GeoJSONWriter:(function(){return o((function _(){s(this,_),this.parser=new Pw(this.geometryFactory)}),[{key:"write",value:function(_){return this.parser.write(_)}}])})()}}))})(zg)),zg.exports}var $Q=Q2(HQ());function Hl(){return new x_}function x_(){this.reset()}x_.prototype={constructor:x_,reset:function(){this.s=this.t=0},add:function(e){CS(tm,e,this.t),CS(this,tm.s,this.s),this.s?this.t+=tm.t:this.s=tm.t},valueOf:function(){return this.s}};var tm=new x_;function CS(e,t,n){var i=e.s=t+n,s=i-t;e.t=t-(i-s)+(n-s)}var Wn=1e-6,gn=Math.PI,Pa=gn/2,wS=gn/4,Ga=gn*2,Yo=180/gn,Pr=gn/180,Yi=Math.abs,VQ=Math.atan,Iu=Math.atan2,hi=Math.cos,ui=Math.sin,Zu=Math.sqrt;function q2(e){return e>1?0:e<-1?gn:Math.acos(e)}function Rc(e){return e>1?Pa:e<-1?-Pa:Math.asin(e)}function qd(){}function E_(e,t){e&&IS.hasOwnProperty(e.type)&&IS[e.type](e,t)}var SS={Feature:function(e,t){E_(e.geometry,t)},FeatureCollection:function(e,t){for(var n=e.features,i=-1,s=n.length;++i<s;)E_(n[i].geometry,t)}},IS={Sphere:function(e,t){t.sphere()},Point:function(e,t){e=e.coordinates,t.point(e[0],e[1],e[2])},MultiPoint:function(e,t){for(var n=e.coordinates,i=-1,s=n.length;++i<s;)e=n[i],t.point(e[0],e[1],e[2])},LineString:function(e,t){ib(e.coordinates,t,0)},MultiLineString:function(e,t){for(var n=e.coordinates,i=-1,s=n.length;++i<s;)ib(n[i],t,0)},Polygon:function(e,t){MS(e.coordinates,t)},MultiPolygon:function(e,t){for(var n=e.coordinates,i=-1,s=n.length;++i<s;)MS(n[i],t)},GeometryCollection:function(e,t){for(var n=e.geometries,i=-1,s=n.length;++i<s;)E_(n[i],t)}};function ib(e,t,n){var i=-1,s=e.length-n,r;for(t.lineStart();++i<s;)r=e[i],t.point(r[0],r[1],r[2]);t.lineEnd()}function MS(e,t){var n=-1,i=e.length;for(t.polygonStart();++n<i;)ib(e[n],t,1);t.polygonEnd()}function qQ(e,t){e&&SS.hasOwnProperty(e.type)?SS[e.type](e,t):E_(e,t)}Hl();Hl();function sb(e){return[Iu(e[1],e[0]),Rc(e[2])]}function Mu(e){var t=e[0],n=e[1],i=hi(n);return[i*hi(t),i*ui(t),ui(n)]}function nm(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function C_(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function Lv(e,t){e[0]+=t[0],e[1]+=t[1],e[2]+=t[2]}function im(e,t){return[e[0]*t,e[1]*t,e[2]*t]}function rb(e){var t=Zu(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);e[0]/=t,e[1]/=t,e[2]/=t}Hl();function W2(e,t){function n(i,s){return i=e(i,s),t(i[0],i[1])}return e.invert&&t.invert&&(n.invert=function(i,s){return i=t.invert(i,s),i&&e.invert(i[0],i[1])}),n}function ab(e,t){return[e>gn?e-Ga:e<-gn?e+Ga:e,t]}ab.invert=ab;function WQ(e,t,n){return(e%=Ga)?t||n?W2(LS(e),BS(t,n)):LS(e):t||n?BS(t,n):ab}function TS(e){return function(t,n){return t+=e,[t>gn?t-Ga:t<-gn?t+Ga:t,n]}}function LS(e){var t=TS(e);return t.invert=TS(-e),t}function BS(e,t){var n=hi(e),i=ui(e),s=hi(t),r=ui(t);function a(o,l){var c=hi(l),h=hi(o)*c,d=ui(o)*c,f=ui(l),m=f*n+h*i;return[Iu(d*s-m*r,h*n-f*i),Rc(m*s+d*r)]}return a.invert=function(o,l){var c=hi(l),h=hi(o)*c,d=ui(o)*c,f=ui(l),m=f*s-d*r;return[Iu(d*s+f*r,h*n+m*i),Rc(m*n-h*i)]},a}function YQ(e,t,n,i,s,r){if(n){var a=hi(t),o=ui(t),l=i*n;s==null?(s=t+i*Ga,r=t-l/2):(s=RS(a,s),r=RS(a,r),(i>0?s<r:s>r)&&(s+=i*Ga));for(var c,h=s;i>0?h>r:h<r;h-=l)c=sb([a,-o*hi(h),-o*ui(h)]),e.point(c[0],c[1])}}function RS(e,t){t=Mu(t),t[0]-=e,rb(t);var n=q2(-t[1]);return((-t[2]<0?-n:n)+Ga-Wn)%Ga}function Y2(){var e=[],t;return{point:function(n,i){t.push([n,i])},lineStart:function(){e.push(t=[])},lineEnd:qd,rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))},result:function(){var n=e;return e=[],t=null,n}}}function jQ(e,t,n,i,s,r){var a=e[0],o=e[1],l=t[0],c=t[1],h=0,d=1,f=l-a,m=c-o,A=n-a;if(!(!f&&A>0)){if(A/=f,f<0){if(A<h)return;A<d&&(d=A)}else if(f>0){if(A>d)return;A>h&&(h=A)}if(A=s-a,!(!f&&A<0)){if(A/=f,f<0){if(A>d)return;A>h&&(h=A)}else if(f>0){if(A<h)return;A<d&&(d=A)}if(A=i-o,!(!m&&A>0)){if(A/=m,m<0){if(A<h)return;A<d&&(d=A)}else if(m>0){if(A>d)return;A>h&&(h=A)}if(A=r-o,!(!m&&A<0)){if(A/=m,m<0){if(A>d)return;A>h&&(h=A)}else if(m>0){if(A<h)return;A<d&&(d=A)}return h>0&&(e[0]=a+h*f,e[1]=o+h*m),d<1&&(t[0]=a+d*f,t[1]=o+d*m),!0}}}}}function Qg(e,t){return Yi(e[0]-t[0])<Wn&&Yi(e[1]-t[1])<Wn}function sm(e,t,n,i){this.x=e,this.z=t,this.o=n,this.e=i,this.v=!1,this.n=this.p=null}function j2(e,t,n,i,s){var r=[],a=[],o,l;if(e.forEach(function(A){if(!((y=A.length-1)<=0)){var y,x=A[0],v=A[y],b;if(Qg(x,v)){for(s.lineStart(),o=0;o<y;++o)s.point((x=A[o])[0],x[1]);s.lineEnd();return}r.push(b=new sm(x,A,null,!0)),a.push(b.o=new sm(x,null,b,!1)),r.push(b=new sm(v,A,null,!1)),a.push(b.o=new sm(v,null,b,!0))}}),!!r.length){for(a.sort(t),kS(r),kS(a),o=0,l=a.length;o<l;++o)a[o].e=n=!n;for(var c=r[0],h,d;;){for(var f=c,m=!0;f.v;)if((f=f.n)===c)return;h=f.z,s.lineStart();do{if(f.v=f.o.v=!0,f.e){if(m)for(o=0,l=h.length;o<l;++o)s.point((d=h[o])[0],d[1]);else i(f.x,f.n.x,1,s);f=f.n}else{if(m)for(h=f.p.z,o=h.length-1;o>=0;--o)s.point((d=h[o])[0],d[1]);else i(f.x,f.p.x,-1,s);f=f.p}f=f.o,h=f.z,m=!m}while(!f.v);s.lineEnd()}}}function kS(e){if(t=e.length){for(var t,n=0,i=e[0],s;++n<t;)i.n=s=e[n],s.p=i,i=s;i.n=s=e[0],s.p=i}}function X2(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function XQ(e){return e.length===1&&(e=ZQ(e)),{left:function(t,n,i,s){for(i==null&&(i=0),s==null&&(s=t.length);i<s;){var r=i+s>>>1;e(t[r],n)<0?i=r+1:s=r}return i},right:function(t,n,i,s){for(i==null&&(i=0),s==null&&(s=t.length);i<s;){var r=i+s>>>1;e(t[r],n)>0?s=r:i=r+1}return i}}}function ZQ(e){return function(t,n){return X2(e(t),n)}}XQ(X2);function Z2(e){for(var t=e.length,n,i=-1,s=0,r,a;++i<t;)s+=e[i].length;for(r=new Array(s);--t>=0;)for(a=e[t],n=a.length;--n>=0;)r[--s]=a[n];return r}var Wd=1e9,rm=-Wd;function JQ(e,t,n,i){function s(c,h){return e<=c&&c<=n&&t<=h&&h<=i}function r(c,h,d,f){var m=0,A=0;if(c==null||(m=a(c,d))!==(A=a(h,d))||l(c,h)<0^d>0)do f.point(m===0||m===3?e:n,m>1?i:t);while((m=(m+d+4)%4)!==A);else f.point(h[0],h[1])}function a(c,h){return Yi(c[0]-e)<Wn?h>0?0:3:Yi(c[0]-n)<Wn?h>0?2:1:Yi(c[1]-t)<Wn?h>0?1:0:h>0?3:2}function o(c,h){return l(c.x,h.x)}function l(c,h){var d=a(c,1),f=a(h,1);return d!==f?d-f:d===0?h[1]-c[1]:d===1?c[0]-h[0]:d===2?c[1]-h[1]:h[0]-c[0]}return function(c){var h=c,d=Y2(),f,m,A,y,x,v,b,w,S,R,k,L={point:T,lineStart:O,lineEnd:N,polygonStart:I,polygonEnd:M};function T(P,U){s(P,U)&&h.point(P,U)}function C(){for(var P=0,U=0,Q=m.length;U<Q;++U)for(var z=m[U],H=1,W=z.length,te=z[0],J,K,re=te[0],ce=te[1];H<W;++H)J=re,K=ce,te=z[H],re=te[0],ce=te[1],K<=i?ce>i&&(re-J)*(i-K)>(ce-K)*(e-J)&&++P:ce<=i&&(re-J)*(i-K)<(ce-K)*(e-J)&&--P;return P}function I(){h=d,f=[],m=[],k=!0}function M(){var P=C(),U=k&&P,Q=(f=Z2(f)).length;(U||Q)&&(c.polygonStart(),U&&(c.lineStart(),r(null,null,1,c),c.lineEnd()),Q&&j2(f,o,P,r,c),c.polygonEnd()),h=c,f=m=A=null}function O(){L.point=D,m&&m.push(A=[]),R=!0,S=!1,b=w=NaN}function N(){f&&(D(y,x),v&&S&&d.rejoin(),f.push(d.result())),L.point=T,S&&h.lineEnd()}function D(P,U){var Q=s(P,U);if(m&&A.push([P,U]),R)y=P,x=U,v=Q,R=!1,Q&&(h.lineStart(),h.point(P,U));else if(Q&&S)h.point(P,U);else{var z=[b=Math.max(rm,Math.min(Wd,b)),w=Math.max(rm,Math.min(Wd,w))],H=[P=Math.max(rm,Math.min(Wd,P)),U=Math.max(rm,Math.min(Wd,U))];jQ(z,H,e,t,n,i)?(S||(h.lineStart(),h.point(z[0],z[1])),h.point(H[0],H[1]),Q||h.lineEnd(),k=!1):Q&&(h.lineStart(),h.point(P,U),k=!1)}b=P,w=U,S=Q}return L}}var Bv=Hl();function KQ(e,t){var n=t[0],i=t[1],s=[ui(n),-hi(n),0],r=0,a=0;Bv.reset();for(var o=0,l=e.length;o<l;++o)if(h=(c=e[o]).length)for(var c,h,d=c[h-1],f=d[0],m=d[1]/2+wS,A=ui(m),y=hi(m),x=0;x<h;++x,f=b,A=S,y=R,d=v){var v=c[x],b=v[0],w=v[1]/2+wS,S=ui(w),R=hi(w),k=b-f,L=k>=0?1:-1,T=L*k,C=T>gn,I=A*S;if(Bv.add(Iu(I*L*ui(T),y*R+I*hi(T))),r+=C?k+L*Ga:k,C^f>=n^b>=n){var M=C_(Mu(d),Mu(v));rb(M);var O=C_(s,M);rb(O);var N=(C^k>=0?-1:1)*Rc(O[2]);(i>N||i===N&&(M[0]||M[1]))&&(a+=C^k>=0?1:-1)}}return(r<-Wn||r<Wn&&Bv<-Wn)^a&1}Hl();function NS(e){return e}Hl();Hl();var Tu=1/0,w_=Tu,Pp=-Tu,S_=Pp,PS={point:e4,lineStart:qd,lineEnd:qd,polygonStart:qd,polygonEnd:qd,result:function(){var e=[[Tu,w_],[Pp,S_]];return Pp=S_=-(w_=Tu=1/0),e}};function e4(e,t){e<Tu&&(Tu=e),e>Pp&&(Pp=e),t<w_&&(w_=t),t>S_&&(S_=t)}Hl();function J2(e,t,n,i){return function(s,r){var a=t(r),o=s.invert(i[0],i[1]),l=Y2(),c=t(l),h=!1,d,f,m,A={point:y,lineStart:v,lineEnd:b,polygonStart:function(){A.point=w,A.lineStart=S,A.lineEnd=R,f=[],d=[]},polygonEnd:function(){A.point=y,A.lineStart=v,A.lineEnd=b,f=Z2(f);var k=KQ(d,o);f.length?(h||(r.polygonStart(),h=!0),j2(f,n4,k,n,r)):k&&(h||(r.polygonStart(),h=!0),r.lineStart(),n(null,null,1,r),r.lineEnd()),h&&(r.polygonEnd(),h=!1),f=d=null},sphere:function(){r.polygonStart(),r.lineStart(),n(null,null,1,r),r.lineEnd(),r.polygonEnd()}};function y(k,L){var T=s(k,L);e(k=T[0],L=T[1])&&r.point(k,L)}function x(k,L){var T=s(k,L);a.point(T[0],T[1])}function v(){A.point=x,a.lineStart()}function b(){A.point=y,a.lineEnd()}function w(k,L){m.push([k,L]);var T=s(k,L);c.point(T[0],T[1])}function S(){c.lineStart(),m=[]}function R(){w(m[0][0],m[0][1]),c.lineEnd();var k=c.clean(),L=l.result(),T,C=L.length,I,M,O;if(m.pop(),d.push(m),m=null,!!C){if(k&1){if(M=L[0],(I=M.length-1)>0){for(h||(r.polygonStart(),h=!0),r.lineStart(),T=0;T<I;++T)r.point((O=M[T])[0],O[1]);r.lineEnd()}return}C>1&&k&2&&L.push(L.pop().concat(L.shift())),f.push(L.filter(t4))}}return A}}function t4(e){return e.length>1}function n4(e,t){return((e=e.x)[0]<0?e[1]-Pa-Wn:Pa-e[1])-((t=t.x)[0]<0?t[1]-Pa-Wn:Pa-t[1])}var DS=J2(function(){return!0},i4,r4,[-gn,-Pa]);function i4(e){var t=NaN,n=NaN,i=NaN,s;return{lineStart:function(){e.lineStart(),s=1},point:function(r,a){var o=r>0?gn:-gn,l=Yi(r-t);Yi(l-gn)<Wn?(e.point(t,n=(n+a)/2>0?Pa:-Pa),e.point(i,n),e.lineEnd(),e.lineStart(),e.point(o,n),e.point(r,n),s=0):i!==o&&l>=gn&&(Yi(t-i)<Wn&&(t-=i*Wn),Yi(r-o)<Wn&&(r-=o*Wn),n=s4(t,n,r,a),e.point(i,n),e.lineEnd(),e.lineStart(),e.point(o,n),s=0),e.point(t=r,n=a),i=o},lineEnd:function(){e.lineEnd(),t=n=NaN},clean:function(){return 2-s}}}function s4(e,t,n,i){var s,r,a=ui(e-n);return Yi(a)>Wn?VQ((ui(t)*(r=hi(i))*ui(n)-ui(i)*(s=hi(t))*ui(e))/(s*r*a)):(t+i)/2}function r4(e,t,n,i){var s;if(e==null)s=n*Pa,i.point(-gn,s),i.point(0,s),i.point(gn,s),i.point(gn,0),i.point(gn,-s),i.point(0,-s),i.point(-gn,-s),i.point(-gn,0),i.point(-gn,s);else if(Yi(e[0]-t[0])>Wn){var r=e[0]<t[0]?gn:-gn;s=n*r/2,i.point(-r,s),i.point(0,s),i.point(r,s)}else i.point(t[0],t[1])}function a4(e,t){var n=hi(e),i=n>0,s=Yi(n)>Wn;function r(h,d,f,m){YQ(m,e,t,f,h,d)}function a(h,d){return hi(h)*hi(d)>n}function o(h){var d,f,m,A,y;return{lineStart:function(){A=m=!1,y=1},point:function(x,v){var b=[x,v],w,S=a(x,v),R=i?S?0:c(x,v):S?c(x+(x<0?gn:-gn),v):0;if(!d&&(A=m=S)&&h.lineStart(),S!==m&&(w=l(d,b),(!w||Qg(d,w)||Qg(b,w))&&(b[0]+=Wn,b[1]+=Wn,S=a(b[0],b[1]))),S!==m)y=0,S?(h.lineStart(),w=l(b,d),h.point(w[0],w[1])):(w=l(d,b),h.point(w[0],w[1]),h.lineEnd()),d=w;else if(s&&d&&i^S){var k;!(R&f)&&(k=l(b,d,!0))&&(y=0,i?(h.lineStart(),h.point(k[0][0],k[0][1]),h.point(k[1][0],k[1][1]),h.lineEnd()):(h.point(k[1][0],k[1][1]),h.lineEnd(),h.lineStart(),h.point(k[0][0],k[0][1])))}S&&(!d||!Qg(d,b))&&h.point(b[0],b[1]),d=b,m=S,f=R},lineEnd:function(){m&&h.lineEnd(),d=null},clean:function(){return y|(A&&m)<<1}}}function l(h,d,f){var m=Mu(h),A=Mu(d),y=[1,0,0],x=C_(m,A),v=nm(x,x),b=x[0],w=v-b*b;if(!w)return!f&&h;var S=n*v/w,R=-n*b/w,k=C_(y,x),L=im(y,S);Lv(L,im(x,R));var T=k,C=nm(L,T),I=nm(T,T),M=C*C-I*(nm(L,L)-1);if(!(M<0)){var O=Zu(M),N=im(T,(-C-O)/I);if(Lv(N,L),N=sb(N),!f)return N;var D=h[0],P=d[0],U=h[1],Q=d[1],z;P<D&&(z=D,D=P,P=z);var H=P-D,W=Yi(H-gn)<Wn,te=W||H<Wn;if(!W&&Q<U&&(z=U,U=Q,Q=z),te?W?U+Q>0^N[1]<(Yi(N[0]-D)<Wn?U:Q):U<=N[1]&&N[1]<=Q:H>gn^(D<=N[0]&&N[0]<=P)){var J=im(T,(-C+O)/I);return Lv(J,L),[N,sb(J)]}}}function c(h,d){var f=i?e:gn-e,m=0;return h<-f?m|=1:h>f&&(m|=2),d<-f?m|=4:d>f&&(m|=8),m}return J2(a,o,r,i?[0,-e]:[-gn,e-gn])}function K2(e){return function(t){var n=new ob;for(var i in e)n[i]=e[i];return n.stream=t,n}}function ob(){}ob.prototype={constructor:ob,point:function(e,t){this.stream.point(e,t)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}};function eR(e,t,n){var i=t[1][0]-t[0][0],s=t[1][1]-t[0][1],r=e.clipExtent&&e.clipExtent();e.scale(150).translate([0,0]),r!=null&&e.clipExtent(null),qQ(n,e.stream(PS));var a=PS.result(),o=Math.min(i/(a[1][0]-a[0][0]),s/(a[1][1]-a[0][1])),l=+t[0][0]+(i-o*(a[1][0]+a[0][0]))/2,c=+t[0][1]+(s-o*(a[1][1]+a[0][1]))/2;return r!=null&&e.clipExtent(r),e.scale(o*150).translate([l,c])}function o4(e,t,n){return eR(e,[[0,0],t],n)}var FS=16,l4=hi(30*Pr);function OS(e,t){return+t?h4(e,t):c4(e)}function c4(e){return K2({point:function(t,n){t=e(t,n),this.stream.point(t[0],t[1])}})}function h4(e,t){function n(i,s,r,a,o,l,c,h,d,f,m,A,y,x){var v=c-i,b=h-s,w=v*v+b*b;if(w>4*t&&y--){var S=a+f,R=o+m,k=l+A,L=Zu(S*S+R*R+k*k),T=Rc(k/=L),C=Yi(Yi(k)-1)<Wn||Yi(r-d)<Wn?(r+d)/2:Iu(R,S),I=e(C,T),M=I[0],O=I[1],N=M-i,D=O-s,P=b*N-v*D;(P*P/w>t||Yi((v*N+b*D)/w-.5)>.3||a*f+o*m+l*A<l4)&&(n(i,s,r,a,o,l,M,O,C,S/=L,R/=L,k,y,x),x.point(M,O),n(M,O,C,S,R,k,c,h,d,f,m,A,y,x))}}return function(i){var s,r,a,o,l,c,h,d,f,m,A,y,x={point:v,lineStart:b,lineEnd:S,polygonStart:function(){i.polygonStart(),x.lineStart=R},polygonEnd:function(){i.polygonEnd(),x.lineStart=b}};function v(T,C){T=e(T,C),i.point(T[0],T[1])}function b(){d=NaN,x.point=w,i.lineStart()}function w(T,C){var I=Mu([T,C]),M=e(T,C);n(d,f,h,m,A,y,d=M[0],f=M[1],h=T,m=I[0],A=I[1],y=I[2],FS,i),i.point(d,f)}function S(){x.point=v,i.lineEnd()}function R(){b(),x.point=k,x.lineEnd=L}function k(T,C){w(s=T,C),r=d,a=f,o=m,l=A,c=y,x.point=w}function L(){n(d,f,h,m,A,y,r,a,s,o,l,c,FS,i),x.lineEnd=S,S()}return x}}var u4=K2({point:function(e,t){this.stream.point(e*Pr,t*Pr)}});function d4(e){return p4(function(){return e})()}function p4(e){var t,n=150,i=480,s=250,r,a,o=0,l=0,c=0,h=0,d=0,f,m,A=null,y=DS,x=null,v,b,w,S=NS,R=.5,k=OS(M,R),L,T;function C(D){return D=m(D[0]*Pr,D[1]*Pr),[D[0]*n+r,a-D[1]*n]}function I(D){return D=m.invert((D[0]-r)/n,(a-D[1])/n),D&&[D[0]*Yo,D[1]*Yo]}function M(D,P){return D=t(D,P),[D[0]*n+r,a-D[1]*n]}C.stream=function(D){return L&&T===D?L:L=u4(y(f,k(S(T=D))))},C.clipAngle=function(D){return arguments.length?(y=+D?a4(A=D*Pr,6*Pr):(A=null,DS),N()):A*Yo},C.clipExtent=function(D){return arguments.length?(S=D==null?(x=v=b=w=null,NS):JQ(x=+D[0][0],v=+D[0][1],b=+D[1][0],w=+D[1][1]),N()):x==null?null:[[x,v],[b,w]]},C.scale=function(D){return arguments.length?(n=+D,O()):n},C.translate=function(D){return arguments.length?(i=+D[0],s=+D[1],O()):[i,s]},C.center=function(D){return arguments.length?(o=D[0]%360*Pr,l=D[1]%360*Pr,O()):[o*Yo,l*Yo]},C.rotate=function(D){return arguments.length?(c=D[0]%360*Pr,h=D[1]%360*Pr,d=D.length>2?D[2]%360*Pr:0,O()):[c*Yo,h*Yo,d*Yo]},C.precision=function(D){return arguments.length?(k=OS(M,R=D*D),N()):Zu(R)},C.fitExtent=function(D,P){return eR(C,D,P)},C.fitSize=function(D,P){return o4(C,D,P)};function O(){m=W2(f=WQ(c,h,d),t);var D=t(o,l);return r=i-D[0]*n,a=s+D[1]*n,N()}function N(){return L=T=null,C}return function(){return t=e.apply(this,arguments),C.invert=t.invert&&I,O()}}function tR(e){return function(t,n){var i=hi(t),s=hi(n),r=e(i*s);return[r*s*ui(t),r*ui(n)]}}function nR(e){return function(t,n){var i=Zu(t*t+n*n),s=e(i),r=ui(s),a=hi(s);return[Iu(t*r,i*a),Rc(i&&n*r/i)]}}var f4=tR(function(e){return Zu(2/(1+e))});f4.invert=nR(function(e){return 2*Rc(e/2)});var iR=tR(function(e){return(e=q2(e))&&e/ui(e)});iR.invert=nR(function(e){return e});function m4(){return d4(iR).scale(79.4188).clipAngle(179.999)}function US(e,t){return[e,t]}US.invert=US;var{BufferOp:g4,GeoJSONReader:_4,GeoJSONWriter:A4}=$Q;function v4(e,t,n){n=n||{};var i=n.units||"kilometers",s=n.steps||8;if(!e)throw new Error("geojson is required");if(typeof n!="object")throw new Error("options must be an object");if(typeof s!="number")throw new Error("steps must be an number");if(t===void 0)throw new Error("radius is required");if(s<=0)throw new Error("steps must be greater than 0");var r=[];switch(e.type){case"GeometryCollection":return Gl(e,function(a){var o=Gg(a,t,i,s);o&&r.push(o)}),Kt(r);case"FeatureCollection":return Po(e,function(a){var o=Gg(a,t,i,s);o&&Po(o,function(l){l&&r.push(l)})}),Kt(r)}return Gg(e,t,i,s)}function Gg(e,t,n,i){var s=e.properties||{},r=e.type==="Feature"?e.geometry:e;if(r.type==="GeometryCollection"){var a=[];return Gl(e,function(f){var m=Gg(f,t,n,i);m&&a.push(m)}),Kt(a)}var o=y4(r),l={type:r.type,coordinates:rR(r.coordinates,o)},c=new _4().read(l),h=SE(M2(t,n),"meters"),d=g4.bufferOp(c,h,i);if(d=new A4().write(d),!sR(d.coordinates))return or({type:d.type,coordinates:aR(d.coordinates,o)},s)}function sR(e){return Array.isArray(e[0])?sR(e[0]):isNaN(e[0])}function rR(e,t){return typeof e[0]!="object"?t(e):e.map(function(n){return rR(n,t)})}function aR(e,t){return typeof e[0]!="object"?t.invert(e):e.map(function(n){return aR(n,t)})}function y4(e){var t=V2(e).geometry.coordinates,n=[-t[0],-t[1]];return m4().rotate(n).scale($i)}function Dp(e,t={}){let n=0,i=0,s=0;return Ql(e,function(r){n+=r[0],i+=r[1],s++},!0),wi([n/s,i/s],t.properties)}function Es(e){if(!e)throw new Error("geojson is required");switch(e.type){case"Feature":return oR(e);case"FeatureCollection":return b4(e);case"Point":case"LineString":case"Polygon":case"MultiPoint":case"MultiLineString":case"MultiPolygon":case"GeometryCollection":return NE(e);default:throw new Error("unknown GeoJSON type")}}function oR(e){const t={type:"Feature"};return Object.keys(e).forEach(n=>{switch(n){case"type":case"properties":case"geometry":return;default:t[n]=e[n]}}),t.properties=lR(e.properties),e.geometry==null?t.geometry=null:t.geometry=NE(e.geometry),t}function lR(e){const t={};return e&&Object.keys(e).forEach(n=>{const i=e[n];typeof i=="object"?i===null?t[n]=null:Array.isArray(i)?t[n]=i.map(s=>s):t[n]=lR(i):t[n]=i}),t}function b4(e){const t={type:"FeatureCollection"};return Object.keys(e).forEach(n=>{switch(n){case"type":case"features":return;default:t[n]=e[n]}}),t.features=e.features.map(n=>oR(n)),t}function NE(e){const t={type:e.type};return e.bbox&&(t.bbox=e.bbox),e.type==="GeometryCollection"?(t.geometries=e.geometries.map(n=>NE(n)),t):(t.coordinates=cR(e.coordinates),t)}function cR(e){const t=e;return typeof t[0]!="object"?t.slice():t.map(n=>cR(n))}var x4=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Rv=Math.ceil,Rr=Math.floor,Zs="[BigNumber Error] ",zS=Zs+"Number primitive has more than 15 significant digits: ",Xr=1e14,Gt=14,kv=9007199254740991,Nv=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],jo=1e7,Qi=1e9;function hR(e){var t,n,i,s=b.prototype={constructor:b,toString:null,valueOf:null},r=new b(1),a=20,o=4,l=-7,c=21,h=-1e7,d=1e7,f=!1,m=1,A=0,y={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:" ",suffix:""},x="0123456789abcdefghijklmnopqrstuvwxyz",v=!0;function b(T,C){var I,M,O,N,D,P,U,Q,z=this;if(!(z instanceof b))return new b(T,C);if(C==null){if(T&&T._isBigNumber===!0){z.s=T.s,!T.c||T.e>d?z.c=z.e=null:T.e<h?z.c=[z.e=0]:(z.e=T.e,z.c=T.c.slice());return}if((P=typeof T=="number")&&T*0==0){if(z.s=1/T<0?(T=-T,-1):1,T===~~T){for(N=0,D=T;D>=10;D/=10,N++);N>d?z.c=z.e=null:(z.e=N,z.c=[T]);return}Q=String(T)}else{if(!x4.test(Q=String(T)))return i(z,Q,P);z.s=Q.charCodeAt(0)==45?(Q=Q.slice(1),-1):1}(N=Q.indexOf("."))>-1&&(Q=Q.replace(".","")),(D=Q.search(/e/i))>0?(N<0&&(N=D),N+=+Q.slice(D+1),Q=Q.substring(0,D)):N<0&&(N=Q.length)}else{if(ri(C,2,x.length,"Base"),C==10&&v)return z=new b(T),k(z,a+z.e+1,o);if(Q=String(T),P=typeof T=="number"){if(T*0!=0)return i(z,Q,P,C);if(z.s=1/T<0?(Q=Q.slice(1),-1):1,b.DEBUG&&Q.replace(/^0\.0*|\./,"").length>15)throw Error(zS+T)}else z.s=Q.charCodeAt(0)===45?(Q=Q.slice(1),-1):1;for(I=x.slice(0,C),N=D=0,U=Q.length;D<U;D++)if(I.indexOf(M=Q.charAt(D))<0){if(M=="."){if(D>N){N=U;continue}}else if(!O&&(Q==Q.toUpperCase()&&(Q=Q.toLowerCase())||Q==Q.toLowerCase()&&(Q=Q.toUpperCase()))){O=!0,D=-1,N=0;continue}return i(z,String(T),P,C)}P=!1,Q=n(Q,C,10,z.s),(N=Q.indexOf("."))>-1?Q=Q.replace(".",""):N=Q.length}for(D=0;Q.charCodeAt(D)===48;D++);for(U=Q.length;Q.charCodeAt(--U)===48;);if(Q=Q.slice(D,++U)){if(U-=D,P&&b.DEBUG&&U>15&&(T>kv||T!==Rr(T)))throw Error(zS+z.s*T);if((N=N-D-1)>d)z.c=z.e=null;else if(N<h)z.c=[z.e=0];else{if(z.e=N,z.c=[],D=(N+1)%Gt,N<0&&(D+=Gt),D<U){for(D&&z.c.push(+Q.slice(0,D)),U-=Gt;D<U;)z.c.push(+Q.slice(D,D+=Gt));D=Gt-(Q=Q.slice(D)).length}else D-=U;for(;D--;Q+="0");z.c.push(+Q)}}else z.c=[z.e=0]}b.clone=hR,b.ROUND_UP=0,b.ROUND_DOWN=1,b.ROUND_CEIL=2,b.ROUND_FLOOR=3,b.ROUND_HALF_UP=4,b.ROUND_HALF_DOWN=5,b.ROUND_HALF_EVEN=6,b.ROUND_HALF_CEIL=7,b.ROUND_HALF_FLOOR=8,b.EUCLID=9,b.config=b.set=function(T){var C,I;if(T!=null)if(typeof T=="object"){if(T.hasOwnProperty(C="DECIMAL_PLACES")&&(I=T[C],ri(I,0,Qi,C),a=I),T.hasOwnProperty(C="ROUNDING_MODE")&&(I=T[C],ri(I,0,8,C),o=I),T.hasOwnProperty(C="EXPONENTIAL_AT")&&(I=T[C],I&&I.pop?(ri(I[0],-Qi,0,C),ri(I[1],0,Qi,C),l=I[0],c=I[1]):(ri(I,-Qi,Qi,C),l=-(c=I<0?-I:I))),T.hasOwnProperty(C="RANGE"))if(I=T[C],I&&I.pop)ri(I[0],-Qi,-1,C),ri(I[1],1,Qi,C),h=I[0],d=I[1];else if(ri(I,-Qi,Qi,C),I)h=-(d=I<0?-I:I);else throw Error(Zs+C+" cannot be zero: "+I);if(T.hasOwnProperty(C="CRYPTO"))if(I=T[C],I===!!I)if(I)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))f=I;else throw f=!I,Error(Zs+"crypto unavailable");else f=I;else throw Error(Zs+C+" not true or false: "+I);if(T.hasOwnProperty(C="MODULO_MODE")&&(I=T[C],ri(I,0,9,C),m=I),T.hasOwnProperty(C="POW_PRECISION")&&(I=T[C],ri(I,0,Qi,C),A=I),T.hasOwnProperty(C="FORMAT"))if(I=T[C],typeof I=="object")y=I;else throw Error(Zs+C+" not an object: "+I);if(T.hasOwnProperty(C="ALPHABET"))if(I=T[C],typeof I=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(I))v=I.slice(0,10)=="0123456789",x=I;else throw Error(Zs+C+" invalid: "+I)}else throw Error(Zs+"Object expected: "+T);return{DECIMAL_PLACES:a,ROUNDING_MODE:o,EXPONENTIAL_AT:[l,c],RANGE:[h,d],CRYPTO:f,MODULO_MODE:m,POW_PRECISION:A,FORMAT:y,ALPHABET:x}},b.isBigNumber=function(T){if(!T||T._isBigNumber!==!0)return!1;if(!b.DEBUG)return!0;var C,I,M=T.c,O=T.e,N=T.s;e:if({}.toString.call(M)=="[object Array]"){if((N===1||N===-1)&&O>=-Qi&&O<=Qi&&O===Rr(O)){if(M[0]===0){if(O===0&&M.length===1)return!0;break e}if(C=(O+1)%Gt,C<1&&(C+=Gt),String(M[0]).length==C){for(C=0;C<M.length;C++)if(I=M[C],I<0||I>=Xr||I!==Rr(I))break e;if(I!==0)return!0}}}else if(M===null&&O===null&&(N===null||N===1||N===-1))return!0;throw Error(Zs+"Invalid BigNumber: "+T)},b.maximum=b.max=function(){return S(arguments,-1)},b.minimum=b.min=function(){return S(arguments,1)},b.random=(function(){var T=9007199254740992,C=Math.random()*T&2097151?function(){return Rr(Math.random()*T)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(I){var M,O,N,D,P,U=0,Q=[],z=new b(r);if(I==null?I=a:ri(I,0,Qi),D=Rv(I/Gt),f)if(crypto.getRandomValues){for(M=crypto.getRandomValues(new Uint32Array(D*=2));U<D;)P=M[U]*131072+(M[U+1]>>>11),P>=9e15?(O=crypto.getRandomValues(new Uint32Array(2)),M[U]=O[0],M[U+1]=O[1]):(Q.push(P%1e14),U+=2);U=D/2}else if(crypto.randomBytes){for(M=crypto.randomBytes(D*=7);U<D;)P=(M[U]&31)*281474976710656+M[U+1]*1099511627776+M[U+2]*4294967296+M[U+3]*16777216+(M[U+4]<<16)+(M[U+5]<<8)+M[U+6],P>=9e15?crypto.randomBytes(7).copy(M,U):(Q.push(P%1e14),U+=7);U=D/7}else throw f=!1,Error(Zs+"crypto unavailable");if(!f)for(;U<D;)P=C(),P<9e15&&(Q[U++]=P%1e14);for(D=Q[--U],I%=Gt,D&&I&&(P=Nv[Gt-I],Q[U]=Rr(D/P)*P);Q[U]===0;Q.pop(),U--);if(U<0)Q=[N=0];else{for(N=-1;Q[0]===0;Q.splice(0,1),N-=Gt);for(U=1,P=Q[0];P>=10;P/=10,U++);U<Gt&&(N-=Gt-U)}return z.e=N,z.c=Q,z}})(),b.sum=function(){for(var T=1,C=arguments,I=new b(C[0]);T<C.length;)I=I.plus(C[T++]);return I},n=(function(){var T="0123456789";function C(I,M,O,N){for(var D,P=[0],U,Q=0,z=I.length;Q<z;){for(U=P.length;U--;P[U]*=M);for(P[0]+=N.indexOf(I.charAt(Q++)),D=0;D<P.length;D++)P[D]>O-1&&(P[D+1]==null&&(P[D+1]=0),P[D+1]+=P[D]/O|0,P[D]%=O)}return P.reverse()}return function(I,M,O,N,D){var P,U,Q,z,H,W,te,J,K=I.indexOf("."),re=a,ce=o;for(K>=0&&(z=A,A=0,I=I.replace(".",""),J=new b(M),W=J.pow(I.length-K),A=z,J.c=C(io(Tr(W.c),W.e,"0"),10,O,T),J.e=J.c.length),te=C(I,M,O,D?(P=x,T):(P=T,x)),Q=z=te.length;te[--z]==0;te.pop());if(!te[0])return P.charAt(0);if(K<0?--Q:(W.c=te,W.e=Q,W.s=N,W=t(W,J,re,ce,O),te=W.c,H=W.r,Q=W.e),U=Q+re+1,K=te[U],z=O/2,H=H||U<0||te[U+1]!=null,H=ce<4?(K!=null||H)&&(ce==0||ce==(W.s<0?3:2)):K>z||K==z&&(ce==4||H||ce==6&&te[U-1]&1||ce==(W.s<0?8:7)),U<1||!te[0])I=H?io(P.charAt(1),-re,P.charAt(0)):P.charAt(0);else{if(te.length=U,H)for(--O;++te[--U]>O;)te[U]=0,U||(++Q,te=[1].concat(te));for(z=te.length;!te[--z];);for(K=0,I="";K<=z;I+=P.charAt(te[K++]));I=io(I,Q,P.charAt(0))}return I}})(),t=(function(){function T(M,O,N){var D,P,U,Q,z=0,H=M.length,W=O%jo,te=O/jo|0;for(M=M.slice();H--;)U=M[H]%jo,Q=M[H]/jo|0,D=te*U+Q*W,P=W*U+D%jo*jo+z,z=(P/N|0)+(D/jo|0)+te*Q,M[H]=P%N;return z&&(M=[z].concat(M)),M}function C(M,O,N,D){var P,U;if(N!=D)U=N>D?1:-1;else for(P=U=0;P<N;P++)if(M[P]!=O[P]){U=M[P]>O[P]?1:-1;break}return U}function I(M,O,N,D){for(var P=0;N--;)M[N]-=P,P=M[N]<O[N]?1:0,M[N]=P*D+M[N]-O[N];for(;!M[0]&&M.length>1;M.splice(0,1));}return function(M,O,N,D,P){var U,Q,z,H,W,te,J,K,re,ce,oe,ge,ie,fe,ye,$,Se,Z=M.s==O.s?1:-1,Qe=M.c,Le=O.c;if(!Qe||!Qe[0]||!Le||!Le[0])return new b(!M.s||!O.s||(Qe?Le&&Qe[0]==Le[0]:!Le)?NaN:Qe&&Qe[0]==0||!Le?Z*0:Z/0);for(K=new b(Z),re=K.c=[],Q=M.e-O.e,Z=N+Q+1,P||(P=Xr,Q=kr(M.e/Gt)-kr(O.e/Gt),Z=Z/Gt|0),z=0;Le[z]==(Qe[z]||0);z++);if(Le[z]>(Qe[z]||0)&&Q--,Z<0)re.push(1),H=!0;else{for(fe=Qe.length,$=Le.length,z=0,Z+=2,W=Rr(P/(Le[0]+1)),W>1&&(Le=T(Le,W,P),Qe=T(Qe,W,P),$=Le.length,fe=Qe.length),ie=$,ce=Qe.slice(0,$),oe=ce.length;oe<$;ce[oe++]=0);Se=Le.slice(),Se=[0].concat(Se),ye=Le[0],Le[1]>=P/2&&ye++;do{if(W=0,U=C(Le,ce,$,oe),U<0){if(ge=ce[0],$!=oe&&(ge=ge*P+(ce[1]||0)),W=Rr(ge/ye),W>1)for(W>=P&&(W=P-1),te=T(Le,W,P),J=te.length,oe=ce.length;C(te,ce,J,oe)==1;)W--,I(te,$<J?Se:Le,J,P),J=te.length,U=1;else W==0&&(U=W=1),te=Le.slice(),J=te.length;if(J<oe&&(te=[0].concat(te)),I(ce,te,oe,P),oe=ce.length,U==-1)for(;C(Le,ce,$,oe)<1;)W++,I(ce,$<oe?Se:Le,oe,P),oe=ce.length}else U===0&&(W++,ce=[0]);re[z++]=W,ce[0]?ce[oe++]=Qe[ie]||0:(ce=[Qe[ie]],oe=1)}while((ie++<fe||ce[0]!=null)&&Z--);H=ce[0]!=null,re[0]||re.splice(0,1)}if(P==Xr){for(z=1,Z=re[0];Z>=10;Z/=10,z++);k(K,N+(K.e=z+Q*Gt-1)+1,D,H)}else K.e=Q,K.r=+H;return K}})();function w(T,C,I,M){var O,N,D,P,U;if(I==null?I=o:ri(I,0,8),!T.c)return T.toString();if(O=T.c[0],D=T.e,C==null)U=Tr(T.c),U=M==1||M==2&&(D<=l||D>=c)?om(U,D):io(U,D,"0");else if(T=k(new b(T),C,I),N=T.e,U=Tr(T.c),P=U.length,M==1||M==2&&(C<=N||N<=l)){for(;P<C;U+="0",P++);U=om(U,N)}else if(C-=D+(M===2&&N>D),U=io(U,N,"0"),N+1>P){if(--C>0)for(U+=".";C--;U+="0");}else if(C+=N-P,C>0)for(N+1==P&&(U+=".");C--;U+="0");return T.s<0&&O?"-"+U:U}function S(T,C){for(var I,M,O=1,N=new b(T[0]);O<T.length;O++)M=new b(T[O]),(!M.s||(I=Jl(N,M))===C||I===0&&N.s===C)&&(N=M);return N}function R(T,C,I){for(var M=1,O=C.length;!C[--O];C.pop());for(O=C[0];O>=10;O/=10,M++);return(I=M+I*Gt-1)>d?T.c=T.e=null:I<h?T.c=[T.e=0]:(T.e=I,T.c=C),T}i=(function(){var T=/^(-?)0([xbo])(?=\w[\w.]*$)/i,C=/^([^.]+)\.$/,I=/^\.([^.]+)$/,M=/^-?(Infinity|NaN)$/,O=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(N,D,P,U){var Q,z=P?D:D.replace(O,"");if(M.test(z))N.s=isNaN(z)?null:z<0?-1:1;else{if(!P&&(z=z.replace(T,function(H,W,te){return Q=(te=te.toLowerCase())=="x"?16:te=="b"?2:8,!U||U==Q?W:H}),U&&(Q=U,z=z.replace(C,"$1").replace(I,"0.$1")),D!=z))return new b(z,Q);if(b.DEBUG)throw Error(Zs+"Not a"+(U?" base "+U:"")+" number: "+D);N.s=null}N.c=N.e=null}})();function k(T,C,I,M){var O,N,D,P,U,Q,z,H=T.c,W=Nv;if(H){e:{for(O=1,P=H[0];P>=10;P/=10,O++);if(N=C-O,N<0)N+=Gt,D=C,U=H[Q=0],z=Rr(U/W[O-D-1]%10);else if(Q=Rv((N+1)/Gt),Q>=H.length)if(M){for(;H.length<=Q;H.push(0));U=z=0,O=1,N%=Gt,D=N-Gt+1}else break e;else{for(U=P=H[Q],O=1;P>=10;P/=10,O++);N%=Gt,D=N-Gt+O,z=D<0?0:Rr(U/W[O-D-1]%10)}if(M=M||C<0||H[Q+1]!=null||(D<0?U:U%W[O-D-1]),M=I<4?(z||M)&&(I==0||I==(T.s<0?3:2)):z>5||z==5&&(I==4||M||I==6&&(N>0?D>0?U/W[O-D]:0:H[Q-1])%10&1||I==(T.s<0?8:7)),C<1||!H[0])return H.length=0,M?(C-=T.e+1,H[0]=W[(Gt-C%Gt)%Gt],T.e=-C||0):H[0]=T.e=0,T;if(N==0?(H.length=Q,P=1,Q--):(H.length=Q+1,P=W[Gt-N],H[Q]=D>0?Rr(U/W[O-D]%W[D])*P:0),M)for(;;)if(Q==0){for(N=1,D=H[0];D>=10;D/=10,N++);for(D=H[0]+=P,P=1;D>=10;D/=10,P++);N!=P&&(T.e++,H[0]==Xr&&(H[0]=1));break}else{if(H[Q]+=P,H[Q]!=Xr)break;H[Q--]=0,P=1}for(N=H.length;H[--N]===0;H.pop());}T.e>d?T.c=T.e=null:T.e<h&&(T.c=[T.e=0])}return T}function L(T){var C,I=T.e;return I===null?T.toString():(C=Tr(T.c),C=I<=l||I>=c?om(C,I):io(C,I,"0"),T.s<0?"-"+C:C)}return s.absoluteValue=s.abs=function(){var T=new b(this);return T.s<0&&(T.s=1),T},s.comparedTo=function(T,C){return Jl(this,new b(T,C))},s.decimalPlaces=s.dp=function(T,C){var I,M,O,N=this;if(T!=null)return ri(T,0,Qi),C==null?C=o:ri(C,0,8),k(new b(N),T+N.e+1,C);if(!(I=N.c))return null;if(M=((O=I.length-1)-kr(this.e/Gt))*Gt,O=I[O])for(;O%10==0;O/=10,M--);return M<0&&(M=0),M},s.dividedBy=s.div=function(T,C){return t(this,new b(T,C),a,o)},s.dividedToIntegerBy=s.idiv=function(T,C){return t(this,new b(T,C),0,1)},s.exponentiatedBy=s.pow=function(T,C){var I,M,O,N,D,P,U,Q,z,H=this;if(T=new b(T),T.c&&!T.isInteger())throw Error(Zs+"Exponent not an integer: "+L(T));if(C!=null&&(C=new b(C)),P=T.e>14,!H.c||!H.c[0]||H.c[0]==1&&!H.e&&H.c.length==1||!T.c||!T.c[0])return z=new b(Math.pow(+L(H),P?T.s*(2-am(T)):+L(T))),C?z.mod(C):z;if(U=T.s<0,C){if(C.c?!C.c[0]:!C.s)return new b(NaN);M=!U&&H.isInteger()&&C.isInteger(),M&&(H=H.mod(C))}else{if(T.e>9&&(H.e>0||H.e<-1||(H.e==0?H.c[0]>1||P&&H.c[1]>=24e7:H.c[0]<8e13||P&&H.c[0]<=9999975e7)))return N=H.s<0&&am(T)?-0:0,H.e>-1&&(N=1/N),new b(U?1/N:N);A&&(N=Rv(A/Gt+2))}for(P?(I=new b(.5),U&&(T.s=1),Q=am(T)):(O=Math.abs(+L(T)),Q=O%2),z=new b(r);;){if(Q){if(z=z.times(H),!z.c)break;N?z.c.length>N&&(z.c.length=N):M&&(z=z.mod(C))}if(O){if(O=Rr(O/2),O===0)break;Q=O%2}else if(T=T.times(I),k(T,T.e+1,1),T.e>14)Q=am(T);else{if(O=+L(T),O===0)break;Q=O%2}H=H.times(H),N?H.c&&H.c.length>N&&(H.c.length=N):M&&(H=H.mod(C))}return M?z:(U&&(z=r.div(z)),C?z.mod(C):N?k(z,A,o,D):z)},s.integerValue=function(T){var C=new b(this);return T==null?T=o:ri(T,0,8),k(C,C.e+1,T)},s.isEqualTo=s.eq=function(T,C){return Jl(this,new b(T,C))===0},s.isFinite=function(){return!!this.c},s.isGreaterThan=s.gt=function(T,C){return Jl(this,new b(T,C))>0},s.isGreaterThanOrEqualTo=s.gte=function(T,C){return(C=Jl(this,new b(T,C)))===1||C===0},s.isInteger=function(){return!!this.c&&kr(this.e/Gt)>this.c.length-2},s.isLessThan=s.lt=function(T,C){return Jl(this,new b(T,C))<0},s.isLessThanOrEqualTo=s.lte=function(T,C){return(C=Jl(this,new b(T,C)))===-1||C===0},s.isNaN=function(){return!this.s},s.isNegative=function(){return this.s<0},s.isPositive=function(){return this.s>0},s.isZero=function(){return!!this.c&&this.c[0]==0},s.minus=function(T,C){var I,M,O,N,D=this,P=D.s;if(T=new b(T,C),C=T.s,!P||!C)return new b(NaN);if(P!=C)return T.s=-C,D.plus(T);var U=D.e/Gt,Q=T.e/Gt,z=D.c,H=T.c;if(!U||!Q){if(!z||!H)return z?(T.s=-C,T):new b(H?D:NaN);if(!z[0]||!H[0])return H[0]?(T.s=-C,T):new b(z[0]?D:o==3?-0:0)}if(U=kr(U),Q=kr(Q),z=z.slice(),P=U-Q){for((N=P<0)?(P=-P,O=z):(Q=U,O=H),O.reverse(),C=P;C--;O.push(0));O.reverse()}else for(M=(N=(P=z.length)<(C=H.length))?P:C,P=C=0;C<M;C++)if(z[C]!=H[C]){N=z[C]<H[C];break}if(N&&(O=z,z=H,H=O,T.s=-T.s),C=(M=H.length)-(I=z.length),C>0)for(;C--;z[I++]=0);for(C=Xr-1;M>P;){if(z[--M]<H[M]){for(I=M;I&&!z[--I];z[I]=C);--z[I],z[M]+=Xr}z[M]-=H[M]}for(;z[0]==0;z.splice(0,1),--Q);return z[0]?R(T,z,Q):(T.s=o==3?-1:1,T.c=[T.e=0],T)},s.modulo=s.mod=function(T,C){var I,M,O=this;return T=new b(T,C),!O.c||!T.s||T.c&&!T.c[0]?new b(NaN):!T.c||O.c&&!O.c[0]?new b(O):(m==9?(M=T.s,T.s=1,I=t(O,T,0,3),T.s=M,I.s*=M):I=t(O,T,0,m),T=O.minus(I.times(T)),!T.c[0]&&m==1&&(T.s=O.s),T)},s.multipliedBy=s.times=function(T,C){var I,M,O,N,D,P,U,Q,z,H,W,te,J,K,re,ce=this,oe=ce.c,ge=(T=new b(T,C)).c;if(!oe||!ge||!oe[0]||!ge[0])return!ce.s||!T.s||oe&&!oe[0]&&!ge||ge&&!ge[0]&&!oe?T.c=T.e=T.s=null:(T.s*=ce.s,!oe||!ge?T.c=T.e=null:(T.c=[0],T.e=0)),T;for(M=kr(ce.e/Gt)+kr(T.e/Gt),T.s*=ce.s,U=oe.length,H=ge.length,U<H&&(J=oe,oe=ge,ge=J,O=U,U=H,H=O),O=U+H,J=[];O--;J.push(0));for(K=Xr,re=jo,O=H;--O>=0;){for(I=0,W=ge[O]%re,te=ge[O]/re|0,D=U,N=O+D;N>O;)Q=oe[--D]%re,z=oe[D]/re|0,P=te*Q+z*W,Q=W*Q+P%re*re+J[N]+I,I=(Q/K|0)+(P/re|0)+te*z,J[N--]=Q%K;J[N]=I}return I?++M:J.splice(0,1),R(T,J,M)},s.negated=function(){var T=new b(this);return T.s=-T.s||null,T},s.plus=function(T,C){var I,M=this,O=M.s;if(T=new b(T,C),C=T.s,!O||!C)return new b(NaN);if(O!=C)return T.s=-C,M.minus(T);var N=M.e/Gt,D=T.e/Gt,P=M.c,U=T.c;if(!N||!D){if(!P||!U)return new b(O/0);if(!P[0]||!U[0])return U[0]?T:new b(P[0]?M:O*0)}if(N=kr(N),D=kr(D),P=P.slice(),O=N-D){for(O>0?(D=N,I=U):(O=-O,I=P),I.reverse();O--;I.push(0));I.reverse()}for(O=P.length,C=U.length,O-C<0&&(I=U,U=P,P=I,C=O),O=0;C;)O=(P[--C]=P[C]+U[C]+O)/Xr|0,P[C]=Xr===P[C]?0:P[C]%Xr;return O&&(P=[O].concat(P),++D),R(T,P,D)},s.precision=s.sd=function(T,C){var I,M,O,N=this;if(T!=null&&T!==!!T)return ri(T,1,Qi),C==null?C=o:ri(C,0,8),k(new b(N),T,C);if(!(I=N.c))return null;if(O=I.length-1,M=O*Gt+1,O=I[O]){for(;O%10==0;O/=10,M--);for(O=I[0];O>=10;O/=10,M++);}return T&&N.e+1>M&&(M=N.e+1),M},s.shiftedBy=function(T){return ri(T,-kv,kv),this.times("1e"+T)},s.squareRoot=s.sqrt=function(){var T,C,I,M,O,N=this,D=N.c,P=N.s,U=N.e,Q=a+4,z=new b("0.5");if(P!==1||!D||!D[0])return new b(!P||P<0&&(!D||D[0])?NaN:D?N:1/0);if(P=Math.sqrt(+L(N)),P==0||P==1/0?(C=Tr(D),(C.length+U)%2==0&&(C+="0"),P=Math.sqrt(+C),U=kr((U+1)/2)-(U<0||U%2),P==1/0?C="5e"+U:(C=P.toExponential(),C=C.slice(0,C.indexOf("e")+1)+U),I=new b(C)):I=new b(P+""),I.c[0]){for(U=I.e,P=U+Q,P<3&&(P=0);;)if(O=I,I=z.times(O.plus(t(N,O,Q,1))),Tr(O.c).slice(0,P)===(C=Tr(I.c)).slice(0,P))if(I.e<U&&--P,C=C.slice(P-3,P+1),C=="9999"||!M&&C=="4999"){if(!M&&(k(O,O.e+a+2,0),O.times(O).eq(N))){I=O;break}Q+=4,P+=4,M=1}else{(!+C||!+C.slice(1)&&C.charAt(0)=="5")&&(k(I,I.e+a+2,1),T=!I.times(I).eq(N));break}}return k(I,I.e+a+1,o,T)},s.toExponential=function(T,C){return T!=null&&(ri(T,0,Qi),T++),w(this,T,C,1)},s.toFixed=function(T,C){return T!=null&&(ri(T,0,Qi),T=T+this.e+1),w(this,T,C)},s.toFormat=function(T,C,I){var M,O=this;if(I==null)T!=null&&C&&typeof C=="object"?(I=C,C=null):T&&typeof T=="object"?(I=T,T=C=null):I=y;else if(typeof I!="object")throw Error(Zs+"Argument not an object: "+I);if(M=O.toFixed(T,C),O.c){var N,D=M.split("."),P=+I.groupSize,U=+I.secondaryGroupSize,Q=I.groupSeparator||"",z=D[0],H=D[1],W=O.s<0,te=W?z.slice(1):z,J=te.length;if(U&&(N=P,P=U,U=N,J-=N),P>0&&J>0){for(N=J%P||P,z=te.substr(0,N);N<J;N+=P)z+=Q+te.substr(N,P);U>0&&(z+=Q+te.slice(N)),W&&(z="-"+z)}M=H?z+(I.decimalSeparator||"")+((U=+I.fractionGroupSize)?H.replace(new RegExp("\\d{"+U+"}\\B","g"),"$&"+(I.fractionGroupSeparator||"")):H):z}return(I.prefix||"")+M+(I.suffix||"")},s.toFraction=function(T){var C,I,M,O,N,D,P,U,Q,z,H,W,te=this,J=te.c;if(T!=null&&(P=new b(T),!P.isInteger()&&(P.c||P.s!==1)||P.lt(r)))throw Error(Zs+"Argument "+(P.isInteger()?"out of range: ":"not an integer: ")+L(P));if(!J)return new b(te);for(C=new b(r),Q=I=new b(r),M=U=new b(r),W=Tr(J),N=C.e=W.length-te.e-1,C.c[0]=Nv[(D=N%Gt)<0?Gt+D:D],T=!T||P.comparedTo(C)>0?N>0?C:Q:P,D=d,d=1/0,P=new b(W),U.c[0]=0;z=t(P,C,0,1),O=I.plus(z.times(M)),O.comparedTo(T)!=1;)I=M,M=O,Q=U.plus(z.times(O=Q)),U=O,C=P.minus(z.times(O=C)),P=O;return O=t(T.minus(I),M,0,1),U=U.plus(O.times(Q)),I=I.plus(O.times(M)),U.s=Q.s=te.s,N=N*2,H=t(Q,M,N,o).minus(te).abs().comparedTo(t(U,I,N,o).minus(te).abs())<1?[Q,M]:[U,I],d=D,H},s.toNumber=function(){return+L(this)},s.toPrecision=function(T,C){return T!=null&&ri(T,1,Qi),w(this,T,C,2)},s.toString=function(T){var C,I=this,M=I.s,O=I.e;return O===null?M?(C="Infinity",M<0&&(C="-"+C)):C="NaN":(T==null?C=O<=l||O>=c?om(Tr(I.c),O):io(Tr(I.c),O,"0"):T===10&&v?(I=k(new b(I),a+O+1,o),C=io(Tr(I.c),I.e,"0")):(ri(T,2,x.length,"Base"),C=n(io(Tr(I.c),O,"0"),10,T,M,!0)),M<0&&I.c[0]&&(C="-"+C)),C},s.valueOf=s.toJSON=function(){return L(this)},s._isBigNumber=!0,s[Symbol.toStringTag]="BigNumber",s[Symbol.for("nodejs.util.inspect.custom")]=s.valueOf,e!=null&&b.set(e),b}function kr(e){var t=e|0;return e>0||e===t?t:t-1}function Tr(e){for(var t,n,i=1,s=e.length,r=e[0]+"";i<s;){for(t=e[i++]+"",n=Gt-t.length;n--;t="0"+t);r+=t}for(s=r.length;r.charCodeAt(--s)===48;);return r.slice(0,s+1||1)}function Jl(e,t){var n,i,s=e.c,r=t.c,a=e.s,o=t.s,l=e.e,c=t.e;if(!a||!o)return null;if(n=s&&!s[0],i=r&&!r[0],n||i)return n?i?0:-o:a;if(a!=o)return a;if(n=a<0,i=l==c,!s||!r)return i?0:!s^n?1:-1;if(!i)return l>c^n?1:-1;for(o=(l=s.length)<(c=r.length)?l:c,a=0;a<o;a++)if(s[a]!=r[a])return s[a]>r[a]^n?1:-1;return l==c?0:l>c^n?1:-1}function ri(e,t,n,i){if(e<t||e>n||e!==Rr(e))throw Error(Zs+(i||"Argument")+(typeof e=="number"?e<t||e>n?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function am(e){var t=e.c.length-1;return kr(e.e/Gt)==t&&e.c[t]%2!=0}function om(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function io(e,t,n){var i,s;if(t<0){for(s=n+".";++t;s+=n);e=s+e}else if(i=e.length,++t>i){for(s=n,t-=i;--t;s+=n);e+=s}else t<i&&(e=e.slice(0,t)+"."+e.slice(t));return e}var Da=hR(),E4=class{key;left=null;right=null;constructor(e){this.key=e}},fd=class extends E4{constructor(e){super(e)}},C4=class{size=0;modificationCount=0;splayCount=0;splay(e){const t=this.root;if(t==null)return this.compare(e,e),-1;let n=null,i=null,s=null,r=null,a=t;const o=this.compare;let l;for(;;)if(l=o(a.key,e),l>0){let c=a.left;if(c==null||(l=o(c.key,e),l>0&&(a.left=c.right,c.right=a,a=c,c=a.left,c==null)))break;n==null?i=a:n.left=a,n=a,a=c}else if(l<0){let c=a.right;if(c==null||(l=o(c.key,e),l<0&&(a.right=c.left,c.left=a,a=c,c=a.right,c==null)))break;s==null?r=a:s.right=a,s=a,a=c}else break;return s!=null&&(s.right=a.left,a.left=r),n!=null&&(n.left=a.right,a.right=i),this.root!==a&&(this.root=a,this.splayCount++),l}splayMin(e){let t=e,n=t.left;for(;n!=null;){const i=n;t.left=i.right,i.right=t,t=i,n=t.left}return t}splayMax(e){let t=e,n=t.right;for(;n!=null;){const i=n;t.right=i.left,i.left=t,t=i,n=t.right}return t}_delete(e){if(this.root==null||this.splay(e)!=0)return null;let t=this.root;const n=t,i=t.left;if(this.size--,i==null)this.root=t.right;else{const s=t.right;t=this.splayMax(i),t.right=s,this.root=t}return this.modificationCount++,n}addNewRoot(e,t){this.size++,this.modificationCount++;const n=this.root;if(n==null){this.root=e;return}t<0?(e.left=n,e.right=n.right,n.right=null):(e.right=n,e.left=n.left,n.left=null),this.root=e}_first(){const e=this.root;return e==null?null:(this.root=this.splayMin(e),this.root)}_last(){const e=this.root;return e==null?null:(this.root=this.splayMax(e),this.root)}clear(){this.root=null,this.size=0,this.modificationCount++}has(e){return this.validKey(e)&&this.splay(e)==0}defaultCompare(){return(e,t)=>e<t?-1:e>t?1:0}wrap(){return{getRoot:()=>this.root,setRoot:e=>{this.root=e},getSize:()=>this.size,getModificationCount:()=>this.modificationCount,getSplayCount:()=>this.splayCount,setSplayCount:e=>{this.splayCount=e},splay:e=>this.splay(e),has:e=>this.has(e)}}},I_=class Yd extends C4{root=null;compare;validKey;constructor(t,n){super(),this.compare=t??this.defaultCompare(),this.validKey=n??(i=>i!=null&&i!=null)}delete(t){return this.validKey(t)?this._delete(t)!=null:!1}deleteAll(t){for(const n of t)this.delete(n)}forEach(t){const n=this[Symbol.iterator]();let i;for(;i=n.next(),!i.done;)t(i.value,i.value,this)}add(t){const n=this.splay(t);return n!=0&&this.addNewRoot(new fd(t),n),this}addAndReturn(t){const n=this.splay(t);return n!=0&&this.addNewRoot(new fd(t),n),this.root.key}addAll(t){for(const n of t)this.add(n)}isEmpty(){return this.root==null}isNotEmpty(){return this.root!=null}single(){if(this.size==0)throw"Bad state: No element";if(this.size>1)throw"Bad state: Too many element";return this.root.key}first(){if(this.size==0)throw"Bad state: No element";return this._first().key}last(){if(this.size==0)throw"Bad state: No element";return this._last().key}lastBefore(t){if(t==null)throw"Invalid arguments(s)";if(this.root==null)return null;if(this.splay(t)<0)return this.root.key;let n=this.root.left;if(n==null)return null;let i=n.right;for(;i!=null;)n=i,i=n.right;return n.key}firstAfter(t){if(t==null)throw"Invalid arguments(s)";if(this.root==null)return null;if(this.splay(t)>0)return this.root.key;let n=this.root.right;if(n==null)return null;let i=n.left;for(;i!=null;)n=i,i=n.left;return n.key}retainAll(t){const n=new Yd(this.compare,this.validKey),i=this.modificationCount;for(const s of t){if(i!=this.modificationCount)throw"Concurrent modification during iteration.";this.validKey(s)&&this.splay(s)==0&&n.add(this.root.key)}n.size!=this.size&&(this.root=n.root,this.size=n.size,this.modificationCount++)}lookup(t){return!this.validKey(t)||this.splay(t)!=0?null:this.root.key}intersection(t){const n=new Yd(this.compare,this.validKey);for(const i of this)t.has(i)&&n.add(i);return n}difference(t){const n=new Yd(this.compare,this.validKey);for(const i of this)t.has(i)||n.add(i);return n}union(t){const n=this.clone();return n.addAll(t),n}clone(){const t=new Yd(this.compare,this.validKey);return t.size=this.size,t.root=this.copyNode(this.root),t}copyNode(t){if(t==null)return null;function n(s,r){let a,o;do{if(a=s.left,o=s.right,a!=null){const l=new fd(a.key);r.left=l,n(a,l)}if(o!=null){const l=new fd(o.key);r.right=l,s=o,r=l}}while(o!=null)}const i=new fd(t.key);return n(t,i),i}toSet(){return this.clone()}entries(){return new S4(this.wrap())}keys(){return this[Symbol.iterator]()}values(){return this[Symbol.iterator]()}[Symbol.iterator](){return new w4(this.wrap())}[Symbol.toStringTag]="[object Set]"},uR=class{tree;path=new Array;modificationCount=null;splayCount;constructor(e){this.tree=e,this.splayCount=e.getSplayCount()}[Symbol.iterator](){return this}next(){return this.moveNext()?{done:!1,value:this.current()}:{done:!0,value:null}}current(){if(!this.path.length)return null;const e=this.path[this.path.length-1];return this.getValue(e)}rebuildPath(e){this.path.splice(0,this.path.length),this.tree.splay(e),this.path.push(this.tree.getRoot()),this.splayCount=this.tree.getSplayCount()}findLeftMostDescendent(e){for(;e!=null;)this.path.push(e),e=e.left}moveNext(){if(this.modificationCount!=this.tree.getModificationCount()){if(this.modificationCount==null){this.modificationCount=this.tree.getModificationCount();let n=this.tree.getRoot();for(;n!=null;)this.path.push(n),n=n.left;return this.path.length>0}throw"Concurrent modification during iteration."}if(!this.path.length)return!1;this.splayCount!=this.tree.getSplayCount()&&this.rebuildPath(this.path[this.path.length-1].key);let e=this.path[this.path.length-1],t=e.right;if(t!=null){for(;t!=null;)this.path.push(t),t=t.left;return!0}for(this.path.pop();this.path.length&&this.path[this.path.length-1].right===e;)e=this.path.pop();return this.path.length>0}},w4=class extends uR{getValue(e){return e.key}},S4=class extends uR{getValue(e){return[e.key,e.key]}},dR=e=>()=>e,lb=e=>{const t=e?(n,i)=>i.minus(n).abs().isLessThanOrEqualTo(e):dR(!1);return(n,i)=>t(n,i)?0:n.comparedTo(i)};function I4(e){const t=e?(n,i,s,r,a)=>n.exponentiatedBy(2).isLessThanOrEqualTo(r.minus(i).exponentiatedBy(2).plus(a.minus(s).exponentiatedBy(2)).times(e)):dR(!1);return(n,i,s)=>{const r=n.x,a=n.y,o=s.x,l=s.y,c=a.minus(l).times(i.x.minus(o)).minus(r.minus(o).times(i.y.minus(l)));return t(c,r,a,o,l)?0:c.comparedTo(0)}}var M4=e=>e,T4=e=>{if(e){const t=new I_(lb(e)),n=new I_(lb(e)),i=(r,a)=>a.addAndReturn(r),s=r=>({x:i(r.x,t),y:i(r.y,n)});return s({x:new Da(0),y:new Da(0)}),s}return M4},cb=e=>({set:t=>{Fo=cb(t)},reset:()=>cb(e),compare:lb(e),snap:T4(e),orient:I4(e)}),Fo=cb(),md=(e,t)=>e.ll.x.isLessThanOrEqualTo(t.x)&&t.x.isLessThanOrEqualTo(e.ur.x)&&e.ll.y.isLessThanOrEqualTo(t.y)&&t.y.isLessThanOrEqualTo(e.ur.y),hb=(e,t)=>{if(t.ur.x.isLessThan(e.ll.x)||e.ur.x.isLessThan(t.ll.x)||t.ur.y.isLessThan(e.ll.y)||e.ur.y.isLessThan(t.ll.y))return null;const n=e.ll.x.isLessThan(t.ll.x)?t.ll.x:e.ll.x,i=e.ur.x.isLessThan(t.ur.x)?e.ur.x:t.ur.x,s=e.ll.y.isLessThan(t.ll.y)?t.ll.y:e.ll.y,r=e.ur.y.isLessThan(t.ur.y)?e.ur.y:t.ur.y;return{ll:{x:n,y:s},ur:{x:i,y:r}}},Hg=(e,t)=>e.x.times(t.y).minus(e.y.times(t.x)),pR=(e,t)=>e.x.times(t.x).plus(e.y.times(t.y)),M_=e=>pR(e,e).sqrt(),L4=(e,t,n)=>{const i={x:t.x.minus(e.x),y:t.y.minus(e.y)},s={x:n.x.minus(e.x),y:n.y.minus(e.y)};return Hg(s,i).div(M_(s)).div(M_(i))},B4=(e,t,n)=>{const i={x:t.x.minus(e.x),y:t.y.minus(e.y)},s={x:n.x.minus(e.x),y:n.y.minus(e.y)};return pR(s,i).div(M_(s)).div(M_(i))},QS=(e,t,n)=>t.y.isZero()?null:{x:e.x.plus(t.x.div(t.y).times(n.minus(e.y))),y:n},GS=(e,t,n)=>t.x.isZero()?null:{x:n,y:e.y.plus(t.y.div(t.x).times(n.minus(e.x)))},R4=(e,t,n,i)=>{if(t.x.isZero())return GS(n,i,e.x);if(i.x.isZero())return GS(e,t,n.x);if(t.y.isZero())return QS(n,i,e.y);if(i.y.isZero())return QS(e,t,n.y);const s=Hg(t,i);if(s.isZero())return null;const r={x:n.x.minus(e.x),y:n.y.minus(e.y)},a=Hg(r,t).div(s),o=Hg(r,i).div(s),l=e.x.plus(o.times(t.x)),c=n.x.plus(a.times(i.x)),h=e.y.plus(o.times(t.y)),d=n.y.plus(a.times(i.y));return{x:l.plus(c).div(2),y:h.plus(d).div(2)}},Ma=class fR{point;isLeft;segment;otherSE;consumedBy;static compare(t,n){const i=fR.comparePoints(t.point,n.point);return i!==0?i:(t.point!==n.point&&t.link(n),t.isLeft!==n.isLeft?t.isLeft?1:-1:T_.compare(t.segment,n.segment))}static comparePoints(t,n){return t.x.isLessThan(n.x)?-1:t.x.isGreaterThan(n.x)?1:t.y.isLessThan(n.y)?-1:t.y.isGreaterThan(n.y)?1:0}constructor(t,n){t.events===void 0?t.events=[this]:t.events.push(this),this.point=t,this.isLeft=n}link(t){if(t.point===this.point)throw new Error("Tried to link already linked events");const n=t.point.events;for(let i=0,s=n.length;i<s;i++){const r=n[i];this.point.events.push(r),r.point=this.point}this.checkForConsuming()}checkForConsuming(){const t=this.point.events.length;for(let n=0;n<t;n++){const i=this.point.events[n];if(i.segment.consumedBy===void 0)for(let s=n+1;s<t;s++){const r=this.point.events[s];r.consumedBy===void 0&&i.otherSE.point.events===r.otherSE.point.events&&i.segment.consume(r.segment)}}}getAvailableLinkedEvents(){const t=[];for(let n=0,i=this.point.events.length;n<i;n++){const s=this.point.events[n];s!==this&&!s.segment.ringOut&&s.segment.isInResult()&&t.push(s)}return t}getLeftmostComparator(t){const n=new Map,i=s=>{const r=s.otherSE;n.set(s,{sine:L4(this.point,t.point,r.point),cosine:B4(this.point,t.point,r.point)})};return(s,r)=>{n.has(s)||i(s),n.has(r)||i(r);const{sine:a,cosine:o}=n.get(s),{sine:l,cosine:c}=n.get(r);return a.isGreaterThanOrEqualTo(0)&&l.isGreaterThanOrEqualTo(0)?o.isLessThan(c)?1:o.isGreaterThan(c)?-1:0:a.isLessThan(0)&&l.isLessThan(0)?o.isLessThan(c)?-1:o.isGreaterThan(c)?1:0:l.isLessThan(a)?-1:l.isGreaterThan(a)?1:0}}},k4=class ub{events;poly;_isExteriorRing;_enclosingRing;static factory(t){const n=[];for(let i=0,s=t.length;i<s;i++){const r=t[i];if(!r.isInResult()||r.ringOut)continue;let a=null,o=r.leftSE,l=r.rightSE;const c=[o],h=o.point,d=[];for(;a=o,o=l,c.push(o),o.point!==h;)for(;;){const f=o.getAvailableLinkedEvents();if(f.length===0){const y=c[0].point,x=c[c.length-1].point;throw new Error(`Unable to complete output ring starting at [${y.x}, ${y.y}]. Last matching segment found ends at [${x.x}, ${x.y}].`)}if(f.length===1){l=f[0].otherSE;break}let m=null;for(let y=0,x=d.length;y<x;y++)if(d[y].point===o.point){m=y;break}if(m!==null){const y=d.splice(m)[0],x=c.splice(y.index);x.unshift(x[0].otherSE),n.push(new ub(x.reverse()));continue}d.push({index:c.length,point:o.point});const A=o.getLeftmostComparator(a);l=f.sort(A)[0].otherSE;break}n.push(new ub(c))}return n}constructor(t){this.events=t;for(let n=0,i=t.length;n<i;n++)t[n].segment.ringOut=this;this.poly=null}getGeom(){let t=this.events[0].point;const n=[t];for(let c=1,h=this.events.length-1;c<h;c++){const d=this.events[c].point,f=this.events[c+1].point;Fo.orient(d,t,f)!==0&&(n.push(d),t=d)}if(n.length===1)return null;const i=n[0],s=n[1];Fo.orient(i,t,s)===0&&n.shift(),n.push(n[0]);const r=this.isExteriorRing()?1:-1,a=this.isExteriorRing()?0:n.length-1,o=this.isExteriorRing()?n.length:-1,l=[];for(let c=a;c!=o;c+=r)l.push([n[c].x.toNumber(),n[c].y.toNumber()]);return l}isExteriorRing(){if(this._isExteriorRing===void 0){const t=this.enclosingRing();this._isExteriorRing=t?!t.isExteriorRing():!0}return this._isExteriorRing}enclosingRing(){return this._enclosingRing===void 0&&(this._enclosingRing=this._calcEnclosingRing()),this._enclosingRing}_calcEnclosingRing(){let t=this.events[0];for(let s=1,r=this.events.length;s<r;s++){const a=this.events[s];Ma.compare(t,a)>0&&(t=a)}let n=t.segment.prevInResult(),i=n?n.prevInResult():null;for(;;){if(!n)return null;if(!i)return n.ringOut;if(i.ringOut!==n.ringOut)return i.ringOut?.enclosingRing()!==n.ringOut?n.ringOut:n.ringOut?.enclosingRing();n=i.prevInResult(),i=n?n.prevInResult():null}}},HS=class{exteriorRing;interiorRings;constructor(e){this.exteriorRing=e,e.poly=this,this.interiorRings=[]}addInterior(e){this.interiorRings.push(e),e.poly=this}getGeom(){const e=this.exteriorRing.getGeom();if(e===null)return null;const t=[e];for(let n=0,i=this.interiorRings.length;n<i;n++){const s=this.interiorRings[n].getGeom();s!==null&&t.push(s)}return t}},N4=class{rings;polys;constructor(e){this.rings=e,this.polys=this._composePolys(e)}getGeom(){const e=[];for(let t=0,n=this.polys.length;t<n;t++){const i=this.polys[t].getGeom();i!==null&&e.push(i)}return e}_composePolys(e){const t=[];for(let n=0,i=e.length;n<i;n++){const s=e[n];if(!s.poly)if(s.isExteriorRing())t.push(new HS(s));else{const r=s.enclosingRing();r?.poly||t.push(new HS(r)),r?.poly?.addInterior(s)}}return t}},P4=class{queue;tree;segments;constructor(e,t=T_.compare){this.queue=e,this.tree=new I_(t),this.segments=[]}process(e){const t=e.segment,n=[];if(e.consumedBy)return e.isLeft?this.queue.delete(e.otherSE):this.tree.delete(t),n;e.isLeft&&this.tree.add(t);let i=t,s=t;do i=this.tree.lastBefore(i);while(i!=null&&i.consumedBy!=null);do s=this.tree.firstAfter(s);while(s!=null&&s.consumedBy!=null);if(e.isLeft){let r=null;if(i){const o=i.getIntersection(t);if(o!==null&&(t.isAnEndpoint(o)||(r=o),!i.isAnEndpoint(o))){const l=this._splitSafely(i,o);for(let c=0,h=l.length;c<h;c++)n.push(l[c])}}let a=null;if(s){const o=s.getIntersection(t);if(o!==null&&(t.isAnEndpoint(o)||(a=o),!s.isAnEndpoint(o))){const l=this._splitSafely(s,o);for(let c=0,h=l.length;c<h;c++)n.push(l[c])}}if(r!==null||a!==null){let o=null;r===null?o=a:a===null?o=r:o=Ma.comparePoints(r,a)<=0?r:a,this.queue.delete(t.rightSE),n.push(t.rightSE);const l=t.split(o);for(let c=0,h=l.length;c<h;c++)n.push(l[c])}n.length>0?(this.tree.delete(t),n.push(e)):(this.segments.push(t),t.prev=i)}else{if(i&&s){const r=i.getIntersection(s);if(r!==null){if(!i.isAnEndpoint(r)){const a=this._splitSafely(i,r);for(let o=0,l=a.length;o<l;o++)n.push(a[o])}if(!s.isAnEndpoint(r)){const a=this._splitSafely(s,r);for(let o=0,l=a.length;o<l;o++)n.push(a[o])}}}this.tree.delete(t)}return n}_splitSafely(e,t){this.tree.delete(e);const n=e.rightSE;this.queue.delete(n);const i=e.split(t);return i.push(n),e.consumedBy===void 0&&this.tree.add(e),i}},D4=class{type;numMultiPolys;run(e,t,n){jd.type=e;const i=[new VS(t,!0)];for(let o=0,l=n.length;o<l;o++)i.push(new VS(n[o],!1));if(jd.numMultiPolys=i.length,jd.type==="difference"){const o=i[0];let l=1;for(;l<i.length;)hb(i[l].bbox,o.bbox)!==null?l++:i.splice(l,1)}if(jd.type==="intersection")for(let o=0,l=i.length;o<l;o++){const c=i[o];for(let h=o+1,d=i.length;h<d;h++)if(hb(c.bbox,i[h].bbox)===null)return[]}const s=new I_(Ma.compare);for(let o=0,l=i.length;o<l;o++){const c=i[o].getSweepEvents();for(let h=0,d=c.length;h<d;h++)s.add(c[h])}const r=new P4(s);let a=null;for(s.size!=0&&(a=s.first(),s.delete(a));a;){const o=r.process(a);for(let l=0,c=o.length;l<c;l++){const h=o[l];h.consumedBy===void 0&&s.add(h)}s.size!=0?(a=s.first(),s.delete(a)):a=null}return Fo.reset(),new N4(k4.factory(r.segments)).getGeom()}},jd=new D4,Fp=jd,F4=0,T_=class $g{id;leftSE;rightSE;rings;windings;ringOut;consumedBy;prev;_prevInResult;_beforeState;_afterState;_isInResult;static compare(t,n){const i=t.leftSE.point.x,s=n.leftSE.point.x,r=t.rightSE.point.x,a=n.rightSE.point.x;if(a.isLessThan(i))return 1;if(r.isLessThan(s))return-1;const o=t.leftSE.point.y,l=n.leftSE.point.y,c=t.rightSE.point.y,h=n.rightSE.point.y;if(i.isLessThan(s)){if(l.isLessThan(o)&&l.isLessThan(c))return 1;if(l.isGreaterThan(o)&&l.isGreaterThan(c))return-1;const d=t.comparePoint(n.leftSE.point);if(d<0)return 1;if(d>0)return-1;const f=n.comparePoint(t.rightSE.point);return f!==0?f:-1}if(i.isGreaterThan(s)){if(o.isLessThan(l)&&o.isLessThan(h))return-1;if(o.isGreaterThan(l)&&o.isGreaterThan(h))return 1;const d=n.comparePoint(t.leftSE.point);if(d!==0)return d;const f=t.comparePoint(n.rightSE.point);return f<0?1:f>0?-1:1}if(o.isLessThan(l))return-1;if(o.isGreaterThan(l))return 1;if(r.isLessThan(a)){const d=n.comparePoint(t.rightSE.point);if(d!==0)return d}if(r.isGreaterThan(a)){const d=t.comparePoint(n.rightSE.point);if(d<0)return 1;if(d>0)return-1}if(!r.eq(a)){const d=c.minus(o),f=r.minus(i),m=h.minus(l),A=a.minus(s);if(d.isGreaterThan(f)&&m.isLessThan(A))return 1;if(d.isLessThan(f)&&m.isGreaterThan(A))return-1}return r.isGreaterThan(a)?1:r.isLessThan(a)||c.isLessThan(h)?-1:c.isGreaterThan(h)?1:t.id<n.id?-1:t.id>n.id?1:0}constructor(t,n,i,s){this.id=++F4,this.leftSE=t,t.segment=this,t.otherSE=n,this.rightSE=n,n.segment=this,n.otherSE=t,this.rings=i,this.windings=s}static fromRing(t,n,i){let s,r,a;const o=Ma.comparePoints(t,n);if(o<0)s=t,r=n,a=1;else if(o>0)s=n,r=t,a=-1;else throw new Error(`Tried to create degenerate segment at [${t.x}, ${t.y}]`);return new $g(new Ma(s,!0),new Ma(r,!1),[i],[a])}replaceRightSE(t){this.rightSE=t,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const t=this.leftSE.point.y,n=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:t.isLessThan(n)?t:n},ur:{x:this.rightSE.point.x,y:t.isGreaterThan(n)?t:n}}}vector(){return{x:this.rightSE.point.x.minus(this.leftSE.point.x),y:this.rightSE.point.y.minus(this.leftSE.point.y)}}isAnEndpoint(t){return t.x.eq(this.leftSE.point.x)&&t.y.eq(this.leftSE.point.y)||t.x.eq(this.rightSE.point.x)&&t.y.eq(this.rightSE.point.y)}comparePoint(t){return Fo.orient(this.leftSE.point,t,this.rightSE.point)}getIntersection(t){const n=this.bbox(),i=t.bbox(),s=hb(n,i);if(s===null)return null;const r=this.leftSE.point,a=this.rightSE.point,o=t.leftSE.point,l=t.rightSE.point,c=md(n,o)&&this.comparePoint(o)===0,h=md(i,r)&&t.comparePoint(r)===0,d=md(n,l)&&this.comparePoint(l)===0,f=md(i,a)&&t.comparePoint(a)===0;if(h&&c)return f&&!d?a:!f&&d?l:null;if(h)return d&&r.x.eq(l.x)&&r.y.eq(l.y)?null:r;if(c)return f&&a.x.eq(o.x)&&a.y.eq(o.y)?null:o;if(f&&d)return null;if(f)return a;if(d)return l;const m=R4(r,this.vector(),o,t.vector());return m===null||!md(s,m)?null:Fo.snap(m)}split(t){const n=[],i=t.events!==void 0,s=new Ma(t,!0),r=new Ma(t,!1),a=this.rightSE;this.replaceRightSE(r),n.push(r),n.push(s);const o=new $g(s,a,this.rings.slice(),this.windings.slice());return Ma.comparePoints(o.leftSE.point,o.rightSE.point)>0&&o.swapEvents(),Ma.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),i&&(s.checkForConsuming(),r.checkForConsuming()),n}swapEvents(){const t=this.rightSE;this.rightSE=this.leftSE,this.leftSE=t,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let n=0,i=this.windings.length;n<i;n++)this.windings[n]*=-1}consume(t){let n=this,i=t;for(;n.consumedBy;)n=n.consumedBy;for(;i.consumedBy;)i=i.consumedBy;const s=$g.compare(n,i);if(s!==0){if(s>0){const r=n;n=i,i=r}if(n.prev===i){const r=n;n=i,i=r}for(let r=0,a=i.rings.length;r<a;r++){const o=i.rings[r],l=i.windings[r],c=n.rings.indexOf(o);c===-1?(n.rings.push(o),n.windings.push(l)):n.windings[c]+=l}i.rings=null,i.windings=null,i.consumedBy=n,i.leftSE.consumedBy=n.leftSE,i.rightSE.consumedBy=n.rightSE}}prevInResult(){return this._prevInResult!==void 0?this._prevInResult:(this.prev?this.prev.isInResult()?this._prevInResult=this.prev:this._prevInResult=this.prev.prevInResult():this._prevInResult=null,this._prevInResult)}beforeState(){if(this._beforeState!==void 0)return this._beforeState;if(!this.prev)this._beforeState={rings:[],windings:[],multiPolys:[]};else{const t=this.prev.consumedBy||this.prev;this._beforeState=t.afterState()}return this._beforeState}afterState(){if(this._afterState!==void 0)return this._afterState;const t=this.beforeState();this._afterState={rings:t.rings.slice(0),windings:t.windings.slice(0),multiPolys:[]};const n=this._afterState.rings,i=this._afterState.windings,s=this._afterState.multiPolys;for(let o=0,l=this.rings.length;o<l;o++){const c=this.rings[o],h=this.windings[o],d=n.indexOf(c);d===-1?(n.push(c),i.push(h)):i[d]+=h}const r=[],a=[];for(let o=0,l=n.length;o<l;o++){if(i[o]===0)continue;const c=n[o],h=c.poly;if(a.indexOf(h)===-1)if(c.isExterior)r.push(h);else{a.indexOf(h)===-1&&a.push(h);const d=r.indexOf(c.poly);d!==-1&&r.splice(d,1)}}for(let o=0,l=r.length;o<l;o++){const c=r[o].multiPoly;s.indexOf(c)===-1&&s.push(c)}return this._afterState}isInResult(){if(this.consumedBy)return!1;if(this._isInResult!==void 0)return this._isInResult;const t=this.beforeState().multiPolys,n=this.afterState().multiPolys;switch(Fp.type){case"union":{const i=t.length===0,s=n.length===0;this._isInResult=i!==s;break}case"intersection":{let i,s;t.length<n.length?(i=t.length,s=n.length):(i=n.length,s=t.length),this._isInResult=s===Fp.numMultiPolys&&i<s;break}case"xor":{const i=Math.abs(t.length-n.length);this._isInResult=i%2===1;break}case"difference":{const i=s=>s.length===1&&s[0].isSubject;this._isInResult=i(t)!==i(n);break}}return this._isInResult}},$S=class{poly;isExterior;segments;bbox;constructor(e,t,n){if(!Array.isArray(e)||e.length===0)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=t,this.isExterior=n,this.segments=[],typeof e[0][0]!="number"||typeof e[0][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const i=Fo.snap({x:new Da(e[0][0]),y:new Da(e[0][1])});this.bbox={ll:{x:i.x,y:i.y},ur:{x:i.x,y:i.y}};let s=i;for(let r=1,a=e.length;r<a;r++){if(typeof e[r][0]!="number"||typeof e[r][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const o=Fo.snap({x:new Da(e[r][0]),y:new Da(e[r][1])});o.x.eq(s.x)&&o.y.eq(s.y)||(this.segments.push(T_.fromRing(s,o,this)),o.x.isLessThan(this.bbox.ll.x)&&(this.bbox.ll.x=o.x),o.y.isLessThan(this.bbox.ll.y)&&(this.bbox.ll.y=o.y),o.x.isGreaterThan(this.bbox.ur.x)&&(this.bbox.ur.x=o.x),o.y.isGreaterThan(this.bbox.ur.y)&&(this.bbox.ur.y=o.y),s=o)}(!i.x.eq(s.x)||!i.y.eq(s.y))&&this.segments.push(T_.fromRing(s,i,this))}getSweepEvents(){const e=[];for(let t=0,n=this.segments.length;t<n;t++){const i=this.segments[t];e.push(i.leftSE),e.push(i.rightSE)}return e}},O4=class{multiPoly;exteriorRing;interiorRings;bbox;constructor(e,t){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");this.exteriorRing=new $S(e[0],this,!0),this.bbox={ll:{x:this.exteriorRing.bbox.ll.x,y:this.exteriorRing.bbox.ll.y},ur:{x:this.exteriorRing.bbox.ur.x,y:this.exteriorRing.bbox.ur.y}},this.interiorRings=[];for(let n=1,i=e.length;n<i;n++){const s=new $S(e[n],this,!1);s.bbox.ll.x.isLessThan(this.bbox.ll.x)&&(this.bbox.ll.x=s.bbox.ll.x),s.bbox.ll.y.isLessThan(this.bbox.ll.y)&&(this.bbox.ll.y=s.bbox.ll.y),s.bbox.ur.x.isGreaterThan(this.bbox.ur.x)&&(this.bbox.ur.x=s.bbox.ur.x),s.bbox.ur.y.isGreaterThan(this.bbox.ur.y)&&(this.bbox.ur.y=s.bbox.ur.y),this.interiorRings.push(s)}this.multiPoly=t}getSweepEvents(){const e=this.exteriorRing.getSweepEvents();for(let t=0,n=this.interiorRings.length;t<n;t++){const i=this.interiorRings[t].getSweepEvents();for(let s=0,r=i.length;s<r;s++)e.push(i[s])}return e}},VS=class{isSubject;polys;bbox;constructor(e,t){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");try{typeof e[0][0][0]=="number"&&(e=[e])}catch{}this.polys=[],this.bbox={ll:{x:new Da(Number.POSITIVE_INFINITY),y:new Da(Number.POSITIVE_INFINITY)},ur:{x:new Da(Number.NEGATIVE_INFINITY),y:new Da(Number.NEGATIVE_INFINITY)}};for(let n=0,i=e.length;n<i;n++){const s=new O4(e[n],this);s.bbox.ll.x.isLessThan(this.bbox.ll.x)&&(this.bbox.ll.x=s.bbox.ll.x),s.bbox.ll.y.isLessThan(this.bbox.ll.y)&&(this.bbox.ll.y=s.bbox.ll.y),s.bbox.ur.x.isGreaterThan(this.bbox.ur.x)&&(this.bbox.ur.x=s.bbox.ur.x),s.bbox.ur.y.isGreaterThan(this.bbox.ur.y)&&(this.bbox.ur.y=s.bbox.ur.y),this.polys.push(s)}this.isSubject=t}getSweepEvents(){const e=[];for(let t=0,n=this.polys.length;t<n;t++){const i=this.polys[t].getSweepEvents();for(let s=0,r=i.length;s<r;s++)e.push(i[s])}return e}},U4=(e,...t)=>Fp.run("union",e,t),z4=(e,...t)=>Fp.run("intersection",e,t),Q4=(e,...t)=>Fp.run("difference",e,t);Fo.set;function mR(e){const t=[];if(Gl(e,s=>{t.push(s.coordinates)}),t.length<2)throw new Error("Must have at least two features");const n=e.features[0].properties||{},i=Q4(t[0],...t.slice(1));return i.length===0?null:i.length===1?Hr(i[0],n):mA(i,n)}function G4(e,t,n={}){const i=Si(e),s=Si(t);return s[0]+=s[0]-i[0]>180?-360:i[0]-s[0]>180?360:0,T2(H4(i,s),"meters",n.units)}function H4(e,t,n){n=n===void 0?$i:Number(n);const i=n,s=e[1]*Math.PI/180,r=t[1]*Math.PI/180,a=r-s;let o=Math.abs(t[0]-e[0])*Math.PI/180;o>Math.PI&&(o-=2*Math.PI);const l=Math.log(Math.tan(r/2+Math.PI/4)/Math.tan(s/2+Math.PI/4)),c=Math.abs(l)>1e-11?a/l:Math.cos(s);return Math.sqrt(a*a+c*c*o*o)*i}function gR(e,t,n,i={}){const s=t<0;let r=T2(Math.abs(t),i.units,"meters");s&&(r=-Math.abs(r));const a=Si(e),o=$4(a,r,n);return o[0]+=o[0]-a[0]>180?-360:a[0]-o[0]>180?360:0,wi(o,i.properties)}function $4(e,t,n,i){i=i===void 0?$i:Number(i);const s=t/i,r=e[0]*Math.PI/180,a=Qs(e[1]),o=Qs(n),l=s*Math.cos(o);let c=a+l;Math.abs(c)>Math.PI/2&&(c=c>0?Math.PI-c:-Math.PI-c);const h=Math.log(Math.tan(c/2+Math.PI/4)/Math.tan(a/2+Math.PI/4)),d=Math.abs(h)>1e-11?l/h:Math.cos(a);return[((r+s*Math.sin(o)/d)*180/Math.PI+540)%360-180,c*180/Math.PI]}function V4(e,t={}){const n=[];if(Gl(e,s=>{n.push(s.coordinates)}),n.length<2)throw new Error("Must specify at least 2 geometries");const i=z4(n[0],...n.slice(1));return i.length===0?null:i.length===1?Hr(i[0],t.properties):mA(i,t.properties)}function q4(e,t,n){if(n=n||{},!bf(n))throw new Error("options is invalid");const i=n.origin||"centroid",s=n.mutate||!1;if(!e)throw new Error("geojson required");if(typeof t!="number"||t<=0)throw new Error("invalid factor");const r=Array.isArray(i)||typeof i=="object";return s!==!0&&(e=Es(e)),e.type==="FeatureCollection"&&!r?(Po(e,function(a,o){e.features[o]=qS(a,t,i)}),e):qS(e,t,i)}function qS(e,t,n){const i=v_(e)==="Point",s=W4(e,n);return t===1||i||(Ql(e,function(r){const a=G4(s,r),o=fz(s,r),l=as(gR(s,a*t,o));r[0]=l[0],r[1]=l[1],r.length===3&&(r[2]*=t)}),delete e.bbox),e}function W4(e,t){if(t==null&&(t="centroid"),Array.isArray(t)||typeof t=="object")return Si(t);const n=e.bbox?e.bbox:si(e,{recompute:!0}),i=n[0],s=n[1],r=n[2],a=n[3];switch(t){case"sw":case"southwest":case"westsouth":case"bottomleft":return wi([i,s]);case"se":case"southeast":case"eastsouth":case"bottomright":return wi([r,s]);case"nw":case"northwest":case"westnorth":case"topleft":return wi([i,a]);case"ne":case"northeast":case"eastnorth":case"topright":return wi([r,a]);case"center":return V2(e);case void 0:case null:case"centroid":return Dp(e);default:throw new Error("invalid origin")}}function Y4(e,t){var n=e[0]-t[0],i=e[1]-t[1];return n*n+i*i}function j4(e,t,n){var i=t[0],s=t[1],r=n[0]-i,a=n[1]-s;if(r!==0||a!==0){var o=((e[0]-i)*r+(e[1]-s)*a)/(r*r+a*a);o>1?(i=n[0],s=n[1]):o>0&&(i+=r*o,s+=a*o)}return r=e[0]-i,a=e[1]-s,r*r+a*a}function X4(e,t){for(var n=e[0],i=[n],s,r=1,a=e.length;r<a;r++)s=e[r],Y4(s,n)>t&&(i.push(s),n=s);return n!==s&&i.push(s),i}function db(e,t,n,i,s){for(var r=i,a,o=t+1;o<n;o++){var l=j4(e[o],e[t],e[n]);l>r&&(a=o,r=l)}r>i&&(a-t>1&&db(e,t,a,i,s),s.push(e[a]),n-a>1&&db(e,a,n,i,s))}function Z4(e,t){var n=e.length-1,i=[e[0]];return db(e,0,n,t,i),i.push(e[n]),i}function L_(e,t,n){if(e.length<=2)return e;var i=t!==void 0?t*t:1;return e=n?e:X4(e,i),e=Z4(e,i),e}function pb(e,t={}){var n,i,s;if(t=t??{},!bf(t))throw new Error("options is invalid");const r=(n=t.tolerance)!=null?n:1,a=(i=t.highQuality)!=null?i:!1,o=(s=t.mutate)!=null?s:!1;if(!e)throw new Error("geojson is required");if(r&&r<0)throw new Error("invalid tolerance");return o!==!0&&(e=Es(e)),Gl(e,function(l){J4(l,r,a)}),e}function J4(e,t,n){const i=e.type;if(i==="Point"||i==="MultiPoint")return e;if(z2(e,{mutate:!0}),i!=="GeometryCollection")switch(i){case"LineString":e.coordinates=L_(e.coordinates,t,n);break;case"MultiLineString":e.coordinates=e.coordinates.map(s=>L_(s,t,n));break;case"Polygon":e.coordinates=WS(e.coordinates,t,n);break;case"MultiPolygon":e.coordinates=e.coordinates.map(s=>WS(s,t,n))}return e}function WS(e,t,n){return e.map(function(i){if(i.length<4)throw new Error("invalid polygon");let s=t,r=L_(i,s,n);for(;!YS(r)&&s>=Number.EPSILON;)s-=s*.01,r=L_(i,s,n);return YS(r)?((r[r.length-1][0]!==r[0][0]||r[r.length-1][1]!==r[0][1])&&r.push(r[0]),r):i})}function YS(e){return e.length<3?!1:!(e.length===3&&e[2][0]===e[0][0]&&e[2][1]===e[0][1])}function fb(e,t,n,i){if(i=i||{},!bf(i))throw new Error("options is invalid");var s=i.units,r=i.zTranslation,a=i.mutate;if(!e)throw new Error("geojson is required");if(t==null||isNaN(t))throw new Error("distance is required");if(r&&typeof r!="number"&&isNaN(r))throw new Error("zTranslation is not a number");if(r=r!==void 0?r:0,t===0&&r===0)return e;if(n==null||isNaN(n))throw new Error("direction is required");return t<0&&(t=-t,n=n+180),(a===!1||a===void 0)&&(e=Es(e)),Ql(e,function(o){var l=as(gR(o,t,n,{units:s}));o[0]=l[0],o[1]=l[1],r&&o.length===3&&(o[2]+=r)}),e}function K4(e,t={}){const n=[];if(Gl(e,s=>{n.push(s.coordinates)}),n.length<2)throw new Error("Must have at least 2 geometries");const i=U4(n[0],...n.slice(1));return i.length===0?null:i.length===1?Hr(i[0],t.properties):mA(i,t.properties)}function eG(e,t){if(e.geometry.type!=="Polygon")throw new Error("The input feature must be a Polygon");for(var n=e.geometry.coordinates,i=[],s={},r=[],a=0;a<n.length;a++)for(var o=0;o<n[a].length-1;o++)r.push(f(a,o));var l=new IE;l.load(r);for(var c=0;c<n.length;c++)for(var h=0;h<n[c].length-1;h++)l.search(f(c,h)).forEach(function(m){var A=m.ring,y=m.edge;d(c,h,A,y)});return i;function d(m,A,y,x){var v=n[m][A],b=n[m][A+1],w=n[y][x],S=n[y][x+1],R=tG(v,b,w,S);if(R!==null){var k,L;if(b[0]!==v[0]?k=(R[0]-v[0])/(b[0]-v[0]):k=(R[1]-v[1])/(b[1]-v[1]),S[0]!==w[0]?L=(R[0]-w[0])/(S[0]-w[0]):L=(R[1]-w[1])/(S[1]-w[1]),!(k>=1||k<=0||L>=1||L<=0)){var T=R,C=!s[T.toString()];C&&(s[T.toString()]=!0),t&&i.push(t(R,m,A,v,b,k,y,x,w,S,L,C))}}}function f(m,A){var y=n[m][A],x=n[m][A+1],v,b,w,S;return y[0]<x[0]?(v=y[0],b=x[0]):(v=x[0],b=y[0]),y[1]<x[1]?(w=y[1],S=x[1]):(w=x[1],S=y[1]),{minX:v,minY:w,maxX:b,maxY:S,ring:m,edge:A}}}function tG(e,t,n,i){if(Xd(e,n)||Xd(e,i)||Xd(t,n)||Xd(i,n))return null;var s=e[0],r=e[1],a=t[0],o=t[1],l=n[0],c=n[1],h=i[0],d=i[1],f=(s-a)*(c-d)-(r-o)*(l-h);return f===0?null:[((s*o-r*a)*(l-h)-(s-a)*(l*d-c*h))/f,((s*o-r*a)*(c-d)-(r-o)*(l*d-c*h))/f]}function Xd(e,t){if(!e||!t||e.length!==t.length)return!1;for(var n=0,i=e.length;n<i;n++)if(e[n]instanceof Array&&t[n]instanceof Array){if(!Xd(e[n],t[n]))return!1}else if(e[n]!==t[n])return!1;return!0}function nG(e){if(e.type!="Feature")throw new Error("The input must a geojson object of type Feature");if(e.geometry===void 0||e.geometry==null)throw new Error("The input must a geojson object with a non-empty geometry");if(e.geometry.type!="Polygon")throw new Error("The input must be a geojson Polygon");for(var t=e.geometry.coordinates.length,n=[],v=0;v<t;v++){var i=e.geometry.coordinates[v];Zd(i[0],i[i.length-1])||i.push(i[0]);for(var s=0;s<i.length-1;s++)n.push(i[s])}if(!sG(n))throw new Error("The input polygon may not have duplicate vertices (except for the first and last vertex of each ring)");var r=n.length,a=eG(e,function(K,re,ce,oe,ge,ie,fe,ye,$,Se,Z,Qe){return[K,re,ce,oe,ge,ie,fe,ye,$,Se,Z,Qe]}),o=a.length;if(o==0){for(var k=[],v=0;v<t;v++)k.push(Hr([e.geometry.coordinates[v]],{parent:-1,winding:iG(e.geometry.coordinates[v])}));let K=Kt(k);return H(K),W(K),K}for(var l=[],c=[],v=0;v<t;v++){l.push([]);for(var s=0;s<e.geometry.coordinates[v].length-1;s++)l[v].push([new jS(e.geometry.coordinates[v][ou(s+1,e.geometry.coordinates[v].length-1)],1,[v,s],[v,ou(s+1,e.geometry.coordinates[v].length-1)],void 0)]),c.push(new XS(e.geometry.coordinates[v][s],[v,ou(s-1,e.geometry.coordinates[v].length-1)],[v,s],void 0,void 0,!1,!0))}for(var v=0;v<o;v++)l[a[v][1]][a[v][2]].push(new jS(a[v][0],a[v][5],[a[v][1],a[v][2]],[a[v][6],a[v][7]],void 0)),a[v][11]&&c.push(new XS(a[v][0],[a[v][1],a[v][2]],[a[v][6],a[v][7]],void 0,void 0,!0,!0));for(var h=c.length,v=0;v<l.length;v++)for(var s=0;s<l[v].length;s++)l[v][s].sort(function(re,ce){return re.param<ce.param?-1:1});for(var d=[],v=0;v<h;v++)d.push({minX:c[v].coord[0],minY:c[v].coord[1],maxX:c[v].coord[0],maxY:c[v].coord[1],index:v});var f=new IE;f.load(d);for(var v=0;v<l.length;v++)for(var s=0;s<l[v].length;s++)for(var m=0;m<l[v][s].length;m++){let re;m==l[v][s].length-1?re=l[v][ou(s+1,e.geometry.coordinates[v].length-1)][0].coord:re=l[v][s][m+1].coord;var A=f.search({minX:re[0],minY:re[1],maxX:re[0],maxY:re[1]})[0];l[v][s][m].nxtIsectAlongEdgeIn=A.index}for(var v=0;v<l.length;v++)for(var s=0;s<l[v].length;s++)for(var m=0;m<l[v][s].length;m++){let ce=l[v][s][m].coord;var A=f.search({minX:ce[0],minY:ce[1],maxX:ce[0],maxY:ce[1]})[0],y=A.index;y<r?c[y].nxtIsectAlongRingAndEdge2=l[v][s][m].nxtIsectAlongEdgeIn:Zd(c[y].ringAndEdge1,l[v][s][m].ringAndEdgeIn)?c[y].nxtIsectAlongRingAndEdge1=l[v][s][m].nxtIsectAlongEdgeIn:c[y].nxtIsectAlongRingAndEdge2=l[v][s][m].nxtIsectAlongEdgeIn}for(var x=[],v=0,s=0;s<t;s++){for(var b=v,m=0;m<e.geometry.coordinates[s].length-1;m++)c[v].coord[0]<c[b].coord[0]&&(b=v),v++;for(var w=c[b].nxtIsectAlongRingAndEdge2,m=0;m<c.length;m++)if(c[m].nxtIsectAlongRingAndEdge1==b||c[m].nxtIsectAlongRingAndEdge2==b){var S=m;break}var R=Vg([c[S].coord,c[b].coord,c[w].coord],!0)?1:-1;x.push({isect:b,parent:-1,winding:R})}x.sort(function(J,K){return c[J.isect].coord>c[K.isect].coord?-1:1});for(var k=[];x.length>0;){var L=x.pop(),T=L.isect,C=L.parent,I=L.winding,M=k.length,O=[c[T].coord],N=T;if(c[T].ringAndEdge1Walkable)var D=c[T].ringAndEdge1,P=c[T].nxtIsectAlongRingAndEdge1;else var D=c[T].ringAndEdge2,P=c[T].nxtIsectAlongRingAndEdge2;for(;!Zd(c[T].coord,c[P].coord);){O.push(c[P].coord);for(var U=void 0,v=0;v<x.length;v++)if(x[v].isect==P){U=v;break}if(U!=null&&x.splice(U,1),Zd(D,c[P].ringAndEdge1)){if(D=c[P].ringAndEdge2,c[P].ringAndEdge2Walkable=!1,c[P].ringAndEdge1Walkable){var Q={isect:P};Vg([c[N].coord,c[P].coord,c[c[P].nxtIsectAlongRingAndEdge2].coord],I==1)?(Q.parent=C,Q.winding=-I):(Q.parent=M,Q.winding=I),x.push(Q)}N=P,P=c[P].nxtIsectAlongRingAndEdge2}else{if(D=c[P].ringAndEdge1,c[P].ringAndEdge1Walkable=!1,c[P].ringAndEdge2Walkable){var Q={isect:P};Vg([c[N].coord,c[P].coord,c[c[P].nxtIsectAlongRingAndEdge1].coord],I==1)?(Q.parent=C,Q.winding=-I):(Q.parent=M,Q.winding=I),x.push(Q)}N=P,P=c[P].nxtIsectAlongRingAndEdge1}}O.push(c[P].coord),k.push(Hr([O],{index:M,parent:C,winding:I,netWinding:void 0}))}let z=Kt(k);H(z),W(z);function H(J){for(var K=[],re=0;re<J.features.length;re++)J.features[re].properties.parent==-1&&K.push(re);if(K.length>1)for(var re=0;re<K.length;re++){for(var ce=-1,oe=1/0,ge=0;ge<J.features.length;ge++)K[re]!=ge&&Ii(J.features[K[re]].geometry.coordinates[0][0],J.features[ge],{ignoreBoundary:!0})&&y_(J.features[ge])<oe&&(ce=ge);J.features[K[re]].properties.parent=ce}}function W(J){for(var K=0;K<J.features.length;K++)if(J.features[K].properties.parent==-1){var re=J.features[K].properties.winding;J.features[K].properties.netWinding=re,te(J,K,re)}}function te(J,K,re){for(var ce=0;ce<J.features.length;ce++)if(J.features[ce].properties.parent==K){var oe=re+J.features[ce].properties.winding;J.features[ce].properties.netWinding=oe,te(J,ce,oe)}}return z}var jS=class{constructor(e,t,n,i,s){this.coord=e,this.param=t,this.ringAndEdgeIn=n,this.ringAndEdgeOut=i,this.nxtIsectAlongEdgeIn=s}},XS=class{constructor(e,t,n,i,s,r,a){this.coord=e,this.ringAndEdge1=t,this.ringAndEdge2=n,this.nxtIsectAlongRingAndEdge1=i,this.nxtIsectAlongRingAndEdge2=s,this.ringAndEdge1Walkable=r,this.ringAndEdge2Walkable=a}};function Vg(e,t){if(typeof t>"u"&&(t=!0),e.length!=3)throw new Error("This function requires an array of three points [x,y]");return(e[1][0]-e[0][0])*(e[2][1]-e[0][1])-(e[1][1]-e[0][1])*(e[2][0]-e[0][0])>=0==t}function iG(e){for(var t=0,n=0;n<e.length-1;n++)e[n][0]<e[t][0]&&(t=n);if(Vg([e[ou(t-1,e.length-1)],e[t],e[ou(t+1,e.length-1)]],!0))var i=1;else var i=-1;return i}function Zd(e,t){if(!e||!t||e.length!=t.length)return!1;for(var n=0,i=e.length;n<i;n++)if(e[n]instanceof Array&&t[n]instanceof Array){if(!Zd(e[n],t[n]))return!1}else if(e[n]!=t[n])return!1;return!0}function ou(e,t){return(e%t+t)%t}function sG(e){for(var t={},n=1,i=0,s=e.length;i<s;++i){if(Object.prototype.hasOwnProperty.call(t,e[i].toString())){n=0;break}t[e[i].toString()]=1}return n}function rG(e){var t=[];return Do(e,function(n){n.geometry.type==="Polygon"&&Po(nG(n),function(i){t.push(Hr(i.geometry.coordinates,n.properties))})}),Kt(t)}var aG=class{undoStack=[];redoStack=[];maxSize;isExecuting=!1;onHistoryChange;constructor(e=50,t){this.maxSize=e,this.onHistoryChange=t}record(e){if(!this.isExecuting){for(this.undoStack.push(e);this.undoStack.length>this.maxSize;)this.undoStack.shift();this.redoStack=[],this.notifyChange()}}undo(){if(!this.canUndo())return!1;const e=this.undoStack.pop();this.isExecuting=!0;try{e.undo()}finally{this.isExecuting=!1}return this.redoStack.push(e),this.notifyChange(),!0}redo(){if(!this.canRedo())return!1;const e=this.redoStack.pop();this.isExecuting=!0;try{e.execute()}finally{this.isExecuting=!1}return this.undoStack.push(e),this.notifyChange(),!0}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}isExecutingCommand(){return this.isExecuting}getState(){return{canUndo:this.canUndo(),canRedo:this.canRedo(),undoCount:this.undoStack.length,redoCount:this.redoStack.length}}clear(){this.undoStack=[],this.redoStack=[],this.notifyChange()}getUndoDescription(){return this.undoStack.length===0?null:this.undoStack[this.undoStack.length-1].description}getRedoDescription(){return this.redoStack.length===0?null:this.redoStack[this.redoStack.length-1].description}notifyChange(){this.onHistoryChange&&this.onHistoryChange(this.canUndo(),this.canRedo())}},ZS=class{description;type="create";feature;featureId=null;context;constructor(e,t){this.feature=Es(e),this.context=t,this.featureId=this.extractFeatureId(e);const n=e.geometry?.type||"feature";this.description=`Create ${n}`}execute(){const e=this.context.featuresApi.importGeoJsonFeature(this.feature);e&&(this.featureId=String(e.id),this.context.onFeatureCreate?.(this.feature))}undo(){if(!this.featureId)return;const e=[];try{this.context.featuresApi.forEach(t=>{const n=String(t.id),i=this.getGeomanFeature(t),s=i?this.extractFeatureId(i):null;(n===this.featureId||s===this.featureId)&&e.push(t)}),e.forEach(t=>{try{this.context.featuresApi.delete(t)}catch{try{t.delete()}catch{}}}),e.length>0&&this.featureId&&this.context.onFeatureDelete?.(this.featureId)}catch{}}extractFeatureId(e){const t=e.properties,n=e.id??t?.__gm_id??t?.id;return n!=null?String(n):null}getGeomanFeature(e){if(!e)return null;if(typeof e.getGeoJson=="function")try{return e.getGeoJson()}catch{return null}return e.geoJson??null}},oG=class{description;type="edit";oldFeature;newFeature;featureId;context;constructor(e,t,n){this.oldFeature=Es(e),this.newFeature=Es(t),this.context=n,this.featureId=this.extractFeatureId(t)||this.extractFeatureId(e);const i=t.geometry?.type||"feature";this.description=`Edit ${i}`}execute(){this.updateFeatureGeometry(this.newFeature)}undo(){this.updateFeatureGeometry(this.oldFeature)}updateFeatureGeometry(e){if(this.featureId)try{this.context.featuresApi.forEach(t=>{const n=String(t.id),i=this.getGeomanFeature(t),s=i?this.extractFeatureId(i):null;(n===this.featureId||s===this.featureId)&&(t.updateGeometry?t.updateGeometry(e.geometry):t.updateGeoJsonGeometry&&t.updateGeoJsonGeometry(e.geometry))})}catch{this.deleteAndReimport(e)}}deleteAndReimport(e){if(!this.featureId)return;const t=[];try{this.context.featuresApi.forEach(i=>{const s=String(i.id),r=this.getGeomanFeature(i),a=r?this.extractFeatureId(r):null;(s===this.featureId||a===this.featureId)&&t.push(i)}),t.forEach(i=>{try{this.context.featuresApi.delete(i)}catch{try{i.delete()}catch{}}})}catch{}const n=this.context.featuresApi.importGeoJsonFeature(e);n&&(this.featureId=String(n.id))}extractFeatureId(e){const t=e.properties,n=e.id??t?.__gm_id??t?.id;return n!=null?String(n):null}getGeomanFeature(e){if(!e)return null;if(typeof e.getGeoJson=="function")try{return e.getGeoJson()}catch{return null}return e.geoJson??null}},JS=class{description;type="delete";feature;featureId;context;constructor(e,t){this.feature=Es(e),this.context=t,this.featureId=this.extractFeatureId(e);const n=e.geometry?.type||"feature";this.description=`Delete ${n}`}execute(){if(!this.featureId)return;const e=[];try{this.context.featuresApi.forEach(t=>{const n=String(t.id),i=this.getGeomanFeature(t),s=i?this.extractFeatureId(i):null;(n===this.featureId||s===this.featureId)&&e.push(t)}),e.forEach(t=>{try{this.context.featuresApi.delete(t)}catch{try{t.delete()}catch{}}}),e.length>0&&this.featureId&&this.context.onFeatureDelete?.(this.featureId)}catch{}}undo(){const e=this.context.featuresApi.importGeoJsonFeature(this.feature);e&&(this.featureId=String(e.id),this.context.onFeatureCreate?.(this.feature))}extractFeatureId(e){const t=e.properties,n=e.id??t?.__gm_id??t?.id;return n!=null?String(n):null}getGeomanFeature(e){if(!e)return null;if(typeof e.getGeoJson=="function")try{return e.getGeoJson()}catch{return null}return e.geoJson??null}},lG=class{description;type="composite";commands;constructor(e,t){this.commands=e,this.description=t}execute(){for(const e of this.commands)e.execute()}undo(){for(let e=this.commands.length-1;e>=0;e--)this.commands[e].undo()}getCommandCount(){return this.commands.length}},cG=["polygon","line","rectangle","circle","marker"],hG=["select","drag","change","rotate","cut","delete","scale","copy","split","union","difference","simplify","lasso"],Pv=["select","scale","copy","split","union","difference","simplify","lasso"],uG=["snapping","measurements"],dG=["open","save"],pG={position:"top-left",collapsed:!1,drawModes:cG,editModes:hG,helperModes:uG,fileModes:dG,toolbarOrientation:"vertical",showLabels:!1,simplifyTolerance:.001,snappingEnabled:!0,measurementsEnabled:!1,hideGeomanControl:!0,saveFilename:"features.geojson",onFeatureCreate:()=>{},onFeatureEdit:()=>{},onFeatureDelete:()=>{},onSelectionChange:()=>{},onModeChange:()=>{},onGeoJsonLoad:()=>{},onGeoJsonSave:()=>{},showFeatureProperties:!0,fitBoundsOnLoad:!0,columns:2,enableHistory:!0,maxHistorySize:50,onHistoryChange:()=>{},enableAttributeEditing:!1,attributeSchema:void 0,onAttributeChange:()=>{},attributePanelPosition:"right",attributePanelWidth:300,attributePanelMaxHeight:"80vh",attributePanelTop:10,attributePanelSideOffset:10,attributePanelTitle:"Feature Properties"},rt="geo-editor",gt={LASSO_SOURCE:"geo-editor-lasso-source",LASSO_LAYER:"geo-editor-lasso-layer",LASSO_LINE_LAYER:"geo-editor-lasso-line-layer",SCALE_HANDLES_SOURCE:"geo-editor-scale-handles-source",SCALE_HANDLES_LAYER:"geo-editor-scale-handles-layer",SPLIT_LINE_SOURCE:"geo-editor-split-line-source",SPLIT_LINE_LAYER:"geo-editor-split-line-layer",SELECTION_SOURCE:"geo-editor-selection-source",SELECTION_FILL_LAYER:"geo-editor-selection-fill-layer",SELECTION_LINE_LAYER:"geo-editor-selection-line-layer",SELECTION_CIRCLE_LAYER:"geo-editor-selection-circle-layer",FREEHAND_SOURCE:"geo-editor-freehand-source",FREEHAND_FILL_LAYER:"geo-editor-freehand-fill-layer",FREEHAND_LINE_LAYER:"geo-editor-freehand-line-layer"},sh={handleSize:10,handleColor:"#3388ff",handleBorderColor:"#ffffff",handleBorderWidth:2,minScale:.1,maxScale:10},Dv={tolerance:.001,highQuality:!1,mutate:!1},KS={offset:[5e-4,5e-4],generateNewIds:!0};function Oo(){return`feature_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}function _R(e){return e.geometry.type==="Polygon"||e.geometry.type==="MultiPolygon"}function fG(e){return e.geometry.type==="LineString"||e.geometry.type==="MultiLineString"}function e1(e,t,n){return Math.min(Math.max(e,t),n)}function gd(e){return gz(e).length}var mG=class{options;constructor(e={}){this.options={offset:e.offset??KS.offset,generateNewIds:e.generateNewIds??KS.generateNewIds}}copy(e,t){const n=Es(e),i=t??this.options.offset;return this.options.generateNewIds&&(n.id=Oo(),n.properties&&(n.properties={...n.properties,id:n.id})),i[0]!==0||i[1]!==0?fb(n,Math.sqrt(i[0]**2+i[1]**2)*111,Math.atan2(i[0],i[1])*180/Math.PI,{units:"kilometers"}):n}copyMultiple(e,t){return e.map(n=>this.copy(n,t))}copyToLocation(e,t){if(e.length===0)return[];const n=Dp(Kt(e)).geometry.coordinates,i=t[0]-n[0],s=t[1]-n[1];return e.map(r=>{const a=Es(r);return this.options.generateNewIds&&(a.id=Oo(),a.properties&&(a.properties={...a.properties,id:a.id})),fb(a,Math.sqrt(i**2+s**2)*111,Math.atan2(i,s)*180/Math.PI,{units:"kilometers"})})}setOffset(e){this.options.offset=e}getOffset(){return this.options.offset}},gG=class{defaultOptions;constructor(e){this.defaultOptions={tolerance:e?.tolerance??Dv.tolerance,highQuality:e?.highQuality??Dv.highQuality,mutate:e?.mutate??Dv.mutate}}simplify(e,t){return pb(e,{...this.defaultOptions,...t})}simplifyWithStats(e,t){const n={...this.defaultOptions,...t},i=gd(e),s=pb(e,n),r=gd(s);return{result:s,original:e,verticesBefore:i,verticesAfter:r,reductionPercent:i>0?(i-r)/i*100:0}}getSimplificationStats(e,t){const n=gd(e),i=gd(this.simplify(e,{tolerance:t}));return{before:n,after:i,reduction:n>0?(n-i)/n*100:0}}previewTolerances(e,t){const n=new Map;for(const i of t)n.set(i,this.simplifyWithStats(e,{tolerance:i}));return n}getSuggestedTolerances(e){const t=gd(e),n=[1e-4,5e-4,.001,.005,.01];return t>1e3?[.001,.005,.01,.05,.1]:t>100?[5e-4,.001,.005,.01,.05]:n}findOptimalTolerance(e,t){const n=[1e-5,5e-5,1e-4,5e-4,.001,.005,.01,.05,.1];let i=n[0],s=this.simplifyWithStats(e,{tolerance:i}),r=Math.abs(s.reductionPercent-t);for(const a of n.slice(1)){const o=this.simplifyWithStats(e,{tolerance:a}),l=Math.abs(o.reductionPercent-t);l<r&&(r=l,i=a,s=o)}return{tolerance:i,result:s}}setDefaultTolerance(e){this.defaultOptions.tolerance=e}getDefaultTolerance(){return this.defaultOptions.tolerance}},_G=class{union(e,t){if(e.length===0)return{result:null,originals:[],success:!1,error:"No features provided"};if(e.length===1){const n=Es(e[0]);return n.id=Oo(),t?.properties&&(n.properties={...n.properties,...t.properties}),{result:n,originals:e,success:!0}}try{const n=K4(Kt(e));return n&&(n.id=Oo(),t?.properties&&(n.properties={...n.properties,...t.properties})),{result:n,originals:e,success:n!==null,error:n===null?"Union operation returned null":void 0}}catch(n){return{result:null,originals:e,success:!1,error:`Union operation failed: ${n instanceof Error?n.message:"Unknown error"}`}}}canMerge(e){if(e.length<2)return{canMerge:!1,reason:"Need at least 2 polygons to merge"};for(const t of e)if(t.geometry.type!=="Polygon"&&t.geometry.type!=="MultiPolygon")return{canMerge:!1,reason:"All features must be polygons"};return{canMerge:!0}}hasOverlap(e){for(let t=0;t<e.length;t++)for(let n=t+1;n<e.length;n++)try{if(G2(e[t],e[n])||kE(e[t],e[n]))return!0}catch{}return!1}getCombinedArea(e){return e.reduce((t,n)=>{try{return t+y_(n)}catch{return t}},0)}getUnionArea(e){const t=this.union(e);if(t.success&&t.result)try{return y_(t.result)}catch{return null}return null}},AG=class{difference(e,t,n){if(t.length===0){const i=Es(e);return i.id=Oo(),{result:i,base:e,subtracted:[],success:!0}}try{let i=Es(e);for(const s of t){if(!i)break;i=mR(Kt([i,s]))}return i&&(i.id=Oo(),n?.properties&&(i.properties={...i.properties,...n.properties})),{result:i,base:e,subtracted:t,success:!0}}catch(i){return{result:null,base:e,subtracted:t,success:!1,error:`Difference operation failed: ${i instanceof Error?i.message:"Unknown error"}`}}}canSubtract(e,t){if(e.geometry.type!=="Polygon"&&e.geometry.type!=="MultiPolygon")return{canSubtract:!1,overlap:!1,reason:"Base must be a polygon"};if(t.geometry.type!=="Polygon"&&t.geometry.type!=="MultiPolygon")return{canSubtract:!1,overlap:!1,reason:"Subtract feature must be a polygon"};try{return G2(e,t)||_S(e,t)||kE(e,t)?{canSubtract:!0,overlap:!0}:{canSubtract:!1,overlap:!1,reason:"Polygons do not overlap"}}catch{return{canSubtract:!1,overlap:!1,reason:"Could not determine overlap"}}}getSubtractedArea(e,t){try{const n=V4(Kt([e,t]));return n?y_(n):0}catch{return null}}preview(e,t){return this.difference(e,t).result}createHole(e,t){try{return _S(e,t)?this.difference(e,[t]).result:(console.warn("Hole must be completely inside the polygon"),null)}catch{return null}}},vG=class{map=null;options;activeFeature=null;originalFeature=null;handles=[];activeHandle=null;startPoint=null;onScaleCallback=null;constructor(e={}){this.options={maintainAspectRatio:e.maintainAspectRatio??!0,scaleFromCenter:e.scaleFromCenter??!0,minScale:e.minScale??sh.minScale,maxScale:e.maxScale??sh.maxScale}}init(e){this.map=e}scale(e,t,n){const i=q4(e,e1(t,this.options.minScale,this.options.maxScale),{origin:n||Dp(e).geometry.coordinates});return i.id=e.id||Oo(),i.properties={...e.properties},i}scaleFromHandle(e,t,n,i){const s=si(e),r=Dp(e).geometry.coordinates,a=this.distanceFromCenter(n,r);let o=this.distanceFromCenter(i,r)/a;o=e1(o,this.options.minScale,this.options.maxScale);let l;return this.options.scaleFromCenter?l=r:l=this.getOppositeCorner(s,t),this.scale(e,o,l)}createHandles(e){const[t,n,i,s]=si(e),r=(t+i)/2,a=(n+s)/2;return this.handles=[{position:"nw",coordinates:[t,s]},{position:"n",coordinates:[r,s]},{position:"ne",coordinates:[i,s]},{position:"e",coordinates:[i,a]},{position:"se",coordinates:[i,n]},{position:"s",coordinates:[r,n]},{position:"sw",coordinates:[t,n]},{position:"w",coordinates:[t,a]}],this.handles}startScale(e,t,n,i){this.activeFeature=Es(e),this.originalFeature=Es(e),this.activeHandle=t,this.startPoint=n,this.onScaleCallback=i||null,this.showHandles(e)}showHandlesForFeature(e){this.showHandles(e)}updateScale(e){if(!this.activeFeature||!this.originalFeature||!this.activeHandle||!this.startPoint)return null;const t=this.scaleFromHandle(this.originalFeature,this.activeHandle,this.startPoint,e);this.activeFeature=t,this.updateHandlePositions(t);const n=si(this.originalFeature),i=si(t),s=(i[2]-i[0])/(n[2]-n[0]);return this.onScaleCallback&&this.onScaleCallback(t,s),t}endScale(){if(!this.activeFeature||!this.originalFeature)return null;const e=si(this.originalFeature),t=si(this.activeFeature),n=(t[2]-t[0])/(e[2]-e[0]),i={feature:this.activeFeature,factor:n};return this.hideHandles(),this.activeFeature=null,this.originalFeature=null,this.activeHandle=null,this.startPoint=null,this.onScaleCallback=null,i}cancelScale(){this.hideHandles(),this.activeFeature=null,this.originalFeature=null,this.activeHandle=null,this.startPoint=null,this.onScaleCallback=null}showHandles(e){if(!this.map)return;const t=this.createHandles(e).map(n=>wi(n.coordinates,{position:n.position}));if(!this.map.getSource(gt.SCALE_HANDLES_SOURCE))this.map.addSource(gt.SCALE_HANDLES_SOURCE,{type:"geojson",data:Kt(t)}),this.map.addLayer({id:gt.SCALE_HANDLES_LAYER,type:"circle",source:gt.SCALE_HANDLES_SOURCE,paint:{"circle-radius":sh.handleSize/2,"circle-color":sh.handleColor,"circle-stroke-color":sh.handleBorderColor,"circle-stroke-width":sh.handleBorderWidth}});else{const n=this.map.getSource(gt.SCALE_HANDLES_SOURCE);n&&n.setData(Kt(t))}}updateHandlePositions(e){if(!this.map)return;const t=this.createHandles(e).map(i=>wi(i.coordinates,{position:i.position})),n=this.map.getSource(gt.SCALE_HANDLES_SOURCE);n&&n.setData(Kt(t))}hideHandles(){this.map&&(this.map.getLayer(gt.SCALE_HANDLES_LAYER)&&this.map.removeLayer(gt.SCALE_HANDLES_LAYER),this.map.getSource(gt.SCALE_HANDLES_SOURCE)&&this.map.removeSource(gt.SCALE_HANDLES_SOURCE))}distanceFromCenter(e,t){return Math.sqrt(Math.pow(e[0]-t[0],2)+Math.pow(e[1]-t[1],2))}getOppositeCorner(e,t){const[n,i,s,r]=e,a=(n+s)/2,o=(i+r)/2;return{nw:[s,i],n:[a,i],ne:[n,i],e:[n,o],se:[n,r],s:[a,r],sw:[s,r],w:[s,o]}[t]}getHandleAtPoint(e,t=1e-4){for(const n of this.handles)if(this.distanceFromCenter(e,n.coordinates)<t)return n.position;return null}destroy(){this.cancelScale(),this.map=null}},yG=class{map=null;isDrawing=!1;points=[];options;onCompleteCallback=null;dragPanEnabled=null;boxZoomEnabled=null;doubleClickZoomEnabled=null;handleMouseDown=null;handleMouseMove=null;handleMouseUp=null;constructor(e={}){this.options={mode:e.mode??"intersects"}}init(e){this.map=e}enable(e){this.map&&(this.onCompleteCallback=e||null,this.disableMapInteractions(),this.setupLassoLayers(),this.attachEventListeners(),this.map.getCanvas().style.cursor="crosshair")}disable(){this.removeEventListeners(),this.clearLasso(),this.isDrawing=!1,this.points=[],this.onCompleteCallback=null,this.restoreMapInteractions(),this.map&&(this.map.getCanvas().style.cursor="")}selectWithinLasso(e,t){return t.filter(n=>{try{return this.options.mode==="contains"?RQ(n,e):kE(n,e)}catch{return!1}})}buildLassoPolygon(){if(this.points.length<3)return null;const e=[...this.points,this.points[0]];try{return Hr([e])}catch{return null}}setMode(e){this.options.mode=e}isActive(){return this.isDrawing}setupLassoLayers(){this.map&&(this.map.getSource(gt.LASSO_SOURCE)||this.map.addSource(gt.LASSO_SOURCE,{type:"geojson",data:Kt([])}),this.map.getLayer(gt.LASSO_LAYER)||this.map.addLayer({id:gt.LASSO_LAYER,type:"fill",source:gt.LASSO_SOURCE,paint:{"fill-color":"#3388ff","fill-opacity":.2}}),this.map.getLayer(gt.LASSO_LINE_LAYER)||this.map.addLayer({id:gt.LASSO_LINE_LAYER,type:"line",source:gt.LASSO_SOURCE,paint:{"line-color":"#3388ff","line-width":2,"line-dasharray":[2,2]}}))}attachEventListeners(){this.map&&(this.handleMouseDown=e=>{e.preventDefault(),this.isDrawing=!0,this.points=[[e.lngLat.lng,e.lngLat.lat]],this.updateLassoVisualization()},this.handleMouseMove=e=>{this.isDrawing&&(e.preventDefault(),this.points.push([e.lngLat.lng,e.lngLat.lat]),this.updateLassoVisualization())},this.handleMouseUp=()=>{this.isDrawing&&(this.isDrawing=!1,this.completeLasso())},this.map.on("mousedown",this.handleMouseDown),this.map.on("mousemove",this.handleMouseMove),this.map.on("mouseup",this.handleMouseUp))}removeEventListeners(){this.map&&(this.handleMouseDown&&this.map.off("mousedown",this.handleMouseDown),this.handleMouseMove&&this.map.off("mousemove",this.handleMouseMove),this.handleMouseUp&&this.map.off("mouseup",this.handleMouseUp),this.handleMouseDown=null,this.handleMouseMove=null,this.handleMouseUp=null)}updateLassoVisualization(){if(!this.map||this.points.length<2)return;const e=this.map.getSource(gt.LASSO_SOURCE);if(!e)return;const t=[...this.points];if(t.length>=3){t.push(t[0]);const n=Hr([t]);e.setData(Kt([n]))}else{const n=xs(t);e.setData(Kt([n]))}}completeLasso(){const e=this.buildLassoPolygon();if(e&&this.onCompleteCallback){const t={selected:[],lasso:e};this.onCompleteCallback(t)}setTimeout(()=>{this.clearLasso(),this.points=[]},100)}clearLasso(){if(!this.map)return;const e=this.map.getSource(gt.LASSO_SOURCE);e&&e.setData(Kt([]))}disableMapInteractions(){this.map&&(this.dragPanEnabled=this.map.dragPan.isEnabled(),this.dragPanEnabled&&this.map.dragPan.disable(),this.map.boxZoom&&(this.boxZoomEnabled=this.map.boxZoom.isEnabled(),this.boxZoomEnabled&&this.map.boxZoom.disable()),this.map.doubleClickZoom&&(this.doubleClickZoomEnabled=this.map.doubleClickZoom.isEnabled(),this.doubleClickZoomEnabled&&this.map.doubleClickZoom.disable()))}restoreMapInteractions(){this.map&&(this.dragPanEnabled&&this.map.dragPan.enable(),this.boxZoomEnabled&&this.map.boxZoom&&this.map.boxZoom.enable(),this.doubleClickZoomEnabled&&this.map.doubleClickZoom&&this.map.doubleClickZoom.enable(),this.dragPanEnabled=null,this.boxZoomEnabled=null,this.doubleClickZoomEnabled=null)}removeLayers(){this.map&&(this.map.getLayer(gt.LASSO_LINE_LAYER)&&this.map.removeLayer(gt.LASSO_LINE_LAYER),this.map.getLayer(gt.LASSO_LAYER)&&this.map.removeLayer(gt.LASSO_LAYER),this.map.getSource(gt.LASSO_SOURCE)&&this.map.removeSource(gt.LASSO_SOURCE))}destroy(){this.disable(),this.removeLayers(),this.map=null}},bG=class{map=null;isDrawing=!1;splitLinePoints=[];targetFeature=null;onCompleteCallback=null;handleClick=null;handleMouseMove=null;handleDblClick=null;constructor(){}init(e){this.map=e}splitPolygon(e,t,n){try{if(ju(b_(e),t).features.length<2)return{original:e,parts:[],success:!1,error:"Splitting line must intersect polygon at least twice"};if(!this.clipLineToBbox(t,si(e)))return{original:e,parts:[],success:!1,error:"Could not clip splitting line to polygon"};const i=this.performPolygonSplit(e,t);return i.length===0?{original:e,parts:[],success:!1,error:"Split operation produced no valid parts"}:(i.forEach(s=>{s.id=Oo(),s.properties={...e.properties}}),{original:e,parts:i,success:!0})}catch(i){return{original:e,parts:[],success:!1,error:`Split operation failed: ${i instanceof Error?i.message:"Unknown error"}`}}}splitLine(e,t){try{const n=TE(e,t);return n.features.length<=1?{original:e,parts:[],success:!1,error:"Splitter does not intersect the line"}:{original:e,parts:n.features.map(i=>{const s=i;return s.id=Oo(),s.properties={...e.properties},s}),success:!0}}catch(n){return{original:e,parts:[],success:!1,error:`Split operation failed: ${n instanceof Error?n.message:"Unknown error"}`}}}startSplit(e,t){this.map&&(this.targetFeature=e,this.onCompleteCallback=t,this.splitLinePoints=[],this.isDrawing=!0,this.setupSplitLineLayers(),this.attachEventListeners(),this.map.getCanvas().style.cursor="crosshair")}cancelSplit(){this.cleanup(),this.targetFeature=null,this.onCompleteCallback=null}isActive(){return this.isDrawing}performPolygonSplit(e,t){try{const n=v4(t,1e-5,{units:"degrees"});if(!n)return[];const i=mR(Kt([e,n]));if(!i)return[];if(i.geometry.type==="MultiPolygon")return i.geometry.coordinates.map(r=>Hr(r));const s=rG(i);return s.features.length>1?s.features:[i]}catch{return[]}}clipLineToBbox(e,t){try{return xz(e,t)}catch{return null}}setupSplitLineLayers(){this.map&&(this.map.getSource(gt.SPLIT_LINE_SOURCE)||this.map.addSource(gt.SPLIT_LINE_SOURCE,{type:"geojson",data:Kt([])}),this.map.getLayer(gt.SPLIT_LINE_LAYER)||this.map.addLayer({id:gt.SPLIT_LINE_LAYER,type:"line",source:gt.SPLIT_LINE_SOURCE,paint:{"line-color":"#ff4444","line-width":3,"line-dasharray":[3,3]}}))}attachEventListeners(){this.map&&(this.handleClick=e=>{this.splitLinePoints.push([e.lngLat.lng,e.lngLat.lat]),this.updateSplitLineVisualization()},this.handleMouseMove=e=>{if(this.splitLinePoints.length===0)return;const t=[...this.splitLinePoints,[e.lngLat.lng,e.lngLat.lat]];this.updateSplitLineVisualization(t)},this.handleDblClick=e=>{e.preventDefault(),this.completeSplit()},this.map.on("click",this.handleClick),this.map.on("mousemove",this.handleMouseMove),this.map.on("dblclick",this.handleDblClick))}removeEventListeners(){this.map&&(this.handleClick&&this.map.off("click",this.handleClick),this.handleMouseMove&&this.map.off("mousemove",this.handleMouseMove),this.handleDblClick&&this.map.off("dblclick",this.handleDblClick),this.handleClick=null,this.handleMouseMove=null,this.handleDblClick=null)}updateSplitLineVisualization(e){if(!this.map)return;const t=this.map.getSource(gt.SPLIT_LINE_SOURCE);if(!t)return;const n=e||this.splitLinePoints;if(n.length<2){t.setData(Kt([]));return}const i=xs(n);t.setData(Kt([i]))}completeSplit(){if(!this.targetFeature||!this.onCompleteCallback||this.splitLinePoints.length<2){this.cleanup();return}const e=xs(this.splitLinePoints);let t;this.targetFeature.geometry.type==="Polygon"?t=this.splitPolygon(this.targetFeature,e):t=this.splitLine(this.targetFeature,e),this.onCompleteCallback(t),this.cleanup()}cleanup(){this.removeEventListeners(),this.clearSplitLine(),this.isDrawing=!1,this.splitLinePoints=[],this.map&&(this.map.getCanvas().style.cursor="")}clearSplitLine(){if(!this.map)return;const e=this.map.getSource(gt.SPLIT_LINE_SOURCE);e&&e.setData(Kt([]))}removeLayers(){this.map&&(this.map.getLayer(gt.SPLIT_LINE_LAYER)&&this.map.removeLayer(gt.SPLIT_LINE_LAYER),this.map.getSource(gt.SPLIT_LINE_SOURCE)&&this.map.removeSource(gt.SPLIT_LINE_SOURCE))}destroy(){this.cancelSplit(),this.removeLayers(),this.map=null}},xG=class{map=null;isDrawing=!1;points=[];options;onCompleteCallback=null;dragPanEnabled=null;boxZoomEnabled=null;doubleClickZoomEnabled=null;handleMouseDown=null;handleMouseMove=null;handleMouseUp=null;constructor(e={}){this.options={type:e.type??"polygon",simplifyTolerance:e.simplifyTolerance??1e-5,minPoints:e.minPoints??(e.type==="line"?2:3)}}init(e){this.map=e}enable(e){this.map&&(this.onCompleteCallback=e||null,this.disableMapInteractions(),this.setupFreehandLayers(),this.attachEventListeners(),this.map.getCanvas().style.cursor="crosshair")}disable(){this.removeEventListeners(),this.clearFreehand(),this.isDrawing=!1,this.points=[],this.onCompleteCallback=null,this.restoreMapInteractions(),this.map&&(this.map.getCanvas().style.cursor="")}setType(e){this.options.type=e,this.options.minPoints=e==="line"?2:3}isActive(){return this.isDrawing}buildFeature(){if(this.points.length<this.options.minPoints)return null;try{let e=this.removeDuplicatePoints(this.points);if(e.length<this.options.minPoints)return null;if(e.length>10&&(e=pb(xs(e),{tolerance:this.options.simplifyTolerance,highQuality:!0}).geometry.coordinates),e=this.removeDuplicatePoints(e),this.options.type==="polygon"){if(e.length<3)return null;for(;e.length>3&&this.arePointsEqual(e[0],e[e.length-1]);)e=e.slice(0,-1);if(e.length<3)return null;const t=e.map(i=>[i[0],i[1]]),n=[t[0][0],t[0][1]];return z2(Hr([[...t,n]]))}else return e.length<2?null:xs(e.map(t=>[t[0],t[1]]))}catch(e){return console.warn("FreehandFeature: Error building feature:",e),null}}removeDuplicatePoints(e){if(e.length<=1)return e;const t=[e[0]];for(let n=1;n<e.length;n++)this.arePointsEqual(e[n],e[n-1])||t.push(e[n]);return t}arePointsEqual(e,t){return Math.abs(e[0]-t[0])<1e-7&&Math.abs(e[1]-t[1])<1e-7}setupFreehandLayers(){this.map&&(this.map.getSource(gt.FREEHAND_SOURCE)||this.map.addSource(gt.FREEHAND_SOURCE,{type:"geojson",data:Kt([])}),this.map.getLayer(gt.FREEHAND_FILL_LAYER)||this.map.addLayer({id:gt.FREEHAND_FILL_LAYER,type:"fill",source:gt.FREEHAND_SOURCE,filter:["==",["geometry-type"],"Polygon"],paint:{"fill-color":"#3388ff","fill-opacity":.2}}),this.map.getLayer(gt.FREEHAND_LINE_LAYER)||this.map.addLayer({id:gt.FREEHAND_LINE_LAYER,type:"line",source:gt.FREEHAND_SOURCE,paint:{"line-color":"#3388ff","line-width":3}}))}attachEventListeners(){this.map&&(this.handleMouseDown=e=>{e.preventDefault(),this.isDrawing=!0,this.points=[[e.lngLat.lng,e.lngLat.lat]],this.updateFreehandVisualization()},this.handleMouseMove=e=>{this.isDrawing&&(e.preventDefault(),this.points.push([e.lngLat.lng,e.lngLat.lat]),this.updateFreehandVisualization())},this.handleMouseUp=()=>{this.isDrawing&&(this.isDrawing=!1,this.completeFreehand())},this.map.on("mousedown",this.handleMouseDown),this.map.on("mousemove",this.handleMouseMove),this.map.on("mouseup",this.handleMouseUp))}removeEventListeners(){this.map&&(this.handleMouseDown&&this.map.off("mousedown",this.handleMouseDown),this.handleMouseMove&&this.map.off("mousemove",this.handleMouseMove),this.handleMouseUp&&this.map.off("mouseup",this.handleMouseUp),this.handleMouseDown=null,this.handleMouseMove=null,this.handleMouseUp=null)}updateFreehandVisualization(){if(!this.map||this.points.length<2)return;const e=this.map.getSource(gt.FREEHAND_SOURCE);if(!e)return;const t=[...this.points];if(this.options.type==="polygon"&&t.length>=3){const n=Hr([[...t,t[0]]]);e.setData(Kt([n]))}else{const n=xs(t);e.setData(Kt([n]))}}completeFreehand(){const e=this.buildFeature(),t={feature:e,success:e!==null,error:e?void 0:`Need at least ${this.options.minPoints} points`};this.onCompleteCallback&&this.onCompleteCallback(t),setTimeout(()=>{this.clearFreehand(),this.points=[]},100)}clearFreehand(){if(!this.map)return;const e=this.map.getSource(gt.FREEHAND_SOURCE);e&&e.setData(Kt([]))}disableMapInteractions(){this.map&&(this.dragPanEnabled=this.map.dragPan.isEnabled(),this.dragPanEnabled&&this.map.dragPan.disable(),this.map.boxZoom&&(this.boxZoomEnabled=this.map.boxZoom.isEnabled(),this.boxZoomEnabled&&this.map.boxZoom.disable()),this.map.doubleClickZoom&&(this.doubleClickZoomEnabled=this.map.doubleClickZoom.isEnabled(),this.doubleClickZoomEnabled&&this.map.doubleClickZoom.disable()))}restoreMapInteractions(){this.map&&(this.dragPanEnabled&&this.map.dragPan.enable(),this.boxZoomEnabled&&this.map.boxZoom&&this.map.boxZoom.enable(),this.doubleClickZoomEnabled&&this.map.doubleClickZoom&&this.map.doubleClickZoom.enable(),this.dragPanEnabled=null,this.boxZoomEnabled=null,this.doubleClickZoomEnabled=null)}removeLayers(){this.map&&(this.map.getLayer(gt.FREEHAND_LINE_LAYER)&&this.map.removeLayer(gt.FREEHAND_LINE_LAYER),this.map.getLayer(gt.FREEHAND_FILL_LAYER)&&this.map.removeLayer(gt.FREEHAND_FILL_LAYER),this.map.getSource(gt.FREEHAND_SOURCE)&&this.map.removeSource(gt.FREEHAND_SOURCE))}destroy(){this.disable(),this.removeLayers(),this.map=null}};function lm(e){return e.filter(_R)}var mb=class{map;geoman=null;container;options;state;copyFeature;simplifyFeature;unionFeature;differenceFeature;scaleFeature;lassoFeature;splitFeature;freehandFeature;boundKeyHandler=null;boundClickHandler=null;boundScaleMouseDown=null;boundScaleMouseMove=null;boundScaleMouseUp=null;isSelectMode=!1;pendingOperation=null;snappingEnabled=!1;lastCreatedFeature=null;lastEditedFeature=null;lastDeletedFeature=null;lastDeletedFeatureId=null;isScaling=!1;scaleTargetFeature=null;scaleTargetGeomanData=null;scaleStartFeature=null;scaleDragPanEnabled=null;isMultiDragging=!1;multiDragStartPoint=null;multiDragOriginalFeatures=[];multiDragGeomanData=[];multiDragPanEnabled=null;boundMultiDragMouseDown=null;boundMultiDragMouseMove=null;boundMultiDragMouseUp=null;toolbar=null;fileInput=null;propertiesPopup=null;historyManager=null;pendingEditFeature=null;isPerformingCompositeOperation=!1;attributePanel=null;attributePanelVisible=!1;currentEditingFeature=null;currentEditingGeomanData=null;isNewFeature=!1;originalProperties=null;boundStyleDataHandler=null;_eventHandlers=new globalThis.Map;constructor(e={}){this.options={...pG,...e},this.state={activeDrawMode:null,activeEditMode:null,selectedFeatures:[],isDrawing:!1,isEditing:!1,clipboard:[],collapsed:this.options.collapsed},this.snappingEnabled=this.options.snappingEnabled,this.copyFeature=new mG,this.simplifyFeature=new gG({tolerance:this.options.simplifyTolerance}),this.unionFeature=new _G,this.differenceFeature=new AG,this.scaleFeature=new vG,this.lassoFeature=new yG,this.splitFeature=new bG,this.freehandFeature=new xG,this.options.enableHistory!==!1&&(this.historyManager=new aG(this.options.maxHistorySize,(t,n)=>{this.updateHistoryButtonStates(t,n),this.options.onHistoryChange?.(t,n)}))}onAdd(e){return this.map=e,this.scaleFeature.init(e),this.lassoFeature.init(e),this.splitFeature.init(e),this.freehandFeature.init(e),this.container=document.createElement("div"),this.container.className=`maplibregl-ctrl maplibregl-ctrl-group ${rt}-control`,this.createToolbar(),this.setupFileInput(),this.setupKeyboardShortcuts(),this.setupSelectionHandler(),this.setupScaleHandler(),this.setupMultiDragHandler(),this.setupVertexMarkerStyleListener(),this.setupGeomanEvents(),this.options.enableAttributeEditing&&this.createAttributePanel(),this.geoman||this._autoInitGeoman(),this.container}onRemove(){this.removeKeyboardShortcuts(),this.removeSelectionHandler(),this.removeScaleHandler(),this.removeMultiDragHandler(),this.removeVertexMarkerStyleListener(),this.disableAllModes(),this.hideFeaturePropertiesPopup(),this.hideAttributePanel(),this.removeAttributePanel(),this.scaleFeature.destroy(),this.lassoFeature.destroy(),this.splitFeature.destroy(),this.freehandFeature.destroy(),this.fileInput&&this.fileInput.parentNode&&(this.fileInput.parentNode.removeChild(this.fileInput),this.fileInput=null),this.container.parentNode&&this.container.parentNode.removeChild(this.container),this.map=void 0}setGeoman(e){this.geoman=e,this.setupGeomanEvents(),this.applySnappingState(),this.options.hideGeomanControl&&this.hideGeomanControl()}_autoInitGeoman(){Promise.resolve().then(()=>require("./maplibre-geoman.es-zvPUPZr7.cjs")).then(({Geoman:e})=>{if(this.map&&!this.geoman){const t=new e(this.map);t.addControls=async()=>{},t.removeControls=()=>{},this.setGeoman(t)}}).catch(()=>{})}hideGeomanControl(){if(this.geoman)try{this.geoman.removeControls()}catch{[".maplibregl-ctrl.geoman-controls",".gm-control",".maplibregl-ctrl-group.geoman",'[class*="geoman"]'].forEach(e=>{document.querySelectorAll(e).forEach(t=>{t.classList.contains("geo-editor-control")||(t.style.display="none")})})}}setupSelectionHandler(){this.boundClickHandler=e=>{if(!this.isSelectMode&&!this.pendingOperation||!this.geoman)return;const t=this.findFeatureByMouseEvent(e)||this.findFeatureAtPoint(e.lngLat.lng,e.lngLat.lat);if(t){const{feature:n,geomanData:i}=t;this.pendingOperation?(n.geometry.type==="Polygon"||n.geometry.type==="MultiPolygon")&&this.addToSelection(n,i):e.originalEvent.shiftKey?this.toggleFeatureSelection(n,i):this.selectFeatures([n],[i])}else!e.originalEvent.shiftKey&&!this.pendingOperation&&this.clearSelection()},this.map.on("click",this.boundClickHandler)}getClickToleranceKm(){const e=this.map.getZoom();return 40075/(512*Math.pow(2,e))*15}findFeatureAtPoint(e,t){if(!this.geoman)return null;const n=wi([e,t]);let i=null;const s=this.getClickToleranceKm();let r=[];const a=new Map;try{let o=0;this.geoman.features.forEach(l=>{const c=this.getGeomanFeature(l);if(!l||!c||!c.geometry){o++;return}const h=String(l.id??c.id??`feature-${o}`);r.push(c),a.set(h,l),a.set(`idx-${o}`,l),o++})}catch{try{r=(this.geoman.features.getAll().features||[]).filter(o=>o&&o.geometry)}catch{return null}}for(let o=0;o<r.length;o++){const l=r[o];if(!l||!l.geometry)continue;const c=String(l.id??`feature-${o}`),h=a.get(c)||a.get(`idx-${o}`);try{let d=!1;if(l.geometry.type==="Point")d=dp(n,wi(l.geometry.coordinates),{units:"kilometers"})<s;else if(l.geometry.type==="Polygon"||l.geometry.type==="MultiPolygon")d=Ii(n,l);else if(l.geometry.type==="LineString"||l.geometry.type==="MultiLineString"){const f=au(l,n);d=f.properties.dist!==void 0&&f.properties.dist<s}if(d){const f=h||this.findGeomanDataForFeature(l);if(f){i={feature:l,geomanData:f};break}}}catch{}}return i}findFeatureByMouseEvent(e){if(!this.geoman||!e.originalEvent)return null;try{const t=this.geoman.features.getFeatureByMouseEvent({event:e}),n=this.getGeomanFeature(t);if(n&&t)return{feature:n,geomanData:t}}catch{}return null}findGeomanDataForFeature(e){if(!this.geoman)return null;let t=null;const n=this.getGeomanIdFromFeature(e);try{this.geoman.features.forEach(i=>{if(t)return;const s=this.getGeomanFeature(i);s&&(n&&String(s.id)===n||n&&this.getGeomanIdFromFeature(s)===n||JSON.stringify(s.geometry)===JSON.stringify(e.geometry))&&(t=i)})}catch{}return t}getGeomanIdFromFeature(e){const t=e.properties,n=e.id??t?.__gm_id??t?.id;return n!=null?String(n):null}getGeomanFeature(e){if(!e)return null;if(typeof e.getGeoJson=="function")try{return e.getGeoJson()}catch{return null}return e.geoJson??null}removeSelectionHandler(){this.boundClickHandler&&(this.map.off("click",this.boundClickHandler),this.boundClickHandler=null)}setupScaleHandler(){this.boundScaleMouseDown=e=>{if(this.state.activeEditMode!=="scale")return;const t=this.getScaleHandleFromEvent(e);!t||!this.scaleTargetFeature||!this.scaleTargetGeomanData||(e.preventDefault(),this.isScaling=!0,this.scaleStartFeature=this.scaleTargetFeature,this.disableScaleDragPan(),this.scaleFeature.startScale(this.scaleTargetFeature,t,[e.lngLat.lng,e.lngLat.lat],(n,i)=>{this.applyScaledFeature(n),this.emitEvent("gm:scale",{feature:n,scaleFactor:i})}),this.emitEvent("gm:scalestart",{feature:this.scaleTargetFeature}))},this.boundScaleMouseMove=e=>{if(!this.isScaling)return;const t=this.scaleFeature.updateScale([e.lngLat.lng,e.lngLat.lat]);t&&this.applyScaledFeature(t)},this.boundScaleMouseUp=()=>{if(!this.isScaling)return;this.isScaling=!1;const e=this.scaleFeature.endScale();this.restoreScaleDragPan(),e&&(this.applyScaledFeature(e.feature),this.scaleStartFeature&&this.options.onFeatureEdit?.(e.feature,this.scaleStartFeature),this.lastEditedFeature=e.feature,this.logSelectedFeatureCollection("edited",e.feature),this.scaleFeature.showHandlesForFeature(e.feature),this.bringScaleHandlesToFront(),this.emitEvent("gm:scaleend",{feature:e.feature,scaleFactor:e.factor})),this.scaleStartFeature=null},this.map.on("mousedown",this.boundScaleMouseDown),this.map.on("mousemove",this.boundScaleMouseMove),this.map.on("mouseup",this.boundScaleMouseUp)}removeScaleHandler(){this.boundScaleMouseDown&&(this.map.off("mousedown",this.boundScaleMouseDown),this.boundScaleMouseDown=null),this.boundScaleMouseMove&&(this.map.off("mousemove",this.boundScaleMouseMove),this.boundScaleMouseMove=null),this.boundScaleMouseUp&&(this.map.off("mouseup",this.boundScaleMouseUp),this.boundScaleMouseUp=null)}setupMultiDragHandler(){this.boundMultiDragMouseDown=e=>{if(this.state.activeEditMode!=="drag"||this.state.selectedFeatures.length<2)return;const t=this.findFeatureByMouseEvent(e)||this.findFeatureAtPoint(e.lngLat.lng,e.lngLat.lat);if(!t)return;const n=this.getGeomanIdFromFeature(t.feature);this.state.selectedFeatures.some(i=>this.getGeomanIdFromFeature(i.feature)===n)&&(e.preventDefault(),this.isMultiDragging=!0,this.multiDragStartPoint=[e.lngLat.lng,e.lngLat.lat],this.multiDragOriginalFeatures=this.state.selectedFeatures.map(i=>Es(i.feature)),this.multiDragGeomanData=this.state.selectedFeatures.map(i=>i.geomanData??this.findGeomanDataForFeature(i.feature)),this.disableMultiDragPan())},this.boundMultiDragMouseMove=e=>{if(!this.isMultiDragging||!this.multiDragStartPoint)return;const t=this.multiDragStartPoint,n=[e.lngLat.lng,e.lngLat.lat],i=dp(wi(t),wi(n),{units:"kilometers"}),s=L2(wi(t),wi(n)),r=[];this.multiDragOriginalFeatures.forEach((a,o)=>{const l=fb(a,i,s,{units:"kilometers"}),c=this.multiDragGeomanData[o];c?.updateGeometry?c.updateGeometry(l.geometry):c?.updateGeoJsonGeometry&&c.updateGeoJsonGeometry(l.geometry),r.push(l)}),this.state.selectedFeatures=this.state.selectedFeatures.map((a,o)=>({...a,feature:r[o]??a.feature})),this.updateSelectionHighlight()},this.boundMultiDragMouseUp=()=>{this.isMultiDragging&&(this.isMultiDragging=!1,this.restoreMultiDragPan(),this.state.selectedFeatures.length>0&&(this.state.selectedFeatures.forEach((e,t)=>{const n=this.multiDragOriginalFeatures[t];n&&this.options.onFeatureEdit?.(e.feature,n)}),this.lastEditedFeature=this.state.selectedFeatures[this.state.selectedFeatures.length-1]?.feature??null,this.logSelectedFeatureCollection("edited",this.lastEditedFeature)),this.multiDragStartPoint=null,this.multiDragOriginalFeatures=[],this.multiDragGeomanData=[])},this.map.on("mousedown",this.boundMultiDragMouseDown),this.map.on("mousemove",this.boundMultiDragMouseMove),this.map.on("mouseup",this.boundMultiDragMouseUp)}removeMultiDragHandler(){this.boundMultiDragMouseDown&&(this.map.off("mousedown",this.boundMultiDragMouseDown),this.boundMultiDragMouseDown=null),this.boundMultiDragMouseMove&&(this.map.off("mousemove",this.boundMultiDragMouseMove),this.boundMultiDragMouseMove=null),this.boundMultiDragMouseUp&&(this.map.off("mouseup",this.boundMultiDragMouseUp),this.boundMultiDragMouseUp=null)}disableMultiDragPan(){this.multiDragPanEnabled=this.map.dragPan.isEnabled(),this.multiDragPanEnabled&&this.map.dragPan.disable()}restoreMultiDragPan(){this.multiDragPanEnabled&&this.map.dragPan.enable(),this.multiDragPanEnabled=null}getScaleHandleFromEvent(e){if(!this.map.getLayer(gt.SCALE_HANDLES_LAYER))return null;const t=this.map.queryRenderedFeatures(e.point,{layers:[gt.SCALE_HANDLES_LAYER]});if(!t.length)return null;const n=t[0].properties?.position;return typeof n=="string"?n:null}disableScaleDragPan(){this.scaleDragPanEnabled=this.map.dragPan.isEnabled(),this.scaleDragPanEnabled&&this.map.dragPan.disable()}restoreScaleDragPan(){this.scaleDragPanEnabled&&this.map.dragPan.enable(),this.scaleDragPanEnabled=null}applyScaledFeature(e){if(this.scaleTargetGeomanData?.updateGeometry?this.scaleTargetGeomanData.updateGeometry(e.geometry):this.scaleTargetGeomanData?.updateGeoJsonGeometry&&this.scaleTargetGeomanData.updateGeoJsonGeometry(e.geometry),this.state.selectedFeatures.length>0){const t=this.state.selectedFeatures[0];this.state.selectedFeatures[0]={...t,id:String(this.scaleTargetGeomanData?.id??e.id??t.id),feature:e,geomanData:this.scaleTargetGeomanData??t.geomanData},this.scaleTargetFeature=e}this.updateSelectionHighlight(),this.bringScaleHandlesToFront()}bringScaleHandlesToFront(){if(this.map.getLayer(gt.SCALE_HANDLES_LAYER))try{this.map.moveLayer(gt.SCALE_HANDLES_LAYER)}catch{}}logSelectedFeatureCollection(e,t){const n=t?this.getGeomanIdFromFeature(t):null;console.log("GeoEditor",{action:e,featureId:n,feature:t,selection:this.getSelectedFeatureCollection()})}extractFeatureFromEvent(e){if(!e||typeof e!="object")return null;const t=e;if(typeof t.getGeoJson=="function")try{return t.getGeoJson()}catch{return null}return t.geoJson?t.geoJson:"geometry"in t?t:null}toggleFeatureSelection(e,t){const n=t??this.findGeomanDataForFeature(e),i=String(n?.id??e.id);this.state.selectedFeatures.some(s=>s.id===i)?this.removeFromSelection(i):this.addToSelection(e,n??void 0)}enableSelectMode(){this.disableAllModes(),this.isSelectMode=!0,this.map.getCanvas().style.cursor="pointer",this.updateToolbarState()}disableSelectMode(){this.isSelectMode=!1,this.map.getCanvas().style.cursor=""}getState(){return{...this.state}}getSelectedFeatures(){return this.state.selectedFeatures.map(e=>e.feature)}getSelectedFeatureCollection(){return{type:"FeatureCollection",features:this.getSelectedFeatures()}}getFeatures(){if(this.geoman)try{return this.geoman.features.getAll()}catch{const e=[];return this.geoman.features.forEach(t=>{const n=this.getGeomanFeature(t);n&&e.push(n)}),{type:"FeatureCollection",features:e}}return{type:"FeatureCollection",features:[]}}getAllFeatureCollection(){return this.getFeatures()}getLastCreatedFeature(){return this.lastCreatedFeature}getLastEditedFeature(){return this.lastEditedFeature}getLastDeletedFeature(){return this.lastDeletedFeature}getLastDeletedFeatureId(){return this.lastDeletedFeatureId}enableDrawMode(e){this.disableAllModes(),e==="freehand"?this.enableFreehandMode():this.geoman&&(this.geoman.enableDraw(e),setTimeout(()=>this.applyVertexMarkerStyles(),50)),this.state.activeDrawMode=e,this.state.isDrawing=!0,this.options.onModeChange?.(e),this.updateToolbarState()}applyVertexMarkerStyles(){if(!this.map)return;const e=this.map.getStyle();if(!(!e||!e.layers))for(const t of e.layers){const n=t.id.toLowerCase();if(t.type==="circle"&&(n.includes("gm-")||n.includes("geoman")||n.includes("marker")||n.includes("vertex")||n.includes("handle")||n.includes("temp")))try{this.map.getLayer(t.id)&&(this.map.setPaintProperty(t.id,"circle-opacity",.5),this.map.setPaintProperty(t.id,"circle-stroke-opacity",.8))}catch{}}}setupVertexMarkerStyleListener(){this.map&&(this.boundStyleDataHandler=()=>{this.state.isDrawing&&this.applyVertexMarkerStyles()},this.map.on("styledata",this.boundStyleDataHandler))}removeVertexMarkerStyleListener(){this.map&&this.boundStyleDataHandler&&(this.map.off("styledata",this.boundStyleDataHandler),this.boundStyleDataHandler=null)}enableFreehandMode(){this.freehandFeature.enable(e=>{e.success&&e.feature&&this.geoman&&this.geoman.features.importGeoJsonFeature(e.feature)&&(this.options.onFeatureCreate?.(e.feature),this.emitEvent("gm:create",{feature:e.feature}))})}disableFreehandMode(){this.freehandFeature.disable()}enableEditMode(e){if(this.disableAllModes(),Pv.includes(e))this.enableAdvancedEditMode(e);else if(this.geoman)switch(e){case"drag":this.state.selectedFeatures.length<2&&this.geoman.enableGlobalDragMode();break;case"change":this.geoman.enableGlobalEditMode();break;case"rotate":this.geoman.enableGlobalRotateMode();break;case"cut":this.geoman.enableGlobalCutMode();break;case"delete":if(this.state.selectedFeatures.length>0){this.deleteSelectedFeatures();return}this.geoman.enableGlobalRemovalMode();break}this.state.activeEditMode=e,this.state.isEditing=!0,this.options.onModeChange?.(e),this.updateToolbarState()}disableAllModes(){this.geoman&&this.geoman.disableAllModes(),this.scaleFeature.cancelScale(),this.lassoFeature.disable(),this.splitFeature.cancelSplit(),this.disableFreehandMode(),this.disableSelectMode(),this.restoreScaleDragPan(),this.restoreMultiDragPan(),this.isMultiDragging=!1,this.multiDragStartPoint=null,this.multiDragOriginalFeatures=[],this.multiDragGeomanData=[],this.isScaling=!1,this.scaleTargetFeature=null,this.scaleTargetGeomanData=null,this.scaleStartFeature=null,this.pendingOperation=null,this.map.getCanvas().style.cursor="",this.state.activeDrawMode=null,this.state.activeEditMode=null,this.state.isDrawing=!1,this.state.isEditing=!1,this.updateToolbarState(),this.applySnappingState()}enableAdvancedEditMode(e){switch(e){case"select":this.enableSelectMode();break;case"scale":this.enableScaleMode();break;case"copy":this.enableCopyMode();break;case"split":this.enableSplitMode();break;case"union":this.enableUnionMode();break;case"difference":this.enableDifferenceMode();break;case"simplify":this.executeSimplify();break;case"lasso":this.enableLassoMode();break}}enableUnionMode(){if(lm(this.getSelectedFeatures()).length>=2){this.executeUnion();return}this.pendingOperation="union",this.map.getCanvas().style.cursor="pointer"}enableDifferenceMode(){if(lm(this.getSelectedFeatures()).length>=2){this.executeDifference();return}this.pendingOperation="difference",this.map.getCanvas().style.cursor="pointer"}executePendingOperation(){this.pendingOperation&&(this.pendingOperation==="union"?this.executeUnion():this.pendingOperation==="difference"&&this.executeDifference(),this.pendingOperation=null)}cancelPendingOperation(){this.pendingOperation=null,this.clearSelection(),this.map.getCanvas().style.cursor="",this.updateToolbarState()}setupSelectionHighlight(){if(this.map)if(!this.map.getSource(gt.SELECTION_SOURCE))this.map.addSource(gt.SELECTION_SOURCE,{type:"geojson",data:{type:"FeatureCollection",features:[]}}),this.map.addLayer({id:gt.SELECTION_FILL_LAYER,type:"fill",source:gt.SELECTION_SOURCE,filter:["match",["geometry-type"],["Polygon","MultiPolygon"],!0,!1],paint:{"fill-color":"#ffff00","fill-opacity":.3}}),this.map.addLayer({id:gt.SELECTION_LINE_LAYER,type:"line",source:gt.SELECTION_SOURCE,paint:{"line-color":"#ff9900","line-width":5,"line-opacity":1,"line-dasharray":[3,2]}}),this.map.addLayer({id:gt.SELECTION_CIRCLE_LAYER,type:"circle",source:gt.SELECTION_SOURCE,filter:["==",["geometry-type"],"Point"],paint:{"circle-radius":12,"circle-color":"#ffff00","circle-opacity":.5,"circle-stroke-color":"#ff9900","circle-stroke-width":3,"circle-stroke-opacity":1}});else try{this.map.getLayer(gt.SELECTION_FILL_LAYER)&&(this.map.setFilter(gt.SELECTION_FILL_LAYER,["match",["geometry-type"],["Polygon","MultiPolygon"],!0,!1]),this.map.moveLayer(gt.SELECTION_FILL_LAYER)),this.map.getLayer(gt.SELECTION_LINE_LAYER)&&this.map.moveLayer(gt.SELECTION_LINE_LAYER),this.map.getLayer(gt.SELECTION_CIRCLE_LAYER)&&this.map.moveLayer(gt.SELECTION_CIRCLE_LAYER)}catch{}}updateSelectionHighlight(){if(!this.map)return;this.setupSelectionHighlight();const e=this.map.getSource(gt.SELECTION_SOURCE);if(e){const t=this.getSelectedFeatures();e.setData({type:"FeatureCollection",features:t})}}selectFeatures(e,t){const n=t&&t.length?t:e.map(s=>this.findGeomanDataForFeature(s)),i=Date.now();this.state.selectedFeatures=e.map((s,r)=>({id:String(n?.[r]?.id??s.id??`${i}-${r}`),feature:s,layerId:"default",geomanData:n?.[r]??void 0})),this.updateSelectionHighlight(),this.options.onSelectionChange?.(e),this.logSelectedFeatureCollection("selected"),e.length===1&&this.isSelectMode?this.options.enableAttributeEditing?this.showAttributePanel(e[0],n?.[0]??void 0,!1):this.options.showFeatureProperties&&this.showFeaturePropertiesPopup(e[0]):(this.hideAttributePanel(),this.hideFeaturePropertiesPopup())}addToSelection(e,t){const n=t??this.findGeomanDataForFeature(e),i=String(n?.id??e.id);this.state.selectedFeatures.some(s=>s.id===i)||(this.state.selectedFeatures.push({id:i,feature:e,layerId:"default",geomanData:n??void 0}),this.updateSelectionHighlight(),this.options.onSelectionChange?.(this.getSelectedFeatures()),this.logSelectedFeatureCollection("selected"))}removeFromSelection(e){this.state.selectedFeatures=this.state.selectedFeatures.filter(t=>t.id!==e),this.updateSelectionHighlight(),this.options.onSelectionChange?.(this.getSelectedFeatures()),this.logSelectedFeatureCollection("selected")}clearSelection(){this.state.selectedFeatures=[],this.updateSelectionHighlight(),this.hideFeaturePropertiesPopup(),this.hideAttributePanel(),this.options.onSelectionChange?.([]),this.logSelectedFeatureCollection("selected")}showFeaturePropertiesPopup(e){if(!this.options.showFeatureProperties||!e.properties||Object.keys(e.properties).length===0)return;this.hideFeaturePropertiesPopup();const t=Dp(e).geometry.coordinates,n=this.formatPropertiesHtml(e.properties);this.propertiesPopup=new fi.default.Popup({maxWidth:"300px",closeButton:!0,closeOnClick:!1,className:"geo-editor-properties-popup"}).setLngLat(t).setHTML(n).addTo(this.map)}hideFeaturePropertiesPopup(){this.propertiesPopup&&(this.propertiesPopup.remove(),this.propertiesPopup=null)}formatPropertiesHtml(e){const t=Object.entries(e).filter(([n])=>!n.startsWith("__"));return t.length===0?'<div class="geo-editor-popup-empty">No properties</div>':`<table class="geo-editor-popup-table"><tbody>${t.map(([n,i])=>{const s=i==null?"<em>null</em>":typeof i=="object"?this.escapeHtml(JSON.stringify(i)):this.escapeHtml(String(i));return`<tr><td class="geo-editor-popup-key">${this.escapeHtml(n)}</td><td class="geo-editor-popup-value">${s}</td></tr>`}).join("")}</tbody></table>`}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}createAttributePanel(){if(this.attributePanel)return;const e=this.options.attributePanelPosition,t=this.options.attributePanelWidth,n=this.options.attributePanelMaxHeight,i=this.options.attributePanelTop,s=this.options.attributePanelSideOffset;this.attributePanel=document.createElement("div"),this.attributePanel.className=`${rt}-attribute-panel ${rt}-attribute-panel--${e} ${rt}-attribute-panel--hidden`,this.attributePanel.style.width=`${t}px`,this.attributePanel.style.maxHeight=typeof n=="number"?`${n}px`:n,this.attributePanel.style.top=`${i}px`,e==="right"?this.attributePanel.style.right=`${s}px`:this.attributePanel.style.left=`${s}px`;const r=document.createElement("div");r.className=`${rt}-attribute-panel-header`;const a=document.createElement("h3");a.className=`${rt}-attribute-panel-title`,a.textContent=this.options.attributePanelTitle,r.appendChild(a);const o=document.createElement("button");o.className=`${rt}-attribute-panel-close`,o.innerHTML='<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M1 1l12 12M13 1L1 13"/></svg>',o.title="Close",o.addEventListener("click",()=>this.hideAttributePanel()),r.appendChild(o),this.attributePanel.appendChild(r);const l=document.createElement("div");l.className=`${rt}-attribute-panel-body`,l.setAttribute("data-panel-body","true"),this.attributePanel.appendChild(l);const c=document.createElement("div");c.className=`${rt}-attribute-panel-footer`;const h=document.createElement("button");h.className=`${rt}-btn ${rt}-btn--secondary`,h.textContent="Cancel",h.addEventListener("click",()=>this.hideAttributePanel()),c.appendChild(h);const d=document.createElement("button");d.className=`${rt}-btn ${rt}-btn--primary`,d.textContent="Save",d.setAttribute("data-save-btn","true"),d.addEventListener("click",()=>this.saveAttributeChanges()),c.appendChild(d),this.attributePanel.appendChild(c),this.map.getContainer().appendChild(this.attributePanel)}removeAttributePanel(){this.attributePanel&&this.attributePanel.parentNode&&(this.attributePanel.parentNode.removeChild(this.attributePanel),this.attributePanel=null)}showAttributePanel(e,t,n=!1){this.attributePanel&&(this.currentEditingFeature=e,this.currentEditingGeomanData=t??null,this.isNewFeature=n,this.originalProperties=e.properties?{...e.properties}:{},this.buildAttributeForm(e),this.attributePanel.classList.remove(`${rt}-attribute-panel--hidden`),this.attributePanelVisible=!0,this.hideFeaturePropertiesPopup())}hideAttributePanel(){this.attributePanel&&(this.attributePanel.classList.add(`${rt}-attribute-panel--hidden`),this.attributePanelVisible=!1,this.currentEditingFeature=null,this.currentEditingGeomanData=null,this.isNewFeature=!1,this.originalProperties=null)}toggleAttributePanel(){this.attributePanelVisible?this.hideAttributePanel():this.currentEditingFeature&&this.showAttributePanel(this.currentEditingFeature,this.currentEditingGeomanData??void 0,this.isNewFeature)}getSchemaFieldsForGeometry(e){const t=this.options.attributeSchema;if(!t)return[];const n=[];return e==="Polygon"||e==="MultiPolygon"?t.polygon&&n.push(...t.polygon):e==="LineString"||e==="MultiLineString"?t.line&&n.push(...t.line):(e==="Point"||e==="MultiPoint")&&t.point&&n.push(...t.point),t.common&&n.push(...t.common),n}getExtraProperties(e){const t=e.properties||{},n=this.getSchemaFieldsForGeometry(e.geometry.type),i=new Set(n.map(r=>r.name)),s={};for(const[r,a]of Object.entries(t))!r.startsWith("__")&&!i.has(r)&&(s[r]=a);return s}buildAttributeForm(e){if(!this.attributePanel)return;const t=this.attributePanel.querySelector("[data-panel-body]");if(!t)return;t.innerHTML="";const n=e.geometry.type,i=this.getSchemaFieldsForGeometry(n),s=e.properties||{},r=this.attributePanel.querySelector(`.${rt}-attribute-panel-header`);if(r){const l=r.querySelector(`.${rt}-attribute-geometry-badge`);l&&l.remove();const c=document.createElement("span");c.className=`${rt}-attribute-geometry-badge`,c.textContent=this.getGeometryDisplayName(n);const h=r.querySelector(`.${rt}-attribute-panel-title`);h&&h.appendChild(c)}if(i.length>0)i.forEach(l=>{const c=s[l.name],h=this.createFormField(l,c);t.appendChild(h)});else{const l=document.createElement("div");l.className=`${rt}-attribute-empty`,l.textContent="No attribute schema defined",t.appendChild(l)}const a=this.getExtraProperties(e),o=Object.keys(a);if(o.length>0){const l=document.createElement("div");l.className=`${rt}-attribute-extra-section`;const c=document.createElement("div");c.className=`${rt}-attribute-extra-section-title`,c.textContent="Other Properties",l.appendChild(c),o.forEach(h=>{const d=this.createReadOnlyField(h,a[h]);l.appendChild(d)}),t.appendChild(l)}}getGeometryDisplayName(e){return{Point:"Point",MultiPoint:"Multi-Point",LineString:"Line",MultiLineString:"Multi-Line",Polygon:"Polygon",MultiPolygon:"Multi-Polygon",GeometryCollection:"Collection"}[e]||e}createFormField(e,t){const n=document.createElement("div");n.className=`${rt}-attribute-form-group`;const i=document.createElement("label");i.className=`${rt}-attribute-label`,e.required&&i.classList.add(`${rt}-attribute-label--required`),i.textContent=e.label||e.name,i.setAttribute("for",`attr-${e.name}`),n.appendChild(i);const s=this.createInputForFieldType(e,t);return n.appendChild(s),n}createInputForFieldType(e,t){const n=`attr-${e.name}`;switch(e.type){case"boolean":{const i=document.createElement("div");i.className=`${rt}-attribute-checkbox-wrapper`;const s=document.createElement("input");s.type="checkbox",s.id=n,s.name=e.name,s.className=`${rt}-attribute-checkbox`,s.checked=t===!0||t==="true",s.disabled=e.readOnly??!1,i.appendChild(s);const r=document.createElement("label");return r.className=`${rt}-attribute-checkbox-label`,r.setAttribute("for",n),r.textContent=e.label||e.name,i.appendChild(r),i}case"select":{const i=document.createElement("select");if(i.id=n,i.name=e.name,i.className=`${rt}-attribute-select`,i.disabled=e.readOnly??!1,!e.required){const s=document.createElement("option");s.value="",s.textContent="-- Select --",i.appendChild(s)}return e.options&&e.options.forEach(s=>{const r=document.createElement("option");r.value=String(s.value),r.textContent=s.label,String(t)===String(s.value)&&(r.selected=!0),i.appendChild(r)}),i}case"textarea":{const i=document.createElement("textarea");return i.id=n,i.name=e.name,i.className=`${rt}-attribute-textarea`,i.value=t!=null?String(t):"",i.placeholder=e.placeholder||"",i.disabled=e.readOnly??!1,i}case"number":{const i=document.createElement("input");return i.type="number",i.id=n,i.name=e.name,i.className=`${rt}-attribute-input`,i.value=t!=null?String(t):"",i.placeholder=e.placeholder||"",i.disabled=e.readOnly??!1,e.min!==void 0&&(i.min=String(e.min)),e.max!==void 0&&(i.max=String(e.max)),e.step!==void 0&&(i.step=String(e.step)),i}case"date":{const i=document.createElement("input");return i.type="date",i.id=n,i.name=e.name,i.className=`${rt}-attribute-input`,i.value=t!=null?String(t):"",i.disabled=e.readOnly??!1,i}case"color":{const i=document.createElement("input");return i.type="color",i.id=n,i.name=e.name,i.className=`${rt}-attribute-input`,i.value=t!=null?String(t):"#000000",i.disabled=e.readOnly??!1,i}default:{const i=document.createElement("input");return i.type="text",i.id=n,i.name=e.name,i.className=`${rt}-attribute-input`,i.value=t!=null?String(t):"",i.placeholder=e.placeholder||"",i.disabled=e.readOnly??!1,i}}}createReadOnlyField(e,t){const n=document.createElement("div");n.className=`${rt}-attribute-form-group`;const i=document.createElement("label");i.className=`${rt}-attribute-label`,i.textContent=e,n.appendChild(i);const s=document.createElement("div");return s.className=`${rt}-attribute-readonly`,t==null?(s.classList.add(`${rt}-attribute-readonly-null`),s.textContent="null"):typeof t=="object"?s.textContent=JSON.stringify(t):s.textContent=String(t),n.appendChild(s),n}collectFormValues(){if(!this.attributePanel||!this.currentEditingFeature)return{};const e=this.attributePanel.querySelector("[data-panel-body]");if(!e)return{};const t={};return this.getSchemaFieldsForGeometry(this.currentEditingFeature.geometry.type).forEach(n=>{const i=e.querySelector(`[name="${n.name}"]`);if(i)if(n.type==="boolean")t[n.name]=i.checked;else if(n.type==="number"){const s=i.value.trim();t[n.name]=s!==""?parseFloat(s):null}else t[n.name]=i.value||null}),t}validateFormValues(e){if(!this.currentEditingFeature)return{valid:!0,errors:{}};const t=this.getSchemaFieldsForGeometry(this.currentEditingFeature.geometry.type),n={};return t.forEach(i=>{if(i.required){const s=e[i.name];(s==null||s==="")&&(n[i.name]=`${i.label||i.name} is required`)}}),{valid:Object.keys(n).length===0,errors:n}}showValidationErrors(e){if(!this.attributePanel)return;const t=this.attributePanel.querySelector("[data-panel-body]");t&&(t.querySelectorAll(`.${rt}-attribute-error`).forEach(n=>n.remove()),t.querySelectorAll(`.${rt}-attribute-input--error, .${rt}-attribute-select--error, .${rt}-attribute-textarea--error`).forEach(n=>{n.classList.remove(`${rt}-attribute-input--error`),n.classList.remove(`${rt}-attribute-select--error`),n.classList.remove(`${rt}-attribute-textarea--error`)}),Object.entries(e).forEach(([n,i])=>{const s=t.querySelector(`[name="${n}"]`);if(s){s.classList.add(`${rt}-attribute-input--error`);const r=document.createElement("div");r.className=`${rt}-attribute-error`,r.textContent=i,s.parentNode?.appendChild(r)}}))}applyDefaultValues(e){const t=this.getSchemaFieldsForGeometry(e.geometry.type);t.length!==0&&(e.properties||(e.properties={}),t.forEach(n=>{n.defaultValue!==void 0&&e.properties[n.name]===void 0&&(e.properties[n.name]=n.defaultValue)}))}saveAttributeChanges(){if(!this.currentEditingFeature)return;const e=this.collectFormValues(),t=this.validateFormValues(e);if(!t.valid){this.showValidationErrors(t.errors);return}const n={...this.currentEditingFeature.properties,...e};this.currentEditingFeature.properties=n,this.currentEditingGeomanData&&this.updateFeatureProperties(this.currentEditingGeomanData,n);const i={feature:this.currentEditingFeature,previousProperties:this.originalProperties??{},newProperties:n,isNewFeature:this.isNewFeature};this.options.onAttributeChange?.(i),this.hideAttributePanel()}updateFeatureProperties(e,t){const n=e.getGeoJson?e.getGeoJson():e.geoJson;n&&(n.properties=t)}openAttributeEditor(e){if(!this.options.enableAttributeEditing){console.warn("Attribute editing is not enabled");return}const t=this.findGeomanDataForFeature(e);this.showAttributePanel(e,t??void 0,!1)}closeAttributeEditor(){this.hideAttributePanel()}setAttributeSchema(e){this.options.attributeSchema=e,this.attributePanelVisible&&this.currentEditingFeature&&this.buildAttributeForm(this.currentEditingFeature)}getAttributeSchema(){return this.options.attributeSchema}enableScaleMode(){this.scaleTargetFeature=null,this.scaleTargetGeomanData=null;const e=this.getSelectedFeatures();if(e.length===0){console.warn("Select a feature to scale");return}const t=this.findGeomanDataForFeature(e[0]);if(!t){console.warn("Selected feature is not managed by Geoman");return}this.scaleTargetFeature=e[0],this.scaleTargetGeomanData=t,this.scaleFeature.showHandlesForFeature(e[0]),this.bringScaleHandlesToFront(),this.state.selectedFeatures.length>0&&(this.state.selectedFeatures[0]={...this.state.selectedFeatures[0],id:String(t.id),geomanData:t}),this.map.getCanvas().style.cursor="nwse-resize"}enableCopyMode(){this.copySelectedFeatures()}enableSplitMode(){const e=this.getSelectedFeatures();if(e.length===0){console.warn("Select a polygon or line to split");return}const t=e[0];if(!_R(t)&&!fG(t)){console.warn("Can only split polygons and lines");return}this.splitFeature.startSplit(t,n=>{this.handleSplitResult(n)})}enableLassoMode(){this.lassoFeature.enable(e=>{this.handleLassoResult(e)})}executeUnion(){const e=lm(this.getSelectedFeatures());if(e.length<2){console.warn("Select at least 2 polygons to merge");return}const t=this.unionFeature.union(e);this.handleUnionResult(t)}executeDifference(){const e=lm(this.getSelectedFeatures());if(e.length<2){console.warn("Select at least 2 polygons (first is base, rest are subtracted)");return}const[t,...n]=e,i=this.differenceFeature.difference(t,n);this.handleDifferenceResult(i)}executeSimplify(){let e=this.getSelectedFeatures();if(e.length===0&&this.lastCreatedFeature&&(e=[this.lastCreatedFeature]),e.length===0){console.warn("Select a feature to simplify");return}const t=e.map(i=>this.getSimplifyResult(i)).filter(i=>!!i),n=t.length>1;if(t.length===0){console.warn("Simplify: no vertices removed with current tolerance");return}t.forEach(i=>{this.applySimplifyResult(i,{clearSelection:!n,disableModes:!n}),this.logSelectedFeatureCollection("edited",i.result)}),n&&(this.clearSelection(),this.disableAllModes())}getSimplifyResult(e){const t=this.simplifyFeature.simplifyWithStats(e);if(t.verticesAfter<t.verticesBefore)return t;const n=this.simplifyFeature.getSuggestedTolerances(e);for(const i of n){if(i===this.options.simplifyTolerance)continue;const s=this.simplifyFeature.simplifyWithStats(e,{tolerance:i});if(s.verticesAfter<s.verticesBefore)return s}return null}copySelectedFeatures(){const e=this.getSelectedFeatures();if(e.length===0){console.warn("No features selected to copy");return}this.state.clipboard=this.copyFeature.copyMultiple(e),this.emitEvent("gm:copy",{features:e})}pasteFeatures(){if(this.state.clipboard.length===0){console.warn("Clipboard is empty");return}const e=this.copyFeature.copyMultiple(this.state.clipboard);this.geoman&&e.forEach(t=>{this.geoman?.features.importGeoJsonFeature(t),this.options.onFeatureCreate?.(t),this.lastCreatedFeature=t}),this.emitEvent("gm:paste",{features:e})}deleteFeatureById(e){if(this.geoman)try{const t=[];this.geoman.features.forEach(n=>{const i=this.getGeomanFeature(n),s=i?.properties;(String(n.id)===e||String(i?.id)===e||String(s?.__gm_id)===e)&&t.push(n)}),t.forEach(n=>{this.deleteGeomanFeatureData(n)})}catch{}}deleteSelectedFeatures(){const e=this.state.selectedFeatures;e.length!==0&&(e.forEach(t=>{const n=t.geomanData??this.findGeomanDataForFeature(t.feature);this.deleteGeomanFeatureData(n,t.id),this.options.onFeatureDelete?.(t.id),this.lastDeletedFeature=t.feature,this.lastDeletedFeatureId=t.id,this.logSelectedFeatureCollection("deleted",t.feature)}),this.clearSelection())}deleteGeomanFeatureData(e,t){if(this.geoman){if(e){try{this.geoman.features.delete(e);return}catch{}try{e.delete();return}catch{}}t&&this.deleteFeatureById(t)}}deleteGeomanFeatures(e){e.forEach(t=>{const n=this.findGeomanDataForFeature(t),i=this.getGeomanIdFromFeature(t);this.deleteGeomanFeatureData(n,i??void 0),i&&this.options.onFeatureDelete?.(i),this.lastDeletedFeature=t,this.lastDeletedFeatureId=i??null,this.logSelectedFeatureCollection("deleted",t)})}clearGeomanTemporaryFeatures(){if(this.geoman)try{if(typeof this.geoman.features.tmpForEach=="function"){this.geoman.features.tmpForEach(e=>{try{e.delete()}catch{}});return}this.geoman.features.forEach(e=>{if(e.temporary)try{e.delete()}catch{}})}catch{}}handleSplitResult(e){if(!e.success){console.warn("Split failed:",e.error);return}this.recordCompositeOperation([e.original],e.parts,"Split"),this.isPerformingCompositeOperation=!0;try{this.deleteGeomanFeatures([e.original]),this.clearGeomanTemporaryFeatures(),this.clearSelection(),this.geoman&&e.parts.forEach(t=>{this.geoman?.features.importGeoJsonFeature(t),this.options.onFeatureCreate?.(t),this.lastCreatedFeature=t,this.logSelectedFeatureCollection("created",t)})}finally{this.isPerformingCompositeOperation=!1}this.emitEvent("gm:split",e),this.disableAllModes()}handleUnionResult(e){if(!e.success||!e.result){console.warn("Union failed:",e.error);return}this.recordCompositeOperation(e.originals,[e.result],"Union"),this.isPerformingCompositeOperation=!0;try{this.deleteGeomanFeatures(e.originals),this.clearGeomanTemporaryFeatures(),this.clearSelection(),this.geoman&&(this.geoman.features.importGeoJsonFeature(e.result),this.options.onFeatureCreate?.(e.result),this.lastCreatedFeature=e.result,this.logSelectedFeatureCollection("created",e.result))}finally{this.isPerformingCompositeOperation=!1}this.emitEvent("gm:union",e),this.disableAllModes()}handleDifferenceResult(e){if(!e.success){console.warn("Difference failed:",e.error);return}const t=[e.base,...e.subtracted],n=e.result?[e.result]:[];this.recordCompositeOperation(t,n,"Difference"),this.isPerformingCompositeOperation=!0;try{this.deleteGeomanFeatures([e.base,...e.subtracted]),this.clearGeomanTemporaryFeatures(),this.clearSelection(),e.result&&this.geoman&&(this.geoman.features.importGeoJsonFeature(e.result),this.options.onFeatureCreate?.(e.result),this.lastCreatedFeature=e.result,this.logSelectedFeatureCollection("created",e.result))}finally{this.isPerformingCompositeOperation=!1}this.emitEvent("gm:difference",e),this.disableAllModes()}applySimplifyResult(e,t){this.recordCompositeOperation([e.original],[e.result],"Simplify"),this.isPerformingCompositeOperation=!0;try{this.deleteGeomanFeatures([e.original]),this.clearGeomanTemporaryFeatures(),this.geoman&&(e.result.id=this.getGeomanIdFromFeature(e.original)??e.result.id,this.geoman.features.importGeoJsonFeature(e.result),this.options.onFeatureEdit?.(e.result,e.original),this.lastEditedFeature=e.result)}finally{this.isPerformingCompositeOperation=!1}this.emitEvent("gm:simplify",e),t.clearSelection&&this.clearSelection(),t.disableModes&&this.disableAllModes()}handleLassoResult(e){const t=this.getFeatures().features,n=this.lassoFeature.selectWithinLasso(e.lasso,t);this.selectFeatures(n),this.emitEvent("gm:lassoend",{...e,selected:n}),this.disableAllModes()}createToolbar(){this.toolbar=document.createElement("div"),this.toolbar.className=`${rt}-toolbar ${rt}-toolbar--${this.options.toolbarOrientation}`,this.options.toolbarOrientation==="vertical"&&this.options.columns>1&&this.toolbar.classList.add(`${rt}-toolbar--columns-${this.options.columns}`),this.state.collapsed&&this.toolbar.classList.add(`${rt}-toolbar--collapsed`);const e=this.createCollapseButton();this.toolbar.appendChild(e);const t=document.createElement("div");if(t.className=`${rt}-tools-wrapper`,this.options.drawModes.length>0){const r=this.createToolGroup("Draw",this.options.drawModes,"draw");t.appendChild(r)}const n=this.options.editModes.filter(r=>!Pv.includes(r));if(n.length>0){const r=this.createToolGroup("Edit",n,"edit");t.appendChild(r)}const i=this.options.editModes.filter(r=>Pv.includes(r));if(i.length>0){const r=this.createToolGroup("Advanced",i,"edit");t.appendChild(r)}if(this.historyManager){const r=this.createHistoryToolsGroup();t.appendChild(r)}if(this.options.helperModes.includes("snapping")){const r=this.createHelperToolsGroup();t.appendChild(r)}if(this.options.fileModes&&this.options.fileModes.length>0){const r=this.createFileToolsGroup();t.appendChild(r)}const s=this.createResetToolsGroup();t.appendChild(s),this.toolbar.appendChild(t),this.state.collapsed&&(t.style.display="none"),this.container.appendChild(this.toolbar)}createCollapseButton(){const e=document.createElement("button");e.className=`${rt}-tool-button ${rt}-collapse-btn`,e.title=this.state.collapsed?"Expand toolbar":"Collapse toolbar";const t='<svg viewBox="0 0 24 24" width="18" height="18"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 0 0 0-1.41l-2.34-2.34a1 1 0 0 0-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z" fill="currentColor"/></svg>',n='<svg viewBox="0 0 24 24" width="18" height="18"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" fill="currentColor"/></svg>';return e.innerHTML=this.state.collapsed?t:n,e.addEventListener("click",()=>{this.toggleCollapse(),e.innerHTML=this.state.collapsed?t:n,e.title=this.state.collapsed?"Expand toolbar":"Collapse toolbar"}),e}toggleCollapse(){if(this.state.collapsed=!this.state.collapsed,this.toolbar){this.toolbar.classList.toggle(`${rt}-toolbar--collapsed`,this.state.collapsed);const e=this.toolbar.querySelector(`.${rt}-tools-wrapper`);e&&(e.style.display=this.state.collapsed?"none":"")}this._emitControlEvent(this.state.collapsed?"collapse":"expand")}isCollapsed(){return this.state.collapsed}setCollapsed(e){this.state.collapsed!==e&&this.toggleCollapse()}expand(){this.setCollapsed(!1)}collapse(){this.setCollapsed(!0)}on(e,t){this._eventHandlers.has(e)||this._eventHandlers.set(e,new Set),this._eventHandlers.get(e).add(t)}off(e,t){this._eventHandlers.get(e)?.delete(t)}_emitControlEvent(e,t){const n=this._eventHandlers.get(e);n&&n.forEach(i=>i(t))}createHelperToolsGroup(){const e=document.createElement("div");if(e.className=`${rt}-tool-group`,this.options.showLabels){const i=document.createElement("div");i.className=`${rt}-tool-group-label`,i.textContent="Helper",e.appendChild(i)}const t=document.createElement("div");t.className=`${rt}-tool-buttons`;const n=document.createElement("button");return n.className=`${rt}-tool-button`,n.dataset.helper="snapping",n.title="Toggle Snapping",n.innerHTML='<svg viewBox="0 0 24 24" width="18" height="18"><path d="M7 3h4v6H7V3zm6 0h4v6h-4V3zM7 9h4v3a3 3 0 0 0 6 0V9h4v3a7 7 0 0 1-14 0V9z" fill="currentColor"/></svg>',this.snappingEnabled&&n.classList.add(`${rt}-tool-button--active`),n.addEventListener("click",i=>{i.stopPropagation(),this.toggleSnapping(),n.classList.toggle(`${rt}-tool-button--active`,this.snappingEnabled)}),t.appendChild(n),e.appendChild(t),e}createResetToolsGroup(){const e=document.createElement("div");if(e.className=`${rt}-tool-group`,this.options.showLabels){const i=document.createElement("div");i.className=`${rt}-tool-group-label`,i.textContent="Reset",e.appendChild(i)}const t=document.createElement("div");t.className=`${rt}-tool-buttons`;const n=document.createElement("button");return n.className=`${rt}-tool-button`,n.title="Clear selection and disable tools",n.innerHTML='<svg viewBox="0 0 24 24" width="18" height="18"><path d="M12 5a7 7 0 1 1-6.32 4H3l3.5-3.5L10 9H7.74A5 5 0 1 0 12 7v2l3-3-3-3v2z" fill="currentColor"/></svg>',n.addEventListener("click",()=>{this.disableAllModes(),this.clearSelection(),this.updateToolbarState()}),t.appendChild(n),e.appendChild(t),e}createFileToolsGroup(){const e=document.createElement("div");if(e.className=`${rt}-tool-group`,this.options.showLabels){const n=document.createElement("div");n.className=`${rt}-tool-group-label`,n.textContent="File",e.appendChild(n)}const t=document.createElement("div");if(t.className=`${rt}-tool-buttons`,this.options.fileModes.includes("open")){const n=document.createElement("button");n.className=`${rt}-tool-button`,n.dataset.file="open",n.title="Open GeoJSON file",n.innerHTML='<svg viewBox="0 0 24 24" width="18" height="18"><path d="M20 6h-8l-2-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 12H4V8h16v10z" fill="currentColor"/></svg>',n.addEventListener("click",()=>this.openFileDialog()),t.appendChild(n)}if(this.options.fileModes.includes("save")){const n=document.createElement("button");n.className=`${rt}-tool-button`,n.dataset.file="save",n.title="Save GeoJSON file",n.innerHTML='<svg viewBox="0 0 24 24" width="18" height="18"><path d="M17 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm2 16H5V5h11.17L19 7.83V19zm-7-7c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3zM6 6h9v4H6V6z" fill="currentColor"/></svg>',n.addEventListener("click",()=>this.saveGeoJson()),t.appendChild(n)}return e.appendChild(t),e}setupFileInput(){this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept=".geojson,.json,application/geo+json,application/json",this.fileInput.style.display="none",this.fileInput.addEventListener("change",e=>this.handleFileSelect(e)),document.body.appendChild(this.fileInput)}openFileDialog(){this.fileInput&&this.fileInput.click()}handleFileSelect(e){const t=e.target,n=t.files?.[0];if(!n)return;const i=new FileReader;i.onload=s=>{try{const r=s.target?.result,a=JSON.parse(r);this.loadGeoJson(a,n.name)}catch(r){console.error("GeoEditor: Failed to parse GeoJSON file:",r);const a={filename:n.name,message:r instanceof Error?r.message:String(r),error:r};this.emitEvent("gm:geojsonloaderror",a)}},i.readAsText(n),t.value=""}loadGeoJson(e,t="loaded.geojson"){if(!this.geoman)throw new Error("Geoman not initialized");try{this.geoman.features.deleteAll()}catch{this.geoman.features.forEach(r=>{try{r.delete()}catch{}})}this.clearSelection();let n;if(e.type==="Feature")n={type:"FeatureCollection",features:[e]};else if(e.type==="FeatureCollection")n=e;else throw new Error("Invalid GeoJSON: expected Feature or FeatureCollection");const i=this.geoman.features.importGeoJson(n),s={features:n.features,count:i.success,filename:t};return this.options.fitBoundsOnLoad&&n.features.length>0&&this.fitBoundsToFeatures(n),this.options.onGeoJsonLoad?.(s),this.emitEvent("gm:geojsonload",s),console.log(`GeoEditor: Loaded ${s.count} features from ${t}`),s}fitBoundsToFeatures(e){if(!(!e.features||e.features.length===0))try{const t=si(e);if(!this.isValidBBox(t)){console.warn("GeoEditor: Invalid bounding box for loaded features");return}const n=[[t[0],t[1]],[t[2],t[3]]];this.map.fitBounds(n,{padding:50,maxZoom:18,duration:500})}catch(t){console.warn("GeoEditor: Failed to fit bounds to features:",t)}}isValidBBox(e){return e.every(t=>isFinite(t)&&!isNaN(t))&&e[0]<=e[2]&&e[1]<=e[3]}fitToAllFeatures(){const e=this.getFeatures();if(e.features.length===0){console.warn("GeoEditor: No features to fit bounds to");return}this.fitBoundsToFeatures(e)}saveGeoJson(e){const t=this.getFeatures(),n=e||this.options.saveFilename||"features.geojson",i=new Blob([JSON.stringify(t,null,2)],{type:"application/geo+json"}),s=URL.createObjectURL(i),r=document.createElement("a");r.href=s,r.download=n,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(s);const a={featureCollection:t,count:t.features.length,filename:n};return this.options.onGeoJsonSave?.(a),this.emitEvent("gm:geojsonsave",a),console.log(`GeoEditor: Saved ${a.count} features to ${n}`),a}toggleSnapping(){this.snappingEnabled=!this.snappingEnabled,this.applySnappingState()}isSnappingEnabled(){return this.snappingEnabled}setSnapping(e){this.snappingEnabled=e,this.applySnappingState()}applySnappingState(){if(this.geoman)try{if(typeof this.geoman.enableMode=="function"){this.snappingEnabled?this.geoman.enableMode("helper","snapping"):this.geoman.disableMode("helper","snapping");return}const e=this.geoman;typeof e.setGlobalOptions=="function"?e.setGlobalOptions({snapping:this.snappingEnabled}):typeof e.enableSnapping=="function"&&this.snappingEnabled?e.enableSnapping():typeof e.disableSnapping=="function"&&!this.snappingEnabled&&e.disableSnapping()}catch{console.info("Snapping toggle: Geoman version does not support snapping.")}}createToolGroup(e,t,n){const i=document.createElement("div");if(i.className=`${rt}-tool-group`,this.options.showLabels){const r=document.createElement("div");r.className=`${rt}-tool-group-label`,r.textContent=e,i.appendChild(r)}const s=document.createElement("div");return s.className=`${rt}-tool-buttons`,t.forEach(r=>{const a=this.createToolButton(r,n);s.appendChild(a)}),i.appendChild(s),i}createToolButton(e,t){const n=document.createElement("button");return n.className=`${rt}-tool-button`,n.dataset.mode=e,n.dataset.type=t,n.title=this.getModeLabel(e),n.innerHTML=this.getModeIcon(e),n.addEventListener("click",()=>{t==="draw"?this.enableDrawMode(e):this.enableEditMode(e)}),n}updateToolbarState(){this.container.querySelectorAll(`.${rt}-tool-button`).forEach(e=>{const t=e,n=t.dataset.mode,i=t.dataset.type;if(t.dataset.helper)return;let s=!1;i==="draw"?s=n===this.state.activeDrawMode:i==="edit"&&(n==="select"?s=this.isSelectMode:n==="union"?s=this.pendingOperation==="union":n==="difference"?s=this.pendingOperation==="difference":s=n===this.state.activeEditMode),t.classList.toggle(`${rt}-tool-button--active`,s);const r=t.querySelector("svg");r&&r.querySelectorAll("path, polygon, rect, circle, ellipse, line, text").forEach(a=>{const o=a;o.style.fill="",o.style.stroke=""})})}getModeLabel(e){return{marker:"Marker",circle:"Circle",circle_marker:"Circle Marker",ellipse:"Ellipse",text_marker:"Text",line:"Line",rectangle:"Rectangle",polygon:"Polygon",freehand:"Freehand",select:"Select (click features)",drag:"Drag",change:"Edit",rotate:"Rotate",cut:"Cut",delete:"Delete",scale:"Scale",copy:"Copy",split:"Split",union:"Union (select 2+ polygons)",difference:"Difference (select 2+ polygons)",simplify:"Simplify",lasso:"Lasso Select"}[e]||e}getModeIcon(e){return{polygon:'<svg viewBox="0 0 24 24" width="18" height="18"><polygon points="12,2 22,8 18,22 6,22 2,8" fill="none" stroke="currentColor" stroke-width="2"/></svg>',line:'<svg viewBox="0 0 24 24" width="18" height="18"><line x1="4" y1="20" x2="20" y2="4" stroke="currentColor" stroke-width="2"/></svg>',rectangle:'<svg viewBox="0 0 24 24" width="18" height="18"><rect x="3" y="5" width="18" height="14" fill="none" stroke="currentColor" stroke-width="2"/></svg>',circle:'<svg viewBox="0 0 24 24" width="18" height="18"><circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="2"/></svg>',marker:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7z" fill="none" stroke="currentColor" stroke-width="2"/></svg>',select:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M4 3l6 14 2-6 6-2L4 3z" fill="currentColor"/><path d="M12.5 13.5l4.5 4.5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>',drag:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M10 9h4V6h3l-5-5-5 5h3v3zm-1 1H6V7l-5 5 5 5v-3h3v-4zm14 2l-5-5v3h-3v4h3v3l5-5zm-9 3h-4v3H7l5 5 5-5h-3v-3z" fill="currentColor"/></svg>',change:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a.996.996 0 0 0 0-1.41l-2.34-2.34a.996.996 0 0 0-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z" fill="currentColor"/></svg>',rotate:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M17.65 6.35A7.958 7.958 0 0 0 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08A5.99 5.99 0 0 1 12 18c-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z" fill="currentColor"/></svg>',cut:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M9.64 7.64c.23-.5.36-1.05.36-1.64 0-2.21-1.79-4-4-4S2 3.79 2 6s1.79 4 4 4c.59 0 1.14-.13 1.64-.36L10 12l-2.36 2.36C7.14 14.13 6.59 14 6 14c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4c0-.59-.13-1.14-.36-1.64L12 14l7 7h3v-1L9.64 7.64z" fill="currentColor"/></svg>',delete:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z" fill="currentColor"/></svg>',scale:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M21 15h2v2h-2v-2zm0-4h2v2h-2v-2zm2 8h-2v2c1 0 2-1 2-2zM13 3h2v2h-2V3zm8 4h2v2h-2V7zm0-4v2h2c0-1-1-2-2-2zM1 7h2v2H1V7zm16-4h2v2h-2V3zm0 16h2v2h-2v-2zM3 3C2 3 1 4 1 5h2V3zm6 0h2v2H9V3zM5 3h2v2H5V3zm-4 8v8c0 1.1.9 2 2 2h12V11H1z" fill="currentColor"/></svg>',copy:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z" fill="currentColor"/></svg>',split:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M14 4l2.29 2.29-2.88 2.88 1.42 1.42 2.88-2.88L20 10V4h-6zm-4 0H4v6l2.29-2.29 4.71 4.7V20h2v-8.41l-5.29-5.3L10 4z" fill="currentColor"/></svg>',union:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M4 4h7v7H4V4zm9 0h7v7h-7V4zm-9 9h7v7H4v-7zm9 0h7v7h-7v-7z" fill="currentColor"/></svg>',difference:'<svg viewBox="0 0 24 24" width="18" height="18"><rect x="4" y="4" width="10" height="10" fill="none" stroke="currentColor" stroke-width="2"/><rect x="10" y="10" width="10" height="10" fill="none" stroke="currentColor" stroke-width="2"/><path d="M13 7h6v2h-6z" fill="currentColor"/></svg>',simplify:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M4 17l5-5 3 3 6-6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M5 6h14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>',lasso:'<svg viewBox="0 0 24 24" width="18" height="18"><ellipse cx="12" cy="10" rx="8" ry="6" fill="none" stroke="currentColor" stroke-width="2" stroke-dasharray="4 2"/><circle cx="12" cy="18" r="3" fill="currentColor"/></svg>',freehand:'<svg viewBox="0 0 24 24" width="18" height="18"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25z" fill="none" stroke="currentColor" stroke-width="2"/></svg>',circle_marker:'<svg viewBox="0 0 24 24" width="18" height="18"><circle cx="12" cy="12" r="4" fill="currentColor"/></svg>',ellipse:'<svg viewBox="0 0 24 24" width="18" height="18"><ellipse cx="12" cy="12" rx="10" ry="6" fill="none" stroke="currentColor" stroke-width="2"/></svg>',text_marker:'<svg viewBox="0 0 24 24" width="18" height="18"><text x="12" y="16" text-anchor="middle" font-size="14" fill="currentColor">T</text></svg>'}[e]||`<span>${e[0].toUpperCase()}</span>`}setupKeyboardShortcuts(){this.boundKeyHandler=e=>{const t=e.target instanceof HTMLInputElement||e.target instanceof HTMLTextAreaElement||e.target instanceof HTMLElement&&e.target.isContentEditable;if((e.ctrlKey||e.metaKey)&&e.key==="z"&&!e.shiftKey){this.undo(),e.preventDefault();return}if((e.ctrlKey||e.metaKey)&&(e.key==="y"||e.key==="z"&&e.shiftKey||e.key==="Z"&&e.shiftKey)){this.redo(),e.preventDefault();return}(e.ctrlKey||e.metaKey)&&e.key==="c"&&(this.copySelectedFeatures(),e.preventDefault()),(e.ctrlKey||e.metaKey)&&e.key==="v"&&(this.pasteFeatures(),e.preventDefault()),(e.key==="Delete"||e.key==="Backspace")&&!t&&!(e.target instanceof Element&&e.target.closest(".geo-editor-attribute-panel"))&&(this.deleteSelectedFeatures(),e.preventDefault()),e.key==="Enter"&&this.pendingOperation&&(this.executePendingOperation(),e.preventDefault()),e.key==="Escape"&&(this.pendingOperation?this.cancelPendingOperation():(this.disableAllModes(),this.clearSelection()))},document.addEventListener("keydown",this.boundKeyHandler)}removeKeyboardShortcuts(){this.boundKeyHandler&&(document.removeEventListener("keydown",this.boundKeyHandler),this.boundKeyHandler=null)}setupGeomanEvents(){this.geoman&&this.geoman.setGlobalEventsListener(e=>{const t=e.name??e.type??"",n=this.extractFeatureFromEvent(e.feature),i=e.action??"";if((t==="gm:create"||e.type==="gm:create")&&n&&(this.lastCreatedFeature=n,this.options.onFeatureCreate?.(n),this.logSelectedFeatureCollection("created",n),this.recordCreateOperation(n),this.options.enableAttributeEditing)){this.applyDefaultValues(n);const s=this.findGeomanDataForFeature(n);this.showAttributePanel(n,s??void 0,!0)}i==="feature_edit_start"&&n&&(this.pendingEditFeature=Es(n)),i==="feature_edit_end"&&n&&(this.lastEditedFeature=n,this.logSelectedFeatureCollection("edited",n),this.pendingEditFeature&&(this.recordEditOperation(this.pendingEditFeature,n),this.pendingEditFeature=null)),i==="feature_removed"&&n&&(this.lastDeletedFeature=n,this.lastDeletedFeatureId=this.getGeomanIdFromFeature(n),this.logSelectedFeatureCollection("deleted",n),this.recordDeleteOperation(n)),(t.includes("modetoggled")||e.type?.includes("modetoggled"))&&this.updateToolbarState()})}emitEvent(e,t){const n=new CustomEvent(e,{detail:t});this.map.getContainer().dispatchEvent(n)}undo(){return this.historyManager?this.historyManager.undo():!1}redo(){return this.historyManager?this.historyManager.redo():!1}canUndo(){return this.historyManager?.canUndo()??!1}canRedo(){return this.historyManager?.canRedo()??!1}clearHistory(){this.historyManager?.clear()}getHistoryState(){return this.historyManager?.getState()??null}getCommandContext(){return this.geoman?{featuresApi:this.geoman.features,onFeatureCreate:this.options.onFeatureCreate,onFeatureDelete:this.options.onFeatureDelete,onFeatureEdit:this.options.onFeatureEdit}:null}recordCreateOperation(e){if(!this.historyManager||this.historyManager.isExecutingCommand()||this.isPerformingCompositeOperation)return;const t=this.getCommandContext();if(!t)return;const n=new ZS(e,t);this.historyManager.record(n)}recordEditOperation(e,t){if(!this.historyManager||this.historyManager.isExecutingCommand()||this.isPerformingCompositeOperation)return;const n=this.getCommandContext();if(!n)return;const i=new oG(e,t,n);this.historyManager.record(i)}recordDeleteOperation(e){if(!this.historyManager||this.historyManager.isExecutingCommand()||this.isPerformingCompositeOperation)return;const t=this.getCommandContext();if(!t)return;const n=new JS(e,t);this.historyManager.record(n)}recordCompositeOperation(e,t,n){if(!this.historyManager||this.historyManager.isExecutingCommand())return;const i=this.getCommandContext();if(!i)return;const s=[];for(const a of e)s.push(new JS(a,i));for(const a of t)s.push(new ZS(a,i));const r=new lG(s,n);this.historyManager.record(r)}updateHistoryButtonStates(e,t){const n=this.container.querySelector('[data-history="undo"]'),i=this.container.querySelector('[data-history="redo"]');n&&(n.disabled=!e),i&&(i.disabled=!t)}createHistoryToolsGroup(){const e=document.createElement("div");if(e.className=`${rt}-tool-group`,this.options.showLabels){const s=document.createElement("div");s.className=`${rt}-tool-group-label`,s.textContent="History",e.appendChild(s)}const t=document.createElement("div");t.className=`${rt}-tool-buttons`;const n=document.createElement("button");n.className=`${rt}-tool-button`,n.dataset.history="undo",n.title="Undo (Ctrl+Z)",n.disabled=!0,n.innerHTML='<svg viewBox="0 0 24 24" width="18" height="18"><path d="M12.5 8c-2.65 0-5.05 1.04-6.93 2.75L2.5 7.69v7.81h7.81l-3.12-3.12c1.36-1.2 3.13-1.88 5.04-1.88 3.31 0 6.13 2.04 7.31 4.94l2.33-.91C20.32 10.93 16.73 8 12.5 8z" fill="currentColor"/></svg>',n.addEventListener("click",()=>this.undo()),t.appendChild(n);const i=document.createElement("button");return i.className=`${rt}-tool-button`,i.dataset.history="redo",i.title="Redo (Ctrl+Y)",i.disabled=!0,i.innerHTML='<svg viewBox="0 0 24 24" width="18" height="18"><path d="M18.43 10.75C16.55 9.04 14.15 8 11.5 8c-4.23 0-7.82 2.93-9.37 6.53l2.33.91c1.18-2.9 4-4.94 7.31-4.94 1.91 0 3.68.68 5.04 1.88l-3.12 3.12h7.81V7.69l-3.07 3.06z" fill="currentColor"/></svg>',i.addEventListener("click",()=>this.redo()),t.appendChild(i),e.appendChild(t),e}getPanelElement(){return this.attributePanel??null}},Fv="geo-editor-features",AR=class{type="geo-editor";_control;_changeCallbacks=[];_visible=!0;_opacity=1;_hasFeatures=!1;constructor(e){this._control=e,this._setupEventListeners()}_setupEventListeners(){}getLayerIds(){const e=this._control.getFeatures(),t=e&&e.features&&e.features.length>0;return t&&!this._hasFeatures?(this._hasFeatures=!0,this._changeCallbacks.forEach(n=>n("add",Fv))):!t&&this._hasFeatures&&(this._hasFeatures=!1,this._changeCallbacks.forEach(n=>n("remove",Fv))),t?[Fv]:[]}getLayerState(e){const t=this._control.getFeatures();return!t||!t.features||t.features.length===0?null:{visible:this._visible,opacity:this._opacity,name:this.getName(e),isCustomLayer:!0,customLayerType:"geo-editor"}}setVisibility(e,t){this._visible=t;const n=this._control.map;if(!n)return;const i=n.getStyle();if(i?.layers)for(const s of i.layers)s.source&&typeof s.source=="string"&&s.source.startsWith("geoman")&&n.setLayoutProperty(s.id,"visibility",t?"visible":"none")}setOpacity(e,t){this._opacity=t;const n=this._control.map;if(!n)return;const i=n.getStyle();if(i?.layers)for(const s of i.layers)s.source&&typeof s.source=="string"&&s.source.startsWith("geoman")&&(s.type==="fill"?n.setPaintProperty(s.id,"fill-opacity",t*.3):s.type==="line"?n.setPaintProperty(s.id,"line-opacity",t):s.type==="circle"&&n.setPaintProperty(s.id,"circle-opacity",t))}getName(e){return"Drawn Features"}getSymbolType(e){return"fill"}removeLayer(e){const t=this._control.geoman;t?.features&&t.features.forEach(n=>{n.delete()}),this._hasFeatures=!1}onLayerChange(e){return this._changeCallbacks.push(e),()=>{const t=this._changeCallbacks.indexOf(e);t>=0&&this._changeCallbacks.splice(t,1)}}destroy(){this._changeCallbacks=[]}},EG=Object.defineProperty,CG=(e,t,n)=>t in e?EG(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,oi=(e,t,n)=>CG(e,typeof t!="symbol"?t+"":t,n),wG="https://planetarycomputer.microsoft.com/api/stac/v1",SG=class{constructor(e=wG){oi(this,"baseUrl"),oi(this,"abortController",null),this.baseUrl=e.replace(/\/$/,"")}async getCollections(){return(await this.fetch("/collections")).collections}async getCollection(e){return this.fetch(`/collections/${encodeURIComponent(e)}`)}async search(e){var t;return(t=this.abortController)==null||t.abort(),this.abortController=new AbortController,(await this.fetch("/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:this.abortController.signal})).features}async searchWithContext(e){var t;return(t=this.abortController)==null||t.abort(),this.abortController=new AbortController,this.fetch("/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:this.abortController.signal})}async getCollectionItems(e,t=50){return(await this.fetch(`/collections/${encodeURIComponent(e)}/items?limit=${t}`)).features}async getItem(e,t){return this.fetch(`/collections/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}`)}cancelPending(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null}getBaseUrl(){return this.baseUrl}async fetch(e,t){const n=`${this.baseUrl}${e}`;try{const i=await fetch(n,t);if(!i.ok){const s=await i.text();throw new Error(`STAC API error: ${i.status} ${i.statusText} - ${s}`)}return i.json()}catch(i){throw i instanceof Error&&i.name==="AbortError"?new Error("Request was cancelled"):i}}},IG="https://planetarycomputer.microsoft.com/api/data/v1",MG=class{constructor(e=IG){oi(this,"baseUrl"),this.baseUrl=e.replace(/\/$/,"")}getItemTileUrl(e,t,n={}){const i=this.buildQueryString(n),s=i?`?${i}`:"";return`${this.baseUrl}/item/tiles/WebMercatorQuad/{z}/{x}/{y}@1x?collection=${encodeURIComponent(e)}&item=${encodeURIComponent(t)}${s?"&"+i:""}`}getCollectionTileUrl(e,t={},n){const i=this.buildQueryString(t),s=n?this.buildSearchParams(n):"",r=[`collection=${encodeURIComponent(e)}`,i,s].filter(Boolean).join("&");return`${this.baseUrl}/mosaic/tiles/WebMercatorQuad/{z}/{x}/{y}@1x?${r}`}async registerMosaic(e,t={}){const n=await fetch(`${this.baseUrl}/mosaic/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({collections:e.collections,filter:e.filter,"filter-lang":e["filter-lang"]||"cql2-json",sortby:e.sortby})});if(!n.ok)throw new Error(`Failed to register mosaic: ${n.statusText}`);const i=await n.json(),s=i.id||i.searchid,r=this.buildQueryString(t);return{searchId:s,tileUrl:`${this.baseUrl}/mosaic/tiles/WebMercatorQuad/{z}/{x}/{y}@1x?searchid=${s}${r?"&"+r:""}`}}async getItemInfo(e,t,n){const i=n?.length?`&assets=${n.join(",")}`:"",s=await fetch(`${this.baseUrl}/item/info?collection=${encodeURIComponent(e)}&item=${encodeURIComponent(t)}${i}`);if(!s.ok)throw new Error(`Failed to get item info: ${s.statusText}`);return s.json()}async getItemStatistics(e,t,n){const i=n?.length?`&assets=${n.join(",")}`:"",s=await fetch(`${this.baseUrl}/item/statistics?collection=${encodeURIComponent(e)}&item=${encodeURIComponent(t)}${i}`);if(!s.ok)throw new Error(`Failed to get item statistics: ${s.statusText}`);return s.json()}getBaseUrl(){return this.baseUrl}buildQueryString(e){var t;const n=new URLSearchParams;return(t=e.assets)!=null&&t.length&&e.assets.forEach(i=>n.append("assets",i)),e.expression&&n.set("expression",e.expression),e.rescale&&n.set("rescale",e.rescale),e.colormap_name&&n.set("colormap_name",e.colormap_name),e.colormap&&n.set("colormap",JSON.stringify(e.colormap)),e.nodata!==void 0&&n.set("nodata",String(e.nodata)),e.resampling&&n.set("resampling",e.resampling),e.return_mask!==void 0&&n.set("return_mask",String(e.return_mask)),e.tile_size&&n.set("tile_size",String(e.tile_size)),e.asset_bidx&&Object.entries(e.asset_bidx).forEach(([i,s])=>{n.append("asset_bidx",`${i}|${s}`)}),n.toString()}buildSearchParams(e){const t=[];return e.datetime&&t.push(`datetime=${encodeURIComponent(e.datetime)}`),e.bbox&&t.push(`bbox=${e.bbox.join(",")}`),t.join("&")}},TG="https://planetarycomputer.microsoft.com/api/sas/v1/token",LG=class{constructor(e=300*1e3){oi(this,"cache",new Map),oi(this,"bufferMs"),this.bufferMs=e}async getToken(e){const t=this.cache.get(e),n=new Date;if(t&&t.expiry.getTime()-n.getTime()>this.bufferMs)return t.token;const i=await fetch(`${TG}/${encodeURIComponent(e)}`);if(!i.ok)throw new Error(`Failed to get SAS token for ${e}: ${i.statusText}`);const s=await i.json(),r=s.token,a=new Date(s["msft:expiry"]);return this.cache.set(e,{token:r,expiry:a}),r}async signUrl(e,t){const n=await this.getToken(t);return`${e}${e.includes("?")?"&":"?"}${n}`}hasValidToken(e){const t=this.cache.get(e);if(!t)return!1;const n=new Date;return t.expiry.getTime()-n.getTime()>this.bufferMs}clearCache(){this.cache.clear()}clearToken(e){this.cache.delete(e)}},BG=[{name:"true-color",label:"True Color",description:"Natural color composite (RGB)",params:{assets:["visual"]}},{name:"false-color",label:"False Color (Vegetation)",description:"NIR-Red-Green composite for vegetation analysis",params:{assets:["B08","B04","B03"],rescale:"0,3000"}},{name:"ndvi",label:"NDVI",description:"Normalized Difference Vegetation Index",params:{expression:"(B08-B04)/(B08+B04)",rescale:"-1,1",colormap_name:"rdylgn"}},{name:"ndwi",label:"NDWI",description:"Normalized Difference Water Index",params:{expression:"(B03-B08)/(B03+B08)",rescale:"-1,1",colormap_name:"blues"}},{name:"swir",label:"SWIR Composite",description:"SWIR-NIR-Red for geology and moisture",params:{assets:["B12","B08","B04"],rescale:"0,3000"}}],RG=[{name:"true-color",label:"True Color",description:"Natural color composite (RGB)",params:{assets:["red","green","blue"],rescale:"0,20000"}},{name:"false-color",label:"False Color (Vegetation)",description:"NIR-Red-Green composite",params:{assets:["nir08","red","green"],rescale:"0,20000"}},{name:"ndvi",label:"NDVI",description:"Normalized Difference Vegetation Index",params:{expression:"(nir08-red)/(nir08+red)",rescale:"-1,1",colormap_name:"rdylgn"}},{name:"thermal",label:"Thermal",description:"Land surface temperature",params:{assets:["lwir11"],rescale:"290,320",colormap_name:"magma"}}],kG=[{name:"rgb",label:"RGB",description:"Natural color",params:{assets:["image"],asset_bidx:{image:"1,2,3"}}},{name:"cir",label:"Color Infrared",description:"NIR-Red-Green composite",params:{assets:["image"],asset_bidx:{image:"4,1,2"}}},{name:"ndvi",label:"NDVI",description:"Vegetation index from NAIP",params:{expression:"(image_b4-image_b1)/(image_b4+image_b1)",rescale:"-1,1",colormap_name:"rdylgn"}}],t1=[{name:"elevation",label:"Elevation",description:"Color-coded elevation",params:{assets:["data"],colormap_name:"terrain",rescale:"0,4000"}},{name:"hillshade",label:"Hillshade",description:"Shaded relief visualization",params:{assets:["data"],colormap_name:"gray",rescale:"0,255"}}],NG=[{collectionId:"sentinel-2-l2a",defaultPreset:"true-color",presets:BG},{collectionId:"landsat-c2-l2",defaultPreset:"true-color",presets:RG},{collectionId:"naip",defaultPreset:"rgb",presets:kG},{collectionId:"cop-dem-glo-30",defaultPreset:"elevation",presets:t1},{collectionId:"cop-dem-glo-90",defaultPreset:"elevation",presets:t1}];function vR(e){return NG.find(t=>t.collectionId===e)}function n1(e){const t=vR(e);return t?.presets??[]}function i1(e){const t=vR(e);if(t)return t.presets.find(n=>n.name===t.defaultPreset)}function s1(e=""){const t=Date.now().toString(36),n=Math.random().toString(36).substring(2,8);return e?`${e}-${t}-${n}`:`${t}-${n}`}function r1(e){if(!e)return"Unknown";try{return new Date(e).toLocaleDateString()}catch{return e}}function a1(e){return e.datetime||e.start_datetime||e.end_datetime||null}function PG(e,t){return e.length<=t?e:e.substring(0,t)+"..."}function DG(e){const[t,n,i,s]=e;return`${t.toFixed(2)}, ${n.toFixed(2)}, ${i.toFixed(2)}, ${s.toFixed(2)}`}var FG=class{constructor(e,t){oi(this,"map"),oi(this,"tilerClient"),oi(this,"layers",new Map),this.map=e,this.tilerClient=t}addItemLayer(e,t){const n=`${e.id.replace(/[^a-zA-Z0-9-_]/g,"-").slice(0,50)}-${s1().slice(-6)}`,i=`${n}-source`,s=e.collection||"";let r=t?.renderParams||{},a=t?.presetName;if(!t?.renderParams&&!t?.assets&&s){const h=i1(s);h&&(r=h.params,a=h.name)}const o=t?.assets||r.assets||this.getDefaultAssets(e);r={...r,assets:o};const l=this.tilerClient.getItemTileUrl(s,e.id,r);this.map.addSource(i,{type:"raster",tiles:[l],tileSize:256,bounds:e.bbox,attribution:"Microsoft Planetary Computer"}),this.map.addLayer({id:n,type:"raster",source:i,paint:{"raster-opacity":1}});const c={id:n,type:"item",sourceId:i,item:e,collection:void 0,visible:!0,opacity:1,assets:o,renderParams:r,presetName:a};return this.layers.set(n,c),c}addCollectionLayer(e,t){const n=`${(e.title||e.id).replace(/[^a-zA-Z0-9-_]/g,"-").slice(0,50)}-${s1().slice(-6)}`,i=`${n}-source`;let s=t?.renderParams||{},r=t?.presetName;if(!t?.renderParams&&!t?.assets){const h=i1(e.id);h&&(s=h.params,r=h.name)}const a=t?.assets||s.assets||this.getDefaultCollectionAssets(e);s={...s,assets:a};const o=this.tilerClient.getCollectionTileUrl(e.id,s),l=t?.bbox||this.getCollectionBounds(e);this.map.addSource(i,{type:"raster",tiles:[o],tileSize:256,bounds:l,attribution:"Microsoft Planetary Computer"}),this.map.addLayer({id:n,type:"raster",source:i,paint:{"raster-opacity":1}});const c={id:n,type:"collection",sourceId:i,collection:e,visible:!0,opacity:1,assets:a,renderParams:s,presetName:r};return this.layers.set(n,c),c}removeLayer(e){const t=this.layers.get(e);t&&(this.map.getLayer(e)&&this.map.removeLayer(e),this.map.getSource(t.sourceId)&&this.map.removeSource(t.sourceId),this.layers.delete(e))}updateLayer(e,t){const n=this.layers.get(e);n&&(t.visible!==void 0&&this.map.setLayoutProperty(e,"visibility",t.visible?"visible":"none"),t.opacity!==void 0&&this.map.setPaintProperty(e,"raster-opacity",t.opacity),(t.renderParams||t.assets)&&this.updateLayerSource(e,t),this.layers.set(e,{...n,...t}))}getLayer(e){return this.layers.get(e)}getLayers(){return Array.from(this.layers.values())}removeAllLayers(){for(const e of this.layers.keys())this.removeLayer(e)}zoomToLayer(e){var t;const n=this.layers.get(e);if(!n)return;let i;(t=n.item)!=null&&t.bbox?i=n.item.bbox:n.collection&&(i=this.getCollectionBounds(n.collection)),i&&this.map.fitBounds([[i[0],i[1]],[i[2],i[3]]],{padding:50})}getMap(){return this.map}updateLayerSource(e,t){var n;const i=this.layers.get(e);if(!i)return;const s={...i.renderParams,...t.renderParams},r=t.assets||i.assets;let a;if(i.type==="item"&&i.item){const h=i.item.collection||"";a=this.tilerClient.getItemTileUrl(h,i.item.id,{...s,assets:r})}else if(i.type==="collection"&&i.collection)a=this.tilerClient.getCollectionTileUrl(i.collection.id,{...s,assets:r});else return;const o=this.map.getLayoutProperty(e,"visibility"),l=this.map.getPaintProperty(e,"raster-opacity");this.map.removeLayer(e),this.map.removeSource(i.sourceId);const c=((n=i.item)==null?void 0:n.bbox)||(i.collection?this.getCollectionBounds(i.collection):void 0);this.map.addSource(i.sourceId,{type:"raster",tiles:[a],tileSize:256,bounds:c,attribution:"Microsoft Planetary Computer"}),this.map.addLayer({id:e,type:"raster",source:i.sourceId,layout:{visibility:o},paint:{"raster-opacity":l??1}})}getDefaultAssets(e){for(const i of["visual","data","image","cog_default"])if(e.assets[i])return[i];for(const[i,s]of Object.entries(e.assets)){const r=s.type||"";if(r.includes("tiff")||r.includes("geotiff")||r.includes("cog"))return[i]}const t=["thumbnail","overview","metadata","tilejson","rendered_preview"],n=Object.keys(e.assets).find(i=>!t.some(s=>i.toLowerCase().includes(s)));return n?[n]:[]}getDefaultCollectionAssets(e){const t=e.item_assets||{};for(const s of["visual","data","image","cog_default"])if(t[s])return[s];for(const[s,r]of Object.entries(t)){const a=r.type||"";if(a.includes("tiff")||a.includes("geotiff")||a.includes("cog"))return[s]}const n=["thumbnail","overview","metadata","tilejson","rendered_preview"],i=Object.keys(t).find(s=>!n.some(r=>s.toLowerCase().includes(r)));return i?[i]:[]}getCollectionBounds(e){var t,n,i;const s=(i=(n=(t=e.extent)==null?void 0:t.spatial)==null?void 0:n.bbox)==null?void 0:i[0];if(s&&s.length>=4)return[s[0],s[1],s[2],s[3]]}},OG={collapsed:!0,position:"top-right",title:"Planetary Computer",panelWidth:380,maxHeight:500,className:"",stacApiUrl:"https://planetarycomputer.microsoft.com/api/stac/v1",tilerApiUrl:"https://planetarycomputer.microsoft.com/api/data/v1",defaultCollections:[],enableBboxSelector:!0,maxSearchResults:50,autoLoadCollections:!0},gb=class{constructor(e){oi(this,"_map"),oi(this,"_mapContainer"),oi(this,"_container"),oi(this,"_panel"),oi(this,"_contentEl"),oi(this,"_options"),oi(this,"_state"),oi(this,"_eventHandlers",new globalThis.Map),oi(this,"_stacClient"),oi(this,"_tilerClient"),oi(this,"_sasManager"),oi(this,"_layerManager"),oi(this,"_resizeHandler",null),oi(this,"_mapResizeHandler",null),oi(this,"_clickOutsideHandler",null),this._options={...OG,...e},this._state=this._getInitialState(),this._stacClient=new SG(this._options.stacApiUrl),this._tilerClient=new MG(this._options.tilerApiUrl),this._sasManager=new LG}onAdd(e){return this._map=e,this._mapContainer=e.getContainer(),this._layerManager=new FG(e,this._tilerClient),this._container=this._createContainer(),this._panel=this._createPanel(),this._mapContainer.appendChild(this._panel),this._setupEventListeners(),this._state.collapsed||(this._panel.classList.add("expanded"),requestAnimationFrame(()=>this._updatePanelPosition())),this._options.autoLoadCollections&&this._loadCollections(),this._container}onRemove(){var e,t,n,i,s;this._resizeHandler&&(window.removeEventListener("resize",this._resizeHandler),this._resizeHandler=null),this._mapResizeHandler&&this._map&&(this._map.off("resize",this._mapResizeHandler),this._mapResizeHandler=null),this._clickOutsideHandler&&(document.removeEventListener("click",this._clickOutsideHandler),this._clickOutsideHandler=null),this._stacClient.cancelPending(),this._sasManager.clearCache(),(e=this._layerManager)==null||e.removeAllLayers(),(n=(t=this._panel)==null?void 0:t.parentNode)==null||n.removeChild(this._panel),(s=(i=this._container)==null?void 0:i.parentNode)==null||s.removeChild(this._container),this._map=void 0,this._eventHandlers.clear()}getState(){return{...this._state}}toggle(){this._state.collapsed=!this._state.collapsed,this._updatePanelVisibility(),this._emit(this._state.collapsed?"collapse":"expand"),this._emit("statechange")}expand(){this._state.collapsed&&this.toggle()}collapse(){this._state.collapsed||this.toggle()}async loadCollections(){return this._loadCollections()}async search(e){const t={...this._state.searchParams,...e,limit:this._options.maxSearchResults};this._state.searchParams=t,this._state.searchLoading=!0,this._state.error=null,this._emit("search:start"),this._emit("statechange");try{const n=await this._stacClient.search(t);return this._state.searchResults=n,this._state.activeView="results",this._emit("search:complete"),this._emit("search"),n}catch(n){const i=n instanceof Error?n.message:"Search failed";throw this._state.error=i,this._emit("search:error"),this._emit("error"),n}finally{this._state.searchLoading=!1,this._emit("statechange"),this._renderContent()}}addItemLayer(e,t){if(!this._layerManager)throw new Error("Control not added to map");const n=this._layerManager.addItemLayer(e,t);return this._state.activeLayers.push(n),this._emit("layer:add"),this._emit("statechange"),this._renderContent(),n}addCollectionLayer(e,t){if(!this._layerManager)throw new Error("Control not added to map");const n=this._layerManager.addCollectionLayer(e,t);return this._state.activeLayers.push(n),this._emit("layer:add"),this._emit("statechange"),this._renderContent(),n}removeLayer(e){var t;(t=this._layerManager)==null||t.removeLayer(e),this._state.activeLayers=this._state.activeLayers.filter(n=>n.id!==e),this._emit("layer:remove"),this._emit("statechange"),this._renderContent()}updateLayer(e,t){var n;(n=this._layerManager)==null||n.updateLayer(e,t);const i=this._state.activeLayers.findIndex(s=>s.id===e);i>=0&&(this._state.activeLayers[i]={...this._state.activeLayers[i],...t}),this._emit("layer:update"),this._emit("statechange")}zoomToLayer(e){var t;(t=this._layerManager)==null||t.zoomToLayer(e)}async getDownloadUrl(e,t){const n=e.assets[t];if(!n)throw new Error(`Asset '${t}' not found`);const i=e.collection||"";return this._sasManager.signUrl(n.href,i)}selectCollection(e){this._state.selectedCollection=e,this._state.searchParams=e?{collections:[e.id]}:{},this._state.activeView=e?"search":"collections",this._state.searchResults=[],this._emit("collection:select"),this._emit("statechange"),this._renderContent()}selectItem(e){this._state.selectedItem=e,this._state.activeView=e?"item":"results",this._emit("item:select"),this._emit("statechange"),this._renderContent()}setView(e){this._state.activeView=e,this._emit("statechange"),this._renderContent()}on(e,t){this._eventHandlers.has(e)||this._eventHandlers.set(e,new Set),this._eventHandlers.get(e).add(t)}off(e,t){var n;(n=this._eventHandlers.get(e))==null||n.delete(t)}getMap(){return this._map}getContainer(){return this._container}_getInitialState(){return{collapsed:this._options.collapsed,panelWidth:this._options.panelWidth,activeView:"collections",collections:[],collectionsLoading:!1,selectedCollection:null,searchParams:{},searchResults:[],searchLoading:!1,selectedItem:null,activeLayers:[],error:null,bboxSelectorActive:!1,drawnBbox:null}}_emit(e,t){const n=this._eventHandlers.get(e);if(n){const i={type:e,state:this.getState(),data:t};n.forEach(s=>s(i))}}_createContainer(){const e=document.createElement("div");e.className=`maplibregl-ctrl maplibregl-ctrl-group pc-control${this._options.className?` ${this._options.className}`:""}`;const t=document.createElement("button");return t.className="pc-control-toggle",t.type="button",t.setAttribute("aria-label",this._options.title),t.innerHTML=`
273
273
  <span class="pc-control-icon">
274
274
  <svg viewBox="0 0 23 23" width="22" height="22">
275
275
  <rect x="1" y="1" width="10" height="10" fill="#666"/>